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 @@ + + + + + +Mathly 2 screens + + + +
+

Mathly 2 · מסכים מוקאפ סטטי עם נתונים לדוגמה · דרישות לפי docs/tasks/prd-mathly.md

+
+ + + +
+
+
+ +
+ + +
+
+ + + + + + +
+

ACC-1 · דף הכניסה בסגנון mathly1

+
+ +
+ +
+ +
+
+
+

מבחן במתמטיקה · 16.11

עוד 9 ימים
+
62בדרךמוכנות (תקרה 80 עד הסימולציה)
+
+
שליטה 70%מבחני תרגול 54סימולציה —
+

המשימה של היום

+ +
+

המשימות שלי

+
דף עבודה: פירוק טרינוםעד 10.11
+
בוחן כתוב: טכניקה אלגברית 1✓ 85
+
+

תקועים על תרגיל? צלמו אותו

+

המורה רואה את התמונה קודם, ואז מגיעים רמזים אחד־אחד.

+
תרגיל מצולם · ממתין למורה
+ +
+ +
+
ביתמסלולציוניםהאוסף
+
+ +
+
+
יעד יומי: 3 מתוך 5
🔥 4 ימים
+
+
🦉
התחלה
+
+
טכניקה אלגברית 12 מתוך 5 נשלטו
+ + + + + +
+
🏆 בוחן השיעור
10 שאלות · 15 דק׳ · הציון הטוב: 85
+
+
פירוק לגורמים0 מתוך 3 נשלטו
+ + + +
+
✦
סוף המסלול
+
+
+
ביתמסלולציוניםהאוסף
+
+ +
+
+
טכניקה אלגברית 1

חוק הפילוג המורחב

+
+

כל איבר בסוגריים הראשונים כופל כל איבר בסוגריים השניים.

+
שאלה 3 מתוך 10
+
(x + 3)(x − 5) = ?
+
+ + + + +
+ +
+

נכונות ברצף: 2 מתוך 3 · נדרשים שני ימים שונים

+

דורשת: כפל איברים פותחת: פירוק טרינום

+
+
+ +
+
+

ציונים

+ + + + + +
מהציון
בוחן · טכניקה אלגברית 1 (הטוב מבין 2)85
בוחן · משוואות70
מבחן תרגול 1 · מבחן 16.1154
משימה · בוחן כתוב85
+
+
ביתמסלולציוניםהאוסף
+
+ +
+
+

האוסף שלי

+

כל מיומנות שנשלטה היא כוכב; שיעור שהושלם מצייר קבוצת כוכבים. שביט שלא נתפס מוצג כ־?.

+
⭐ 12 כוכבים · 1 קבוצת כוכבים
✦⋆✦דלתון
הושלם
+
☄️ שביטים 3 מתוך 12
πפאי
φיחס הזהב
0אפס
?עוד לא נתפס
?עוד לא נתפס
?עוד לא נתפס
+
+
ביתמסלולציוניםהאוסף
+
+ +
+
+ + +
+
+ +
+
+

TCH-1, TCH-9 · המורה מוסיפה ומסירה תלמידים בכיתה שלה בלבד

+
+

ט׳3

25 תלמידים
+

שיעורים: טכניקה אלגברית 1, משוואות, פירוק לגורמים · AI: פועל

+ + +
תלמיד
noa@school.org
yoav@school.org
+
+

ט׳4

22 תלמידים

AI: כבוי (מנהל הכיתות מפעיל)

+
+
+
+

TCH-4, AI-4, AI-5 · הישן ראשון; הציון של המורה גובר על הצעת ה־AI

+ + + + +
מהתלמידהוגשהצעת AI
דף עבודה: פירוק טרינוםnoa@ב׳ 08:1070 · "חסר נימוק בסעיף 2"
בקשה לבדוק שובyoav@ב׳ 12:4060
בוחן כתוב: טכניקה 1dana@ג׳ 09:05—
+

בדיקה: noa · דף עבודה

+
+
+

AI-1, AI-6, AI-7 · תלמידים לא פונים ל־AI בעצמם · תקציב יומי לכיתה

+
ט׳3 · נשארו היום 112 מתוך 150 בדיקות · הבקשות האישיות שלי: 2 מתוך 3
+
📷 תרגיל לעזרה · noa · פירוק טרינום
לפני 6 דקות
+
📝 בדיקת תשובה · yoav · דף עבודה
לפני 20 דקות
+
+
+

TST-1, TCH-6, RDY-1

+

מבחן ט׳3 · 16.11

+

שיעורים: טכניקה אלגברית 1, משוואות · 12 שאלות · 45 דק׳ · מחשבון מותר

+

סימולציה: 22 מתוך 25 עשו · חסרים: יואב, עמית, ליה

+
תלמידמוכנותשליטהתרגולסימולציה
נועה81 · כמעט שם80%7090
יואב62 · בדרך70%54—
+
+ +
+
+

TCH-7 · צבע וגם סימן בכל תא

+
+
+ + + + + +
תלמידטכניקה אלגברית 1משוואות
12312
נועה✓✓◐✓○
יואב◐○○◐○
דנה✓◐◐✓✓
+

✓ נשלטה · ◐ בלמידה · ○ לא התחילו

+
+
+
+
+ + +
+
+ +
+
+

CLS-7, MGR-1 · אין למנהל הכיתות גישה לנתוני למידה

+
2 כיתות
+
+

ט׳3

+

שיעורים: טכניקה אלגברית 1, משוואות, פירוק לגורמים
מורה: rina@school.org
25 תלמידים · AI: פועל · 150 בדיקות ביום

+

ט׳4

+

שיעורים: כל 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
+
+
+
+
+
+ + + + diff --git a/docs/tasks/prd-mathly.md b/docs/tasks/prd-mathly.md index f1ca1bb8a8254651b06bd9210c768beb56518140..f676792acef4590929c72ec8f87e2cb720125418 100644 --- a/docs/tasks/prd-mathly.md +++ b/docs/tasks/prd-mathly.md @@ -6,29 +6,43 @@ Mathly is a math practice app for middle- and high-school students and their tea Students often finish a topic without really mastering it, and then arrive at the school test unprepared: they never practiced mixing topics, never worked under time pressure, and don't know where their gaps are. -Mathly solves this with two tools: - -1. **The path** – a self-paced route through every skill, built on proven learning methods - (worked examples, gradual removal of help, immediate feedback, mastery over several days). -2. **The test countdown** – once the teacher sets a test, the app plans the student's last weeks before it: - finish the path, take two exercise tests, take one simulation test, and review what failed. - -Teachers give and check assignments, set tests, and see the class's progress per skill and per lesson. - -**The app is written from scratch.** Only two parts of the current app are kept (see 7.1): -the **exercise bank** and the **drawing board**. Everything else – screens, server, database, sign-in – is new. +This document describes the **whole app**, to be built from scratch. It is written so that a complete OpenSpec +specification can be derived from it, one capability per requirement group (see Appendix A). + +The app has five roles (see 4.1): + +- **Students** practice on **the path**, a self-paced route through every skill, drawn as a trail of stars + (Duolingo-like). Each skill opens an **exercise screen** with a **smart board** for working out solutions. + When the teacher sets a real test, **the test countdown** plans the student's last weeks before it: + finish the path, take two exercise tests, take one simulation test, and review what failed. + Students can also get help with a photographed problem and have handwritten answers checked, always through their teacher. +- **Teachers** give and check assignments, set tests, review the AI's checks of their students' work, and see the + progress of the classes they teach, per skill and per lesson. +- **Managers** create the classes: name, lessons, teacher and students. +- **Admins** give roles to accounts. +- **Developers** (the app's operators) have every permission and the developer tools. + +Everything described here that is not about **quizzes and tests** (4.9–4.13) has a working reference +implementation in the earlier app, called **mathly1** (the code in `app/` and `static/`). Requirements marked +*Reference* name the place to read its behavior. Only the **exercise bank** and the **smart board** are +reused as files (see 7.1); everything else is rebuilt. ### Glossary | Term | Hebrew | Meaning | |---|---|---| -| skill | מיומנות | A specific topic, e.g. פירוק טרינום | +| skill | מיומנות | A specific topic, e.g. פירוק טרינום. Shown on the path as a star | | exercise | תרגיל | A question on a certain topic. Can be either open-ended or multiple choice | -| lesson | שיעור | A set of skills, e.g. טכניקה אלגברית 1 | +| lesson | שיעור | A set of skills, e.g. טכניקה אלגברית 1. Shown on the path as a hub with its skills around it | +| class | כיתה | A named group of students with one teacher and the lessons it studies | | quiz | בוחן | A test on a single lesson. Can be retaken; best grade wins; each retake draws new questions. It is the only quiz type (no one-time summary quiz); its best grade is the lesson's grade | | exercise test | מבחן תרגול | A timed test on a set of lessons. Can be retaken; best grade wins | | simulation test | מבחן סימולציה | A timed test on a set of lessons. One time only | -| test | מבחן | The real-life test. Appears in the app as a date + the lessons it covers + number of questions and time limit (default 12 questions, 90 minutes). Set by the teacher | +| test | מבחן | The real-life test. Appears in the app as a date + the lessons it covers + number of questions and time limit (default 12 questions, 45 minutes). Set by the teacher | +| smart board | לוח | The drawing board on which a student or teacher writes and draws a solution | +| comet | שביט | A rare shooting star that crosses the screen during practice and can be caught for the collection | +| AI queue | תור ה־AI | The list of a class's student requests (a photographed problem, an answer to check) that wait for the teacher to send them to the AI or decline them | +| student / teacher / manager / admin / developer | תלמיד / מורה / מנהל כיתות / מנהל הרשאות / מפתח | The five roles (see 4.1) | ## 2. Goals @@ -36,188 +50,474 @@ the **exercise bank** and the **drawing board**. Everything else – screens, se 2. Help every student **get ready for the real test**: on the test day, the student has mastered the covered skills, practiced mixed and timed questions, and taken one full simulation. 3. Give the teacher a clear, per-student picture of **which skills and lessons** each student has covered. +4. Make practice something students come back to: a clear path, instant feedback, a daily goal, a streak and a collection. +5. Give students help and feedback on written work without students ever calling the AI themselves, and keep the AI's cost under the teacher's and the class's control. ## 3. User Stories **Student** -- As a student, I want to see a solved example and understand *why* each step is done, so I can solve the next one myself. -- As a student, I want the help to fade gradually, so I learn to solve alone without being thrown in at the deep end. -- As a student, when I get something wrong, I want to know *what* my mistake was and get a similar question, so I really learn it and don't just memorize the answer. +- As a student, I want to sign in with my Google account and land on my path, so I can start without setting anything up. +- As a student, I want to see all my lessons as a trail of stars, with the next skill marked, so I always know where to continue. - As a student, I want to open any lesson at any time, so I can follow what my class is learning. +- As a student, I want instant feedback on every answer, and when I'm wrong I want to know *what* my mistake was and get a different question, so I really learn it and don't just memorize the answer. +- As a student, I want a help button with the explanation and a solved example, so I can get unstuck. +- As a student, I want to solve on a smart board beside or over the question, so I can work out a full solution and hand it in. +- As a student, I want to photograph a problem I'm stuck on and get hints one at a time, so I can learn instead of just copying the answer. +- As a student, I want my handwritten answer checked, and to ask my teacher to look again if I disagree. - As a student, I want to see how many days are left until my test, how ready I am, and what to do today, so I don't have to plan by myself. - As a student, I want to practice with timed, mixed tests before the real test, so the real test doesn't surprise me. - As a student, I want one full simulation of the real test, so I know where I stand while there is still time to fix gaps. -- As a student, I want to solve on a drawing board when a question needs a full solution, and hand it in from there. +- As a student, I want to catch comets and fill my collection of stars and constellations, so practice feels like a game. **Teacher** -- As a teacher, I want to give an assignment from a file, from a photo, or by writing it on the drawing board, so I can use whatever material I already have. -- As a teacher, I want to check submitted assignments and give a grade and feedback. +- As a teacher, I want to sign in and see my classes and their students' progress, so I know where each student stands. +- As a teacher, I want to give an assignment from a file, from a photo, or by writing it on the smart board, so I can use whatever material I already have. +- As a teacher, I want one inbox of everything my students handed in that waits for me, so I don't miss anything. +- As a teacher, I want to review my students' AI requests and send the good ones, so students get help while I keep control and the cost stays low. +- As a teacher, I want to check submitted work and give a grade and feedback, and to see the AI's suggested grade first. +- As a teacher, I want to add and remove the students of my own class, so a new student can start without waiting for a manager. - As a teacher, I want to set a test date and the lessons it covers, so the app prepares my students for it. - As a teacher, I want to see who has taken the simulation test. - As a teacher, I want a heat map of skills per student, so I can see at a glance which skills the class struggles with. - As a teacher, I want to see how much of each lesson each student has covered. +**Manager** +- As a manager, I want to create a class with its lessons, its teacher and its students, so a new group can start practicing. +- As a manager, I want to edit or delete a class and set its daily AI budget, so I can keep rosters and costs right. + +**Admin** +- As an admin, I want to give an account a role, or take it away, so the right people can do their jobs. + +**Developer** +- As a developer, I want every permission, so I can help whoever cannot get in or do something. +- As a developer, I want to see what the AI costs, so the budget stays predictable. +- As a developer, I want my own tools (a text prompter and a lab), so I can prepare and test. + ## 4. Functional Requirements -### 4.1 Skill learning (the path) - -Each skill takes the student through four stages, in this order. - -1. **Worked example.** The system must show a fully solved example of the skill, one step at a time. - After each step, the system must ask the student "why this step?" (multiple choice) before revealing the next one. -2. **Faded examples.** The system must show solved examples with steps removed: first one step missing, then two, and so on. - The student must fill in each missing step. A wrong step gets immediate feedback (see requirement 4). -3. **Practice.** The system must give the student practice questions on the skill, taken from the exercise bank. -4. **Feedback on mistakes.** After a wrong answer, the system must: - - show feedback that names the specific mistake, using the mistake attached to the chosen wrong answer in the exercise bank - (its name and tip, e.g. "טעות סימן באיבר האמצעי"); - - not reveal the correct answer; - - give the student a **similar** question (same skill, a different question), not the same question again. -5. **Mastery.** A skill must become **mastered** when the student answers 3 questions correctly in a row, - on the first try, without opening help or the worked example, and these answers are spread over at least 2 different calendar days. -6. **Skill states.** Every skill, for every student, must be in one of these states: - - **not started** – no answers yet; - - **learning** – at least one answer, not yet mastered; - - **mastered** – met the rule in requirement 5. - A mastered skill stays mastered. It must **not** fade or decay over time. -7. **All lessons open.** The student must be able to open any lesson, and any skill inside it, at any time, in any order. -8. **Daily goal and streak.** 5 correct answers per day builds a streak. -9. **Collection.** The student must have a collection screen that shows what they achieved: each mastered skill and each completed lesson. - -### 4.2 Quizzes (בוחן) - -10. **Quiz per lesson.** Each lesson must have a quiz. The student can retake it; the best grade counts; every retake draws new questions. - The quiz's best grade is the lesson's grade. -11. **After a quiz,** the system must list the skills where the student lost points, so they can practice them before retaking. - -### 4.3 Test countdown - -12. **Setting a test.** The teacher must be able to set a test: date + the lessons it covers (+ an optional note), - plus the real test's **number of questions** and **time limit**. These start with defaults - (12 questions, 90 minutes) that the teacher can change. -13. **The countdown plan.** From the moment a test is set, the system must show the student a plan that depends on the days left: - - | Days before the test | What the app asks the student to do | - |---|---| - | until 9 | Finish the path for every covered lesson (bring every covered skill to "mastered") | - | ~9 | Exercise test 1 | - | ~7 | Exercise test 2 | - | ~5 | Simulation test (required) | - | 4 → 1 | Review the skills that failed in the simulation; light mixed review the day before | - - The day numbers are **recommendations**: the student can start each step earlier or later. - If the test is set less than 9 days ahead, the system must keep the same order and shorten the gaps evenly. -14. **Home screen reminder.** The home screen must show, for the nearest test: - days left, the readiness meter (see 4.6), and **one task for today** taken from the plan. - When several tests are coming up, "today's task" comes from the **closest** one. - -### 4.4 Exercise tests (מבחן תרגול) - -15. **Created by the app.** When the teacher sets a test, the system must create 2 exercise tests for every student in the class and place them on the student's countdown. -16. **Teacher can assign one.** The teacher must be able to send an exercise test to the whole class as an assignment. -17. **Retakes.** The student can start or retake an exercise test at any time. Each retake draws new questions; the best grade counts. -18. **Like the simulation.** Exercise tests must have the same number of questions and the same time limit as the simulation - (that is, as the real test, requirement 12), mix questions from all covered lessons, and not show the skill name. - Feedback comes **only at the end**, not after each question. -19. **Question mix.** The system must pick questions in these proportions: - - | Exercise test | Weak skills | Other covered skills | - |---|---|---| - | 1 | 60% | 40% | - | 2 | 30% | 70% | - - "Weak skill" = a skill in the "learning" state, or one the student answered wrong in a previous exercise test. - Skills in the "not started" state must not appear; instead, the card must list them as "practice these first". - If the student has fewer weak skills than needed, fill the rest from the other covered skills. -20. **Result links back.** After an exercise test, the system must show the weak skills it found and link each one to its place in the path. - -### 4.5 Simulation test (מבחן סימולציה) - -21. **Required, one attempt.** Every student must take one simulation test per real test. It can be taken only once. -22. **Like the real test.** The simulation must cover all the lessons of the real test, with the number of questions and the time limit the teacher set for the real test (requirement 12), - no skill names, and no feedback until the end. -23. **Window.** The simulation becomes available ~5 days before the test and stays available until the test day. - It must be shown as **required** on the student's home screen until it is taken. -24. **After the simulation,** the system must list the skills that failed and turn them into the review tasks of the last days (requirement 13). - -### 4.6 Readiness meter - -25. **Readiness meter.** For each upcoming test, the system must show the student (and the teacher) a readiness meter made of: - - % of the covered skills that are mastered; - - the best grade of each exercise test; - - the simulation test grade (once taken). - -### 4.7 Student screens - -26. **Home:** my assignments (המשימות שלי) from the teacher; the upcoming-test reminder (requirement 14); continue the path. -27. **Path:** all lessons and skills, each skill showing its state. -28. **Grades:** all quiz (best grade), exercise test, simulation and assignment grades. -29. **Collection:** see requirement 9. -30. **Drawing board.** Wherever a question needs a written solution (open questions, assignments), the student must be able to - solve on the drawing board and hand in the board as their answer. - -### 4.8 Teacher screens - -31. **Give an assignment.** The teacher must be able to create an assignment (title, note, due date) and load its content from: - - the computer (file upload: PDF or images); - - a photo taken with the device camera; - - the drawing board: the teacher writes or draws the assignment on the board, and it is saved as the assignment's page(s). -32. **Check assignments.** The teacher must be able to open each student's submission, give a grade (0–100) and a note, or send it back for correction. -33. **Tests tab.** The teacher must be able to set a test (requirement 12) and see, for each test, which students have taken the simulation test and which have not. -34. **Class heat map.** - - Rows: students. Columns: skills (grouped by lesson). - - Each cell is colored by the skill state: not started / learning / mastered. - - Tabs for the period: **Sep–Dec** and **Jan–Jun**. A period shows the skills of the lessons taught in it, and states as they were at the end of the period (or today, for the current period). -35. **Student lesson coverage.** - - Rows: students. Columns: lessons. - - Each cell shows the % of the lesson's skills the student has mastered, and the student's best quiz (בוחן) grade for that lesson. - - Same period tabs: **Sep–Dec** and **Jan–Jun**. +Requirements are grouped; each id (for example `ACC-3`) is stable and is what OpenSpec requirements refer to. + +### 4.1 Accounts, sign-in and roles (ACC) + +*Reference: `static/index.html` (`#boot`, the sign-in page), `static/math.js` `boot()`, `app/access.py`, `app/auth.py`.* + +- **ACC-1 Sign-in page.** Before sign-in the only screen is the sign-in page: the app's logo ("לומדים בכיף", the animated logo of mathly1) and mascot, one line of status text, + and one button "כניסה עם Google". The app must not show or serve any student content, class or progress before sign-in. +- **ACC-2 Google sign-in.** Everyone signs in with their Google account. The session stays on the device, + so the person does not sign in at every visit. Sign-out is available on every screen. +- **ACC-3 Roles.** There are five roles: **student**, **teacher**, **manager**, **admin**, **developer**. The server decides a signed-in email's roles on every request, never the device: + - developer: the email is in the app's developer list (a setting); + - teacher: the email is in the app's teacher list (a setting), or is named as a class's teacher, or was given the role (ADM-1); + - manager and admin: the role was given to the account (ADM-1); the app's settings can name the first admins; + - student: any other email. + One person may hold more than one role and then gets the screens of each. +- **ACC-4 Permissions.** + + | Role | Can | + |---|---| + | student | use the path and everything of their own: answers, grades, assignments, requests | + | teacher | see the progress, results, grades, assignments, tests and AI queue of the students of the classes they teach, and nobody else's; add and remove the students of those classes (TCH-9) | + | manager | create, edit and delete classes, set a class's AI budget, and see the list of classes and students. No learning data | + | admin | give and take away roles of accounts. No learning data | + | developer | everything, for every class and every account, plus the developer tools (4.20) | +- **ACC-5 Student in no class.** A signed-in student who is in no class sees a message that their account is not in a class and to ask their teacher or a manager to add them, with the email they signed in with, + and nothing else. When no class exists yet, the same message shows. +- **ACC-6 First sign-in.** The first time a student signs in, their account is linked to the entry the manager made for their email. +- **ACC-7 Failure messages.** When the sign-in service cannot be reached, the page says so and lets the person try again. + When a session has expired, the person is returned to the sign-in page with a short message. +- **ACC-8 Every request is checked.** The server checks the sign-in and the role on every request except the health check; a request without a valid sign-in, or outside the caller's permissions, is refused. +- **ACC-9 Role switcher.** A person with more than one role gets a chip for each role in the header, each opening that role's home; a developer gets all five; a person with one role sees no chips. + The last role chosen is remembered on the device. A link or a reload lands on the screen it points to, and switching role clears the address. + +### 4.2 Classes (CLS) + +*Reference: `static/math.js` `manageClasses`, `drawManagedClasses`, `openClassEditor`; `app/main.py` `/api/classes`.* + +- **CLS-1 Who manages classes.** Only a manager (and a developer) can create, edit and delete classes. They do it in the classes screen (MGR-1). + A class's teacher can also add and remove the students of that class, and nothing else about it (TCH-9). +- **CLS-2 A class** has: a **name** (1–80 characters, unique ignoring case), the **lessons** it studies (chosen from the exercise bank, at least one), + its **students** (email addresses), one **teacher** (an email address), an **AI switch** (off for a new class; see AI-10) and a **daily AI budget** (a number of AI checks a day, default 150, used only while the AI is on). +- **CLS-3 Adding students.** The manager (or the class's teacher) pastes email addresses, one per line (commas and spaces also separate them). Repeated addresses are ignored and + invalid ones are reported. A student may belong to more than one class. +- **CLS-4 The teacher.** A class has at most one teacher, given by email. A teacher is never also a student of the same class. A teacher may teach several classes. +- **CLS-5 Editing.** The manager can change a class's name, lessons, students, teacher and AI budget. Removing a student from a class does not delete that student's progress. +- **CLS-6 Deleting.** The manager can delete a class after confirming. Deleting a class does not delete its students' progress. +- **CLS-7 Class list.** The list shows, for each class, its name, lessons, number of students and their emails, and its teacher, with shortcuts to edit and delete. +- **CLS-8 Lessons in the path.** A student's path shows the lessons of their classes (all of them, when the student is in several classes). + Within those lessons everything is open (PTH-4). + +### 4.3 The exercise bank (BNK) + +- **BNK-1 Content.** The app's content is the exercise bank described in 7.1: lessons, skills, questions and mistakes. + Every question has exactly one correct choice; every wrong choice names a mistake; every mistake has a name and a tip. +- **BNK-2 Checked when the app starts.** The bank is checked when the server starts (unique ids, one correct choice per question, + every mistake and skill referred to exists). A broken bank stops the server from starting and says what is wrong. +- **BNK-3 Math and figures.** Math written as `$…$` in the bank is shown as formulas. Questions that have a figure (geometry) or a graph show it. +- **BNK-4 No answers on the device.** A practice question sent to the device carries no sign of which choice is correct. + The server grades. +- **BNK-6 Ten practice questions.** Practice on the exercise screen uses 10 questions per skill: the first 10 of the skill's questions in the bank (five skills have 30). The other questions stay in the bank and are still drawn by quizzes, exercise tests and the simulation. +- **BNK-5 Bank content tools.** A tool lists what the bank still lacks (see 7.3). + +### 4.4 The path (PTH) + +*Reference: `static/math.js` `pathView`, `orbitRing`, `status`/`next`; `static/math-sky.js` (the owl, the spark/star); the `.mx-trail` / `.mx-star` styles in `static/math.css`.* + +The path is the student's main screen: a trail of stars. + +- **PTH-1 Layout.** Every lesson is a **hub** that shows its name and "mastered of total". The lesson's skills sit around the hub in a **ring**, + in order, numbered from the top and clockwise. The hubs are joined by a vertical **trail** from a start marker (with the mascot) to an end marker. + After a lesson's ring comes its **quiz** (4.9) as a node on the trail. +- **PTH-2 Stars and states.** Each skill is a star showing its state: **not started**, **learning** or **mastered** (4.7). + A mastered skill looks clearly different from the other two. The state is also shown with a symbol and a word under the star + ("○ לא התחלת", "◐ בלמידה", "✓ נשלטה"), never by color alone. A mastered star that has faded (MST-8) shows its dimmed look and the word "דועך" as well. +- **PTH-3 Next skill.** One skill is marked as the suggested next, with the mascot perched on its star: the unmastered skill the student answered most recently, + or else the first unmastered skill in the bank's order. When everything is mastered nothing is marked. The marker is a suggestion: it never locks, hides or reorders anything. +- **PTH-4 All open.** The student can open any lesson, and any skill inside it, at any time, in any order. Nothing is ever locked. +- **PTH-5 Opening a skill.** Tapping a star opens that skill's exercise screen (4.5) over the path. Closing it returns to the path with the star updated. + When the path opens, it scrolls to the next skill. +- **PTH-6 Top of the path.** The path shows today's progress toward the daily goal and the current streak (MST-6). +- **PTH-7 Accessibility.** Each star is a control whose accessible name is its number, the skill's name and its state in words. It can be reached and opened from the keyboard. + Animations stop when the device asks for reduced motion. The path is dark, like the rest of the app. +- **PTH-9 Choosing a subject.** After sign-in a student first sees the subjects of their classes as cards (as in mathly1), each with an icon, the subject's name + and a bar "N מתוך M מיומנויות" (skills mastered of all skills in the student's lessons). Today the only subject is math (מתמטיקה), so there is one card. + Tapping a card opens that subject's home (STU-1, as in mathly1), and the tab bar leads from there to the path, the grades and the collection; the subject's screens have a way back to the subjects. A reload or a link to a skill (`#/skill/…`) opens its path directly. +- **PTH-8 Phone first.** The path fits a 360px-wide screen without sideways scrolling, including the lesson with the most skills. + +### 4.5 The exercise screen (EXR) + +*Reference: `static/math.js` `open()` and `answer()` (the skill sheet), `choiceButtons`, `figures`, `autoAdvance`.* + +The exercise screen is where a student practices one skill. + +- **EXR-1 Layout.** It opens as a sheet over the path. The header shows the lesson's name, the skill's name, a completed mark when the skill is mastered, + a button for the smart board (4.6), a help button "?" and a close button. Under the header is the skill's short explanation. +- **EXR-2 The question.** The sheet shows one question at a time: its text with formulas, its figure or graph if it has one, and its choices. + The choices appear in a new random order each time the question is shown. A line "question n of N" and a row of N dots show how far the student is in the round of the skill's practice questions (BNK-6: at most 10): a dot is filled for a right answer, marked for a wrong one, and empty for a question not answered yet. +- **EXR-3 Answering.** The student taps a choice. The server grades it and the sheet answers at once. While the server is checking, the tapped choice shows a spinner, a line says "בודקים…" and the other choices are dimmed and cannot be tapped; with reduced motion the words stay and the spinner is still. +- **EXR-4 A right answer.** A right answer gets a short celebration (an animation; sound and vibration where the device allows) and the count of right answers in a row. + After a short countdown the next question appears; the student can skip the countdown or cancel it. +- **EXR-5 A wrong answer.** A wrong answer is quiet. The feedback names the specific mistake attached to the chosen choice in the bank (its name and its tip, + for example "טעות סימן באיבר האמצעי"), talks about the mistake and not about the student, and does **not** reveal the correct answer. The chosen choice is marked on the choice itself with a symbol and a word ("✗ לא נכון"), not by colour alone; no other choice is marked. + When the mistake names a skill to go back to, the feedback links to it. The next question is a **different** question on the same skill (a skill with one question repeats it). +- **EXR-6 Which question comes next.** Practice on a skill is a **round**: the skill's practice questions (at most 10), each shown once in a random order (EXR-12). The next question is one of the round that was not answered yet; a wrong question does not come back in the round. +- **EXR-7 Help.** The help button shows the skill's explanation and, where the bank has one, a solved example. Opening help before answering means that answer **does not count** + toward mastery (it neither counts nor breaks the run; see MST-3). It still counts toward the daily goal. + Help is a ladder: the "?" gives instant help (explanation and solved example); if that is not enough, its last line offers "עדיין תקועים? צלמו" and opens photo help (STU-6) when the class has the AI on. +- **EXR-8 Related skills.** The sheet shows the skills this one requires and the skills it opens, as tappable chips. They are links, not locks. +- **EXR-9 Resuming.** Reopening a skill continues with the question that was on screen. +- **EXR-10 Skills without questions.** A skill with no questions says there is no practice for it yet, and cannot be mastered. +- **EXR-11 Comets.** Comets can cross the exercise screen (CMT-1). +- **EXR-12 Rounds.** After the last answer of a round (EXR-6) the sheet shows the result "N מתוך 10" and, for each wrong answer, the question, the mistake's name and tip and a link to the skill to go back to (never the correct answers). It offers "סבב חדש" (all the questions again in a new order) and a way back to the path. The server remembers the round: leaving and coming back continues it, and a finished round shows its result until a new one starts. Mastery (MST-2) is counted across rounds. + +### 4.6 The smart board (BRD) + +*Reference (kept as files): `static/math-board.js`, `static/board-math.js`, `static/vendor/mathlive/`. It exposes `window.MathlyBoard`.* + +- **BRD-1 Where it is available.** On the exercise screen, in quizzes and tests, in assignments the student hands in, and where the teacher writes an assignment. + A button in the sheet's header opens it. +- **BRD-2 Placement.** On a desktop screen the board sits **beside** the exercise; the device remembers whether it is on. + On a phone or tablet it opens **full screen** over the exercise from the same button, and closes back to the question. +- **BRD-3 Tools.** Move; **pen** (three ink colors; follows pen pressure); straight **line**; **circle** (dragged from its center); + **angle** (pointing at a corner where two lines meet shows the arc; a click adds it and asks for its words; a number gets a degree sign; + one, two or three arcs or a right-angle square); typed **math** (a math keyboard set up for ninth grade: digits, x and y, fractions, powers, roots, brackets, absolute value, + ± ≤ ≥ ≠, π, degrees, angle and triangle signs, and a letters tab); **eraser** (three sizes); **undo**; and **clear**. +- **BRD-4 Everything is an object.** Every pen stroke, line, circle, angle and formula on the board can be selected, moved and erased. +- **BRD-5 Snapping.** Line ends and circle centers snap to ends and centers already drawn, so a triangle closes neatly; lines that meet that way move together. + The eraser removes the lines and circles it touches and cuts pen strokes. +- **BRD-6 The question on the board.** A copy of the question (its text and figures) can be placed on the board. The eraser leaves it alone; select it and delete it instead. +- **BRD-7 Endless paper.** The paper grows downward and to the right. The mouse wheel scrolls it (sideways with Shift or a trackpad); two fingers scroll in any direction while one finger draws; + dragging empty paper with the move tool scrolls too. +- **BRD-8 Pen and palm.** Once a pen has touched the screen, a single finger is ignored. While the pen writes (and a moment after) every touch is ignored, and a wide contact is treated as a palm. +- **BRD-9 Sketches stay local.** Each question keeps its own sketch as long as the page is open. Nothing is sent anywhere unless the student hands it in. +- **BRD-10 Handing in.** Where a question needs a written solution (assignments), the sketch becomes a picture that the student hands in from the board (see ANS-1). +- **BRD-11 Calculator.** A scientific calculator (the layout of a Casio fx-991ES PLUS, with SHIFT functions) opens on a panel over a corner of the paper from a toolbar button. + It is available everywhere the board is, including quizzes, exercise tests and the simulation. +- **BRD-12 Labels.** Every tool has a Hebrew label and a line icon; the board works with touch, pen and mouse. + +### 4.7 Skill states, mastery, daily goal and collection (MST) + +*Reference for fading and the collection: `static/math-sky.js`.* + +- **MST-1 Skill states.** Every skill, for every student, is in exactly one state: **not started** (no answers yet), **learning** (at least one answer, not yet mastered) + or **mastered** (met MST-2). +- **MST-2 Mastery.** A skill becomes **mastered** when the student answers 3 questions on it correctly in a row, each on the first try and without opening help, + and these answers fall on at least 2 different calendar days. +- **MST-3 Help does not break the run.** An answer given after opening help is skipped for mastery: it neither counts toward the 3 nor breaks the run. + A wrong answer restarts the run. +- **MST-4 Mastery does not decay.** A mastered skill stays mastered. It does not need re-mastering over time, even after later wrong answers. + The readiness meter, the exercise tests, the heat map and the coverage view all use this state. +- **MST-5 The server decides.** The server stores the date of every answer (the calendar day in Israel, decided by the server, never by the device) and decides mastery from it. +- **MST-6 Daily goal and streak.** 5 correct answers in a day make a streak day. The path shows today's count and the number of days in a row. + A streak is kept through the morning of a new day and counted up to yesterday until the new day's 5 are reached. +- **MST-7 Collection.** A collection screen shows what the student achieved: each mastered skill as a star, each completed lesson (all of its skills mastered) + as a constellation drawn from its stars, and the comets caught (CMT-3). +- **MST-8 Fading stars.** A mastered skill the student has not answered for 14 days has a **faded** star: it dims and says "דועך". One answer on the skill (correct or not) relights it. + Fading is only a review cue: the skill is still mastered (MST-4), so the readiness meter, heat map and exercise tests are unchanged. + +### 4.8 Comets (CMT) + +*Reference: `static/math-sky.js` (`COMETS`, `cometDue`, `catchComet`).* + +- **CMT-1 A comet crosses.** After a right answer on the exercise screen a comet may cross the screen for a few seconds. At most one comet comes in a day. + The first comet comes surely the first time the student reaches the daily goal (MST-6), which can happen in the first session, so the reward arrives early; + after that each right answer has a small chance (about 12%) while there are comets left to catch. +- **CMT-2 Catching.** Tapping the comet while it crosses catches it. A caught comet is one the student does not yet have, picked at random. The catch shows the comet's name and a short fact. + Comets stop when the student has all of them. Comets never change a skill's state, a grade or the streak. +- **CMT-3 The comets.** There are twelve: π, Fibonacci, the golden ratio, infinity, e, √2, zero, Pythagoras, primes, Pascal's triangle, Euler's formula and the Möbius strip. + Each has a symbol, a name and a fact in Hebrew. The collection shows each caught comet with its fact, and each missing one as "?" with "עוד לא נתפס". +- **CMT-4 Reduced motion.** With reduced motion, a comet does not cross; the student is offered it once as a tappable item. + +### 4.9 Quizzes (בוחן) (QZ) + +- **QZ-1 Quiz per lesson.** Every lesson has one quiz: the lesson's "boss level", a node on the trail after the lesson's ring. It is always open (PTH-4). The student can retake it at any time; + the best grade counts, and the quiz's best grade is the lesson's grade. +- **QZ-2 Format.** A quiz is **10 multiple-choice questions** drawn from the bank questions of the lesson's skills, at least one per skill and the rest spread evenly across the skills, in **15 minutes**. + The timer runs on the server; when it ends the quiz is submitted as it stands and unanswered questions count as wrong. Skill names are not shown and there is no feedback until the end. + The smart board and the calculator are available. +- **QZ-3 Retakes draw new questions.** Each retake prefers questions the student has not had in earlier attempts at this lesson's quiz, the least-used first. The bank has at least 10 questions per skill, so this is always possible. +- **QZ-4 After a quiz.** The student sees the grade, the skills where points were lost (each linked to its star, so they can practice before retaking) and, for each missed question, the name and tip of the mistake they made (as in EXR-5). + The correct answers are never shown, so a retake tests understanding and not memory. +- **QZ-5 Grades on the server.** Quiz grades and timers are computed and stored on the server. +- **QZ-6 Written quizzes.** The four written quizzes authored in the bank (four written questions, 100 points, 45 minutes) are not lesson quizzes. A teacher can give one to a class as an assignment (TCH-2). + +### 4.10 Test countdown (TST) + +- **TST-1 Setting a test.** The teacher sets a test: date + the lessons it covers (+ an optional note), plus the real test's **number of questions** and **time limit**. + These start with defaults (12 questions, 45 minutes) that the teacher can change. +- **TST-2 The countdown plan.** From the moment a test is set, the system shows the student a plan that depends on the days left: + + | Days before the test | What the app asks the student to do | + |---|---| + | until 9 | Finish the path for every covered lesson (bring every covered skill to "mastered") | + | ~9 | Exercise test 1 | + | ~7 | Exercise test 2 | + | ~5 | Simulation test (required) | + | 4 → 1 | Review the skills that failed in the simulation; light mixed review the day before | + + The day numbers are **recommendations**: the student can start each step earlier or later. + If the test is set less than 9 days ahead, the system keeps the same order and shortens the gaps evenly. +- **TST-3 Home screen reminder.** The home screen shows, for the nearest test: days left, the readiness meter (RDY-1), and **one task for today** taken from the plan. + When several tests are coming up, "today's task" comes from the **closest** one. + +### 4.11 Exercise tests (מבחן תרגול) (EXT) + +- **EXT-1 Created by the app.** When the teacher sets a test, the system creates 2 exercise tests for every student in the class and places them on the student's countdown. +- **EXT-2 Teacher can assign one.** The teacher can send an exercise test to the whole class as an assignment (built with the assignments, stage 6): it shows in "המשימות שלי", opens the exercise test and counts as done when the student has taken it; it is not handed in as a picture. +- **EXT-3 Retakes.** The student can start or retake an exercise test at any time. Each retake draws new questions; the best grade counts. +- **EXT-4 Like the simulation.** Exercise tests have the same number of questions and the same time limit as the simulation (that is, as the real test, TST-1), + mix questions from all covered lessons, and do not show the skill name. Feedback comes **only at the end**, not after each question. +- **EXT-5 Question mix.** The system picks questions in these proportions: + + | Exercise test | Weak skills | Other covered skills | + |---|---|---| + | 1 | 60% | 40% | + | 2 | 30% | 70% | + + "Weak skill" = a skill in the "learning" state, or one the student answered wrong in a previous exercise test. + Skills in the "not started" state do not appear; instead, the card lists them as "practice these first". + If the student has fewer weak skills than needed, the rest comes from the other covered skills. +- **EXT-6 Result links back.** After an exercise test, the system shows the weak skills it found and links each one to its star on the path. +- **EXT-7 Grades on the server.** Exercise test grades and the timer are computed and kept on the server. + +### 4.12 Simulation test (מבחן סימולציה) (SIM) + +- **SIM-1 Required, one attempt.** Every student takes one simulation test per real test. It can be taken only once. +- **SIM-2 Like the real test.** The simulation covers all the lessons of the real test, with the number of questions and the time limit the teacher set for it (TST-1), + no skill names, and no feedback until the end. +- **SIM-3 Window.** The simulation becomes available ~5 days before the test and stays available until the test day. + It is shown as **required** on the student's home screen until it is taken. +- **SIM-4 Server timer.** The timer is kept on the server, so refreshing or closing the app does not reset it. The grade is stored on the server. +- **SIM-5 After the simulation,** the system lists the skills that failed and turns them into the review tasks of the last days (TST-2). + +### 4.13 Grades and readiness meter (GRD, RDY) + +- **GRD-1 One scale.** Every grade (quiz, exercise test, simulation, assignment) is a whole number from 0 to 100. In a multiple-choice quiz or test every question is worth the same, and the grade is the share of right answers, rounded. + Teachers' grades for assignments are on the same scale. +- **GRD-2 When time ends.** When a timer ends (quiz, exercise test, simulation) the attempt is submitted as it stands, and unanswered questions count as wrong. + Leaving the screen does not stop the timer. +- **RDY-1 Readiness meter.** For each upcoming test, the system shows the student (and the teacher) one **readiness number from 0 to 100**, drawn as a level bar, with its three parts under it: + - **M**: the % of the covered skills that are mastered; + - **E**: the average of the best grade of each exercise test taken; + - **S**: the simulation test grade (once taken). +- **RDY-2 How the number is made.** It is the weighted average of the parts that exist, with weights M 50, E 20, S 30; a part that does not exist yet (no exercise test taken, no simulation) is left out and the others are scaled up. +- **RDY-3 No false confidence.** Until the simulation is taken the number is capped at 80, and the bar says so. The bar's label by number is: 0–39 "מתחילים", 40–69 "בדרך", 70–84 "כמעט שם", 85–100 "מוכנים". "מוכנים" can only show after the simulation. + +### 4.14 Handwritten answers and phone photos (ANS, PSH) + +*Reference: `static/answer-scans.js`, `app/answer_scans.py`, `app/answer_routes.py`, `app/answer_cleanup.py`, `app/push.py`, `static/service-worker.js`.* + +- **ANS-1 Handing in a written answer.** A written answer is handed in as a picture: from the smart board (BRD-10), or by photographing the paper. On a phone the camera opens; + on a computer the student uploads an image or asks their own phone to take the photo (ANS-2). +- **ANS-2 Photo request to the phone.** The computer creates a photo request for one answer. The student's phone, signed in to the same account, shows the request's window with a **4-digit code** + that the student matches against the computer; the student photographs the answer there. The computer shows the request's state: waiting for the phone, uploading, received, failed, expired or replaced by a newer request. + A request expires after a while and a newer request for the same answer replaces an older one. +- **ANS-3 Where the pictures live.** Answer pictures are kept in private storage tied to the account and are read only by the server. The server removes, every hour, pictures no answer refers to. + Pictures are kept until the end of the school year (31 August) and then removed; the grade and the teacher's comment stay. A teacher of the class, a manager or a developer can delete a student's pictures earlier on request. +- **PSH-1 Notification to the phone.** A phone can turn notifications on. When the computer asks for a photo of an answer, the phone is notified even if the app is closed; tapping the notification opens the app on the request's window. +- **PSH-2 Which devices.** Only phones subscribe; the computer that made the request gets no notification. A subscription the push service no longer knows is deleted. On an iPhone, notifications work only from the app added to the home screen (iOS 16.4 or later). + The server's push key is a setting; changing it drops every subscription, and each phone turns notifications on again. + +### 4.15 The AI (AI) + +*Reference: `app/math_photo.py`, `app/answer_grading.py`, `app/ai_queue.py`, `app/ai_batches.py`, `app/teacher_ai.py`, `app/ai_usage.py`, `app/teacher_review.py`, `app/homework_grading.py`.* + +- **AI-1 Students never call the AI.** A student's request (a photographed problem, or an answer to check) becomes a request in the AI queue of the class's teacher. The teacher looks at the picture and either sends it to the AI or declines it + with an optional note. The student's page shows the request waiting (it looks for the answer every few seconds while it is open), and then its result or the teacher's note. The student can cancel a waiting request. + A student has at most 5 requests waiting at once and at most 20 photos a day. + A student in more than one class chooses which teacher a request goes to, defaulting to the teacher of the class with the nearest upcoming test and then to the one used last. The request counts against that class's budget. +- **AI-2 Who sends straight.** A teacher or a developer sends without the queue when the request is their own. Everyone else's requests wait in the queue; a teacher sees the queue of their classes' students and a developer sees every queue. +- **AI-3 Photographed-problem help.** The student photographs a problem. The AI reads it and solves it, and answers in a fixed shape: the problem as it read it (so the student can check the reading), the solution as steps, each with a **hint** that does not give the step away and the step itself, + the final answer, and the skill on the path that the problem practises (linked to its star). The page shows the hints one by one, and the steps and the answer only when the student asks for them. The photo is sent to the AI and is not kept. +- **AI-4 Checking handwritten answers.** The AI checks a saved handwritten answer against the question as it was when the student answered it (a stored copy, so later changes to the bank do not change an old grade), and returns a score and a comment. + This is a **suggestion** to the teacher. Where an answer's score is used, the teacher's score wins over the AI's. The AI's check is never edited: the teacher's review is kept next to it, the latest review counts, and older ones stay as history. +- **AI-5 Asking the teacher to look again.** A student who disagrees with a check asks the teacher to look again; there is at most one open request per answer and five per student. Saving a review closes the request. +- **AI-6 Budgets.** Each class has a daily number of AI checks of its students' work (CLS-2), counted by the Israel date and taken in one step in the database, so two batches at once never pass it. A check that fails, or whose picture the AI could not read, is given back. + A teacher also has a personal allowance of 3 AI requests a day for their own use (a problem they photograph, an answer of their own they check, or a student's request they send). Developers have no limit. Students are not counted. +- **AI-7 Batches.** A teacher can send every pending check of one scope in a single action, oldest first: one assignment's submissions, or the single answers waiting. When the budget is short it sends what is left and the rest stays pending for the next day. +- **AI-8 When the AI fails.** The people who can fix it (the teacher who sent it, a developer) see what happened and what to do for each cause: missing key, invalid key, no permission, model not found, no credit, rate limit, overloaded, no connection, refused, cut short, or an unusable answer, with the technical detail. + The student sees a short "try again later". +- **AI-9 Usage and cost.** Every AI call records its tokens and an estimated cost. Developers can see the totals (DEV-4). +- **AI-10 Privacy.** The AI is **off for a class** until a manager switches it on for that class, which the school does only after it has confirmed that families agree to an outside AI looking at their children's work. + A student of a class with the AI off sees no AI buttons. Nothing that names a student (name or email) is sent to the AI: only the picture and the question. Before a first photo the student sees a reminder not to write their name or personal details in it. + +### 4.16 Student screens (STU) + +A tab bar at the bottom of the screen leads between them. + +- **STU-1 Home:** my assignments (המשימות שלי) from the teacher; the upcoming-test reminder (TST-3); a button that continues the path at the next skill; my AI requests and their state (AI-1). +- **STU-2 Path:** see 4.4. +- **STU-3 Grades:** all quiz (best grade), exercise test, simulation and assignment grades. +- **STU-4 Collection:** see MST-7. +- **STU-5 Assignments.** The student opens an assignment, works on it (on the smart board, or by photographing paper; ANS-1) and hands it in; they see the teacher's grade and note, or that it was sent back for correction. +- **STU-6 Photo help.** A camera button lets the student photograph a problem (AI-3). Pressing it opens the device's camera or gallery. The picture is shrunk on the device and its metadata is dropped before it is sent + (JPEG, PNG or WebP). A sheet then shows the student's picture and the request's state, and the hints once the teacher has sent it. + The button appears in two places, and only for students of a class with the AI on (AI-10): + - on the **exercise screen**, in the header beside the "?" help; a request made there also tells the teacher which skill the student was on; + - on the **home screen**, as a card "תקועים על תרגיל? צלמו אותו" that also shows the student's open requests and their state. + It is not on the path, which stays a clean trail. The sheet says plainly that the teacher sees the picture first, so the student knows the answer is not instant. + *mathly1 has no visible entry for this today (checked in a local run with sign-in off); this is new UI.* + +### 4.17 Teacher screens (TCH) + +- **TCH-1 Teacher home.** A teacher's home lists the classes they teach, each with its students and a shortcut to its progress. A teacher does not see the student path as their main screen. A teacher who teaches no class is told that a manager chooses who teaches each class. +- **TCH-2 Give an assignment.** The teacher creates an assignment (title, note, due date) and loads its content from: + - the computer (file upload: PDF or images); + - a photo taken with the device camera; + - the smart board: the teacher writes or draws the assignment, and it is saved as the assignment's page(s); + - one of the written quizzes authored in the bank (QZ-6). +- **TCH-3 Choosing who gets it.** An assignment goes to the whole class (or one class of those the teacher teaches). +- **TCH-4 Inbox and checking.** One inbox lists everything the teacher's students handed in that waits for them, oldest first: assignment submissions not checked yet (a returned one waits for the student) + and open requests to look again (AI-5). The teacher opens each, sees the AI's suggested score and comment (AI-4) if there is one, gives a grade (0–100) and a note, or sends it back for correction. +- **TCH-5 AI queue.** The teacher sees their classes' AI requests (AI-1), with the picture, and sends or declines each, or sends a whole batch (AI-7). +- **TCH-6 Tests tab.** The teacher sets a test (TST-1) and sees, for each test, which students have taken the simulation test and which have not. +- **TCH-7 Class heat map.** + - Rows: students. Columns: skills (grouped by lesson). + - Each cell shows the skill state: not started / learning / mastered, by color **and** by a symbol or word. + - Tabs for the period: **Sep–Dec** and **Jan–Jun**. A period shows the skills of the lessons taught in it, and states as they were at the end of the period (or today, for the current period). +- **TCH-8 Student lesson coverage.** + - Rows: students. Columns: lessons. + - Each cell shows the % of the lesson's skills the student has mastered, and the student's best quiz (בוחן) grade for that lesson. + - Same period tabs. +- **TCH-9 Roster of my class.** For each class they teach, the teacher can paste email addresses to add students and can remove a student (CLS-3, CLS-5). They cannot change the class's name, lessons, teacher or AI budget, + and a teacher cannot add themselves as a student. Removing a student does not delete their progress. + +### 4.18 Manager screens (MGR) + +- **MGR-1 Classes.** The manager's home lists all classes (CLS-7) with a button for a new class, and an editor for creating and changing a class (CLS-2 – CLS-6). When a save is refused (for example the teacher is also one of the students), the editor says why right above the save button, in view, and keeps what was typed. +- **MGR-2 Students.** A list of all students with the classes each belongs to. + +### 4.19 Admin screens (ADM) + +- **ADM-1 Roles.** An admin sees the accounts the app knows (students from classes, teachers, managers, admins) and can give an account the role student, teacher, manager or admin, or take it away. The developer role is never given here; it comes only from the app's settings. + Roles belong to an **email address**, so an admin can type an email that has never signed in and give it a role; the role takes effect at that person's first sign-in. + The last admin cannot take away their own admin role. A role change shows within 30 seconds. +- **ADM-2 Own access.** A page shows the signed-in account's own roles and permissions. + +### 4.20 Developer tools (DEV) + +*Reference: `app/prompter.py`, `static/prompter.js`, and the management sheet in `static/math.js`.* + +- **DEV-1 Every permission.** A developer can open any class's progress, heat map, coverage, tests, assignments, inbox and AI queue, as the class's teacher can, and everything managers and admins can do. +- **DEV-2 Prompter (פרומפטר).** A developer writes or pastes a text and shows it full screen as a scrolling teleprompter. Saved texts (a title up to 120 characters; up to 200 texts) belong to the account and are on every device; what is being edited is also kept in the browser, so nothing is lost before it is saved. + Keys: space starts and stops, ↑/↓ change speed, +/− change size, M mirrors, F is full screen, Esc leaves; the mouse and a presentation remote work too. + A saved text can have an **outline (ראשי פרקים)**: on request the AI rewrites the text as the same slides with two to four very short topic reminders each, once; it is kept with the text and can be edited. Changing the text without sending an outline drops the outline, so a stale one is never shown. +- **DEV-3 Lab (מעבדה).** A developers-only area for testing and development tools. In mathly1 it is an empty page that says tools will be added; the same here, until the first tool is chosen. +- **DEV-4 AI usage.** A page shows the AI's calls and estimated cost (AI-9): by day, by class and by kind of call. ## 5. Non-Goals (Out of Scope) -- Reusing any part of the current app other than the exercise bank and the drawing board. -- Skills do not decay or need re-mastering over time. -- Lessons are never locked; the app does not force an order. -- There is no one-time summary quiz (בוחן מסכם). -- The app does not grade the real school test or import its grades. -- The app does not replace the teacher's lesson plan or teach new material in class. -- No student-to-student features (chat, leaderboards). +- Subjects other than math (the subject cards are built for them, but only math has content). +- Locked lessons or a forced order of lessons. +- Mastery that really decays: a faded star is only a cue (MST-8). +- Worked-example and faded-example stages before practice (the help button's explanation and solved example replace them). +- A one-time summary quiz (בוחן מסכם). +- Grading the real school test or importing its grades; a calendar of school tests (the teacher's test, TST-1, replaces it). +- Spaced-review cards, misconception-pattern cards, a teacher's preview of the student screens, monitoring dashboards, and a video library. +- Student-to-student features (chat, leaderboards). +- Students calling the AI directly. ## 6. Design Considerations -- Hebrew, right-to-left. Works on phones first; the teacher views (heat map, coverage) must also work well on a computer. -- Math is written in LaTeX inside `$…$` in the exercise bank; the app must render it. +- Hebrew, right-to-left. Works on phones first; the teacher, manager, admin and developer views (heat map, coverage, classes, roles) must also work well on a computer. +- The look follows the path's "sky" theme: a dark-blue night with aurora and starlight accents, gold for mastery, and an owl mascot that perches on the next skill. The app is always dark, as mathly1 is: the page background is a dark night with two soft glows and small fixed stars; it does not move. There is no light mode. +- Math is written in `$…$` text in the exercise bank; the app must render it as formulas. +- State and result never rely on color alone: every state has a symbol or a word (stars, heat map cells, feedback). - Mastered skills must look clearly different from "learning" and "not started" ones. -- Heat map colors must be readable in light and dark mode and must not rely on color alone (add a symbol or text in each cell). -- The "one task for today" on home must be a single, obvious button. +- Touch targets are at least 44px. Animations (stars, celebrations, comets) respect the device's reduced-motion setting. +- The "one task for today" on home is a single, obvious button. +- The smart board works with touch, pen and mouse, and keeps working when the device rotates. ## 7. Technical Considerations -### 7.1 What is kept from the current app +### 7.1 What is kept as files **Exercise bank** – `app/math_algebra9.json` (9th grade algebra/geometry): -- `units`: 24 lessons (id, name, month, and for 4 of them a `quiz` with open questions, points, minutes and the skills each question tests). +- `units`: 24 lessons (id, name, month, and for 4 of them a written `quiz` of four questions with points, 45 minutes and the skills each question tests; used as assignable material, QZ-6). - `skills`: 96 skills (id, lesson, name, short name, description, prerequisites, month, `questions`). -- `questions`: 1,050 multiple-choice questions. Each wrong choice has a `mistake` id. -- `mistakes`: 244 mistakes, each with a name, a tip, and the skill to go back to (`back`). +- `questions`: 1,050 multiple-choice questions, 410 with a geometry figure and 53 with a graph. Each wrong choice has a `mistake` id. One skill (`a_30_side`) has no multiple-choice question, only an open-ended `sample` question. +- `mistakes`: 244 mistakes, each with a name and a tip; 40 also name a skill to go back to (`back`). -**Drawing board** – `static/math-board.js` (the board), `static/board-math.js` (typed math on the board) and +**Smart board** – `static/math-board.js` (the board), `static/board-math.js` (typed math on the board) and `static/vendor/mathlive/` (the math keyboard library, MIT license, loaded by board-math.js). It exposes `window.MathlyBoard` and turns a sketch into a picture for handing in. -### 7.2 Notes for the new build - -- **Content gaps in the bank.** The new app needs content the bank does not have yet: - - worked examples and faded examples (requirements 1–2): no skill has one today; - - "why this step?" choices for each step of a worked example; - - quizzes for 20 of the 24 lessons (requirement 10); - - one skill has no questions; - - enough questions per skill for "similar question" (requirement 4) and for retakes that draw new questions. - `scripts/draft_examples.py` from the current app drafts worked examples with AI for a teacher to approve; it may be reused as a tool. -- Grades that matter (quiz, exercise test, simulation) must be computed and stored on the server, so a student cannot change them from the device. -- Mastery (requirement 5) needs the date of each answer, so the server can check the "2 different days" rule. -- The simulation's timer must be kept on the server, so refreshing or closing the app does not reset it. -- Open questions in quizzes and assignments need checking: by the teacher (requirement 32), possibly with AI help (see Open Questions). +### 7.2 Behavior to port from mathly1 + +Rebuilt, not copied as a whole; read the places named in each requirement group. The notes in this document come from reading mathly1's code; the one claim also checked by running it (locally, sign-in off) is that mathly1 has no visible photo-help entry. + +| Area | Where in mathly1 | +|---|---| +| Sign-in page and session | `static/index.html`, `static/math.js` `boot()` | +| Roles and permissions | `app/access.py`, `app/auth.py` | +| Classes | `static/math.js` `manageClasses`…, `app/main.py` `/api/classes` | +| The path, stars, fading, comets | `static/math.js` `pathView`, `orbitRing`; `static/math-sky.js`; `static/math.css` | +| Exercise screen | `static/math.js` `open`, `answer`, `choiceButtons`, `figures` (geometry figures and graphs) | +| Handwritten answers and phone photos | `static/answer-scans.js`, `app/answer_scans.py`, `app/answer_routes.py`, `app/push.py`, `static/service-worker.js` | +| The AI | `app/math_photo.py`, `app/answer_grading.py`, `app/ai_queue.py`, `app/ai_batches.py`, `app/teacher_ai.py`, `app/ai_usage.py`, `app/teacher_review.py`, `app/teacher_inbox.py` | +| Prompter | `app/prompter.py`, `static/prompter.js` | + +### 7.3 Notes for the build + +- **Stack and hosting.** FastAPI (Python), Supabase (sign-in and storage), plain JavaScript modules in the browser, one Docker container run as a **Hugging Face Space**, replacing mathly1's. + Settings come from, in order, real environment variables, the app's own `.env` if it has one, and the repository's `.env` (the one mathly1 uses, with the same keys); earlier sources win. With Supabase unset, local development uses an in-memory store and a "dev only" email sign-in, and a half-configured server refuses to start. + The app page and its styles and scripts are sent with `Cache-Control: no-cache`, so after an update every device gets the new version without clearing its cache (an unchanged file is still answered from the cache). The page declares mathly1's icon (`static/icons/`), shown in the browser tab. + The server reads the same fact once per request, makes independent database reads at the same time, and reuses its connections: a student's screen waits for the database at most 3 times in a row and a practice answer at most 4 (each call to a remote database costs about 0.4 seconds). + Further settings: the AI key and model (`ANTHROPIC_API_KEY`, `MATH_MODEL`), the push keys (`VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`), the private bucket for answer pictures, and the teacher and developer email lists. +- **Server decides.** Correctness of answers, the date of each answer, mastery, grades, the budgets, and the simulation and exercise-test timers are decided and stored on the server. + Grades that matter cannot be changed from the device. +- **Content gaps in the bank.** The app needs content the bank does not have yet: + - nothing for lesson quizzes: they are drawn from the existing questions (QZ-2); + - one skill has no multiple-choice question; + - a **solved example for the help button: none of the 96 skills has one** (every skill has an explanation; the single `sample` is an open question); + - a skill to go back to for 204 of the 244 mistakes; + - enough questions per skill for "a different question" and for retakes that draw new questions. + A drafting tool can write solved examples with AI for a teacher to approve. +- **Database problems.** When the database cannot be reached, or refuses a request that is not a conflict the person caused, the person sees a message saying so, with a hint that migrations may be missing, and the reason goes to the server log. It is never reported as a different problem, such as a name already in use. +- **Start empty.** The app starts with no students, classes or progress; nothing is imported from mathly1. +- **Fallback to mathly1.** mathly1's database must keep working untouched, so the Space can be switched back to mathly1 and its students find their data as they left it. + The app therefore only **adds** its own tables (named with an `m2_` prefix, as the migrations do) and never changes, empties or deletes any table, policy or storage bucket that mathly1 uses. + Sign-in accounts are the Supabase project's, so the same Google accounts work in both. mathly1's code stays in the repository (tagged) so its image can be redeployed. + mathly2 uses mathly1's Supabase project, with the `m2_` tables beside the old ones. Before the Space is switched, mathly1's own uncommitted work is committed and tagged so the fallback is exactly what ran before. ## 8. Success Metrics @@ -225,12 +525,47 @@ It exposes `window.MathlyBoard` and turns a sketch into a picture for handing in - On test day, students have mastered on average ≥ 80% of the covered skills. - ≥ 75% of students take both exercise tests before each real test. - Teachers open the heat map or the coverage view at least once a week. +- The AI's estimated cost stays within each class's daily budget on every day. ## 9. Open Questions -1. **Default time limit:** 90 minutes was chosen as the default for a real test. Is that right for most tests, or should it be 45? -2. **Existing data:** should students, classes and progress from the current app move to the new one, or does the new app start empty? -3. **Sign-in and roles:** keep sign-in with the school's Google accounts? Is there an admin role (creates classes, adds students), or does the teacher do that? -4. **Subjects:** math only, or also science (the current app has a small science part)? -5. **Checking open answers:** does the teacher check everything by hand, or should AI suggest a grade for the teacher to approve? -6. **Tech stack and location:** same repository (new folder) or a new one? Any preferred stack, or keep Python + Supabase? +None. Every question raised so far is decided below; new ones are added here as they come up. + +### Decisions already taken + +- Math only. The app starts empty (no data import). Google sign-in. +- A real test defaults to 12 questions and 45 minutes. The calculator is allowed in quizzes, exercise tests and the simulation. +- A class's teacher adds and removes the students of their own class; managers do everything else about classes. +- The developer lab starts empty. +- The app runs as a Hugging Face Space, replacing mathly1. **mathly1's database is kept unchanged** so the Space can be switched back to mathly1 at any time (see 7.3, Fallback). + mathly2 uses mathly1's Supabase project, with its own `m2_` tables beside the old ones. +- Lesson quizzes are 10 multiple-choice questions drawn from the bank, 15 minutes, 0–100; the four authored written quizzes become assignable material. +- Readiness is one 0–100 number from mastery (50), exercise tests (20) and the simulation (30), capped at 80 until the simulation is taken. +- Photo help has two entries (exercise screen and home), is routed to a teacher the student chooses when they are in several classes, and works only in classes where a manager has switched the AI on. +- Roles are keyed by email, so an admin can give a role before the person's first sign-in. The Hebrew role names are מנהל כיתות (manager) and מנהל הרשאות (admin). +- The first comet arrives with the first daily goal reached. +- Answer pictures are kept until 31 August of the school year; no names or emails are sent to the AI. +- A class's teacher is never also one of its students: a refused save says why, in view, and keeps what was typed. +- Settings are read from the environment, then `mathly2/.env`, then the repository's `.env`. +- Five roles: student, teacher, manager (creates classes), admin (gives roles to accounts, sees no learning data), developer (everything and the developer tools). +- Mastery is the 3-correct-on-2-days rule with no decay; fading stars are only a visual review cue; the worked-example and faded-example stages are not part of the app. +- The AI is always reached through the teacher; a class has a daily budget. +- Stack: FastAPI + Supabase + plain JavaScript, in this repository, new folder. + +## Appendix A. OpenSpec changes and capabilities + +The OpenSpec plan in `openspec/changes/` follows this table: one change per stage, built and archived in order. Each capability belongs to exactly one change. +Screens for the student, teacher and manager: `docs/mockups/mathly2-screens.html`. + +| Stage | Change | Capabilities | Requirements | +|---|---|---|---| +| 1 | `rebuild-foundation` | `app-basics`, `accounts-and-classes`, `exercise-bank` (existing, modified) | 6 and 7.3 (look, server decisions, fallback), ACC, ADM, CLS, MGR, TCH-1, TCH-9, BNK | +| 2 | `add-learning-core` | `skill-mastery`, `exercise-screen`, `learning-path`, `smart-board` | MST-1 – MST-5, EXR, PTH (without the quiz node and the daily goal), BRD | +| 3 | `add-rewards` | `rewards` | MST-6 – MST-8, CMT, PTH-6 | +| 4 | `add-lesson-quizzes` | `lesson-quizzes`, `grades` | QZ, GRD, STU-3 | +| 5 | `add-test-readiness` | `real-tests`, `test-countdown`, `exercise-tests`, `simulation-test`, `readiness-meter`, `student-home` | TST, TCH-6, EXT, SIM, RDY, STU-1 | +| 6 | `add-written-work` | `written-answers`, `assignments` | ANS, PSH, TCH-2 – TCH-4, STU-5, QZ-6 | +| 7 | `add-ai-help` | `ai-help` | AI, STU-6, TCH-5 | +| 8 | `add-class-progress-views` | `class-progress-views` | TCH-7, TCH-8 | +| 9 | `add-developer-tools` | `developer-tools` | DEV-1 – DEV-4 | +| 10 | `launch-on-space` | none (operations only) | 7.3 Fallback | diff --git a/mathly2/.env.example b/mathly2/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..8da6fca2fa9a6e1d09f071fd476c4703ee223e42 --- /dev/null +++ b/mathly2/.env.example @@ -0,0 +1,18 @@ +# Settings for mathly2. They are read from, in order: real environment variables, mathly2/.env, then the repository's .env +# (shared with mathly1: it already holds the Supabase keys). Copy this file to mathly2/.env only to override the repository's. + +# Leave the three Supabase values EMPTY for local development: the app then uses an in-memory store and a +# "dev only" sign-in that accepts any email. Set all three, or none. +SUPABASE_URL= +SUPABASE_PUBLISHABLE_KEY= +SUPABASE_SECRET_KEY= + +# Who is a teacher, a developer (every permission), or one of the first admins (they give roles to others). +# Separate addresses by commas, spaces or new lines. A class's teacher is also a teacher; everyone else in a class is a student. +TEACHER_EMAILS= +DEVELOPER_EMAILS= +ADMIN_EMAILS= + +# Only for the drafting tool (mathly2/scripts/draft_examples.py). Spends API money; leave empty otherwise. +ANTHROPIC_API_KEY= +# MATH_MODEL=claude-opus-5-5 diff --git a/mathly2/Dockerfile.dockerignore b/mathly2/Dockerfile.dockerignore index 4ad9e8d7e67ee31cbe86e11790227dcf12faf689..ec5282b7516887b846783b7aaef6c01bb84eaf25 100644 --- a/mathly2/Dockerfile.dockerignore +++ b/mathly2/Dockerfile.dockerignore @@ -2,3 +2,5 @@ !mathly2 mathly2/tests mathly2/**/__pycache__ +mathly2/.env +mathly2/.env.* diff --git a/mathly2/README.md b/mathly2/README.md index 7e845b0e301316da121e59be0b5ca0eaf7071f1a..531937ddc248b7d89dff4735721e151a57e38cea 100644 --- a/mathly2/README.md +++ b/mathly2/README.md @@ -13,9 +13,15 @@ venv/bin/python -m pip install -r mathly2/requirements-dev.txt venv/bin/python -m uvicorn mathly2.main:app --port 7861 ``` -Open . With the Supabase settings empty, the app uses an in-memory store and a -"dev only" sign-in that takes an email address; nothing is saved after a restart. -Add teachers with `TEACHER_EMAILS=you@school.example venv/bin/python -m uvicorn …`. +Settings are read from real environment variables, then `mathly2/.env` (optional), then the repository's `.env` (the one mathly1 uses, +with the same Supabase project; both files are git-ignored). Earlier sources win. `mathly2/.env.example` lists every setting. With the Supabase +values empty, the app uses an in-memory store and a "dev only" sign-in that takes an email address; nothing is saved +after a restart. Put your own address in `ADMIN_EMAILS=` (to give roles) or `DEVELOPER_EMAILS=` (every permission) in the file. No variables are needed on the command line. + +Open . To try every screen alone, put your address in `DEVELOPER_EMAILS=` (every permission): a chip for each role +(תלמיד, מורה, מנהל כיתות, מנהל הרשאות, מפתח) appears in the header. A normal flow: an admin (`ADMIN_EMAILS`, or any account an admin +gave the role) gives someone the **manager** role; the manager makes a class (lessons, a teacher, students); the class's teacher adds more +students; a student signs in and sees the lessons of their classes. Roles belong to an email, so they can be given before a first sign-in. ## Tests @@ -32,6 +38,8 @@ venv/bin/python -m pytest mathly2/tests | `SUPABASE_PUBLISHABLE_KEY` | The publishable key. Sent to the browser for Google sign-in | | `SUPABASE_SECRET_KEY` | The secret key. Server only; never sent to the browser | | `TEACHER_EMAILS` | Teachers' email addresses, separated by commas, spaces or new lines | +| `DEVELOPER_EMAILS` | Developers' email addresses: every permission and the developer tools. The developer role comes only from here | +| `ADMIN_EMAILS` | The first admins. Admins give roles (student, teacher, manager, admin) to other accounts | | `PORT` | The port in the container (default 7860) | Set all three Supabase values or none. With none, the app runs locally with the in-memory store and the @@ -62,3 +70,30 @@ whose root `Dockerfile` is `mathly2/Dockerfile` with the `mathly2/` paths unchan ```bash venv/bin/python -m mathly2.scripts.content_gaps ``` + +## Writing the solved examples + +A skill's "?" help shows its explanation and, where the bank has one, a **solved example**: one question solved in steps (what is +done, and why) with its answer. No skill has one yet, and every skill works without it. Examples are added skill by skill with a draft, +a teacher's review, and a merge. Students never call the AI. + +```bash +# 1. See which skills of a lesson lack an example and what would be sent. Sends nothing, needs no key. +venv/bin/python -m mathly2.scripts.draft_examples draft --lesson t --dry-run + +# 2. Ask Claude for drafts. Spends API money (one request per skill). Writes mathly2/content/drafts/t.json +venv/bin/python -m mathly2.scripts.draft_examples draft --lesson t + +# 3. The teacher reads mathly2/content/drafts/t.json, fixes what is wrong, and for each good skill sets +# "approved": true and "reviewed_by": "". + +# 4. Add the approved drafts to the bank. Anything not approved, or breaking the bank's rules, is left out. +venv/bin/python -m mathly2.scripts.draft_examples merge mathly2/content/drafts/t.json +``` + +`draft` refuses to overwrite an existing review file (it may hold a teacher's work) unless you pass `--force`. +`--skill ID` (repeatable) and `--limit N` choose which skills to draft. `MATH_MODEL` picks the model. +To see what is still missing across the whole bank: `venv/bin/python -m mathly2.scripts.content_gaps`. + +The example's shape (`worked_example`: a question, steps each with `do` and a text `why`, and an answer) is checked by +`mathly2/bank.py` every time the bank loads. diff --git a/mathly2/access.py b/mathly2/access.py new file mode 100644 index 0000000000000000000000000000000000000000..f65049bec47142fb99f024b7643c2f0411f2514a --- /dev/null +++ b/mathly2/access.py @@ -0,0 +1,96 @@ +"""Roles and permissions. Every route says which permission it needs, not which role: this file is the one place +that knows what each role may do. Roles are decided by the server on every request (never by the device).""" +from __future__ import annotations + +import threading +import time +from typing import Callable, Iterable + +from fastapi import Depends, HTTPException, Request + +from . import reads +from .auth import current_user + +ROLES = ("student", "teacher", "manager", "admin", "developer") +GRANTABLE = ("student", "teacher", "manager", "admin") # roles an admin can give; developer comes only from the settings + +# What each role may do. "*" (developer) is every permission. +PERMISSIONS: dict[str, frozenset[str]] = { + "student": frozenset({"path.use"}), + "teacher": frozenset({"path.use", "class.teach", "class.roster"}), + "manager": frozenset({"classes.manage", "class.roster", "students.list"}), + "admin": frozenset({"roles.manage"}), + "developer": frozenset({"*"}), +} +CACHE_SECONDS = 30 # a role change shows within this many seconds (sooner on the server that made it) + + +def permissions_of(roles: Iterable[str]) -> frozenset[str]: + return frozenset().union(*(PERMISSIONS.get(role, frozenset()) for role in roles)) + + +def allowed(roles: Iterable[str], permission: str) -> bool: + permissions = permissions_of(roles) + return "*" in permissions or permission in permissions + + +def need(permission: str) -> Callable[..., dict]: + """A route dependency: the caller is signed in and one of their roles has `permission`; else 403.""" + def dependency(user: dict = Depends(current_user)) -> dict: + if not allowed(user["roles"], permission): + raise HTTPException(403, "אין הרשאה לפעולה הזו") + return user + return dependency + + +def learner(request: Request, user: dict = Depends(need("path.use"))) -> dict: + """Someone who may use the path: a teacher or developer, or a student who is in a class. A person whose + only role is student and who is in no class is asked to talk to their teacher (403).""" + if set(user["roles"]) == {"student"} and not reads.of(request).classes_of_student(user["email"]): + raise HTTPException(403, "ask your teacher to add you to a class") + return user + + +class RoleResolver: + """The roles of an email, from the settings, the roles table and the classes (a class's teacher is a teacher, + a class's student is a student). Cached per email for a few seconds so a page load costs a few store calls.""" + + def __init__(self, settings, store, ttl: float = CACHE_SECONDS, clock: Callable[[], float] = time.monotonic) -> None: + self.settings, self.store, self.ttl, self.clock = settings, store, ttl, clock + self._cache: dict[str, tuple[float, frozenset[str]]] = {} + self._lock = threading.Lock() + + def resolve(self, email: str, source=None) -> frozenset[str]: + """`source` is the request's reads (so the classes read here are not read again by the handler); the store when None.""" + email = email.strip().lower() + now = self.clock() + with self._lock: + cached = self._cache.get(email) + if cached and cached[0] > now: + return cached[1] + source = source or self.store + if hasattr(source, "prefetch"): # the three reads do not depend on each other: one wait + source.prefetch(("roles_of", email), ("classes_taught", email), ("classes_of_student", email)) + roles = set(source.roles_of(email)) & set(GRANTABLE) # a 'developer' row is ignored: it comes only from the settings + if email in self.settings.developers: + roles.add("developer") + if email in self.settings.admins: + roles.add("admin") + if email in self.settings.teachers or source.classes_taught(email): + roles.add("teacher") + if source.classes_of_student(email): + roles.add("student") + if not roles: + roles.add("student") + found = frozenset(roles) + with self._lock: + self._cache[email] = (now + self.ttl, found) + return found + + def forget(self, email: str | None = None) -> None: + """Drop one email's cached roles, or all of them (after a class or role change).""" + with self._lock: + if email is None: + self._cache.clear() + else: + self._cache.pop(email.strip().lower(), None) diff --git a/mathly2/accounts.py b/mathly2/accounts.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5bda0b5db0f591b715df780430d672cd10724c --- /dev/null +++ b/mathly2/accounts.py @@ -0,0 +1,58 @@ +"""Roles of accounts: an admin gives and takes away student, teacher, manager and admin. The developer role comes only +from the app's settings. Roles belong to an email, so one can be given before the person has ever signed in.""" +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Request + +from .access import GRANTABLE, need +from .auth import EMAIL + +router = APIRouter(prefix="/api/accounts") + + +def settings_roles(settings, email: str) -> list[str]: + found = [] + if email in settings.developers: + found.append("developer") + if email in settings.admins: + found.append("admin") + if email in settings.teachers: + found.append("teacher") + return found + + +def checked(email: str, role: str) -> tuple[str, str]: + email = email.strip().lower() + if not EMAIL.match(email) or len(email) > 254: + raise HTTPException(422, "כתובת המייל לא נראית תקינה") + if role not in GRANTABLE: + raise HTTPException(422, "אפשר לתת רק את התפקידים תלמיד, מורה, מנהל כיתות ומנהל הרשאות") + return email, role + + +@router.get("") +def list_accounts(request: Request, user: dict = Depends(need("roles.manage"))) -> list[dict]: + """Every email the app knows, with the roles given here and the ones the app's settings give.""" + settings = request.app.state.settings + seen = {a["email"]: a for a in request.app.state.store.accounts()} + for email in settings.developers | settings.admins | settings.teachers: + seen.setdefault(email, {"email": email, "roles": []}) + return [{**a, "from_settings": settings_roles(settings, a["email"])} for _, a in sorted(seen.items())] + + +@router.post("/{email}/roles/{role}", status_code=204) +def give_role(email: str, role: str, request: Request, user: dict = Depends(need("roles.manage"))) -> None: + email, role = checked(email, role) + request.app.state.store.give_role(email, role, user["email"]) + request.app.state.roles.forget(email) + + +@router.delete("/{email}/roles/{role}", status_code=204) +def take_role(email: str, role: str, request: Request, user: dict = Depends(need("roles.manage"))) -> None: + email, role = checked(email, role) + result = request.app.state.store.take_role(email, role, len(request.app.state.settings.admins)) + if result == "last_admin": + raise HTTPException(409, "אי אפשר להסיר את מנהל ההרשאות האחרון") + if result == "absent": + raise HTTPException(404, "לחשבון הזה אין את התפקיד") + request.app.state.roles.forget(email) diff --git a/mathly2/attempts.py b/mathly2/attempts.py new file mode 100644 index 0000000000000000000000000000000000000000..396f5e53d2e6f51e2173f2870a14c8a3e493028b --- /dev/null +++ b/mathly2/attempts.py @@ -0,0 +1,75 @@ +"""Timed, graded attempts (the engine under lesson quizzes; exercise tests and the simulation will use it too). + +An attempt is open until it is graded. The server settles an overdue attempt on the first read after its deadline, so there is no +background job and the answer is right even if nothing ran at the deadline. Nothing here ever says which choice was right.""" +from __future__ import annotations + +from datetime import datetime + +QUIZ_SIZE = 10 +QUIZ_MINUTES = 15 + + +def percent(right: int, total: int) -> int: + """The grade: the share of right answers as a whole number 0-100, rounded half up (7/10 -> 70, 8/12 -> 67).""" + return 0 if total <= 0 else (200 * right + total) // (2 * total) + + +def _right(bank, question: dict, answers: dict) -> bool: + choice = answers.get(question["key"]) + graded = bank.grade(question["skill_id"], question["key"], choice) if isinstance(choice, int) else None + return bool(graded and graded["correct"]) + + +def grade(bank, questions: list[dict], answers: dict) -> tuple[int, int]: + """(grade, number right). A question without an answer, or with an answer the bank does not know, is wrong.""" + right = sum(1 for q in questions if _right(bank, q, answers)) + return percent(right, len(questions)), right + + +def is_open(row: dict) -> bool: + return row["submitted_at"] is None + + +def is_overdue(row: dict, now: datetime) -> bool: + return is_open(row) and now >= row["due_at"] + + +def settle(store, bank, row: dict, now: datetime) -> dict: + """Grade an overdue open attempt from the answers saved so far. Anything else is returned as it is.""" + if not is_overdue(row, now): + return row + value, _ = grade(bank, row["questions"], row["answers"]) + return store.save_attempt(row["id"], submitted_at=row["due_at"], timed_out=True, grade=value) + + +def submit(store, bank, row: dict, now: datetime) -> dict: + """The student hands in. Idempotent: a submitted attempt is returned unchanged; one past its deadline is settled as timed out.""" + if not is_open(row): + return row + if is_overdue(row, now): + return settle(store, bank, row, now) + value, _ = grade(bank, row["questions"], row["answers"]) + return store.save_attempt(row["id"], submitted_at=now, timed_out=False, grade=value) + + +def result(bank, row: dict) -> dict: + """What the student sees after a submitted attempt: the grade, the skills that lost points and, for each missed question, the + mistake's name and tip. It never carries a `correct` flag, the right choice or its position. A question the bank no longer has is skipped.""" + lost: dict[str, dict] = {} + missed = [] + for q in row["questions"]: + skill = bank.skill(q["skill_id"]) + served = bank.practice_question(q["skill_id"], q["key"]) + if skill is None or served is None or _right(bank, q, row["answers"]): + continue + choice = row["answers"].get(q["key"]) + graded = bank.grade(q["skill_id"], q["key"], choice) if isinstance(choice, int) else None + mistake = graded["mistake"] if graded else None + picked = next((c["text"] for c in served["choices"] if c["index"] == choice), None) + lost.setdefault(q["skill_id"], {"id": q["skill_id"], "name": skill["name"], "missed": 0})["missed"] += 1 + missed.append({"skill_id": q["skill_id"], "skill_name": skill["name"], "question": served["question"], "picked": picked, + "mistake": {"name": mistake["name"], "tip": mistake["tip"]} if mistake else None}) + right = sum(1 for q in row["questions"] if _right(bank, q, row["answers"])) + return {"id": row["id"], "grade": row["grade"], "right": right, "total": len(row["questions"]), "timed_out": row["timed_out"], + "lesson": row["scope"], "lost_skills": list(lost.values()), "missed": missed} diff --git a/mathly2/auth.py b/mathly2/auth.py index ce01d9e67ccc0447093e8fd2d70ec7d4e78dc307..f076da22aaf8d4b1c556b4cc3d49dbe854b959e5 100644 --- a/mathly2/auth.py +++ b/mathly2/auth.py @@ -1,5 +1,5 @@ """Who is calling. The browser signs in with Google through Supabase and sends its access token; -the server asks Supabase who the token belongs to. Teachers are the emails in TEACHER_EMAILS; everyone else is a student.""" +the server asks Supabase who the token belongs to, then decides the person's roles (access.py).""" from __future__ import annotations import json @@ -7,11 +7,12 @@ import re import threading import time import urllib.error -import urllib.request import uuid from fastapi import Depends, HTTPException, Request +from . import pooled + TIMEOUT = 10 CACHE_SECONDS = 300 EMAIL = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,255}\.[^@\s]{2,}$") @@ -33,11 +34,10 @@ class SupabaseAuthenticator: cached = self._cache.get(token) if cached and cached[0] > now: return cached[1] - request = urllib.request.Request(self.url + "/auth/v1/user", - headers={"Authorization": f"Bearer {token}", "apikey": self.key, "User-Agent": "mathly2/1.0"}) try: - with urllib.request.urlopen(request, timeout=TIMEOUT) as response: - data = json.load(response) + _, raw = pooled.request("GET", self.url + "/auth/v1/user", + {"Authorization": f"Bearer {token}", "apikey": self.key, "User-Agent": "mathly2/1.0"}, None, TIMEOUT) + data = json.loads(raw) except urllib.error.HTTPError as exc: if exc.code in (400, 401, 403): return None @@ -67,6 +67,7 @@ class DevAuthenticator: def current_user(request: Request) -> dict: + """The signed-in person: id, email and roles (decided now, by the server: see access.RoleResolver).""" header = request.headers.get("authorization", "") token = header[7:].strip() if header.lower().startswith("bearer ") else "" if not token: @@ -77,11 +78,5 @@ def current_user(request: Request) -> dict: raise HTTPException(503, "sign-in service unavailable, try again") from None if not user: raise HTTPException(401, "sign in required") - role = "teacher" if user["email"] in request.app.state.settings.teachers else "student" - return {**user, "role": role} - - -def teacher_only(user: dict = Depends(current_user)) -> dict: - if user["role"] != "teacher": - raise HTTPException(403, "teachers only") - return user + from . import reads + return {**user, "roles": sorted(request.app.state.roles.resolve(user["email"], reads.of(request)))} diff --git a/mathly2/bank.py b/mathly2/bank.py index 92b87805cd469deadca6f36ab60b64ad4996b15d..d12a24d64ac1ff857925c81174ff149627a36009 100644 --- a/mathly2/bank.py +++ b/mathly2/bank.py @@ -1,8 +1,10 @@ """The exercise bank: lessons (units), skills, questions and mistakes. Loaded once and checked on start-up.""" from __future__ import annotations +import hashlib import json from dataclasses import dataclass +from functools import cached_property from pathlib import Path BANK_PATH = Path(__file__).parent / "content" / "math_algebra9.json" @@ -12,6 +14,53 @@ class BankError(RuntimeError): """The bank is broken; the message lists every problem found.""" +PRACTICE_QUESTIONS = 10 # practice shows "question n of N" with N at most this, whatever the skill has in the bank + + +def question_key(skill_id: str, question: dict) -> str: + """A stable id for a question: the skill plus a hash of the question's content. + Reordering or adding questions keeps every key; editing a question gives it a new one.""" + canonical = json.dumps(question, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + return f"{skill_id}:{hashlib.sha1(canonical.encode('utf-8')).hexdigest()[:10]}" + + +def _one_correct(choices: list, where: str, mistakes: dict, problems: list[str]) -> None: + if not isinstance(choices, list) or len(choices) < 2: + problems.append(f"{where}: fewer than 2 choices") + return + right = sum(1 for c in choices if c.get("correct")) + if right != 1: + problems.append(f"{where}: {right} correct choices, expected 1") + for choice in choices: + mistake = choice.get("mistake") + if mistake is not None and mistake not in mistakes: + problems.append(f"{where}: unknown mistake '{mistake}'") + + +def example_problems(skill: dict, mistakes: dict) -> list[str]: + """What is wrong with a skill's solved example (the same checks the bank is loaded with).""" + problems: list[str] = [] + _check_example(skill, problems) + return problems + + +def _check_example(skill: dict, problems: list[str]) -> None: + """The help button's solved example is optional; when present it is one question solved in steps, each with what is done + and why, and an answer. It is plain text: nothing is chosen. (`faded_examples` from an earlier plan is not read.)""" + example = skill.get("worked_example") + if example is None: + return + where = f"skill '{skill['id']}' solved example" + steps = example.get("steps") or [] + if not example.get("question") or not steps or not example.get("answer"): + problems.append(f"{where}: needs a question, steps and an answer") + for number, step in enumerate(steps, 1): + if not step.get("do"): + problems.append(f"{where} step {number}: no 'do'") + if not isinstance(step.get("why"), str) or not step["why"].strip(): + problems.append(f"{where} step {number}: 'why' must be text") + + def check_bank(data: dict) -> list[str]: """Every problem found in a bank, as short messages. An empty list means the bank is sound.""" problems: list[str] = [] @@ -45,18 +94,15 @@ def check_bank(data: dict) -> list[str]: for pre in skill.get("prereqs", []): if pre not in skills: problems.append(f"skill '{sid}': unknown prerequisite '{pre}'") + keys: set[str] = set() for number, question in enumerate(skill.get("questions", []), 1): where = f"skill '{sid}' question {number}" - choices = question.get("choices", []) - if len(choices) < 2: - problems.append(f"{where}: fewer than 2 choices") - right = sum(1 for c in choices if c.get("correct")) - if right != 1: - problems.append(f"{where}: {right} correct choices, expected 1") - for choice in choices: - mistake = choice.get("mistake") - if mistake is not None and mistake not in mistakes: - problems.append(f"{where}: unknown mistake '{mistake}'") + _one_correct(question.get("choices", []), where, mistakes, problems) + key = question_key(sid, question) + if key in keys: + problems.append(f"{where}: identical to an earlier question of the skill") + keys.add(key) + _check_example(skill, problems) for mid, mistake in mistakes.items(): # `back` is filled in for only some mistakes today (see scripts/content_gaps.py); check it when given. @@ -82,6 +128,55 @@ class Bank: def mistakes(self) -> dict: return self.data["mistakes"] + @cached_property + def _skills_by_id(self) -> dict[str, dict]: + return {s["id"]: s for s in self.skills} + + @cached_property + def _questions(self) -> dict[str, dict[str, dict]]: + """skill id -> question key -> question, in bank order.""" + return {s["id"]: {question_key(s["id"], q): q for q in s.get("questions", [])} for s in self.skills} + + def skill(self, skill_id: str) -> dict | None: + return self._skills_by_id.get(skill_id) + + def question_keys(self, skill_id: str) -> list[str]: + return list(self._questions.get(skill_id, {})) + + def practice_keys(self, skill_id: str) -> list[str]: + """The questions practice on the exercise screen uses: the first PRACTICE_QUESTIONS of the skill. Quizzes and tests draw from all of them.""" + return self.question_keys(skill_id)[:PRACTICE_QUESTIONS] + + def practice_question(self, skill_id: str, key: str) -> dict | None: + """A question as the browser may see it: no `correct` flag and no `mistake`, so nothing reveals the + answer. Each choice keeps its position in the bank (`index`); the browser may shuffle the display.""" + question = self._questions.get(skill_id, {}).get(key) + if question is None: + return None + served = {"key": key, "question": question["question"], + "choices": [{"index": i, "text": c["text"]} for i, c in enumerate(question["choices"])]} + for extra in ("figure", "graph"): + if extra in question: + served[extra] = question[extra] + return served + + def grade(self, skill_id: str, key: str, choice: int) -> dict | None: + """{"correct": bool, "mistake": {"id","name","tip","back"} | None}, or None for an unknown question or choice. + Never says which choice was right.""" + question = self._questions.get(skill_id, {}).get(key) + if question is None or not isinstance(choice, int) or not 0 <= choice < len(question["choices"]): + return None + picked = question["choices"][choice] + if picked.get("correct"): + return {"correct": True, "mistake": None} + return {"correct": False, "mistake": self.mistake(picked.get("mistake"))} + + def mistake(self, mistake_id: str | None) -> dict | None: + found = self.mistakes.get(mistake_id) if mistake_id else None + if not found: + return None + return {"id": mistake_id, "name": found["name"], "tip": found.get("tip", ""), "back": found.get("back") or None} + def lessons_with_skills(self) -> list[dict]: """Lessons with their skills, without any questions (those are served by later endpoints, which hide which choice is correct).""" diff --git a/mathly2/classes.py b/mathly2/classes.py index 03ab22476d230cd6fad9aca875c2ee8c5cee0f38..0a8bc6e1ea45b49e6a44c403105da6bd924f164f 100644 --- a/mathly2/classes.py +++ b/mathly2/classes.py @@ -1,4 +1,5 @@ -"""A teacher's classes and their students.""" +"""Classes. A manager (or a developer) makes, changes and deletes them; a class's teacher, or a manager, adds and +removes its students; a teacher sees the classes they teach; a manager sees every student.""" from __future__ import annotations import re @@ -6,15 +7,23 @@ import re from fastapi import APIRouter, Depends, HTTPException, Request from pydantic import BaseModel, Field -from .auth import EMAIL, teacher_only -from .store import ClassExists, MemberExists +from .access import allowed, need +from .auth import EMAIL +from .store import ClassExists, MemberExists, TeacherIsStudent MAX_EMAILS = 200 +MAX_NAME = 80 router = APIRouter(prefix="/api/classes") +teaching = APIRouter(prefix="/api") -class NewClass(BaseModel): +class ClassBody(BaseModel): name: str = Field(max_length=200) + lessons: list[str] = Field(default_factory=list, max_length=200) + teacher_email: str | None = Field(default=None, max_length=300) + students: str | None = Field(default=None, max_length=40000) # pasted text: the whole roster of the class + ai_enabled: bool = False + ai_daily_checks: int = 150 class NewStudents(BaseModel): @@ -34,65 +43,159 @@ def parse_emails(text: str) -> tuple[list[str], list[str]]: return valid, invalid -def own_class(request: Request, class_id: int, user: dict) -> dict: +def shown(request: Request, row: dict, with_students: bool = True) -> dict: + out = {k: row[k] for k in ("id", "name", "lessons", "teacher_email", "ai_enabled", "ai_daily_checks", "students")} + if with_students: + out["student_emails"] = [m["email"] for m in request.app.state.store.members(row["id"])] + return out + + +def checked(request: Request, body: ClassBody) -> dict: + """The class fields from a request, or an HTTP error that says what is wrong.""" + name = " ".join(body.name.split()) + if not 1 <= len(name) <= MAX_NAME: + raise HTTPException(422, f"שם הכיתה צריך להיות בין תו אחד ל־{MAX_NAME} תווים") + known = [lesson["id"] for lesson in request.app.state.bank.lessons] + lessons = [lesson for lesson in dict.fromkeys(body.lessons) if lesson in known] + if len(lessons) != len(set(body.lessons)) or not lessons: + raise HTTPException(422, "יש לבחור לפחות שיעור אחד מהרשימה") + teacher = (body.teacher_email or "").strip().lower() or None + if teacher and not EMAIL.match(teacher): + raise HTTPException(422, "כתובת המורה לא נראית כמו מייל") + if not 0 <= body.ai_daily_checks <= 10000: + raise HTTPException(422, "מספר בדיקות ה־AI ביום צריך להיות בין 0 ל־10000") + roster, invalid = parse_emails(body.students or "") + if len(roster) > 2 * MAX_EMAILS: + raise HTTPException(422, "יותר מדי תלמידים בבת אחת") + if teacher and teacher in roster: + raise HTTPException(422, "מורה הכיתה לא יכול להיות גם תלמיד בה") + return {"name": name, "lessons": lessons, "teacher_email": teacher, "ai_enabled": body.ai_enabled, + "ai_daily_checks": body.ai_daily_checks, "roster": roster, "invalid": invalid} + + +def sync_roster(store, class_id: int, roster: list[str]) -> None: + """Make the class's students exactly `roster`. Removing a student never deletes their progress.""" + current = {m["email"] for m in store.members(class_id)} + for email in roster: + if email not in current: + store.add_member(class_id, email) + for email in current - set(roster): + store.remove_member(class_id, email) + + +def own_class_for_roster(request: Request, class_id: int, user: dict) -> dict: + """A manager (or developer) reaches any class; a teacher only the classes they teach.""" row = request.app.state.store.get_class(class_id) - if not row or row["teacher_email"] != user["email"]: + if not row: + raise HTTPException(404, "הכיתה לא נמצאה") + if not allowed(user["roles"], "classes.manage") and row["teacher_email"] != user["email"]: raise HTTPException(404, "הכיתה לא נמצאה") return row +# ---- the manager ---- + @router.get("") -def list_classes(request: Request, user: dict = Depends(teacher_only)) -> list[dict]: - return [{"id": c["id"], "name": c["name"], "students": c["students"]} - for c in request.app.state.store.classes_of(user["email"])] +def list_classes(request: Request, user: dict = Depends(need("classes.manage"))) -> list[dict]: + return [shown(request, c) for c in request.app.state.store.classes()] + + +@router.get("/lessons") +def lessons_to_choose(request: Request, user: dict = Depends(need("classes.manage"))) -> list[dict]: + """The bank's lessons, for choosing what a class studies (a manager has no student path, so no /api/lessons).""" + return [{"id": lesson["id"], "name": lesson["name"], "skills": len(lesson["skills"])} + for lesson in request.app.state.bank.lessons_with_skills()] @router.post("", status_code=201) -def create_class(body: NewClass, request: Request, user: dict = Depends(teacher_only)) -> dict: - name = " ".join(body.name.split()) - if not 1 <= len(name) <= 60: - raise HTTPException(422, "שם הכיתה צריך להיות בין תו אחד ל־60 תווים") +def create_class(body: ClassBody, request: Request, user: dict = Depends(need("classes.manage"))) -> dict: + fields = checked(request, body) + store = request.app.state.store + try: + row = store.create_class(user["email"], fields["name"], lessons=fields["lessons"], teacher_email=fields["teacher_email"], + ai_enabled=fields["ai_enabled"], ai_daily_checks=fields["ai_daily_checks"]) + except ClassExists: + raise HTTPException(409, "כבר יש כיתה בשם הזה") from None + sync_roster(store, row["id"], fields["roster"]) + request.app.state.roles.forget() + return {**shown(request, store.get_class(row["id"])), "invalid": fields["invalid"]} + + +@router.put("/{class_id}") +def change_class(class_id: int, body: ClassBody, request: Request, user: dict = Depends(need("classes.manage"))) -> dict: + fields = checked(request, body) + store = request.app.state.store try: - row = request.app.state.store.create_class(user["email"], name) + store.update_class(class_id, name=fields["name"], lessons=fields["lessons"], teacher_email=fields["teacher_email"], + ai_enabled=fields["ai_enabled"], ai_daily_checks=fields["ai_daily_checks"]) + except KeyError: + raise HTTPException(404, "הכיתה לא נמצאה") from None except ClassExists: - raise HTTPException(409, "כבר יש לך כיתה בשם הזה") from None - return {"id": row["id"], "name": row["name"], "students": 0} + raise HTTPException(409, "כבר יש כיתה בשם הזה") from None + except TeacherIsStudent: + raise HTTPException(422, "מורה הכיתה לא יכול להיות גם תלמיד בה") from None + if body.students is not None: + sync_roster(store, class_id, fields["roster"]) + request.app.state.roles.forget() + return {**shown(request, store.get_class(class_id)), "invalid": fields["invalid"]} + + +@router.delete("/{class_id}", status_code=204) +def delete_class(class_id: int, request: Request, user: dict = Depends(need("classes.manage"))) -> None: + if not request.app.state.store.delete_class(class_id): + raise HTTPException(404, "הכיתה לא נמצאה") + request.app.state.roles.forget() @router.get("/{class_id}") -def show_class(class_id: int, request: Request, user: dict = Depends(teacher_only)) -> dict: - row = own_class(request, class_id, user) - members = request.app.state.store.members(class_id) - return {"id": row["id"], "name": row["name"], - "students": [{"email": m["email"], "signed_in": bool(m["user_id"])} for m in members]} +def show_class(class_id: int, request: Request, user: dict = Depends(need("classes.manage"))) -> dict: + row = request.app.state.store.get_class(class_id) + if not row: + raise HTTPException(404, "הכיתה לא נמצאה") + return shown(request, row) + +# ---- the roster: the class's teacher, or a manager ---- @router.post("/{class_id}/students") -def add_students(class_id: int, body: NewStudents, request: Request, user: dict = Depends(teacher_only)) -> dict: - own_class(request, class_id, user) +def add_students(class_id: int, body: NewStudents, request: Request, user: dict = Depends(need("class.roster"))) -> dict: + row = own_class_for_roster(request, class_id, user) store = request.app.state.store valid, invalid = parse_emails(body.emails) if len(valid) > MAX_EMAILS: raise HTTPException(422, f"אפשר להוסיף עד {MAX_EMAILS} תלמידים בכל פעם") - result: dict = {"added": [], "already_here": [], "elsewhere": [], "invalid": invalid} + result: dict = {"added": [], "already_here": [], "teacher": [], "invalid": invalid} for email in valid: - current = store.membership(email) - if current is None: - try: - store.add_member(class_id, email) - result["added"].append(email) - continue - except MemberExists: # added to another class a moment ago - current = store.membership(email) - if current and current["class_id"] == class_id: + try: + store.add_member(row["id"], email) + result["added"].append(email) + except MemberExists: result["already_here"].append(email) - else: - result["elsewhere"].append({"email": email, "class_name": current["class_name"] if current else ""}) + except TeacherIsStudent: + result["teacher"].append(email) + request.app.state.roles.forget() return result @router.delete("/{class_id}/students/{email:path}", status_code=204) -def remove_student(class_id: int, email: str, request: Request, user: dict = Depends(teacher_only)) -> None: - own_class(request, class_id, user) +def remove_student(class_id: int, email: str, request: Request, user: dict = Depends(need("class.roster"))) -> None: + own_class_for_roster(request, class_id, user) if not request.app.state.store.remove_member(class_id, email.strip().lower()): raise HTTPException(404, "התלמיד לא נמצא בכיתה") + request.app.state.roles.forget(email) + + +# ---- the teacher's and the manager's lists ---- + +@teaching.get("/teaching") +def my_classes(request: Request, user: dict = Depends(need("class.teach"))) -> list[dict]: + """The classes I teach, each with its students. A developer sees every class.""" + store = request.app.state.store + rows = store.classes() if allowed(user["roles"], "*") else store.classes_taught(user["email"]) + return [{"id": c["id"], "name": c["name"], "lessons": c["lessons"], "ai_enabled": c["ai_enabled"], + "students": [{"email": m["email"], "signed_in": bool(m["user_id"])} for m in store.members(c["id"])]} for c in rows] + + +@teaching.get("/students") +def all_students(request: Request, user: dict = Depends(need("students.list"))) -> list[dict]: + return request.app.state.store.all_students() diff --git a/mathly2/comets.py b/mathly2/comets.py new file mode 100644 index 0000000000000000000000000000000000000000..ae457ff94dbad6e802e933011104191b5a196bfb --- /dev/null +++ b/mathly2/comets.py @@ -0,0 +1,56 @@ +"""The twelve comets (PRD CMT-3) and the rule for when one crosses (CMT-1). The server decides both: the browser only draws.""" +import random +from datetime import date + +COMETS = [ + {"id": "pi", "sym": "π", "name": "פאי", "fact": "היחס בין ההיקף של מעגל לקוטר שלו. הספרות שלו אחרי הנקודה לא נגמרות ולא חוזרות על עצמן."}, + {"id": "fib", "sym": "1,1,2,3,5", "name": "פיבונאצ׳י", "fact": "כל מספר בסדרה הוא סכום שני הקודמים. הסדרה מופיעה בספירלות של גרעיני חמנייה ובאצטרובלים."}, + {"id": "phi", "sym": "φ", "name": "יחס הזהב", "fact": "בערך 1.618. מחלקים קטע כך שהיחס בין השלם לחלק הגדול שווה ליחס בין הגדול לקטן. מופיע בפרחים, בצדפים ובאמנות."}, + {"id": "inf", "sym": "∞", "name": "אינסוף", "fact": "יש אינסוף מספרים שלמים, ויש גם אינסוף מספרים בין 0 ל־1. מתברר שהאינסוף השני גדול יותר."}, + {"id": "e", "sym": "e", "name": "המספר e", "fact": "בערך 2.718. מופיע בכל מקום שבו משהו גדל בקצב שתלוי בגודל שלו: ריבית, אוכלוסיות, חיידקים."}, + {"id": "r2", "sym": "√2", "name": "שורש 2", "fact": "האורך של אלכסון בריבוע שצלעו 1. כבר היוונים הקדמונים הוכיחו שאי אפשר לכתוב אותו כשבר."}, + {"id": "zero", "sym": "0", "name": "אפס", "fact": "במשך אלפי שנים לא היה סימן לאפס. הוא הגיע מהודו, ובזכותו אפשר לכתוב כל מספר בעשר ספרות בלבד."}, + {"id": "pyth", "sym": "a²+b²=c²", "name": "פיתגורס", "fact": "במשולש ישר זווית, סכום ריבועי הניצבים שווה לריבוע היתר. ידוע ליותר מ־370 הוכחות שונות."}, + {"id": "prime", "sym": "2,3,5,7", "name": "מספרים ראשוניים", "fact": "מספרים שמתחלקים רק ב־1 ובעצמם. יש אינסוף כאלה, ועליהם בנויה ההצפנה של האינטרנט."}, + {"id": "pascal", "sym": "1 2 1", "name": "משולש פסקל", "fact": "כל מספר הוא סכום שני המספרים שמעליו. השורות שלו נותנות את המקדמים של (a + b) בכל חזקה."}, + {"id": "euler", "sym": "V−E+F=2", "name": "נוסחת אוילר", "fact": "בכל גוף משוכלל, קודקודים פחות מקצועות ועוד פאות שווה תמיד 2. נסו על קובייה: 8 − 12 + 6."}, + {"id": "mobius", "sym": "∞", "name": "טבעת מביוס", "fact": "רצועת נייר עם חצי סיבוב: יש לה רק צד אחד ושפה אחת. נמלה שהולכת עליה תעבור בשני ה״צדדים״."}, +] +IDS = [c["id"] for c in COMETS] +CHANCE = 0.12 # a right answer's chance of a comet, once the student has been offered their first + + +def get(comet_id: str) -> dict | None: + return next((c for c in COMETS if c["id"] == comet_id), None) + + +def due(state: dict | None, caught: set[str], today: date, goal_just_reached: bool, roll: float | None = None) -> bool: + """Is a comet due after this right answer? At most one a day; none once all are caught; the first one only on the answer that + reaches the daily goal; after any comet was offered, a small chance on each right answer. `roll` (0..1) is injectable for tests.""" + if len(caught) >= len(COMETS): + return False + last = (state or {}).get("last_comet_day") + if last == today: + return False + if last is None: + return goal_just_reached + return (random.random() if roll is None else roll) < CHANCE + + +def surely_not(state: dict | None, today: date, goal_just_reached: bool, roll: float | None) -> bool: + """True when no comet can be due whatever the student has caught, so the caught list need not be read (the usual case).""" + last = (state or {}).get("last_comet_day") + if last == today: + return True + if last is None: + return not goal_just_reached + return (random.random() if roll is None else roll) >= CHANCE + + +def pick(caught: set[str], roll: float | None = None) -> dict | None: + """A comet the student does not have yet, at random.""" + left = [c for c in COMETS if c["id"] not in caught] + if not left: + return None + return left[int((random.random() if roll is None else roll) * len(left)) % len(left)] + diff --git a/mathly2/config.py b/mathly2/config.py index 05ce7686cc7f9d48ecc5c799a4d3b4b6a6987f69..8006b6aa96d39875abf29d2110fa8a05a800b3e0 100644 --- a/mathly2/config.py +++ b/mathly2/config.py @@ -4,6 +4,12 @@ from __future__ import annotations import os import re from dataclasses import dataclass, field +from pathlib import Path + +from dotenv import load_dotenv + +ENV_FILE = Path(__file__).parent / ".env" # this app's own settings, if it has any +ROOT_ENV_FILE = Path(__file__).parent.parent / ".env" # the repository's .env, shared with mathly1 (same Supabase project) def _emails(name: str) -> frozenset[str]: @@ -16,6 +22,8 @@ class Settings: supabase_key: str = "" # publishable key, sent to the browser for Google sign-in supabase_secret: str = "" # secret key, server only teachers: frozenset[str] = field(default_factory=frozenset) + developers: frozenset[str] = field(default_factory=frozenset) # the developer role comes only from here + admins: frozenset[str] = field(default_factory=frozenset) # the first admins; others are given the role by an admin @property def supabase_on(self) -> bool: @@ -30,11 +38,17 @@ class Settings: return self -def load_settings() -> Settings: +def load_settings(env_file: Path | None = None) -> Settings: + """Settings from the environment. Files fill in what the environment does not set, in this order: mathly2/.env, then the + repository's .env. A real environment variable always wins, so deployments are unaffected. Passing `env_file` reads only that file.""" + for path in ([env_file] if env_file else [ENV_FILE, ROOT_ENV_FILE]): + load_dotenv(path, override=False) env = lambda name: os.environ.get(name, "").strip() return Settings( supabase_url=env("SUPABASE_URL").rstrip("/"), supabase_key=env("SUPABASE_PUBLISHABLE_KEY"), supabase_secret=env("SUPABASE_SECRET_KEY"), teachers=_emails("TEACHER_EMAILS"), + developers=_emails("DEVELOPER_EMAILS"), + admins=_emails("ADMIN_EMAILS"), ).check() diff --git a/mathly2/countdown.py b/mathly2/countdown.py new file mode 100644 index 0000000000000000000000000000000000000000..010c234dac837a29a6d782dd9f2c452129d97c81 --- /dev/null +++ b/mathly2/countdown.py @@ -0,0 +1,87 @@ +"""The countdown plan for a real test, and today's one task (PRD TST-2, TST-3). Pure functions: the server gathers the facts. + +The plan, for a test set 9 or more days ahead (days left): until 9 finish the path; ~9 exercise test 1; ~7 exercise test 2; ~5 the +simulation (open from then until the test day); 4 to 1 review the skills that failed in the simulation, the last day a light mixed +review. For a test set `n < 9` days ahead the same order is kept and every day is scaled by n/9, rounded half up. The days are +recommendations: everything but the simulation's window may be started any time.""" +from __future__ import annotations + +from datetime import date + +FULL = 9 # days of the full plan +BASE = {"ex1": 9, "ex2": 7, "sim": 5, "review_from": 4} + + +def _round(x: float) -> int: + return int(x + 0.5) + + +def plan(test_day: date, set_day: date) -> dict: + """The recommended days (days left) of each step. `set_day` is the day the teacher set the test, so the plan does not shift as days pass.""" + n = max(0, (test_day - set_day).days) + scale = 1.0 if n >= FULL else n / FULL + days = {step: _round(day * scale) if scale < 1 else day for step, day in BASE.items()} + days["review_from"] = max(days["review_from"], 1) + return {"n": n, **days} + + +def step_for(days_left: int, p: dict) -> str: + """The step the plan recommends on a day: path, ex1, ex2, sim or review. It is the step whose recommended day is the nearest one + still ahead (days left at or above today's), the earlier step first when days coincide; before all of them, the path.""" + steps = [("ex1", p["ex1"]), ("ex2", p["ex2"]), ("sim", p["sim"]), ("review", p["review_from"])] + ahead = [(day, i, name) for i, (name, day) in enumerate(steps) if day >= days_left] + return min(ahead)[2] if ahead else "path" + + +def sim_open(days_left: int, p: dict) -> bool: + """The simulation is open from `sim` days before the test until the test day.""" + return 0 <= days_left <= p["sim"] + + +def outline(p: dict, facts: dict) -> list[dict]: + """The plan as steps with their recommended day (days left) and whether they are done, for the test's card.""" + return [{"id": "path", "day": None, "until": p["ex1"], "done": facts["path_done"]}, + {"id": "ex1", "day": p["ex1"], "done": facts["ex1_done"]}, + {"id": "ex2", "day": p["ex2"], "done": facts["ex2_done"]}, + {"id": "sim", "day": p["sim"], "done": facts["sim_taken"]}, + {"id": "review", "day": p["review_from"], "done": facts["sim_taken"] and not facts["review_left"]}] + + +def task(days_left: int, p: dict, facts: dict) -> dict: + """The one task for today. `facts`: path_done, next_path_skill, ex1_done, ex2_done, sim_taken, review_left (failed skills not + practised since), stale (covered skills, the one answered longest ago first). Returns {"kind": ...} with kind one of path, ex1, ex2, + sim, review, mixed_review, continue. The recommended step comes first; when it is done, the next later step that can be started.""" + done = {"path": facts["path_done"], "ex1": facts["ex1_done"], "ex2": facts["ex2_done"], "sim": facts["sim_taken"], "review": False} + order = ["path", "ex1", "ex2", "sim", "review"] + + def can(step: str) -> bool: + if step == "sim": + return sim_open(days_left, p) # the simulation cannot start before its window + return step != "review" or facts["sim_taken"] # a review needs the simulation's result + + def make(step: str) -> dict: + if step == "path": + return {"kind": "path", "skill": facts["next_path_skill"]} + if step == "review": + if days_left == 1 or not facts["review_left"]: + return {"kind": "mixed_review", "skill": facts["stale"][0] if facts["stale"] else None} + return {"kind": "review", "skill": facts["review_left"][0]} + return {"kind": step} + + if days_left < 0: + return {"kind": "continue"} + rec = step_for(days_left, p) + if rec == "review" and not facts["sim_taken"]: # a review needs the simulation first + rec = "sim" + if days_left == 0 and facts["sim_taken"]: # the test day: nothing left to plan + return {"kind": "continue"} + for step in order[order.index(rec):]: # the recommended step, then later ones, early + if not done[step] and can(step): + return make(step) + return {"kind": "continue"} + + +def closest(tests: list[dict], today: date) -> dict | None: + """The nearest test that has not passed (its day is today or later).""" + coming = [t for t in tests if t["date"] >= today] + return min(coming, key=lambda t: (t["date"], t["id"])) if coming else None diff --git a/mathly2/exam.py b/mathly2/exam.py new file mode 100644 index 0000000000000000000000000000000000000000..b4924aede0dfa726e5c999c7609c0f14b3e85dd7 --- /dev/null +++ b/mathly2/exam.py @@ -0,0 +1,55 @@ +"""Drawing an exercise test or a simulation for a real test (PRD EXT-4, EXT-5, SIM-2): mixed questions from all covered lessons, +weighted toward the student's weak skills, never from a skill the student has not started.""" +from __future__ import annotations + +import random + +EXERCISE_SHARE = {1: 0.6, 2: 0.3} # the share of questions that come from weak skills in exercise test 1 and 2; the simulation has none + + +def _round(x: float) -> int: + return int(x + 0.5) + + +def draw(bank, lessons: list[str], states: dict[str, str], n: int, *, share: float = 0.0, weak_before: set[str] | None = None, + used: dict[str, int] | None = None, rng: random.Random | None = None) -> dict: + """{"questions": [{skill_id, key}], "weak": [skill ids], "practice_first": [skill ids]}. + + Covered skills are those of `lessons` that have questions. A skill in the not-started state is never drawn: it is listed in + `practice_first`. A weak skill is a started covered skill in the learning state, or one in `weak_before` (answered wrong in an + earlier exercise test of this real test). Weak skills give one question each, up to `round(n * share)`; the rest comes from the + other skills one per skill round after round (least-used questions first, ties random), then from the weak ones again.""" + used, rng, weak_before = used or {}, rng or random.Random(), weak_before or set() + covered = [s["id"] for s in bank.skills if s["unit"] in lessons and bank.question_keys(s["id"])] + started = [i for i in covered if states.get(i, "not_started") != "not_started"] + practice_first = [i for i in covered if i not in started] + weak = [i for i in started if states.get(i) == "learning" or i in weak_before] + other = [i for i in started if i not in weak] + pools = {i: sorted(bank.question_keys(i), key=lambda key: (used.get(key, 0), rng.random())) for i in started} + taken: list[dict] = [] + seen: set[str] = set() + + def take(skill_id: str) -> bool: + for key in pools[skill_id]: + if key not in seen: + seen.add(key) + taken.append({"skill_id": skill_id, "key": key}) + return True + return False + + wanted = _round(n * share) + shuffled_weak = rng.sample(weak, len(weak)) + for skill_id in shuffled_weak[:wanted]: + take(skill_id) + order = rng.sample(other, len(other)) if share else rng.sample(started, len(started)) # no weak share: an even spread over all + for group in ([order, shuffled_weak] if share else [order]): # the weak skills are used again only when the others run out + progress = True + while len(taken) < n and progress: + progress = False + for skill_id in group: + if len(taken) >= n: + break + if take(skill_id): + progress = True + rng.shuffle(taken) + return {"questions": taken[:n], "weak": weak, "practice_first": practice_first} diff --git a/mathly2/learning.py b/mathly2/learning.py new file mode 100644 index 0000000000000000000000000000000000000000..a59b3f8956a18a09ea16ef9187b0d2d351664185 --- /dev/null +++ b/mathly2/learning.py @@ -0,0 +1,120 @@ +"""The rules of skill learning. Pure functions plus `record_practice_answer`; they work on any store. +Every day is decided by the server (`clock.school_day`), never by the device.""" +from __future__ import annotations + +import random +from datetime import date, timedelta + +MASTERY_RUN = 3 # correct answers in a row... +MASTERY_DAYS = 2 # ...spread over at least this many different calendar days +FADE_DAYS = 14 # a mastered skill not answered for this many days shows a faded star (a visual cue only) +DAILY_GOAL = 5 # correct answers a day that count toward the streak + +NOT_STARTED, LEARNING, MASTERED = "not_started", "learning", "mastered" + + +def is_mastered(last_counted: list[dict]) -> bool: + """`last_counted`: the student's counted practice answers on a skill, oldest first. + Mastered when the last 3 are all correct and fall on 2 or more different days. + Answers given with help are not in the list: they neither extend nor break the run.""" + run = last_counted[-MASTERY_RUN:] + return (len(run) == MASTERY_RUN and all(a["correct"] for a in run) + and len({a["day"] for a in run}) >= MASTERY_DAYS) + + +def skill_state(progress: dict | None) -> str: + if progress and progress.get("mastered_at"): + return MASTERED # never decays: nothing later can clear mastered_at + if progress and progress.get("started_at"): + return LEARNING + return NOT_STARTED + + +def mark_started(store, user_id: str, skill_id: str, now: str) -> dict: + """A first answer moves a skill out of 'not started'.""" + progress = store.get_progress(user_id, skill_id) + if progress and progress.get("started_at"): + return progress + return store.save_progress(user_id, skill_id, started_at=now) + + +def record_practice_answer(store, user_id: str, skill_id: str, question_key: str, correct: bool, counted: bool, + mistake_id: str | None, day: date, now: str) -> dict: + """Store one practice answer, then set `mastered_at` the first time the mastery rule is met. + Returns the progress row.""" + mark_started(store, user_id, skill_id, now) + store.add_answer(user_id, skill_id, question_key, correct, counted, mistake_id, day) + progress = store.get_progress(user_id, skill_id) + if not progress.get("mastered_at") and is_mastered(store.last_counted_answers(user_id, skill_id, MASTERY_RUN)): + progress = store.save_progress(user_id, skill_id, mastered_at=now) + return progress + + +def answer_counts(rows: list[dict]) -> dict[str, int]: + """How often each question was answered, from the student's answers on a skill.""" + counts: dict[str, int] = {} + for r in rows: + counts[r["question_key"]] = counts.get(r["question_key"], 0) + 1 + return counts + + +def solved_keys(rows: list[dict]) -> set[str]: + """The questions answered correctly at least once (with or without help).""" + return {r["question_key"] for r in rows if r["correct"]} + + +def last_counted(rows: list[dict]) -> list[dict]: + """The last MASTERY_RUN answers that were not given with help, oldest first: what the mastery rule looks at.""" + return [r for r in rows if r["counted"]][-MASTERY_RUN:] + + +def current_round(keys: list[str], rows: list[dict], round_start: int | None) -> dict: + """The round in progress on a skill: its practice questions (`keys`), each answered once. `rows` are all the student's answers on the + skill, oldest first, and the round is the answers from `round_start` on (null: the student practised before rounds existed, so all + their answers are past rounds and a new one begins). Returns the answers of the round in order, the questions not answered yet and + whether the round is done.""" + wanted, seen, taken = set(keys), set(), [] + for row in (rows[round_start:] if round_start is not None else []): + if row["question_key"] in wanted and row["question_key"] not in seen: + seen.add(row["question_key"]) + taken.append(row) + left = [k for k in keys if k not in seen] + return {"answers": taken, "left": left, "done": bool(keys) and not left} + + +def next_in_round(left: list[str], just_answered: str | None = None, rng: random.Random | None = None) -> str | None: + """The next question of the round: one not answered yet, at random; none when the round is done.""" + candidates = [k for k in left if k != just_answered] + return (rng or random).choice(candidates) if candidates else None + + +def next_skill(order: list[str], states: dict[str, str], recent: list[str]) -> str | None: + """The suggested next skill: the unmastered skill the student answered most recently (`recent`, newest first), else the + first unmastered skill in `order` (the bank's order, among the skills the student can see). None when everything is mastered. + Only a suggestion: nothing is locked, hidden or reordered by it.""" + visible = set(order) + for skill_id in recent: + if skill_id in visible and states.get(skill_id) != MASTERED: + return skill_id + return next((skill_id for skill_id in order if states.get(skill_id) != MASTERED), None) + + +def is_faded(state: str, last_answered: date | None, today: date) -> bool: + """A faded star: mastered, and not answered for FADE_DAYS days. It never changes the state itself.""" + return state == MASTERED and last_answered is not None and (today - last_answered).days >= FADE_DAYS + + +def today_progress(daily: dict[date, int], today: date) -> dict: + done = daily.get(today, 0) + return {"done": done, "goal": DAILY_GOAL, "reached": done >= DAILY_GOAL} + + +def streak(daily: dict[date, int], today: date) -> int: + """Consecutive days with at least the daily goal. Today counts once reached; until then the streak is kept + (it is still alive) and counted up to yesterday.""" + day = today if daily.get(today, 0) >= DAILY_GOAL else today - timedelta(days=1) + days = 0 + while daily.get(day, 0) >= DAILY_GOAL: + days += 1 + day -= timedelta(days=1) + return days diff --git a/mathly2/main.py b/mathly2/main.py index 58a93bb40c2d57986ea4add90873157c8faf3960..92f8ecf09508854c14dd33de657368df469117e4 100644 --- a/mathly2/main.py +++ b/mathly2/main.py @@ -2,21 +2,35 @@ from __future__ import annotations import json +import logging from pathlib import Path from fastapi import Depends, FastAPI, HTTPException -from fastapi.responses import HTMLResponse +from fastapi import Request +from fastapi.responses import HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles +from .access import RoleResolver, learner, permissions_of from .auth import DevAuthenticator, SupabaseAuthenticator, current_user from .bank import Bank, load_bank -from . import classes +from . import accounts, classes, quizzes, reads, realtests, skills from .config import Settings, load_settings -from .store import InMemoryStore, SupabaseStore +from .store import InMemoryStore, StoreUnavailable, SupabaseStore STATIC = Path(__file__).parent / "static" +class FreshStaticFiles(StaticFiles): + """Static files the browser must check before reusing (`no-cache` keeps the ETag, so an unchanged file is a 304): + after an update every device gets the new styles and scripts without clearing its cache.""" + + def file_response(self, *args, **kwargs): + response = super().file_response(*args, **kwargs) + response.headers["Cache-Control"] = "no-cache" + return response +log = logging.getLogger("mathly2") + + def create_app(settings: Settings | None = None, bank: Bank | None = None, store=None, authenticator=None) -> FastAPI: app = FastAPI(title="Mathly 2") app.state.settings = settings = (settings or load_settings()).check() @@ -28,33 +42,44 @@ def create_app(settings: Settings | None = None, bank: Bank | None = None, store app.state.store = store or InMemoryStore() app.state.authenticator = authenticator or DevAuthenticator() + app.state.roles = RoleResolver(settings, app.state.store) + @app.exception_handler(StoreUnavailable) + async def store_unavailable(request: Request, exc: StoreUnavailable) -> JSONResponse: + log.warning("database problem on %s %s: %s", request.method, request.url.path, exc) + return JSONResponse({"detail": "מסד הנתונים לא ענה או סירב לבקשה. נסו שוב, ואם זה חוזר, בדקו שהמיגרציות הוחלו (ראו את יומן השרת)."}, status_code=503) + app.include_router(classes.router) + app.include_router(classes.teaching) + app.include_router(accounts.router) + app.include_router(skills.router) + app.include_router(quizzes.router) + app.include_router(realtests.router) @app.get("/api/health") def health() -> dict: return {"ok": True} - def my_class(user: dict) -> dict | None: - """The student's class. The first time they sign in, their account is linked to the entry the teacher made.""" - if user["role"] != "student": - return None - membership = app.state.store.membership(user["email"]) - if membership and not membership["user_id"]: - app.state.store.link_user(user["email"], user["id"]) - return {"id": membership["class_id"], "name": membership["class_name"]} if membership else None - @app.get("/api/me") - def me(user: dict = Depends(current_user)) -> dict: - return {"email": user["email"], "role": user["role"], "class": my_class(user)} - - def in_class_or_teacher(user: dict = Depends(current_user)) -> dict: - if user["role"] == "student" and not app.state.store.membership(user["email"]): - raise HTTPException(403, "ask your teacher to add you to a class") - return user + def me(request: Request, user: dict = Depends(current_user)) -> dict: + """Who I am: roles, what they allow, the classes I am a student in and the classes I teach. + The first time a student signs in, their account is linked to the entries a manager or teacher made for their email.""" + store, here = app.state.store, reads.of(request) + here.prefetch(("classes_of_student", user["email"]), ("classes_taught", user["email"])) + classes_as_student = here.classes_of_student(user["email"]) + if classes_as_student: + store.link_user(user["email"], user["id"]) + return {"email": user["email"], "roles": user["roles"], "permissions": sorted(permissions_of(user["roles"])), + "classes": [{"id": c["id"], "name": c["name"]} for c in classes_as_student], + "teaching": [{"id": c["id"], "name": c["name"]} for c in here.classes_taught(user["email"])]} @app.get("/api/lessons") - def lessons(user: dict = Depends(in_class_or_teacher)) -> list[dict]: - return app.state.bank.lessons_with_skills() + def lessons(request: Request, user: dict = Depends(learner)) -> list[dict]: + """The lessons of the student's classes; a teacher or developer sees every lesson.""" + everything = app.state.bank.lessons_with_skills() + if set(user["roles"]) - {"student"}: + return everything + mine = {lesson for c in reads.of(request).classes_of_student(user["email"]) for lesson in c["lessons"]} + return [lesson for lesson in everything if lesson["id"] in mine] @app.get("/", include_in_schema=False) def index() -> HTMLResponse: @@ -65,7 +90,7 @@ def create_app(settings: Settings | None = None, bank: Bank | None = None, store html = (STATIC / "index.html").read_text(encoding="utf-8").replace("__CONFIG__", text) return HTMLResponse(html, headers={"Cache-Control": "no-cache"}) - app.mount("/static", StaticFiles(directory=STATIC), name="static") + app.mount("/static", FreshStaticFiles(directory=STATIC), name="static") return app diff --git a/mathly2/pooled.py b/mathly2/pooled.py new file mode 100644 index 0000000000000000000000000000000000000000..6a8093aad19fd1c85ca0d103cb9f5df883dda7c1 --- /dev/null +++ b/mathly2/pooled.py @@ -0,0 +1,66 @@ +"""HTTP calls that reuse their connection. A new secure connection costs several round trips before the first byte; with a remote database that +is most of a call. Each thread keeps one open connection per host and reuses it; when the server closed an idle one, the call is made again +once on a fresh connection. Errors look like urllib's (HTTPError for an answer of 400 or more, URLError for a connection that failed), so +callers that handled urllib keep working.""" +from __future__ import annotations + +import http.client +import io +import socket +import threading +import urllib.error +import urllib.parse + +_local = threading.local() +STALE = (http.client.RemoteDisconnected, http.client.CannotSendRequest, http.client.ResponseNotReady, BrokenPipeError, ConnectionResetError, + ConnectionAbortedError) + + +def _connection(url: urllib.parse.ParseResult, timeout: float) -> tuple[http.client.HTTPConnection, bool]: + """This thread's connection to the host (made if there is none), and whether it is an old one being reused.""" + pool = _local.__dict__.setdefault("pool", {}) + key = (url.scheme, url.netloc) + conn = pool.get(key) + if conn is not None: + conn.timeout = timeout + if conn.sock is not None: + conn.sock.settimeout(timeout) + return conn, True + cls = http.client.HTTPSConnection if url.scheme == "https" else http.client.HTTPConnection + conn = pool[key] = cls(url.netloc, timeout=timeout) + return conn, False + + +def _drop(url: urllib.parse.ParseResult) -> None: + conn = _local.__dict__.setdefault("pool", {}).pop((url.scheme, url.netloc), None) + if conn is not None: + conn.close() + + +def request(method: str, url: str, headers: dict | None = None, body: bytes | None = None, timeout: float = 10) -> tuple[int, bytes]: + """(status, body) of a call, raising urllib.error.HTTPError for 400 and above and URLError for a connection that failed.""" + parts = urllib.parse.urlparse(url) + path = parts.path + (f"?{parts.query}" if parts.query else "") + for attempt in (1, 2): + conn, reused = _connection(parts, timeout) + try: + conn.request(method, path or "/", body=body, headers=headers or {}) + response = conn.getresponse() + data = response.read() + if response.getheader("Connection", "").lower() == "close": + _drop(parts) + break + except STALE as exc: + _drop(parts) + if reused and attempt == 1: # the server had closed an idle connection: once more, on a new one + continue + raise urllib.error.URLError(exc) from exc + except (socket.timeout, TimeoutError) as exc: + _drop(parts) + raise TimeoutError(str(exc)) from exc + except (OSError, http.client.HTTPException) as exc: + _drop(parts) + raise urllib.error.URLError(exc) from exc + if response.status >= 400: + raise urllib.error.HTTPError(url, response.status, response.reason, response.msg, io.BytesIO(data)) + return response.status, data diff --git a/mathly2/quiz.py b/mathly2/quiz.py new file mode 100644 index 0000000000000000000000000000000000000000..54d0af329cb1fd392793bee51f5cc791de75a2c3 --- /dev/null +++ b/mathly2/quiz.py @@ -0,0 +1,49 @@ +"""Drawing a lesson quiz: 10 multiple-choice questions from the lesson's skills, spread evenly, new questions first on a retake.""" +from __future__ import annotations + +import random + +from .attempts import QUIZ_SIZE + + +def draw(bank, lesson_id: str, used: dict[str, int] | None = None, rng: random.Random | None = None, size: int = QUIZ_SIZE) -> list[dict]: + """[{skill_id, key}] in a shuffled order. Skills without questions are left out. Each skill gets `size // k` questions and the + remainder goes to distinct skills picked at random, so quotas differ by at most one. Within a skill the least-used questions come + first (`used`: how often the student had each question key in earlier quizzes of this lesson), ties in random order.""" + used, rng = used or {}, rng or random.Random() + skills = [s for s in bank.skills if s["unit"] == lesson_id and bank.question_keys(s["id"])] + if not skills: + return [] + quota = {s["id"]: size // len(skills) for s in skills} + for skill in rng.sample(skills, size % len(skills)): + quota[skill["id"]] += 1 + pools = {s["id"]: sorted(bank.question_keys(s["id"]), key=lambda key: (used.get(key, 0), rng.random())) for s in skills} + for skill_id in quota: # a skill with too few questions gives all it has; others take the slack + quota[skill_id] = min(quota[skill_id], len(pools[skill_id])) + slack = size - sum(quota.values()) + while slack > 0: + room = [i for i in quota if quota[i] < len(pools[i])] + if not room: + break + quota[min(room, key=lambda i: (quota[i], rng.random()))] += 1 + slack -= 1 + chosen = [{"skill_id": i, "key": key} for i in quota for key in pools[i][:quota[i]]] + rng.shuffle(chosen) + return chosen + + +def facts(store, bank, user_id: str, now, reads=None) -> dict[str, dict]: + """Per lesson the student has attempted: {best, attempts, open, last}. Overdue open attempts are settled first, so a quiz abandoned + past its deadline is graded from the answers given. `best` is None until an attempt is submitted.""" + from . import attempts + found: dict[str, dict] = {} + for row in (reads or store).attempts_of(user_id, "quiz"): + row = attempts.settle(store, bank, row, now) + item = found.setdefault(row["scope"], {"best": None, "attempts": 0, "open": None, "last": None}) + if attempts.is_open(row): + item["open"] = {"id": row["id"], "due_at": row["due_at"]} + continue + item["attempts"] += 1 + item["best"] = row["grade"] if item["best"] is None else max(item["best"], row["grade"]) + item["last"] = row["submitted_at"] + return found diff --git a/mathly2/quizzes.py b/mathly2/quizzes.py new file mode 100644 index 0000000000000000000000000000000000000000..6bec779a23580e53d5d0bb89206ff4ffd180360c --- /dev/null +++ b/mathly2/quizzes.py @@ -0,0 +1,166 @@ +"""Lesson quizzes and attempts: start a quiz, save answers, submit, read the result, list the grades. The server keeps the timer, +draws the questions and grades; it never says which choice was right.""" +from __future__ import annotations + +from collections import Counter +from datetime import timedelta + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel + +from . import attempts, clock, quiz, reads +from .access import learner +from .skills import visible_lesson_ids + +router = APIRouter(prefix="/api") + + +class AnswerBody(BaseModel): + key: str + choice: int + + +def _lesson(request: Request, user: dict, lesson_id: str) -> dict: + lesson = next((l for l in request.app.state.bank.lessons if l["id"] == lesson_id), None) + shown = visible_lesson_ids(request, user) + if lesson is None or (shown is not None and lesson_id not in shown): + raise HTTPException(404, "השיעור לא נמצא") + return lesson + + +def _lesson_name(request: Request, lesson_id: str) -> str: + return next((l["name"] for l in request.app.state.bank.lessons if l["id"] == lesson_id), lesson_id) + + +def _iso(value) -> str | None: + return value.isoformat() if value else None + + +def _test_info(request: Request, row: dict) -> dict: + """For an exercise test or a simulation: which real test it belongs to (and which exercise test).""" + test_id, _, number = row["scope"].partition(":") + test = request.app.state.store.get_test(int(test_id)) if test_id.isdigit() else None + names = [l["name"] for l in request.app.state.bank.lessons if test and l["id"] in test["lessons"]] + return {"id": int(test_id) if test_id.isdigit() else None, "number": int(number) if number.isdigit() else None, + "date": test["date"].isoformat() if test else None, "lessons": names, "minutes": test["minutes"] if test else None} + + +def view(request: Request, row: dict) -> dict: + """An open attempt: its questions (without right answers), the saved answers and the server's clock. A submitted one: its result. + A quiz carries its `lesson`; an exercise test or a simulation carries its `test`.""" + bank = request.app.state.bank + base = {"id": row["id"], "kind": row["kind"]} + if row["kind"] == "quiz": + base["lesson"] = {"id": row["scope"], "name": _lesson_name(request, row["scope"])} + else: + base["test"] = _test_info(request, row) + if attempts.is_open(row): + questions = [q for q in (bank.practice_question(r["skill_id"], r["key"]) for r in row["questions"]) if q] + return {**base, "state": "open", "due_at": _iso(row["due_at"]), "now": _iso(clock.now()), "answers": row["answers"], "questions": questions} + result = attempts.result(bank, row) + result.pop("lesson", None) + return {**base, "state": "submitted", **result, "submitted_at": _iso(row["submitted_at"])} + + +_view = view + + +def _mine(request: Request, user: dict, attempt_id: str) -> dict: + store = request.app.state.store + row = store.get_attempt(attempt_id) + if row is None or row["user_id"] != user["id"]: + raise HTTPException(404, "הבוחן לא נמצא") + return attempts.settle(store, request.app.state.bank, row, clock.now()) + + +@router.get("/lessons/{lesson_id}/quiz") +def quiz_facts(lesson_id: str, request: Request, user: dict = Depends(learner)) -> dict: + lesson = _lesson(request, user, lesson_id) + found = quiz.facts(request.app.state.store, request.app.state.bank, user["id"], clock.now()).get(lesson_id, {}) + open_ = found.get("open") + return {"lesson": {"id": lesson["id"], "name": lesson["name"]}, "best": found.get("best"), "attempts": found.get("attempts", 0), + "open": {"id": open_["id"], "due_at": _iso(open_["due_at"])} if open_ else None, + "size": attempts.QUIZ_SIZE, "minutes": attempts.QUIZ_MINUTES} + + +@router.post("/lessons/{lesson_id}/quiz/start") +def quiz_start(lesson_id: str, request: Request, user: dict = Depends(learner)) -> dict: + """Resume the open attempt of this lesson if there is one, otherwise draw a new quiz and start the clock.""" + _lesson(request, user, lesson_id) + store, bank, now = request.app.state.store, request.app.state.bank, clock.now() + mine = [attempts.settle(store, bank, r, now) for r in store.attempts_of(user["id"], "quiz", lesson_id)] + for row in mine: + if attempts.is_open(row): + return _view(request, row) + used = Counter(q["key"] for row in mine for q in row["questions"]) + drawn = quiz.draw(bank, lesson_id, used, getattr(request.app.state, "quiz_rng", None)) + if not drawn: + raise HTTPException(409, "אין עדיין שאלות לבוחן בשיעור הזה") + row = store.create_attempt(user["id"], "quiz", lesson_id, now, now + timedelta(minutes=attempts.QUIZ_MINUTES), drawn) + return _view(request, row) + + +@router.get("/attempts/{attempt_id}") +def attempt_read(attempt_id: str, request: Request, user: dict = Depends(learner)) -> dict: + return _view(request, _mine(request, user, attempt_id)) + + +@router.put("/attempts/{attempt_id}/answers") +def attempt_answer(attempt_id: str, body: AnswerBody, request: Request, user: dict = Depends(learner)) -> dict: + store, bank = request.app.state.store, request.app.state.bank + row = _mine(request, user, attempt_id) + if not attempts.is_open(row): + raise HTTPException(409, "הזמן נגמר והבוחן הוגש") + ref = next((q for q in row["questions"] if q["key"] == body.key), None) + if ref is None or bank.grade(ref["skill_id"], body.key, body.choice) is None: + raise HTTPException(422, "תשובה לא חוקית") + saved = store.save_attempt(row["id"], answers={**row["answers"], body.key: body.choice}) + return {"saved": len(saved["answers"]), "of": len(saved["questions"])} + + +@router.post("/attempts/{attempt_id}/submit") +def attempt_submit(attempt_id: str, request: Request, user: dict = Depends(learner)) -> dict: + row = _mine(request, user, attempt_id) + row = attempts.submit(request.app.state.store, request.app.state.bank, row, clock.now()) + return _view(request, row) + + +def _test_ref(request: Request, test: dict) -> dict: + names = [l["name"] for l in request.app.state.bank.lessons if l["id"] in test["lessons"]] + return {"id": test["id"], "date": test["date"].isoformat(), "lessons": names, "removed": bool(test["removed_at"])} + + +@router.get("/grades") +def grades(request: Request, user: dict = Depends(learner)) -> dict: + """Every grade the student has: each lesson's best quiz grade, each real test's exercise tests (best of each) and its simulation. + A removed test keeps its row, so the grades already earned stay.""" + store, bank, now, here, uid = request.app.state.store, request.app.state.bank, clock.now(), reads.of(request), user["id"] + here.prefetch(("attempts_of", uid, "quiz"), ("attempts_of", uid, "exercise_test"), ("attempts_of", uid, "simulation")) # one wait + found = quiz.facts(store, bank, uid, now, here) + lessons = [] + for lesson in bank.lessons: + item = found.get(lesson["id"]) + if item and item["best"] is not None: + lessons.append({"lesson": {"id": lesson["id"], "name": lesson["name"]}, "best": item["best"], "attempts": item["attempts"], + "last": _iso(item["last"])}) + groups: dict[tuple[str, str], list[dict]] = {} + for kind in ("exercise_test", "simulation"): + for row in here.attempts_of(uid, kind): + row = attempts.settle(store, bank, row, now) + if not attempts.is_open(row): + groups.setdefault((kind, row["scope"]), []).append(row) + exercise, simulations = [], [] + for (kind, scope), rows in groups.items(): + test_id, _, number = scope.partition(":") + test = store.get_test(int(test_id)) if test_id.isdigit() else None + if test is None: + continue + item = {"test": _test_ref(request, test), "best": max(r["grade"] for r in rows), "attempts": len(rows), + "last": _iso(max(r["submitted_at"] for r in rows))} + if kind == "exercise_test": + exercise.append({**item, "number": int(number)}) + else: + simulations.append(item) + exercise.sort(key=lambda g: (g["test"]["date"], g["test"]["id"], g["number"])) + simulations.sort(key=lambda g: (g["test"]["date"], g["test"]["id"])) + return {"quizzes": lessons, "exercise_tests": exercise, "simulations": simulations} diff --git a/mathly2/readiness.py b/mathly2/readiness.py new file mode 100644 index 0000000000000000000000000000000000000000..640216da892f2b65c4ae0e7a951baca8bfa59e15 --- /dev/null +++ b/mathly2/readiness.py @@ -0,0 +1,42 @@ +"""The readiness number for a real test (PRD RDY-1 to RDY-3): one 0-100 number from mastery, exercise tests and the simulation.""" +from __future__ import annotations + +WEIGHTS = {"M": 50, "E": 20, "S": 30} +CAP = 80 # the most the number can show before the simulation is taken + + +def label(number: int) -> str: + if number < 40: + return "מתחילים" + if number < 70: + return "בדרך" + if number < 85: + return "כמעט שם" + return "מוכנים" + + +def compute(m: float | None, e: float | None, s: float | None) -> dict: + """M: % of the covered skills mastered. E: average of the best grade of each exercise test taken. S: the simulation grade. + A part that does not exist is None and is left out; the others are scaled up. Without S the number is capped at 80.""" + parts = {"M": m, "E": e, "S": s} + have = {k: v for k, v in parts.items() if v is not None} + if not have: + number = 0 + else: + number = int(sum(WEIGHTS[k] * v for k, v in have.items()) / sum(WEIGHTS[k] for k in have) + 0.5) + capped = s is None and number > CAP + if s is None: + number = min(number, CAP) + number = max(0, min(100, number)) + return {"number": number, "label": label(number), "capped": capped, "waiting_for_simulation": s is None, + "parts": {k: (None if v is None else int(v + 0.5)) for k, v in parts.items()}} + + +def mastery_percent(mastered: int, covered: int) -> float | None: + """M: None when the test covers no skill with questions.""" + return None if covered <= 0 else 100 * mastered / covered + + +def exercise_average(best_grades: list[int]) -> float | None: + """E: the average of the best grade of each exercise test taken; None when none was taken.""" + return sum(best_grades) / len(best_grades) if best_grades else None diff --git a/mathly2/reads.py b/mathly2/reads.py new file mode 100644 index 0000000000000000000000000000000000000000..07b92d5a5ddf258dc07406d73010526d40238b26 --- /dev/null +++ b/mathly2/reads.py @@ -0,0 +1,62 @@ +"""Fewer waits for the database. A request that needs several facts asks for them together (`prefetch`: the ones that do not depend on +each other run at the same time), and a fact asked twice in one request is read once. Only reads go through here; a handler must not +read a fact again after writing it (it uses what it wrote).""" +from __future__ import annotations + +import threading +from concurrent.futures import ThreadPoolExecutor + +from fastapi import Request + +POOL = ThreadPoolExecutor(max_workers=16, thread_name_prefix="db") + +READS = frozenset({"classes_of_student", "classes_taught", "progress_of", "last_answered", "daily_correct", "recent_skills", "attempts_of", + "tests_of_classes", "get_progress", "answers_of", "reward_state", "comets_of", "members", "get_class", "get_test", "roles_of"}) + + +def _key(name: str, args: tuple) -> tuple: + return (name, tuple(tuple(sorted(a)) if isinstance(a, (list, set, frozenset)) else a for a in args)) + + +class Reads: + """The reads of one request, each done once. Thread safe: `prefetch` fills it from several threads.""" + + def __init__(self, store) -> None: + self.store = store + self._done: dict[tuple, object] = {} + self._lock = threading.Lock() + + def _read(self, name: str, *args): + key = _key(name, args) + with self._lock: + if key in self._done: + return self._done[key] + value = getattr(self.store, name)(*args) + with self._lock: + return self._done.setdefault(key, value) + + def __getattr__(self, name: str): + if name in READS: + return lambda *args: self._read(name, *args) + raise AttributeError(name) + + def prefetch(self, *calls: tuple) -> None: + """Start the reads (each `(name, *args)`) that are not done yet, together, and wait for all of them. The first error is raised.""" + missing = [] + with self._lock: + for call in calls: + if _key(call[0], call[1:]) not in self._done: + missing.append(call) + if len(missing) == 1: + self._read(missing[0][0], *missing[0][1:]) + elif missing: + for future in [POOL.submit(self._read, c[0], *c[1:]) for c in missing]: + future.result() + + +def of(request: Request) -> Reads: + """The request's reads (made on first use).""" + found = getattr(request.state, "reads", None) + if found is None: + found = request.state.reads = Reads(getattr(request.app.state, "store", None)) + return found diff --git a/mathly2/realtests.py b/mathly2/realtests.py new file mode 100644 index 0000000000000000000000000000000000000000..a07efe815bb3aaf346400e120dd4f2eddfe8c9f4 --- /dev/null +++ b/mathly2/realtests.py @@ -0,0 +1,302 @@ +"""Real tests: a teacher sets one for a class; every student of the class gets a countdown, two exercise tests, one simulation and a +readiness number from it. Nothing is created per student: it is all derived from the test, the student's skill states and their attempts.""" +from __future__ import annotations + +from datetime import date, timedelta +from datetime import date as Day + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel, Field + +from . import attempts, clock, countdown, exam, readiness, reads +from .access import allowed, learner, need +from .learning import MASTERED, next_skill, skill_state + +router = APIRouter(prefix="/api") + +LESSON_FIELDS = ("date", "lessons", "note", "questions", "minutes") + + +class TestBody(BaseModel): + date: Day + lessons: list[str] = Field(min_length=1, max_length=200) + note: str = Field(default="", max_length=500) + questions: int = Field(default=12, ge=1, le=40) + minutes: int = Field(default=45, ge=5, le=180) + + +class TestChange(BaseModel): + date: Day | None = None + lessons: list[str] | None = Field(default=None, min_length=1, max_length=200) + note: str | None = Field(default=None, max_length=500) + questions: int | None = Field(default=None, ge=1, le=40) + minutes: int | None = Field(default=None, ge=5, le=180) + + +# ---- what a test knows about one student ---- + +def lesson_names(request: Request, ids: list[str]) -> list[str]: + names = {l["id"]: l["name"] for l in request.app.state.bank.lessons} + return [names.get(i, i) for i in ids] + + +def _covered(bank, test: dict) -> list[str]: + """The skills the test covers that have questions, in the bank's order.""" + return [s["id"] for s in bank.skills if s["unit"] in test["lessons"] and bank.question_keys(s["id"])] + + +def _student_reads(user_id: str) -> list[tuple]: + return [("progress_of", user_id), ("last_answered", user_id), ("attempts_of", user_id, "exercise_test"), ("attempts_of", user_id, "simulation")] + + +def facts_for(request: Request, user_id: str | None, test: dict, today: date) -> dict: + """Everything the plan, the readiness meter and the draws need about one student and one test.""" + store, bank, now, here = request.app.state.store, request.app.state.bank, clock.now(), reads.of(request) + covered = _covered(bank, test) + if user_id: + here.prefetch(*_student_reads(user_id)) # the four reads together (done once per request: a second test reuses them) + states = {p["skill_id"]: skill_state(p) for p in here.progress_of(user_id)} if user_id else {} + last = here.last_answered(user_id) if user_id else {} + tid = str(test["id"]) + + def mine(kind: str) -> list[dict]: + rows = here.attempts_of(user_id, kind) if user_id else [] + return [attempts.settle(store, bank, r, now) for r in rows if r["scope"] == tid or r["scope"].startswith(tid + ":")] + + exercise = {1: [], 2: []} + for row in mine("exercise_test"): + exercise[int(row["scope"].split(":")[1])].append(row) + simulation = next(iter(mine("simulation")), None) + submitted = lambda rows: [r for r in rows if not attempts.is_open(r)] + best = {n: max((r["grade"] for r in submitted(rows)), default=None) for n, rows in exercise.items()} + weak_before = {s["id"] for rows in exercise.values() for r in submitted(rows) for s in attempts.result(bank, r)["lost_skills"]} + failed: list[str] = [] + review_left: list[str] = [] + if simulation and not attempts.is_open(simulation): + failed = [s["id"] for s in attempts.result(bank, simulation)["lost_skills"]] + sim_day = clock.school_day(simulation["submitted_at"]) + review_left = [i for i in failed if last.get(i) is None or last[i] <= sim_day] # not practised after the simulation + mastered = [i for i in covered if states.get(i) == MASTERED] + unmastered = [i for i in covered if states.get(i) != MASTERED] + sim_taken = bool(simulation and not attempts.is_open(simulation)) + stale = sorted(covered, key=lambda i: (last.get(i) is not None, last.get(i) or date.min)) + used: dict[str, int] = {} + for rows in list(exercise.values()) + [[simulation] if simulation else []]: + for r in rows: + for q in r["questions"]: + used[q["key"]] = used.get(q["key"], 0) + 1 + return {"covered": covered, "states": states, "mastered": len(mastered), "path_done": bool(covered) and not unmastered, + "next_path_skill": unmastered[0] if unmastered else None, "exercise": exercise, "best": best, "simulation": simulation, + "sim_taken": sim_taken, "ex1_done": bool(submitted(exercise[1])), "ex2_done": bool(submitted(exercise[2])), + "weak_before": weak_before, "failed": failed, "review_left": review_left, "stale": stale, "used": used} + + +def readiness_for(facts: dict) -> dict: + m = readiness.mastery_percent(facts["mastered"], len(facts["covered"])) + e = readiness.exercise_average([g for g in facts["best"].values() if g is not None]) + s = facts["simulation"]["grade"] if facts["sim_taken"] else None + return readiness.compute(m, e, s) + + +def plan_for(test: dict) -> dict: + return countdown.plan(test["date"], clock.school_day(test["created_at"])) + + +def card(request: Request, user_id: str | None, test: dict, today: date) -> dict: + """A test as its student sees it: the plan, readiness, both exercise tests, the simulation, and today's task.""" + bank = request.app.state.bank + facts = facts_for(request, user_id, test, today) + p = plan_for(test) + days_left = (test["date"] - today).days + exercises = [] + for n in (1, 2): + rows = facts["exercise"][n] + open_ = next((r for r in rows if attempts.is_open(r)), None) + exercises.append({"number": n, "best": facts["best"][n], "attempts": len([r for r in rows if not attempts.is_open(r)]), + "open": bool(open_), "due_at": open_["due_at"].isoformat() if open_ else None}) + sim = facts["simulation"] + opens_in = max(0, days_left - p["sim"]) + return {"id": test["id"], "date": test["date"].isoformat(), "days_left": days_left, "note": test["note"], + "lessons": [{"id": i, "name": n} for i, n in zip(test["lessons"], lesson_names(request, test["lessons"]))], + "questions": test["questions"], "minutes": test["minutes"], + "plan": countdown.outline(p, facts), "task": countdown.task(days_left, p, facts), "readiness": readiness_for(facts), + "exercise_tests": exercises, + "practice_first": [{"id": i, "name": bank.skill(i)["name"]} for i in facts["covered"] if facts["states"].get(i, "not_started") == "not_started"], + "simulation": {"open_now": countdown.sim_open(days_left, p), "opens_in_days": opens_in, + "opens_on": (test["date"] - timedelta(days=p["sim"])).isoformat(), "required": countdown.sim_open(days_left, p) and not facts["sim_taken"], + "taken": facts["sim_taken"], "grade": sim["grade"] if facts["sim_taken"] else None, + "attempt": sim["id"] if sim else None, "in_progress": bool(sim and attempts.is_open(sim)), + "review": [{"id": i, "name": bank.skill(i)["name"]} for i in facts["failed"] if bank.skill(i)]}} + + +# ---- the teacher: set, change, remove, and see who took the simulation ---- + +def _my_class(request: Request, user: dict, class_id: int) -> dict: + row = request.app.state.store.get_class(class_id) + if row is None or not (allowed(user["roles"], "*") or (row["teacher_email"] or "").lower() == user["email"]): + raise HTTPException(404, "הכיתה לא נמצאה") + return row + + +def _my_test(request: Request, user: dict, test_id: int) -> tuple[dict, dict]: + test = request.app.state.store.get_test(test_id) + if test is None or test["removed_at"]: + raise HTTPException(404, "המבחן לא נמצא") + return test, _my_class(request, user, test["class_id"]) + + +def _checked_lessons(klass: dict, lessons: list[str]) -> list[str]: + ids = list(dict.fromkeys(lessons)) + if not ids or any(i not in klass["lessons"] for i in ids): + raise HTTPException(422, "אפשר לבחור רק שיעורים של הכיתה") + return ids + + +def teacher_view(request: Request, test: dict, klass: dict, today: date) -> dict: + store, here = request.app.state.store, reads.of(request) + members = store.members(klass["id"]) + here.prefetch(*[call for m in members if m["user_id"] for call in _student_reads(m["user_id"])]) # every student's reads at once + students = [] + for m in members: + facts = facts_for(request, m["user_id"], test, today) + students.append({"email": m["email"], "signed_in": bool(m["user_id"]), "simulation_taken": facts["sim_taken"], + "readiness": readiness_for(facts)}) + taken = sum(1 for s in students if s["simulation_taken"]) + return {"id": test["id"], "class": {"id": klass["id"], "name": klass["name"]}, "date": test["date"].isoformat(), "note": test["note"], + "days_left": (test["date"] - today).days, "questions": test["questions"], "minutes": test["minutes"], + "lessons": [{"id": i, "name": n} for i, n in zip(test["lessons"], lesson_names(request, test["lessons"]))], + "simulation": {"taken": taken, "total": len(students), "missing": [s["email"] for s in students if not s["simulation_taken"]]}, + "students": students} + + +@router.get("/teaching/tests") +def teaching_tests(request: Request, user: dict = Depends(need("class.teach"))) -> list[dict]: + """The tests of the classes I teach (a developer sees every class), each with who took the simulation.""" + store, today = request.app.state.store, clock.school_day() + classes = store.classes() if allowed(user["roles"], "*") else store.classes_taught(user["email"]) + by_id = {c["id"]: c for c in classes} + return [{"class": {"id": c["id"], "name": c["name"], "lessons": [{"id": i, "name": n} for i, n in zip(c["lessons"], lesson_names(request, c["lessons"]))]}, + "tests": [teacher_view(request, t, c, today) for t in store.tests_of_classes([c["id"]])]} for c in by_id.values()] + + +@router.post("/classes/{class_id}/tests", status_code=201) +def set_test(class_id: int, body: TestBody, request: Request, user: dict = Depends(need("class.teach"))) -> dict: + klass = _my_class(request, user, class_id) + today = clock.school_day() + if body.date < today: + raise HTTPException(422, "תאריך המבחן כבר עבר") + lessons = _checked_lessons(klass, body.lessons) + test = request.app.state.store.create_test(class_id, body.date, lessons, user["email"], note=body.note.strip(), questions=body.questions, + minutes=body.minutes, created_at=clock.now()) + return teacher_view(request, test, klass, today) + + +@router.put("/tests/{test_id}") +def change_test(test_id: int, body: TestChange, request: Request, user: dict = Depends(need("class.teach"))) -> dict: + test, klass = _my_test(request, user, test_id) + today = clock.school_day() + if today >= test["date"]: + raise HTTPException(409, "אי אפשר לשנות מבחן ביום המבחן או אחריו") + fields = {k: v for k, v in body.model_dump().items() if v is not None} + if "date" in fields and fields["date"] < today: + raise HTTPException(422, "תאריך המבחן כבר עבר") + if "lessons" in fields: + fields["lessons"] = _checked_lessons(klass, fields["lessons"]) + if "note" in fields: + fields["note"] = fields["note"].strip() + updated = request.app.state.store.update_test(test_id, **fields) if fields else test + return teacher_view(request, updated, klass, today) + + +@router.delete("/tests/{test_id}", status_code=204) +def remove_test(test_id: int, request: Request, user: dict = Depends(need("class.teach"))) -> None: + _my_test(request, user, test_id) + request.app.state.store.remove_test(test_id, clock.now()) + + +# ---- the student: home and a test's card ---- + +def _with_skill_name(request: Request, task: dict) -> dict: + skill = request.app.state.bank.skill(task["skill"]) if task.get("skill") else None + return {**task, "skill_name": skill["name"] if skill else None} + + +def _next_path_skill(request: Request, user: dict) -> str | None: + """The suggested next skill of the student's path (the same rule as the path's owl).""" + from .skills import RECENT, visible_lesson_ids + bank, here = request.app.state.bank, reads.of(request) + shown = visible_lesson_ids(request, user) + order = [s["id"] for lesson in bank.lessons_with_skills() if shown is None or lesson["id"] in shown for s in lesson["skills"]] + states = {p["skill_id"]: skill_state(p) for p in here.progress_of(user["id"])} + return next_skill(order, states, here.recent_skills(user["id"], RECENT)) + + +@router.get("/home") +def home(request: Request, user: dict = Depends(learner)) -> dict: + """The student's home: the upcoming tests (nearest first) with their readiness, today's one task from the nearest test, + the required simulation, and the next skill of the path.""" + here, today, uid = reads.of(request), clock.school_day(), user["id"] + class_ids = [c["id"] for c in here.classes_of_student(user["email"])] + from .skills import RECENT + here.prefetch(("tests_of_classes", class_ids), ("recent_skills", uid, RECENT), *_student_reads(uid)) # the tests and the student's facts: one wait + tests = [t for t in here.tests_of_classes(class_ids) if t["date"] >= today] + cards = [card(request, user["id"], t, today) for t in tests] + nearest = cards[0] if cards else None + next_id = _next_path_skill(request, user) + next_skill_row = request.app.state.bank.skill(next_id) if next_id else None + return {"tests": cards, "task": {"test_id": nearest["id"], **_with_skill_name(request, nearest["task"])} if nearest else None, + "required_simulations": [{"test_id": c["id"], "date": c["date"], "days_left": c["days_left"]} for c in cards if c["simulation"]["required"]], + "next_skill": {"id": next_id, "name": next_skill_row["name"]} if next_skill_row else None} + + +def _student_test(request: Request, user: dict, test_id: int) -> dict: + here = reads.of(request) + test = here.get_test(test_id) + mine = {c["id"] for c in here.classes_of_student(user["email"])} + if test is None or test["removed_at"] or not (test["class_id"] in mine or allowed(user["roles"], "*")): + raise HTTPException(404, "המבחן לא נמצא") + return test + + +@router.get("/tests/{test_id}") +def test_card(test_id: int, request: Request, user: dict = Depends(learner)) -> dict: + reads.of(request).prefetch(("get_test", test_id), *_student_reads(user["id"])) + return card(request, user["id"], _student_test(request, user, test_id), clock.school_day()) + + +# ---- starting an exercise test or the simulation (reading, answering and submitting use the /api/attempts routes) ---- + +def _start(request: Request, user: dict, test: dict, kind: str, scope: str, share: float) -> dict: + """Resume the student's open attempt of this scope, else draw a new one (questions weighted toward weak skills when `share`).""" + from .quizzes import view + store, bank, now = request.app.state.store, request.app.state.bank, clock.now() + facts = facts_for(request, user["id"], test, clock.school_day()) + mine = [r for r in (facts["exercise"][int(scope.split(":")[1])] if kind == "exercise_test" else [facts["simulation"]] if facts["simulation"] else [])] + for row in mine: + if attempts.is_open(row) or kind == "simulation": # open: resume; the simulation is taken once, so its result comes back + return view(request, row) + drawn = exam.draw(bank, test["lessons"], facts["states"], test["questions"], share=share, weak_before=facts["weak_before"], used=facts["used"]) + if not drawn["questions"]: + raise HTTPException(409, "עוד לא התחלתם מיומנויות בשיעורים של המבחן. קודם מתרגלים במסלול.") + row = store.create_attempt(user["id"], kind, scope, now, now + timedelta(minutes=test["minutes"]), drawn["questions"]) + return view(request, row) + + +@router.post("/tests/{test_id}/exercise/{number}/start") +def start_exercise(test_id: int, number: int, request: Request, user: dict = Depends(learner)) -> dict: + if number not in exam.EXERCISE_SHARE: + raise HTTPException(404, "מבחן התרגול לא נמצא") + test = _student_test(request, user, test_id) + return _start(request, user, test, "exercise_test", f"{test_id}:{number}", exam.EXERCISE_SHARE[number]) + + +@router.post("/tests/{test_id}/simulation/start") +def start_simulation(test_id: int, request: Request, user: dict = Depends(learner)) -> dict: + test = _student_test(request, user, test_id) + today = clock.school_day() + p = plan_for(test) + existing = facts_for(request, user["id"], test, today)["simulation"] + if not existing and not countdown.sim_open(( test["date"] - today).days, p): + opens = test["date"] - timedelta(days=p["sim"]) + raise HTTPException(409, f"מבחן הסימולציה ייפתח ב־{opens.day}.{opens.month}" if today < opens else "מבחן הסימולציה נסגר") + return _start(request, user, test, "simulation", str(test_id), 0.0) diff --git a/mathly2/scripts/content_gaps.py b/mathly2/scripts/content_gaps.py index 025be83d62613838aef78d8f36b32deff8e25ca5..47bffbf9ee0cf3a77d038227c2cf5ade09058c98 100644 --- a/mathly2/scripts/content_gaps.py +++ b/mathly2/scripts/content_gaps.py @@ -1,9 +1,8 @@ """List the content the bank still lacks. venv/bin/python -m mathly2.scripts.content_gaps [--min-questions N] -A skill needs: a worked example whose every step has "why this step?" choices, and faded examples -(field names below; build-skill-learning fixes the exact shape of their contents). -A lesson needs a quiz. A skill needs enough questions for similar questions and for retakes. -Mistakes should say which skill to go back to.""" +A skill needs: a solved example for the help button, and enough questions for "a different question" (practice, quizzes and tests +draw from them). Mistakes should say which skill to go back to. Lesson quizzes need no authored content: they are drawn from +the questions.""" from __future__ import annotations import argparse @@ -16,33 +15,20 @@ MIN_QUESTIONS = 10 def find_gaps(data: dict, min_questions: int = MIN_QUESTIONS) -> dict[str, list[str]]: gaps: dict[str, list[str]] = { - "skills without a worked example": [], - "worked-example steps without 'why this step?' choices": [], - "skills without faded examples": [], - "lessons without a quiz": [], + "skills without a solved example": [], "skills without questions": [], f"skills with fewer than {min_questions} questions": [], "mistakes without a skill to go back to": [], } for skill in data["skills"]: sid = skill["id"] - example = skill.get("worked_example") - if not example: - gaps["skills without a worked example"].append(sid) - else: - for number, step in enumerate(example.get("steps", []), 1): - if not step.get("why"): - gaps["worked-example steps without 'why this step?' choices"].append(f"{sid} step {number}") - if not skill.get("faded_examples"): - gaps["skills without faded examples"].append(sid) + if not skill.get("worked_example"): + gaps["skills without a solved example"].append(sid) count = len(skill.get("questions", [])) if count == 0: gaps["skills without questions"].append(sid) elif count < min_questions: gaps[f"skills with fewer than {min_questions} questions"].append(f"{sid} ({count})") - for lesson in data["units"]: - if not lesson.get("quiz"): - gaps["lessons without a quiz"].append(lesson["id"]) for mid, mistake in data["mistakes"].items(): if not mistake.get("back"): gaps["mistakes without a skill to go back to"].append(mid) diff --git a/mathly2/scripts/draft_examples.py b/mathly2/scripts/draft_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..2ed1c0dd71bff638001ede870e1b23e76121f3b4 --- /dev/null +++ b/mathly2/scripts/draft_examples.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +"""Draft the solved example for the help button, for the skills of a lesson, for a teacher to review, and merge the approved ones. + +The "?" help of a skill shows its explanation and, where the bank has one, a solved example: one question solved in steps (what +is done, and why) with its answer. No skill has one yet. Students never call the AI, so the examples are written in advance: + + draft asks Claude for one solved example per skill of a lesson that lacks one, checks each with the same rules the bank is + loaded with, and writes them to a REVIEW FILE. It never touches the bank, and it spends API money (one request per + skill: use --dry-run to see what it would send). + merge puts the drafts a teacher approved into the bank. A draft is approved when its entry in the review file has + "approved": true and the teacher's name in "reviewed_by". The teacher may edit an example in the review file + first: what is merged is what the file says, after the bank's own checks. + + venv/bin/python -m mathly2.scripts.draft_examples draft --lesson t --dry-run + venv/bin/python -m mathly2.scripts.draft_examples draft --lesson t # writes mathly2/content/drafts/t.json + (the teacher reads that file, fixes what is wrong, and marks the good ones approved) + venv/bin/python -m mathly2.scripts.draft_examples merge mathly2/content/drafts/t.json + +Needs ANTHROPIC_API_KEY (or CLAUDE_API_KEY) for `draft`; MATH_MODEL picks the model. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +from datetime import date +from pathlib import Path + +from mathly2.bank import BANK_PATH, check_bank, example_problems, load_bank + +DRAFTS_DIR = BANK_PATH.parent / "drafts" +DEFAULT_MODEL = "claude-opus-5-5" +SAMPLE_QUESTIONS = 6 # practice questions shown to the model per skill +STATUS = "טיוטה: עוד לא נבדקה על ידי מורה. סמנו approved ושם ב־reviewed_by רק אחרי שבדקתם את הדוגמה." + + +class DraftUnavailable(Exception): + """The model could not give a draft; the message says why.""" + + +# Anthropic rejects numerical constraints in output schemas (minItems...): bank.example_problems checks them. +EXAMPLE_SCHEMA = { + "type": "object", "additionalProperties": False, "required": ["worked_example"], + "properties": {"worked_example": { + "type": "object", "additionalProperties": False, "required": ["question", "steps", "answer"], + "properties": { + "question": {"type": "string"}, "answer": {"type": "string"}, + "steps": {"type": "array", "items": { + "type": "object", "additionalProperties": False, "required": ["do", "why"], + "properties": {"do": {"type": "string"}, "why": {"type": "string"}}}}}}}} + +SYSTEM = """אתם מורים למתמטיקה לכיתה ט׳ וכותבים דוגמה פתורה אחת למיומנות אחת במסלול תרגול. +תלמיד שנתקע יפתח את העזרה, יקרא את הדוגמה, ילמד ממנה את השיטה ויחזור לשאלות התרגול של המיומנות. +כתבו שאלה חדשה משלכם באותה רמה ובאותו סגנון של שאלות התרגול. היא לא יכולה להיות אחת מהן, וגם לא אחת מהן עם שינוי קל של המספרים. +פתרו אותה בשלבים קצרים (בין שלושה לשישה). בכל שלב: do הוא מה עושים ומה יוצא, ו־why הוא הסיבה, הרעיון שמאחורי הצעד, +ולא חזרה על ה־do במילים אחרות. אם הטעויות הנפוצות שבהמשך רלוונטיות, הראו בשלב המתאים איך נמנעים מהן. +בסוף כתבו את התשובה בקצרה, ובדקו אותה: חשבו כל שלב פעם נוספת לפני שאתם כותבים אותו. +כתבו בעברית. נוסחאות בין סימני דולר, כמו בשאלות התרגול: $(x + 3)(x − 5)$. השתמשו במינוס ״−״ ובחזקה ״²״ כמו בהן. +החזירו רק את הדוגמה במבנה שנדרש.""" + + +def skills_without_examples(data: dict, lesson_id: str) -> list[dict]: + return [s for s in data["skills"] if s["unit"] == lesson_id and not s.get("worked_example")] + + +def skill_brief(skill: dict, mistakes: dict) -> dict: + """What the model sees of a skill: its description, some practice questions with the right answer, and the + common mistakes that those questions' wrong choices stand for (names and tips, to show how to avoid them).""" + questions, known = [], {} + for q in skill.get("questions", [])[:SAMPLE_QUESTIONS]: + right = next((c["text"] for c in q["choices"] if c.get("correct")), "") + slips = [] + for c in q["choices"]: + if c.get("mistake") in mistakes: + known[c["mistake"]] = {"name": mistakes[c["mistake"]]["name"], "tip": mistakes[c["mistake"]]["tip"]} + slips.append({"answer": c["text"], "mistake": mistakes[c["mistake"]]["name"]}) + questions.append({"question": q["question"], "right_answer": right, "wrong_answers": slips}) + return {"skill": skill["name"], "description": skill.get("description", ""), "practice_questions": questions, + "common_mistakes": list(known.values())} + + +def clean(answer: dict) -> dict: + """The model's answer in the bank's shape.""" + worked = answer["worked_example"] + return {"worked_example": {"question": worked["question"], "answer": worked["answer"], + "steps": [{"do": s["do"], "why": s["why"]} for s in worked["steps"]]}} + + +def draft_one(client, model: str, skill: dict, mistakes: dict) -> dict: + """A solved example for a skill; raises DraftUnavailable if the model could not give one.""" + import anthropic + try: + response = client.messages.create( + model=model, max_tokens=8000, system=SYSTEM, + output_config={"effort": "high", "format": {"type": "json_schema", "schema": EXAMPLE_SCHEMA}}, + messages=[{"role": "user", "content": json.dumps(skill_brief(skill, mistakes), ensure_ascii=False)}]) + except anthropic.APIError as exc: + raise DraftUnavailable(f"{type(exc).__name__}: {getattr(exc, 'message', exc)}") from exc + if response.stop_reason != "end_turn": + raise DraftUnavailable(f"stop_reason={response.stop_reason}") + try: + return clean(json.loads(next(b.text for b in response.content if b.type == "text"))) + except (ValueError, StopIteration, KeyError, TypeError) as exc: + raise DraftUnavailable("the answer was not the expected JSON") from exc + + +def draft_lesson(client, model: str, data: dict, lesson_id: str, only: list[str] | None = None, + limit: int | None = None) -> dict: + """The review file's content for a lesson: a draft (and what is wrong with it, if anything) per skill without one.""" + wanted = [s for s in skills_without_examples(data, lesson_id) if not only or s["id"] in only] + drafts = {} + for skill in wanted[:limit]: + entry = {"approved": False, "reviewed_by": "", "example": None, "problems": []} + try: + entry["example"] = draft_one(client, model, skill, data["mistakes"]) + entry["problems"] = example_problems({**skill, **entry["example"]}, data["mistakes"]) + except DraftUnavailable as exc: + entry["problems"] = [f"no draft: {exc}"] + drafts[skill["id"]] = entry + return {"status": STATUS, "model": model, "lesson": lesson_id, "drafted": date.today().isoformat(), "drafts": drafts} + + +def merge_approved(review: dict, data: dict) -> tuple[dict, list[str], list[str]]: + """The bank data with the approved drafts added, the ids merged, and why any others were left out.""" + merged, skipped = [], [] + skills = {s["id"]: s for s in data["skills"]} + for sid, entry in review.get("drafts", {}).items(): + example = entry.get("example") or {} + if not entry.get("approved"): + skipped.append(f"{sid}: not approved") + elif not str(entry.get("reviewed_by") or "").strip(): + skipped.append(f"{sid}: approved without the reviewer's name (reviewed_by)") + elif sid not in skills: + skipped.append(f"{sid}: no such skill") + elif skills[sid].get("worked_example"): + skipped.append(f"{sid}: already has a solved example") + elif not example.get("worked_example"): + skipped.append(f"{sid}: the draft has no solved example") + elif found := example_problems({**skills[sid], **example}, data["mistakes"]): + skipped.append(f"{sid}: {'; '.join(found)}") + else: + skills[sid]["worked_example"] = example["worked_example"] + merged.append(sid) + return data, merged, skipped + + +def write_bank(data: dict, path: Path | None = None) -> None: + """Write the bank in the file's own format. The path is looked up now, not when this module is loaded.""" + (path or BANK_PATH).write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") # the file's own format + + +def cmd_draft(args) -> int: + data = load_bank().data + if not any(u["id"] == args.lesson for u in data["units"]): + print(f"no lesson {args.lesson}: " + ", ".join(u["id"] for u in data["units"]), file=sys.stderr) + return 2 + todo = [s for s in skills_without_examples(data, args.lesson) if not args.skill or s["id"] in args.skill][:args.limit] + model = os.environ.get("MATH_MODEL", "").strip() or DEFAULT_MODEL + print(f"lesson {args.lesson}: {len(todo)} skills without a solved example: {', '.join(s['id'] for s in todo) or '-'}") + if args.dry_run or not todo: + if todo: + print("\nsystem prompt:\n" + SYSTEM + "\n\nfirst request:\n" + + json.dumps(skill_brief(todo[0], data["mistakes"]), ensure_ascii=False, indent=1)) + print(f"\n(dry run: {len(todo)} requests would be sent to {model}; nothing was sent)") + return 0 + key = os.environ.get("ANTHROPIC_API_KEY", "").strip() or os.environ.get("CLAUDE_API_KEY", "").strip() + if not key: + print("set ANTHROPIC_API_KEY (or CLAUDE_API_KEY)", file=sys.stderr) + return 2 + out = Path(args.out) if args.out else DRAFTS_DIR / f"{args.lesson}.json" + if out.exists() and not args.force: + print(f"{out} exists: it may hold a teacher's review. Use --force to overwrite, or --out for another file.", file=sys.stderr) + return 2 + import anthropic + review = draft_lesson(anthropic.Anthropic(api_key=key, timeout=120.0, max_retries=1), model, data, args.lesson, + args.skill, args.limit) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(review, ensure_ascii=False, indent=1) + "\n", encoding="utf-8") + bad = [sid for sid, e in review["drafts"].items() if e["problems"]] + print(f"wrote {out}: {len(review['drafts'])} drafts, {len(bad)} with problems{': ' + ', '.join(bad) if bad else ''}") + return 0 + + +def cmd_merge(args) -> int: + review = json.loads(Path(args.review).read_text(encoding="utf-8")) + data = json.loads(BANK_PATH.read_text(encoding="utf-8")) + data, merged, skipped = merge_approved(review, data) + for line in skipped: + print("left out: " + line) + if not merged: + print("nothing to merge") + return 1 + if found := check_bank(data): # the app loads the bank with this check: never write what it would refuse + print("refusing to write, the bank would not load: " + "; ".join(found), file=sys.stderr) + return 2 + write_bank(data) + print(f"added solved examples to {BANK_PATH.name}: {', '.join(merged)}") + return 0 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = parser.add_subparsers(dest="command", required=True) + d = sub.add_parser("draft", help="ask Claude for drafts and write a review file") + d.add_argument("--lesson", required=True) + d.add_argument("--skill", action="append", help="only this skill (repeat for several)") + d.add_argument("--limit", type=int, help="at most this many skills") + d.add_argument("--out", help="the review file (default mathly2/content/drafts/.json)") + d.add_argument("--force", action="store_true", help="overwrite an existing review file") + d.add_argument("--dry-run", action="store_true", help="show what would be sent; call nothing") + d.set_defaults(run=cmd_draft) + m = sub.add_parser("merge", help="add the approved drafts of a review file to the bank") + m.add_argument("review") + m.set_defaults(run=cmd_merge) + args = parser.parse_args(argv) + return args.run(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/mathly2/skills.py b/mathly2/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..69ff2af0a7f4d1e195412e9ad1b7c4201970cddd --- /dev/null +++ b/mathly2/skills.py @@ -0,0 +1,264 @@ +"""Practicing a skill: the question on screen, answers and help, the path and the collection. +The server decides right and wrong, the day, and mastery; the browser never receives which choice is correct +for a practice question.""" +from __future__ import annotations + +from fastapi import APIRouter, Depends, HTTPException, Request +from pydantic import BaseModel + +from . import clock, comets, quiz, reads +from .access import learner +from .learning import (DAILY_GOAL, MASTERED, current_round, is_faded, is_mastered, last_counted, next_in_round, next_skill, skill_state, streak, + today_progress) + +router = APIRouter(prefix="/api") +RECENT = 30 # how many recently answered skills the "next skill" looks at + + +class Answer(BaseModel): + question_key: str + choice: int + + +def _skill(request: Request, skill_id: str) -> dict: + skill = request.app.state.bank.skill(skill_id) + if not skill: + raise HTTPException(404, "המיומנות לא נמצאה") + return skill + + +def _run(rows: list[dict]) -> int: + """Correct answers in a row (up to 3) among the answers that count for mastery.""" + run = 0 + for answer in reversed(last_counted(rows)): + if not answer["correct"]: + break + run += 1 + return run + + +def _current_question(request: Request, user: dict, skill_id: str, progress: dict | None, rows: list[dict]) -> tuple[dict | None, dict | None]: + """The question on screen, picked and remembered if there is none. (served question or None when the round is done, progress) + A student who practised before rounds existed begins a new round: their earlier answers are past rounds.""" + bank, store = request.app.state.bank, request.app.state.store + keys = bank.practice_keys(skill_id) + if not keys: + return None, progress + start = progress.get("round_start") if progress else None + rnd = current_round(keys, rows, start) + if rnd["done"]: + return None, progress + key = progress["current_key"] if progress else None + if key not in rnd["left"] or start is None: + key = next_in_round(rnd["left"]) + progress = store.save_progress(user["id"], skill_id, current_key=key, current_helped=False, + **({"round_start": len(rows)} if start is None else {})) + return bank.practice_question(skill_id, key), progress + + +def _named(bank, ids: list[str]) -> list[dict]: + return [{"id": i, "name": bank.skill(i)["name"]} for i in ids if bank.skill(i)] + + +def _round_view(request: Request, skill_id: str, rows: list[dict], round_start: int | None) -> dict: + """Where the student is in the round: how many answered, a result per answer, and when it is done, how it went (never the right answers).""" + bank = request.app.state.bank + keys = bank.practice_keys(skill_id) + rnd = current_round(keys, rows, round_start) + results = [r["correct"] for r in rnd["answers"]] + view = {"total": len(keys), "answered": len(results), "results": results, "done": rnd["done"], "result": None} + if rnd["done"]: + missed = [] + for r in rnd["answers"]: + if r["correct"]: + continue + served = bank.practice_question(skill_id, r["question_key"]) + mistake = bank.mistake(r.get("mistake_id")) + back = bank.skill(mistake["back"]) if mistake and mistake["back"] else None + missed.append({"question": served["question"] if served else "", "mistake": {"name": mistake["name"], "tip": mistake["tip"]} if mistake else None, + "back": {"id": back["id"], "name": back["name"]} if back and back["id"] != skill_id else None}) + view["result"] = {"right": sum(results), "total": len(keys), "missed": missed} + return view + + +def visible_lesson_ids(request: Request, user: dict) -> set[str] | None: + """The lessons the student can see: those of their classes. None means all (a teacher or a developer).""" + if set(user["roles"]) - {"student"}: + return None + return {lesson for c in reads.of(request).classes_of_student(user["email"]) for lesson in c["lessons"]} + + +@router.get("/skills/{skill_id}") +def open_skill(skill_id: str, request: Request, user: dict = Depends(learner)) -> dict: + bank, here = request.app.state.bank, reads.of(request) + skill, uid = _skill(request, skill_id), user["id"] + here.prefetch(("get_progress", uid, skill_id), ("answers_of", uid, skill_id), ("daily_correct", uid)) # one wait for all three + rows = here.answers_of(uid, skill_id) + question, progress = _current_question(request, user, skill_id, here.get_progress(uid, skill_id), rows) + lesson = next(l for l in bank.lessons if l["id"] == skill["unit"]) + return { + "id": skill_id, "name": skill["name"], "description": skill.get("description", ""), + "lesson": {"id": lesson["id"], "name": lesson["name"]}, + "state": skill_state(progress), "question": question, "practice_available": bool(bank.question_keys(skill_id)), + "round": _round_view(request, skill_id, rows, progress.get("round_start") if progress else None), + "correct_in_row": _run(rows), + "requires": _named(bank, skill.get("prereqs", [])), + "opens": _named(bank, [s["id"] for s in bank.skills if skill_id in s.get("prereqs", [])]), + "help": {"explanation": skill.get("description", ""), "solved_example": skill.get("worked_example")}, + "today": today_progress(here.daily_correct(uid), clock.school_day()), + } + + +@router.post("/skills/{skill_id}/help") +def open_help(skill_id: str, request: Request, user: dict = Depends(learner)) -> dict: + """The student opened help for the question on screen: that answer will not count for mastery.""" + _skill(request, skill_id) + request.app.state.store.save_progress(user["id"], skill_id, current_helped=True) + return {"ok": True} + + +@router.post("/skills/{skill_id}/answer") +def answer(skill_id: str, body: Answer, request: Request, user: dict = Depends(learner)) -> dict: + """Grade one practice answer. The waits: the reads together, the answer written, the progress written once.""" + bank, store, here = request.app.state.bank, request.app.state.store, reads.of(request) + _skill(request, skill_id) + uid, today, now = user["id"], clock.school_day(), clock.now().isoformat() + here.prefetch(("get_progress", uid, skill_id), ("answers_of", uid, skill_id), ("daily_correct", uid), ("reward_state", uid)) + progress = here.get_progress(uid, skill_id) + if not progress or progress["current_key"] != body.question_key: + raise HTTPException(409, "השאלה הזו כבר לא על המסך") + graded = bank.grade(skill_id, body.question_key, body.choice) + if graded is None: + raise HTTPException(422, "תשובה לא חוקית") + + correct, counted = graded["correct"], not progress["current_helped"] + mistake_id = graded["mistake"]["id"] if graded["mistake"] else None + store.add_answer(uid, skill_id, body.question_key, correct, counted, mistake_id, today) + before = here.answers_of(uid, skill_id) + rows = before + [{"question_key": body.question_key, "correct": correct, "counted": counted, "day": today, "mistake_id": mistake_id}] + start = progress.get("round_start") + if start is None: # practised before rounds: this answer begins one + start = len(before) + was_mastered = bool(progress.get("mastered_at")) + mastered_now = not was_mastered and is_mastered(last_counted(rows)) + rnd = current_round(bank.practice_keys(skill_id), rows, start) + following = next_in_round(rnd["left"], body.question_key) # None when the round is done: no question comes back + changes = {"current_key": following, "current_helped": False, "round_start": start} + if not progress.get("started_at"): + changes["started_at"] = now # a first answer moves a skill out of "not started" + if mastered_now: + changes["mastered_at"] = now + progress = store.save_progress(uid, skill_id, **changes) # one write, with everything this answer changed + + mistake = graded["mistake"] + if mistake and mistake["back"]: + back = bank.skill(mistake["back"]) + mistake = {**mistake, "back_name": back["name"] if back else None} + daily = dict(here.daily_correct(uid)) + if correct: + daily[today] = daily.get(today, 0) + 1 + today_now = today_progress(daily, today) + return { + "comet": correct and _comet_due(request, uid, today_now, here.reward_state(uid)), + "correct": correct, "mistake": mistake, + "state": skill_state(progress), "mastered_now": mastered_now, + "correct_in_row": _run(rows), "round": _round_view(request, skill_id, rows, start), + "next_question": bank.practice_question(skill_id, following) if following else None, + "today": today_now, + } + + +@router.post("/skills/{skill_id}/round") +def new_round(skill_id: str, request: Request, user: dict = Depends(learner)) -> dict: + """"סבב חדש": after a finished round, all the skill's practice questions again in a new order. Before the round is done it changes nothing.""" + bank, store, here = request.app.state.bank, request.app.state.store, reads.of(request) + _skill(request, skill_id) + uid = user["id"] + here.prefetch(("get_progress", uid, skill_id), ("answers_of", uid, skill_id)) + keys, rows, progress = bank.practice_keys(skill_id), here.answers_of(uid, skill_id), here.get_progress(uid, skill_id) + if keys and current_round(keys, rows, progress.get("round_start") if progress else None)["done"]: + store.save_progress(uid, skill_id, round_start=len(rows), current_key=next_in_round(keys), current_helped=False) + return {"ok": True} + + +def _comet_due(request: Request, user_id: str, today_now: dict, state: dict | None) -> bool: + """After a right answer: does a comet cross? The day is stored at once, so a reload cannot bring a second one. The caught comets are + read only when one could really be due (the first goal of all, or a lucky roll on a day without one).""" + store, today = request.app.state.store, clock.school_day() + roll_of = getattr(request.app.state, "comet_roll", None) + roll = roll_of() if roll_of else None + reached_now = today_now["done"] == DAILY_GOAL # this answer was the fifth right one of the day + if comets.surely_not(state, today, reached_now, roll): + return False + if not comets.due(state, reads.of(request).comets_of(user_id), today, reached_now, roll if roll is not None else 0.0): + return False + store.save_reward_state(user_id, last_comet_day=today) + return True + + +@router.get("/path") +def path(request: Request, user: dict = Depends(learner)) -> dict: + store, here, uid = request.app.state.store, reads.of(request), user["id"] + here.prefetch(("progress_of", uid), ("last_answered", uid), ("daily_correct", uid), ("recent_skills", uid, RECENT), ("attempts_of", uid, "quiz")) + states = {p["skill_id"]: skill_state(p) for p in here.progress_of(uid)} + last, today = here.last_answered(uid), clock.school_day() + quizzes_facts = quiz.facts(store, request.app.state.bank, uid, clock.now(), here) + shown = visible_lesson_ids(request, user) + lessons, order = [], [] + for lesson in request.app.state.bank.lessons_with_skills(): + if shown is not None and lesson["id"] not in shown: + continue + skills = [{"id": s["id"], "name": s["name"], "short": s["short"], "state": states.get(s["id"], "not_started"), + "faded": is_faded(states.get(s["id"], "not_started"), last.get(s["id"]), today)} + for s in lesson["skills"]] + order += [s["id"] for s in skills] + mastered = sum(1 for s in skills if s["state"] == MASTERED) + fact = quizzes_facts.get(lesson["id"], {}) + lessons.append({"id": lesson["id"], "name": lesson["name"], "skills": skills, "mastered": mastered, + "completed": bool(skills) and mastered == len(skills), + "quiz": {"best": fact.get("best"), "open": bool(fact.get("open")), "due_at": fact["open"]["due_at"].isoformat() if fact.get("open") else None}}) + daily = here.daily_correct(uid) + return {"lessons": lessons, "next": next_skill(order, states, here.recent_skills(uid, RECENT)), + "today": today_progress(daily, today), "streak": streak(daily, today)} + + +@router.get("/collection") +def collection(request: Request, user: dict = Depends(learner)) -> dict: + bank, here, uid = request.app.state.bank, reads.of(request), user["id"] + here.prefetch(("progress_of", uid), ("last_answered", uid)) + mastered_at = {p["skill_id"]: p["mastered_at"] for p in here.progress_of(uid) if p.get("mastered_at")} + names = {lesson["id"]: lesson["name"] for lesson in bank.lessons} + last, today = here.last_answered(uid), clock.school_day() + skills = [{"id": s["id"], "name": s["name"], "lesson_id": s["unit"], "lesson_name": names[s["unit"]], + "mastered_at": mastered_at[s["id"]], "faded": is_faded(MASTERED, last.get(s["id"]), today)} + for s in bank.skills if s["id"] in mastered_at] + lessons = [] + for lesson in bank.lessons: + ids = [s["id"] for s in bank.skills if s["unit"] == lesson["id"]] + if ids and all(i in mastered_at for i in ids): + lessons.append({"id": lesson["id"], "name": lesson["name"], "skills": len(ids)}) + return {"skills": skills, "lessons": lessons} + + +@router.get("/comets") +def comet_list(request: Request, user: dict = Depends(learner)) -> dict: + """The twelve comets: the ones the student caught come with their symbol, name and fact; the others only their place.""" + caught = request.app.state.store.comets_of(user["id"]) + return {"comets": [{**c, "caught": True} if c["id"] in caught else {"id": c["id"], "caught": False} for c in comets.COMETS], + "caught": len(caught), "total": len(comets.COMETS)} + + +@router.post("/comets/catch") +def comet_catch(request: Request, user: dict = Depends(learner)) -> dict: + """Catch the comet that crossed today: one catch per crossing, a comet the student does not have, picked by the server.""" + store, today = request.app.state.store, clock.school_day() + state = store.reward_state(user["id"]) or {} + if state.get("last_comet_day") != today or state.get("last_catch_day") == today: + raise HTTPException(409, "אין שביט לתפוס") + roll = getattr(request.app.state, "comet_roll", None) + comet = comets.pick(store.comets_of(user["id"]), roll() if roll else None) + if comet is None: + raise HTTPException(409, "אין שביט לתפוס") + store.add_comet(user["id"], comet["id"]) + store.save_reward_state(user["id"], last_catch_day=today) + return {"comet": comet} diff --git a/mathly2/static/access.js b/mathly2/static/access.js new file mode 100644 index 0000000000000000000000000000000000000000..f5cb499bb2dcccdcf83ea522de14abee55050c1f --- /dev/null +++ b/mathly2/static/access.js @@ -0,0 +1,11 @@ +// "My access": the signed-in account's own roles and what each allows (open to every account). +import { esc } from "./math.js"; +import { ROLE_ALLOWS, ROLE_NAMES, visibleRoles } from "./roles.js"; + +export async function show(me, view) { + const held = visibleRoles(me.roles).filter(role => me.roles.includes(role)); + view(`

ההרשאות שלי

+

${esc(me.email)}

+
    ${held.map(role => `
  • ${ROLE_NAMES[role]}${ROLE_ALLOWS[role]}
  • `).join("")}
+ ${me.roles.includes("developer") ? "" : `

תפקיד חדש נותן מנהל ההרשאות.

`}
`); +} diff --git a/mathly2/static/admin.js b/mathly2/static/admin.js new file mode 100644 index 0000000000000000000000000000000000000000..24ca846d657584d49558ef12342fb04d2a8ef619 --- /dev/null +++ b/mathly2/static/admin.js @@ -0,0 +1,44 @@ +// The admin's screen: the accounts the app knows, with their roles; give a role to any email (even one that never signed in) or take it away. +import { api } from "./api.js"; +import { esc } from "./math.js"; +import { ROLE_NAMES } from "./roles.js"; + +const GRANTABLE = ["student", "teacher", "manager", "admin"]; +let draw; + +async function showAccounts(message = "", error = "") { + const accounts = await api("/api/accounts"); + draw(`

תפקידים

+

מתן תפקיד

+

אפשר להקליד גם כתובת שעוד לא נכנסה לאפליקציה: התפקיד יחול מהכניסה הראשונה שלה. שינוי תפקיד נקלט תוך כחצי דקה.

+
+ + ${error ? `` : ""}${message ? `

${esc(message)}

` : ""} +

+
+ ${accounts.map(a => ` + + `).join("")}
חשבוןתפקידים שניתנומההגדרות
${esc(a.email)}${a.roles.map(r => `${ROLE_NAMES[r]} `).join(" ") || '—'}${a.from_settings.map(r => `${ROLE_NAMES[r]}`).join(" ") || '—'}
`); + document.getElementById("give").addEventListener("submit", async event => { + event.preventDefault(); + const email = document.getElementById("g-email").value.trim(), role = document.getElementById("g-role").value; + try { + await api(`/api/accounts/${encodeURIComponent(email)}/roles/${role}`, { method: "POST" }); + await showAccounts(`${email}: ניתן התפקיד ${ROLE_NAMES[role]}.`); + } catch (e) { await showAccounts("", e.message); } + }); + document.querySelector("#accounts tbody").addEventListener("click", async event => { + const role = event.target.closest("[data-take]")?.dataset.take; + if (!role) return; + const email = event.target.closest("tr").dataset.email; + try { + await api(`/api/accounts/${encodeURIComponent(email)}/roles/${role}`, { method: "DELETE" }); + await showAccounts(`${email}: התפקיד ${ROLE_NAMES[role]} הוסר.`); + } catch (e) { await showAccounts("", e.message); } + }); +} + +export async function show(me, view) { + draw = view; + await showAccounts(); +} diff --git a/mathly2/static/app.css b/mathly2/static/app.css index 3e63d5b3b25c2c64b5fb30cd2594e87a4709884a..e95430e2296d7cdcb061c99c4e20ff9b85620e5c 100644 --- a/mathly2/static/app.css +++ b/mathly2/static/app.css @@ -1,23 +1,31 @@ -/* Phone first: the base styles fit 360px; wider layouts are added with min-width queries. */ +/* Phone first: the base styles fit 360px; wider layouts are added with min-width queries. + One "sky" look for every screen: a night-blue sky with aurora and starlight, gold for mastery, an owl. The --sky-* tokens are + the source; the older names (--bg, --surface, ...) point at them so every screen follows the same look. */ :root { - --bg: #f7f8fb; --surface: #ffffff; --text: #1b2433; --muted: #5b6678; - --line: #d9dee8; --accent: #2557d6; --accent-text: #ffffff; --danger: #b3261e; - --gutter: 16px; --radius: 12px; -} -@media (prefers-color-scheme: dark) { - :root:not([data-theme="light"]) { - --bg: #11151c; --surface: #1a212c; --text: #e8ecf3; --muted: #9aa5b8; - --line: #2d3748; --accent: #7aa2ff; --accent-text: #0b1220; --danger: #ff8a80; - } -} -:root[data-theme="dark"] { - --bg: #11151c; --surface: #1a212c; --text: #e8ecf3; --muted: #9aa5b8; - --line: #2d3748; --accent: #7aa2ff; --accent-text: #0b1220; --danger: #ff8a80; + /* always dark, as in mathly1: there is no light set */ + --sky-bg: #060a19; --sky-surface: #121b3b; --sky-ink: #e9edfb; --sky-mute: #9aa6cf; --sky-line: #27335f; + --sky-accent: #8ea6ff; --sky-on-accent: #0b1220; --sky-aurora: #46e0c8; --sky-gold: #ffd166; --sky-danger: #ff9a7a; + --sky-night: #0e1532; --sky-star: #eaf0ff; --sky-glow: .32; + --sky-owl: #b88458; --sky-owl-belly: #f2d8b8; --sky-owl-eye: #fff7e6; --sky-owl-pupil: #1b2140; --sky-beak: #e08a1e; + --bg: var(--sky-bg); --surface: var(--sky-surface); --text: var(--sky-ink); --muted: var(--sky-mute); + --line: var(--sky-line); --accent: var(--sky-accent); --accent-text: var(--sky-on-accent); --danger: var(--sky-danger); + --gutter: 16px; --radius: 12px; color-scheme: dark; } +/* Nothing moves when the device asks for less motion. */ +@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } } * { box-sizing: border-box; } html, body { margin: 0; } body { - background: var(--bg); color: var(--text); + /* the sky: two soft glows as in mathly1, and small stars; nothing moves, so it needs no reduced-motion rule */ + background: + radial-gradient(1.5px 1.5px at 12% 20%, var(--sky-star), transparent), radial-gradient(1px 1px at 70% 35%, var(--sky-star), transparent), + radial-gradient(1.5px 1.5px at 40% 12%, var(--sky-star), transparent), radial-gradient(1px 1px at 88% 15%, var(--sky-star), transparent), + radial-gradient(1px 1px at 25% 60%, var(--sky-star), transparent), radial-gradient(1.5px 1.5px at 92% 70%, var(--sky-star), transparent), + radial-gradient(1px 1px at 55% 85%, var(--sky-star), transparent), radial-gradient(1px 1px at 6% 90%, var(--sky-star), transparent), + radial-gradient(120% 60% at 85% -10%, rgb(52 70 170 / var(--sky-glow)), transparent 60%), + radial-gradient(90% 50% at 0% 40%, rgb(120 60 160 / calc(var(--sky-glow) / 2)), transparent 70%), + var(--bg); + background-attachment: fixed; color: var(--text); font: 16px/1.5 system-ui, "Segoe UI", Arial, "Noto Sans Hebrew", sans-serif; overflow-x: hidden; } @@ -39,7 +47,7 @@ button, .button { border: 1px solid var(--line); background: var(--surface); color: var(--text); } button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); } -input, textarea { +input, textarea, select { font: inherit; width: 100%; padding: 10px 12px; border-radius: 10px; border: 1px solid var(--line); background: var(--bg); color: var(--text); } @@ -53,3 +61,312 @@ ul.plain li:last-child { border-bottom: 0; } .m { font-family: "STIX Two Math", "Cambria Math", serif; direction: ltr; unicode-bidi: isolate; white-space: nowrap; font-size: 1.05em; } .m.m-img { font-size: 1.12em; } .m-img svg { display: inline-block; overflow: visible; max-width: none; } + +/* Bank figures and graphs (figures.js). Always left-to-right: they are coordinates and letters. */ +.mx-figure, .mx-plot { direction: ltr; margin: 8px auto; width: 100%; max-width: 340px; text-align: center; } +.mx-figure svg, .mx-plot svg { display: block; width: 100%; height: auto; } +.mx-figure .s { stroke: var(--accent); stroke-width: 2.2; fill: none; stroke-linejoin: round; stroke-linecap: round; } +.mx-figure .d { stroke: var(--accent); stroke-width: 1.6; stroke-dasharray: 5 4; fill: none; } +.mx-figure .mk { stroke: var(--text); stroke-width: 1.4; fill: none; opacity: .75; } +.mx-figure .g, .mx-plot .g { stroke: var(--line); stroke-width: 1; } +.mx-figure .ax { stroke: var(--muted); stroke-width: 1.4; } +.mx-figure circle { fill: var(--accent); } +.mx-figure text { text-anchor: middle; fill: var(--text); font: 600 13px system-ui, sans-serif; } +.mx-figure .v { font-style: italic; font-weight: 700; font-size: 15px; } +.mx-figure .n { font-weight: 500; font-size: 9px; fill: var(--muted); } +.mx-figure .t { font-weight: 500; font-size: 13px; fill: var(--muted); } +.mx-figure p { margin: 2px 0 4px; font-weight: 600; } +.mx-figure small { font-size: 12px; color: var(--muted); } +.mx-plot .a { stroke: var(--muted); stroke-width: 1.5; } +.mx-plot .c { fill: none; stroke: var(--accent); stroke-width: 2.5; } +.mx-plot circle { fill: var(--accent); } +.mx-plot text { font: 11px system-ui, sans-serif; fill: var(--muted); } + +/* Student screens */ +.tabs { display: flex; gap: 8px; margin-block: 4px 0; } +.tabs a { flex: 1; text-align: center; padding: 10px; border: 1px solid var(--line); border-radius: 10px; text-decoration: none; color: var(--text); background: var(--surface); } +.tabs a[aria-current="page"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 700; } +.goal { display: flex; gap: 12px; align-items: center; background: var(--bg); border-radius: 10px; padding: 10px 12px; font-size: 14px; } +.grow { flex: 1; } +.bar { height: 8px; background: var(--line); border-radius: 4px; overflow: hidden; margin-top: 4px; } +.bar i { display: block; height: 100%; background: var(--accent); } +.lesson h3 { margin: 0 0 6px; font-size: 16px; } +.lesson h3 small { font-weight: 400; font-size: 13px; } +ul.skills li a { flex: 1; color: var(--text); text-decoration: none; padding-block: 6px; } +.tag { font-size: 12px; border: 1px solid var(--line); border-radius: 999px; padding: 2px 10px; white-space: nowrap; color: var(--muted); } +.tag.st-mastered { border-color: var(--ok, #15803d); color: var(--ok, #15803d); font-weight: 700; background: color-mix(in srgb, var(--ok, #15803d) 12%, transparent); } +.tag.st-learning { border-style: dashed; color: var(--text); } +:root { --ok: #6ee7a0; --warn: #fbbf6a; } + +/* The owl */ +.sky-owl { display: block; overflow: visible; margin-inline: auto; } +.sky-owl .o-b { fill: var(--sky-owl); } .sky-owl .o-belly { fill: var(--sky-owl-belly); } .sky-owl .o-eye { fill: var(--sky-owl-eye); } +.sky-owl .o-pupil { fill: var(--sky-owl-pupil); } .sky-owl .o-glint { fill: #fff; } +.sky-owl .o-feather { fill: none; stroke: var(--sky-owl); stroke-width: 1.6; opacity: .45; } +.sky-owl .o-glass { fill: none; stroke: var(--sky-gold); stroke-width: 3; } +.sky-owl .o-beak { fill: var(--sky-beak); } .sky-owl .o-feet { fill: none; stroke: var(--sky-beak); stroke-width: 3; stroke-linecap: round; } +.sky-owl .o-lid { fill: var(--sky-owl); transform-box: fill-box; transform-origin: center; transform: scaleY(0); animation: sky-blink 5.5s infinite; } +@keyframes sky-blink { 0%, 94%, 100% { transform: scaleY(0); } 96%, 98% { transform: scaleY(1); } } + +/* The sign-in page */ +.signin { display: grid; place-content: center; gap: 14px; text-align: center; min-height: 70vh; padding: 24px 16px; + background: linear-gradient(180deg, var(--sky-night), var(--bg)); border-radius: var(--radius); } +.signin .logo { font-size: 30px; font-weight: 800; letter-spacing: .5px; margin: 0; } +.signin .status { color: var(--muted); margin: 0; } +.signin form { text-align: start; width: min(100%, 320px); margin-inline: auto; } +.pill { border-radius: 999px; min-height: 44px; padding: 10px 24px; border: 0; font-weight: 700; cursor: pointer; + background: var(--sky-aurora); color: #04211b; } +.hint { background: var(--bg); border-radius: 10px; padding: 8px 12px; font-size: 13px; color: var(--muted); } + +/* Header: role chips, access link, sign-out */ +.top nav { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: flex-end; } +.roles { display: flex; flex-wrap: wrap; gap: 6px; } +.roles button { border-radius: 999px; min-height: 40px; padding: 6px 14px; } +.roles button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 700; } + +/* Manager, teacher and admin screens: cards that use a wide screen, tables that scroll inside their box */ +.cards { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); } +.cards .card { margin-block: 0; } +.hrow { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.hrow .grow { flex: 1 1 auto; } +.tag { display: inline-block; font-size: 12px; border: 1px solid var(--line); border-radius: 999px; padding: 1px 10px; color: var(--muted); white-space: nowrap; } +.subtabs { display: flex; flex-wrap: wrap; gap: 8px; margin: 4px 0 12px; } +.subtabs button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 700; } +.tablewrap { overflow-x: auto; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); } +table.data { border-collapse: collapse; width: 100%; } +table.data th, table.data td { padding: 8px 10px; text-align: start; border-bottom: 1px solid var(--line); font-size: 14px; } +table.data th { background: var(--sky-night); } +.checks { display: grid; gap: 6px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); } +.checks label { display: flex; gap: 8px; align-items: center; margin: 0; font-weight: 400; border: 1px solid var(--line); border-radius: 10px; padding: 8px; } +.checks input { width: auto; } +.switch { display: inline-flex; gap: 8px; align-items: center; margin: 0; } +.switch input { width: auto; } +button.danger { color: var(--danger); border-color: var(--danger); } + +/* A role tag with a remove button: the pill stays slim, the button keeps a 44px target */ +.tag:has(button) { display: inline-flex; align-items: center; padding-inline-start: 10px; padding-block: 0; } +.tag button { border: 0; background: transparent; color: inherit; min-width: 44px; min-height: 44px; padding: 0; } + +/* ---- The path: a trail of lessons, each a hub with its skills as stars in a ring ---- */ +.path-top { margin-bottom: 4px; } +.trail { display: flex; flex-direction: column; align-items: center; gap: 28px; margin-top: 18px; } +.trail > * { position: relative; width: 100%; } +.trail > *:not(:first-child)::before { content: ""; position: absolute; bottom: 100%; left: 50%; width: 6px; height: 28px; margin-left: -3px; + background: var(--line); border-radius: 3px; } +.trail .mark { text-align: center; color: var(--muted); } +.trail .mark b { display: block; } +.trail .start b { color: var(--sky-aurora); } +.orbit { container-type: inline-size; } +.orbit .stage { --R: min(112px, 31cqw); position: relative; height: calc(var(--R) * 2.2 + 140px); } +.orbit .ring { position: absolute; left: 50%; top: 50%; width: calc(var(--R) * 2); height: calc(var(--R) * 2.2); + transform: translate(-50%, -50%); pointer-events: none; overflow: visible; } +.orbit .ring path { fill: none; stroke: var(--line); stroke-width: 3; stroke-linecap: round; vector-effect: non-scaling-stroke; } +.orbit .ring path.on { stroke: var(--accent); } +.orbit .ring path.back { opacity: .45; stroke-dasharray: 2 7; } +.orbit .hub { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); width: 112px; text-align: center; z-index: 1; + background: var(--surface); border: 2px solid var(--accent); border-radius: 16px; padding: 7px 5px; } +.orbit .hub h3 { margin: 0; font-size: 13px; line-height: 1.25; } +.orbit .hub .count { display: inline-block; margin-top: 4px; font-size: 11px; border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px; color: var(--muted); } +.orbit.completed .hub { box-shadow: 0 0 0 3px var(--sky-gold); } +.star { position: absolute; left: calc(50% + var(--dx) * var(--R)); top: calc(50% + var(--dy) * var(--R) * 1.1); transform: translate(-50%, -26px); + width: 84px; display: flex; flex-direction: column; align-items: center; gap: 3px; text-decoration: none; color: var(--text); border-radius: 12px; } +.star:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; } +.star .node { position: relative; width: 52px; height: 52px; border-radius: 50%; display: grid; place-items: center; background: var(--surface); + border: 3px solid var(--line); } +.star .node svg { width: 24px; height: 24px; fill: var(--line); } +.star .num { position: absolute; top: -7px; inset-inline-end: -7px; min-width: 20px; height: 20px; border-radius: 999px; background: var(--surface); + border: 2px solid var(--line); font-size: 11px; font-weight: 700; display: grid; place-items: center; } +.star .lbl { font-size: 11.5px; text-align: center; line-height: 1.2; } +.star .lbl em { display: block; font-style: normal; font-size: 10.5px; color: var(--muted); } +.star.st-learning .node { border-color: var(--accent); + background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 30%, var(--surface)) 50%, var(--surface) 50%); } +.star.st-learning .node svg { fill: var(--accent); } +.star.st-mastered .node { border-color: var(--sky-gold); background: color-mix(in srgb, var(--sky-gold) 22%, var(--surface)); } +.star.st-mastered .node svg { fill: var(--sky-gold); width: 28px; height: 28px; } +.star.st-mastered .num { border-color: var(--sky-gold); } +.star.next .node { width: 62px; height: 62px; border-color: var(--sky-aurora); box-shadow: 0 0 0 5px color-mix(in srgb, var(--sky-aurora) 25%, transparent); animation: sky-pulse 1.8s ease-out infinite; } +.star.next .node svg { fill: var(--text); } +.star .perch { position: absolute; top: -26px; inset-inline-start: -30px; width: 30px; pointer-events: none; } +@keyframes sky-pulse { 50% { box-shadow: 0 0 0 10px color-mix(in srgb, var(--sky-aurora) 8%, transparent); } } + +/* ---- The exercise screen (the sheet itself is styled in board.css, with the board) ---- */ +.ex-chip { display: inline-block; font-size: 12px; font-weight: 700; border: 1px solid var(--line); border-radius: 999px; padding: 3px 10px; background: var(--sky-night); color: var(--text); text-decoration: none; } +a.ex-chip.link { color: var(--accent); border-color: var(--accent); margin-inline-end: 4px; } +.mx-sheet h3 { margin: 6px 0 0; font-size: 22px; line-height: 1.2; } +.ex-done { font-size: 13px; font-weight: 700; color: var(--ok, #15803d); border: 1px solid var(--ok, #15803d); border-radius: 999px; padding: 1px 8px; vertical-align: middle; } +.ex-help { min-width: 44px; min-height: 44px; border-radius: 999px; font-weight: 800; font-size: 18px; border: 1px solid var(--line); background: var(--surface); color: var(--text); cursor: pointer; } +.ex-help[aria-expanded="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); } +.mx-x { min-width: 44px; min-height: 44px; } +.ex-explain { margin: 0; color: var(--muted); font-size: 14px; } +.ex-note { margin: 0; background: color-mix(in srgb, var(--sky-gold) 16%, var(--surface)); border-radius: 10px; padding: 8px 12px; font-size: 14px; } +.ex-progress { display: flex; justify-content: space-between; align-items: center; gap: 10px; font-size: 13px; color: var(--muted); } +.ex-dots { display: flex; flex-wrap: wrap; gap: 3px; justify-content: flex-end; } +.ex-dots i { width: 14px; height: 14px; border-radius: 50%; background: var(--line); display: grid; place-items: center; } +.ex-dots i.ok { background: var(--ok, #15803d); } +.mx-q { background: var(--bg); border-radius: 14px; padding: 14px; display: flex; flex-direction: column; gap: 10px; } +.ex-text { margin: 0; font-size: 19px; text-align: center; } +.ex-choices { display: grid; gap: 8px; grid-template-columns: 1fr 1fr; } +@media (max-width: 420px) { .ex-choices { grid-template-columns: 1fr; } } +.ex-choice { position: relative; min-height: 48px; border: 2px solid var(--line); background: var(--surface); color: var(--text); border-radius: 12px; font-size: 17px; padding: 10px; text-align: center; cursor: pointer; direction: ltr; } +.ex-choice:disabled { cursor: default; opacity: .85; } +.ex-choice.right { border-color: var(--ok, #15803d); background: color-mix(in srgb, var(--ok, #15803d) 14%, var(--surface)); opacity: 1; } +.ex-choice.wrong { border-color: var(--danger); background: color-mix(in srgb, var(--danger) 10%, var(--surface)); opacity: 1; } +.ex-choice .burst { position: absolute; inset-inline-end: 10px; top: 4px; color: var(--sky-gold); font-size: 14px; pointer-events: none; animation: ex-burst .9s ease-out forwards; } +@keyframes ex-burst { from { opacity: 1; transform: translateY(6px) scale(.8); } to { opacity: 0; transform: translateY(-14px) scale(1.4); } } +.ex-fb:empty { display: none; } +.ex-ok, .ex-bad { border-radius: 12px; padding: 10px 12px; } +.ex-ok { background: color-mix(in srgb, var(--ok, #15803d) 14%, transparent); border: 1px solid var(--ok, #15803d); } +.ex-bad { background: color-mix(in srgb, var(--danger) 10%, transparent); border: 1px solid var(--danger); } +.ex-ok p, .ex-bad p { margin: 6px 0 0; } +.ex-actions { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; } +.ex-actions span { flex: 1; color: var(--muted); font-size: 14px; } +.ex-actions button { min-height: 44px; } +.ex-helpbox { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; } +.ex-helpbox h4 { margin: 8px 0 4px; } +.ex-helpbox p { margin: 4px 0; } +.ex-eq { font-size: 18px; direction: ltr; text-align: center; } +.ex-steps { padding-inline-start: 22px; margin: 6px 0; } +.ex-steps li { margin-block: 6px; } +.ex-related { margin: 0; font-size: 13px; } + +/* Sign-in logo (mathly1's animated logo) */ +.signin img.logo { width: min(300px, 75vw); height: auto; margin: auto; } + +/* Subjects: the first screen of a student */ +.subjects { display: grid; gap: 12px; } +.subjects h2 { margin: 0; font-size: 20px; } +.subject-card { display: flex; align-items: center; gap: 12px; padding: 14px; border: 1px solid var(--line); border-radius: 16px; + background: linear-gradient(130deg, color-mix(in srgb, var(--sky-accent) 14%, var(--surface)), var(--surface)); color: var(--text); text-decoration: none; min-height: 72px; } +.subject-card .grow { display: grid; gap: 4px; } +.subject-card small { color: var(--muted); } +.subject-icon { flex: none; width: 46px; height: 46px; border-radius: 14px; display: grid; place-items: center; font-size: 24px; font-weight: 700; + background: color-mix(in srgb, var(--sky-accent) 22%, var(--bg)); color: var(--sky-accent); } +.back { display: inline-block; padding: 10px 4px; color: var(--sky-accent); font-weight: 700; text-decoration: none; } + +/* A faded star: mastered, but not practiced for 14 days. Only a cue; the word "דועך" says so too. */ +.star.faded .node { opacity: .55; filter: saturate(.5); box-shadow: none; } +.star.faded .node svg { fill: color-mix(in srgb, var(--sky-gold) 45%, var(--sky-mute)); } +.star.faded .lbl em { color: var(--muted); } + +/* Rewards: constellations, comets */ +.cons { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 12px; } +.con-card { margin: 0; display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 12px 10px; border: 1px solid var(--line); + border-radius: 16px; background: var(--surface); text-align: center; } +.con-card figcaption { display: grid; gap: 2px; font-weight: 700; font-size: 14px; } +.con { width: 100%; max-width: 130px; height: 110px; overflow: visible; } +.con line { stroke: var(--sky-gold); stroke-opacity: .9; stroke-width: 6; stroke-linecap: round; } +.con path { fill: var(--sky-gold); } +#done-skills li.faded a { color: var(--muted); } +.comets { display: grid; grid-template-columns: repeat(auto-fill, minmax(96px, 1fr)); gap: 10px; } +.comet-tile { aspect-ratio: 3 / 4; max-width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 8px; + border-radius: 14px; border: 1px solid var(--line); background: var(--surface); color: var(--text); text-align: center; cursor: pointer; font: inherit; min-height: 44px; } +.comet-tile .sym, .comet-card .sym { font-size: 26px; font-weight: 600; line-height: 1.1; direction: ltr; color: var(--muted); } +.comet-tile small { font-size: 12px; color: var(--muted); } +.comet-tile.have { border-color: var(--sky-gold); background: radial-gradient(circle at 50% 30%, color-mix(in srgb, var(--sky-gold) 22%, var(--surface)), var(--surface) 70%); } +.comet-tile.have .sym, .comet-card .sym { color: var(--sky-gold); } +.comet-tile.have small { color: var(--text); } +.comet-card { display: grid; justify-items: center; gap: 4px; padding: 14px; border-radius: 14px; background: var(--sky-night); } +.comet-dialog { position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 16px; } +.comet-dialog .scrim { position: absolute; inset: 0; background: rgb(0 0 0 / .6); } +.comet-dialog .sheet { position: relative; width: min(100%, 360px); background: var(--surface); border: 1px solid var(--sky-gold); border-radius: 18px; padding: 16px; display: grid; gap: 10px; text-align: center; } +.comet-dialog h2 { margin: 0; font-size: 18px; } +.comet-dialog p { margin: 0; } +.comet { position: fixed; z-index: 70; top: 16%; left: -130px; width: 120px; height: 56px; border: 0; padding: 0; background: none; cursor: pointer; animation: comet-fly 4s linear forwards; } +.comet svg { width: 100%; height: 100%; filter: drop-shadow(0 0 8px var(--sky-gold)); } +@keyframes comet-fly { from { transform: translate(0, 0) rotate(14deg); } to { transform: translate(calc(100vw + 260px), 40vh) rotate(14deg); } } +.comet.still { position: static; width: auto; height: auto; min-height: 44px; animation: none; padding: 10px 16px; border-radius: 999px; + border: 1px solid var(--sky-gold); background: color-mix(in srgb, var(--sky-gold) 18%, var(--surface)); color: var(--text); font-weight: 700; } + +/* Lesson quizzes */ +.quiz-node { display: flex; align-items: center; justify-content: center; gap: 10px; width: min(100%, 300px); min-height: 56px; margin: 4px auto 14px; padding: 8px 18px; + border: 2px dashed var(--sky-accent); border-radius: 999px; color: var(--text); text-decoration: none; background: color-mix(in srgb, var(--sky-accent) 10%, var(--surface)); } +.quiz-node b { display: block; font-size: 16px; } +.quiz-node em { display: block; font-style: normal; font-size: 13px; color: var(--muted); } +.quiz-node.graded { border-style: solid; border-color: var(--sky-gold); } +.quiz-node.open { border-color: var(--sky-aurora); } +.qz-icon svg { width: 26px; height: 26px; fill: var(--sky-gold); } +.qz-bar { display: flex; justify-content: space-between; align-items: center; margin-block: 6px; } +.qz-timer { font-variant-numeric: tabular-nums; font-weight: 800; font-size: 20px; padding: 2px 12px; border-radius: 999px; background: var(--sky-night); border: 1px solid var(--line); } +.qz-dots { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; } +.qz-dot { width: 24px; height: 24px; min-width: 24px; padding: 0; border-radius: 50%; border: 2px solid var(--line); background: transparent; cursor: pointer; position: relative; } +.qz-dot::after { content: ""; position: absolute; inset: -10px; } /* the touch target is 44px */ +.qz-dot.done { background: var(--sky-accent); border-color: var(--sky-accent); } +.qz-dot.cur { box-shadow: 0 0 0 3px color-mix(in srgb, var(--sky-gold) 60%, transparent); } +.qz-choice.picked { border-color: var(--sky-accent); background: color-mix(in srgb, var(--sky-accent) 22%, var(--surface)); font-weight: 700; } +.qz-nav { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 10px; } +.qz-nav button { min-height: 44px; } +.qz-result { text-align: center; } +.qz-grade { margin: 6px 0; display: grid; justify-items: center; } +.qz-grade b { font-size: 56px; line-height: 1; color: var(--sky-gold); } +.qz-grade span { color: var(--muted); } +.qz-missed { padding-inline-start: 22px; display: grid; gap: 12px; } +.qz-actions { display: flex; gap: 8px; flex-wrap: wrap; } +ul.grades li { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; align-items: center; } +ul.grades .gr-num { font-size: 28px; font-weight: 800; color: var(--sky-gold); grid-row: 1; grid-column: 2; } +ul.grades .bar, ul.grades .muted { grid-column: 1 / -1; } +.mx-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } + +/* The student's tab bar sits at the bottom of the screen, above the page and below the sheets */ +.tabs { position: fixed; inset-inline: 0; bottom: 0; z-index: 40; margin: 0; gap: 4px; padding: 6px 8px calc(6px + env(safe-area-inset-bottom, 0px)); + background: var(--surface); border-top: 1px solid var(--line); } +.tabs a { min-height: 44px; display: grid; place-items: center; border: 0; border-radius: 10px; font-weight: 600; } +body:has(.tabs) main { padding-bottom: calc(76px + env(safe-area-inset-bottom, 0px)); } + +/* Home */ +.test-card h2 { margin: 0 0 4px; font-size: 20px; } +.readiness { margin-block: 10px; } +.rd-top { display: flex; align-items: baseline; gap: 10px; margin: 0; } +.rd-num { font-size: 44px; line-height: 1; color: var(--sky-gold); } +.rd-label { font-weight: 700; } +.rd-bar { height: 12px; margin-block: 6px; } +.rd-parts { display: flex; flex-wrap: wrap; gap: 4px 14px; margin: 0; font-size: 14px; } +.rd-part { white-space: nowrap; } +.rd-note { margin: 6px 0 0; font-size: 14px; color: var(--sky-gold); } +.today { display: grid; gap: 6px; margin-block: 10px; } +.big-task, .primary-link { display: flex; justify-content: space-between; align-items: center; gap: 10px; min-height: 56px; padding: 12px 18px; border-radius: 16px; + background: var(--accent); color: var(--accent-text); font-weight: 800; font-size: 18px; text-decoration: none; } +.primary-link { background: color-mix(in srgb, var(--sky-accent) 14%, var(--surface)); color: var(--text); border: 1px solid var(--sky-accent); font-size: 16px; } +.required { display: flex; justify-content: space-between; align-items: center; gap: 10px; min-height: 48px; padding: 10px 16px; margin-block: 8px; border-radius: 14px; + border: 2px solid var(--sky-gold); background: color-mix(in srgb, var(--sky-gold) 12%, var(--surface)); color: var(--text); text-decoration: none; } +.required b { color: var(--sky-gold); } + +/* A test's card */ +ol.plan { list-style: none; padding: 0; margin: 0 0 8px; display: grid; gap: 8px; } +ol.plan li { display: flex; gap: 10px; align-items: flex-start; } +ol.plan .mark { font-weight: 800; color: var(--muted); } +ol.plan li.done .mark { color: var(--sky-aurora); } +.button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 8px 16px; border-radius: 999px; border: 1px solid var(--sky-accent); + color: var(--text); text-decoration: none; font-weight: 700; background: transparent; } +.button.primary { background: var(--accent); color: var(--accent-text); } +#exercises li { display: flex; justify-content: space-between; align-items: center; gap: 10px; } +.req { color: var(--sky-gold); } + +/* The teacher's tests tab */ +.test-form { display: grid; gap: 6px; margin-top: 8px; } +.test-form fieldset { border: 1px solid var(--line); border-radius: 10px; padding: 8px 12px; } +.test-form .check { display: block; padding: 4px 0; } +.test-form .two { display: flex; gap: 12px; } +.test-form .two > span { flex: 1; } +.sim-missing { margin: 4px 0; } +.readiness-list li { display: flex; justify-content: space-between; gap: 10px; } +.test-row { margin-block: 10px; } +.danger { border-color: var(--danger); color: var(--danger); } + +/* The thinking indicator: the tapped choice spins while the server checks it, the others step back */ +.ex-choice.dim { opacity: .45; } +.ex-choice.pending { opacity: 1; border-color: var(--sky-accent); background: color-mix(in srgb, var(--sky-accent) 14%, var(--surface)); } +.ex-choice.pending::after { content: ""; position: absolute; inset-inline-end: 12px; top: 50%; width: 18px; height: 18px; margin-top: -9px; border-radius: 50%; + border: 3px solid color-mix(in srgb, var(--sky-accent) 30%, transparent); border-top-color: var(--sky-accent); animation: ex-spin .8s linear infinite; } +@keyframes ex-spin { to { transform: rotate(360deg); } } +.ex-thinking { margin: 4px 0; color: var(--muted); font-weight: 700; } + +/* A wrong choice: clearly marked, with a word and a symbol on the choice (never colour alone) */ +.ex-choice.wrong { border-width: 3px; background: color-mix(in srgb, var(--danger) 18%, var(--surface)); } +.ex-choice .verdict { position: absolute; inset-inline-end: 10px; top: 6px; font-size: 13px; font-weight: 800; color: var(--danger); } + +/* Rounds: dots filled or marked wrong, and the round's result */ +.ex-dots i.bad { background: color-mix(in srgb, var(--danger) 25%, transparent); box-shadow: inset 0 0 0 1.5px var(--danger); color: var(--danger); font-style: normal; font-size: 10px; font-weight: 800; line-height: 1; } +.ex-round { display: grid; gap: 10px; } +.ex-score { margin: 0; font-size: 18px; } +.ex-score b { font-size: 44px; line-height: 1; color: var(--sky-gold); } +.ex-missed { padding-inline-start: 22px; display: grid; gap: 12px; } diff --git a/mathly2/static/app.js b/mathly2/static/app.js index c82017e18b1d4db19869fe616f9b4f276ceda4d5..56aca54557c23dc5637807b9f853a0fe9fd7e4dc 100644 --- a/mathly2/static/app.js +++ b/mathly2/static/app.js @@ -1,23 +1,34 @@ -// App shell: sign-in, then the screen for the signed-in person's role. +// App shell: the sign-in page, then the home of the role the person chose. A person with several roles gets a chip for each. import { api, ApiError } from "./api.js"; import { esc } from "./math.js"; +import { ROLE_NAMES, visibleRoles } from "./roles.js"; +import { clearRoute, leaveScreen } from "./router.js"; import * as session from "./session.js"; +import { owl } from "./sky.js"; const CFG = JSON.parse(document.getElementById("config").textContent); const app = document.getElementById("app"); const nav = document.getElementById("nav"); +const ROLE_KEY = "mathly2.role"; +const SCREENS = { student: "./student.js", teacher: "./teacher.js", manager: "./manager.js", admin: "./admin.js", developer: "./developer.js" }; export const view = html => { app.innerHTML = html; }; -function showSignIn(message = "") { +const remembered = () => { try { return localStorage.getItem(ROLE_KEY) || ""; } catch { return ""; } }; +const remember = role => { try { localStorage.setItem(ROLE_KEY, role); } catch { /* private window */ } }; + +function showSignIn(message = "", canRetry = false) { + leaveScreen(); nav.innerHTML = ""; - view(`

כניסה

- ${message ? `` : ""} + view(``); +

` + : canRetry ? "" : `

`}
`); + document.getElementById("retry")?.addEventListener("click", () => boot()); document.getElementById("google")?.addEventListener("click", () => session.signInWithGoogle()); document.getElementById("dev")?.addEventListener("submit", event => { event.preventDefault(); @@ -31,9 +42,32 @@ async function signOutAndShow(message) { showSignIn(message); } -function header(me) { - nav.innerHTML = `${esc(me.email)} `; +function header(me, current) { + const roles = visibleRoles(me.roles); + nav.innerHTML = `${esc(me.email)} + ${roles.length > 1 ? `${roles.map(role => + ``).join("")}` : ""} + `; document.getElementById("out").addEventListener("click", () => signOutAndShow()); + document.getElementById("access").addEventListener("click", async () => { + clearRoute(); + nav.querySelectorAll("[data-role]").forEach(b => b.setAttribute("aria-pressed", "false")); + await (await import("./access.js")).show(me, view); + }); + nav.querySelectorAll("[data-role]").forEach(button => button.addEventListener("click", () => open(me, button.dataset.role))); +} + +async function open(me, role, { keepAddress = false } = {}) { + remember(role); + clearRoute({ keepAddress }); + header(me, role); + view(`

טוען…

`); + try { + await (await import(SCREENS[role])).show(me, view); + } catch (error) { + if (error instanceof ApiError && error.status === 401) return signOutAndShow("ההתחברות פגה, יש להיכנס שוב"); + view(`
`); + } } async function boot() { @@ -41,16 +75,16 @@ async function boot() { try { await session.init(CFG); } catch { - return showSignIn("לא הצלחנו לטעון את שירות ההתחברות. בדקו את החיבור לרשת ונסו שוב."); + return showSignIn("לא הצלחנו להתחבר לשירות ההתחברות. בדקו את החיבור לרשת ונסו שוב.", true); } if (!await session.token()) return showSignIn(); try { const me = await api("/api/me"); - header(me); - const screen = await import(me.role === "teacher" ? "./teacher.js" : "./student.js"); - await screen.show(me, view); + const roles = visibleRoles(me.roles); + await open(me, roles.includes(remembered()) ? remembered() : roles[0], { keepAddress: true }); // the first screen honours a link } catch (error) { if (error instanceof ApiError && error.status === 401) return signOutAndShow("ההתחברות פגה, יש להיכנס שוב"); + if (error instanceof ApiError && error.status === 503) return showSignIn("שירות ההתחברות לא זמין כרגע.", true); view(`
`); } } diff --git a/mathly2/static/board-math.js b/mathly2/static/board-math.js new file mode 100644 index 0000000000000000000000000000000000000000..f472d6957750b7b73881cab01cc50cdbafd64fdd --- /dev/null +++ b/mathly2/static/board-math.js @@ -0,0 +1,199 @@ +/* Typed math on the sketch board (static/math-board.js). + The student types with MathLive (static/vendor/mathlive, MIT, loaded only when first needed) and its on-screen + math keyboard, set up here for ninth grade: digits, x and y, fractions, powers, roots, brackets, |x|, ± ≤ ≥ ≠, π, + degrees, angles and triangles, plus a letters tab. What is typed is kept as LaTeX and drawn on the board's + canvas by the small renderer below, so it moves, prints and is handed in with everything else. The renderer + knows the LaTeX that keyboard makes; anything else is drawn as its plain name. */ +(()=>{ +const VENDOR="/static/vendor/mathlive/"; +const SERIF='"STIX Two Text","Cambria Math","Times New Roman",serif'; + +/* ---------- MathLive ---------- */ +let loading=null; +function load(){ + return loading||=new Promise((ok,no)=>{ + if(window.MathfieldElement||window.MathLive) return ok(); + const s=document.createElement("script"); s.src=VENDOR+"mathlive.min.js"; s.onload=ok; s.onerror=()=>{ loading=null; no(Error("mathlive")); }; + document.head.append(s); + }).then(()=>{ + const M=window.MathfieldElement||window.MathLive?.MathfieldElement; + M.fontsDirectory=VENDOR+"fonts"; M.soundsDirectory=null; M.keypressSound=null; M.plonkSound=null; + const k=window.mathVirtualKeyboard; if(k&&!k.__mathly){ k.__mathly=true; k.layouts=[NINTH,"alphabetic"]; k.editToolbar="none"; } + }); +} +const key=(insert,label,tooltip,more={})=>({insert,label,tooltip,...more}); +const NINTH={label:"123",tooltip:"מספרים ופעולות",rows:[ + ["[7]","[8]","[9]",key("\\div","÷","חילוק"),key("\\frac{#@}{#?}","a⁄b","שבר"),"x","y",key("\\pi","π","פאי"),"[backspace]"], + ["[4]","[5]","[6]",key("\\times","×","כפל"),key("#@^2","x²","בריבוע"),key("#@^{#?}","xⁿ","חזקה"),"a","b",key("\\left(#0\\right)","( )","סוגריים")], + ["[1]","[2]","[3]","[-]",key("\\sqrt{#0}","√","שורש"),key("\\sqrt[#?]{#0}","ⁿ√","שורש n"),key("\\left|#0\\right|","|x|","ערך מוחלט"),"[left]","[right]"], + ["[0]","[.]","[=]","[+]",key("\\pm","±","פלוס מינוס"),key("\\le","≤","קטן או שווה"),key("\\ge","≥","גדול או שווה"),key("\\ne","≠","שונה"),"[return]"], + [key("^{\\circ}","°","מעלות"),key("\\angle","∠","זווית"),key("\\triangle","△","משולש"),"<",">",",",key("\\perp","⊥","מאונך"),key("\\parallel","∥","מקביל"),"[hide-keyboard]"]]}; + +/* ---------- reading LaTeX ---------- */ +const SYM={cdot:["⋅","op"],times:["×","op"],div:["÷","op"],pm:["±","op"],mp:["∓","op"],le:["≤","rel"],leq:["≤","rel"],ge:["≥","rel"],geq:["≥","rel"], + ne:["≠","rel"],neq:["≠","rel"],approx:["≈","rel"],sim:["∼","rel"],cong:["≅","rel"],lt:["<","rel"],gt:[">","rel"],to:["→","rel"], + Rightarrow:["⇒","rel"],Leftrightarrow:["⇔","rel"],in:["∈","rel"],perp:["⊥","rel"],parallel:["∥","rel"],mid:["|","rel"], + pi:["π"],alpha:["α"],beta:["β"],gamma:["γ"],delta:["δ"],theta:["θ"],lambda:["λ"],mu:["μ"],sigma:["σ"],phi:["φ"],omega:["ω"],Delta:["Δ"], + angle:["∠"],measuredangle:["∡"],triangle:["△"],circ:["°"],degree:["°"],infty:["∞"],cdots:["⋯"],ldots:["…"],dots:["…"],prime:["′"], + vert:["|"],lvert:["|"],rvert:["|"],"%":["%"],"{":["{"],"}":["}"],lbrace:["{"],rbrace:["}"],colon:[":","punct"],",":[" ","space"], + ":":[" ","space"],";":[" ","space"]," ":[" ","space"],quad:[" ","space"],qquad:[" ","space"],"!":["","space"], + exponentialE:["e"],imaginaryI:["i"]}; +const TEXT=new Set(["text","mathrm","textrm","operatorname","mbox","textit","mathit"]); +const WRAP=new Set(["mathbf","boldsymbol","mathsf","displaystyle","textstyle","mathnormal","bm"]); +const ANGLE_FREE=new Set(["(","[","|","{","−","+"]); + +function tokens(s){ + const out=[]; let i=0; + while(it[i], next=()=>t[i++]; + function list(stop){ + const items=[]; + while(i") return {t:"sym",s:k,kind:"rel"}; + if(k===","||k===";") return {t:"sym",s:k,kind:"punct"}; + return {t:"sym",s:k}; + } + return {t:"row",items:list([])}; +} + +/* ---------- laying it out: each box has a width, a height above the baseline (a) and below it (d) ---------- */ +const meter=document.createElement("canvas").getContext("2d"); +const fontOf=(size,italic)=>`${italic?"italic ":""}${size}px ${SERIF}`; +function width(s,size,italic){ meter.font=fontOf(size,italic); return meter.measureText(s).width; } + +function box(node,z){ // z: the font size + switch(node.t){ + case "row": return row(node.items,z); + case "sym":{ const w=width(node.s,z,node.italic); + return {w,a:.72*z,d:.22*z,kind:node.kind,paint:(c,x,y)=>{ c.font=fontOf(z,node.italic); c.fillText(node.s,x,y); }}; } + case "text":{ const w=width(node.s,z,node.italic); + return {w,a:.72*z,d:.22*z,paint:(c,x,y)=>{ c.font=fontOf(z,node.italic); c.fillText(node.s,x,y); }}; } + case "space": return {w:node.w*z,a:0,d:0,paint:()=>{}}; + case "ph": return {w:.5*z,a:.6*z,d:.1*z,paint:(c,x,y)=>{ c.save(); c.globalAlpha=.35; c.lineWidth=1; c.strokeRect(x+.05*z,y-.6*z,.4*z,.7*z); c.restore(); }}; + case "scripts": return scripts(node,z); + case "frac": return frac(node,z); + case "sqrt": return sqrt(node,z); + case "fence": return fence(node,z); + case "over":{ const b=box(node.body,z), lw=Math.max(1,.05*z); + return {w:b.w,a:b.a+.14*z,d:b.d,paint:(c,x,y)=>{ b.paint(c,x,y); c.lineWidth=lw; c.beginPath(); c.moveTo(x,y-b.a-.08*z); c.lineTo(x+b.w,y-b.a-.08*z); c.stroke(); + if(node.arrow){ c.beginPath(); c.moveTo(x+b.w-.15*z,y-b.a-.15*z); c.lineTo(x+b.w,y-b.a-.08*z); c.lineTo(x+b.w-.15*z,y-b.a-.01*z); c.stroke(); } }}; } + } + return {w:0,a:0,d:0,paint:()=>{}}; +} +function row(items,z){ + const parts=[]; let prev=null; + for(const it of items){ + const b=box(it,z); + // a little room around + − = and the like; a sign at the start, or after another sign or a bracket, is a unary one + const unary=b.kind==="op"&&(!prev||prev.kind==="op"||prev.kind==="rel"||prev.open); + const pad=b.kind==="rel"?.28*z:b.kind==="op"&&!unary?.2*z:b.kind==="punct"?0:0; + const after=b.kind==="punct"?.2*z:pad; + if(it.t==="frac"){ parts.push({b:{w:.08*z,a:0,d:0,paint:()=>{}}}); } + parts.push({b,pre:pad,post:after}); + if(it.t==="frac") parts.push({b:{w:.08*z,a:0,d:0,paint:()=>{}}}); + prev=it.t==="sym"&&ANGLE_FREE.has(it.s)&&b.kind!=="op"?{open:true}:b; + } + let w=0, a=.72*z*(items.length?0:1), d=.22*z*(items.length?0:1); + for(const p of parts){ w+=(p.pre||0)+p.b.w+(p.post||0); a=Math.max(a,p.b.a); d=Math.max(d,p.b.d); } + return {w,a,d,paint:(c,x,y)=>{ let at=x; for(const p of parts){ at+=p.pre||0; p.b.paint(c,at,y); at+=p.b.w+(p.post||0); } }}; +} +function scripts(node,z){ + const b=box(node.base,z), s=Math.max(9,.7*z); + const sup=node.sup?box(node.sup,s):null, sub=node.sub?box(node.sub,s):null; + const up=Math.max(.38*z,b.a-.38*z), down=Math.max(.2*z,b.d+.04*z-(sub?.a||0)*.2); + const gap=.04*z, w=b.w+gap+Math.max(sup?.w||0,sub?.w||0); + return {w,a:Math.max(b.a,sup?up+sup.a:0),d:Math.max(b.d,sub?down+sub.d:0), + paint:(c,x,y)=>{ b.paint(c,x,y); sup?.paint(c,x+b.w+gap,y-up); sub?.paint(c,x+b.w+gap,y+down); }}; +} +function frac(node,z){ + const s=Math.max(10,.85*z), n=box(node.n,s), d=box(node.d,s); + const axis=.28*z, gap=.12*z, lw=Math.max(1,.055*z), w=Math.max(n.w,d.w)+.24*z; + return {w,a:axis+gap+n.d+n.a,d:Math.max(0,d.a+d.d+gap-axis), + paint:(c,x,y)=>{ const bar=y-axis; + c.save(); c.lineWidth=lw; c.beginPath(); c.moveTo(x+.04*z,bar); c.lineTo(x+w-.04*z,bar); c.stroke(); c.restore(); + n.paint(c,x+(w-n.w)/2,bar-gap-n.d); d.paint(c,x+(w-d.w)/2,bar+gap+d.a); }}; +} +function sqrt(node,z){ + const b=box(node.body,z), idx=node.index?.items?.length?box(node.index,Math.max(9,.55*z)):null; + const top=Math.max(b.a,.72*z)+.16*z, hook=.58*z, shift=idx?Math.max(0,idx.w-.28*z):0, lw=Math.max(1,.055*z); + return {w:shift+hook+b.w+.12*z,a:Math.max(top+.06*z,idx?.62*top+idx.a+idx.d:0),d:Math.max(b.d+.06*z,.22*z), + paint:(c,x,y)=>{ const x0=x+shift, bottom=y+Math.max(b.d,.05*z)+.04*z, t=y-top; + c.save(); c.lineWidth=lw; c.lineJoin="round"; c.beginPath(); + c.moveTo(x0,y-.32*z); c.lineTo(x0+.12*z,y-.4*z); c.lineTo(x0+.3*z,bottom); c.lineTo(x0+hook,t); c.lineTo(x0+hook+b.w+.1*z,t); c.stroke(); c.restore(); + b.paint(c,x0+hook+.04*z,y); idx?.paint(c,x0+.3*z-idx.w,y-.62*top); }}; +} +function fence(node,z){ + const b=box(node.body,z), tall=b.a+b.d>1.15*z; + const side=s=>{ if(!s) return {w:.05*z,paint:()=>{}}; + const w=width(s,z,false); + return {w,paint:(c,x,y)=>{ c.save(); c.font=fontOf(z,false); + if(tall){ const h=b.a+b.d+.12*z, k=h/(.98*z); c.translate(x,y-b.a-.06*z); c.scale(1,k); c.fillText(s,0,.76*z); } + else c.fillText(s,x,y); + c.restore(); }}; }; + const l=side(node.l), r=side(node.r), pad=.04*z; + return {w:l.w+pad+b.w+pad+r.w,a:Math.max(b.a+.08*z,.75*z),d:Math.max(b.d+.08*z,.25*z), + paint:(c,x,y)=>{ l.paint(c,x,y); b.paint(c,x+l.w+pad,y); r.paint(c,x+l.w+pad+b.w+pad,y); }}; +} + +const cache=new Map(); +// the laid-out formula at this font size: w, a and d, and paint(context, x, baseline y) in the context's colors +function layout(latex,size){ + const k=size+"|"+latex; + if(!cache.has(k)){ if(cache.size>500) cache.clear(); cache.set(k,box(parse(latex),size)); } + return cache.get(k); +} +// widths are measured with the math font: when it arrives, measure again +document.fonts?.addEventListener?.("loadingdone",()=>{ cache.clear(); window.MathlyBoardMath.onFonts?.(); }); + +window.MathlyBoardMath={load,layout,parse}; +})(); diff --git a/mathly2/static/board.css b/mathly2/static/board.css new file mode 100644 index 0000000000000000000000000000000000000000..40495f16278f0fe9ac1c288071518bb0bd9d8f02 --- /dev/null +++ b/mathly2/static/board.css @@ -0,0 +1,174 @@ +/* The smart board's styles, from mathly1's static/math.css (the block from "the sketch board beside a skill's exercise" to the + teacher-report block), plus the sheet, layer and scrim rules the board's layout relies on. The rules are unchanged: mathly1's variable + names are defined below from the sky tokens in app.css, so the board follows light and dark with no edits. All selectors are .mx-*, + which nothing else in mathly2 uses. */ +:root { + --ink: var(--text); --surface-2: var(--sky-night); + --mx-accent: var(--accent); --mx-accent-soft: color-mix(in srgb, var(--accent) 18%, var(--surface)); --mx-on-accent: var(--accent-text); + --f-body: system-ui, "Segoe UI", Arial, "Noto Sans Hebrew", sans-serif; + --sumac: var(--danger); --sumac-bg: color-mix(in srgb, var(--danger) 14%, var(--surface)); + --gold: var(--sky-gold); --starlight: var(--sky-gold); --amber: var(--sky-gold); + --amber-bg: color-mix(in srgb, var(--sky-gold) 16%, var(--surface)); + --ok-bg: color-mix(in srgb, var(--ok, #15803d) 14%, var(--surface)); --aurora: var(--sky-aurora); + --mx-scrim: rgb(5 8 20 / .55); +} + +/* the sheet over the path that the board sits beside (or covers, on a phone) */ +.mx-layer[hidden]{display:none} +.mx-scrim{position:fixed;inset:0;z-index:61;background:var(--mx-scrim)} +.mx-sheet{position:fixed;inset:auto 0 0 0;z-index:62;max-height:88vh;overflow:auto;background:var(--surface);border-radius:20px 20px 0 0; + box-shadow:0 -6px 30px rgb(0 0 0/.2);display:flex;flex-direction:column;gap:14px; + padding-block:16px calc(24px + env(safe-area-inset-bottom, 0px)); + padding-left:max(18px, env(safe-area-inset-left, 0px));padding-right:max(18px, env(safe-area-inset-right, 0px))} +@media (min-width:720px){.mx-sheet{inset:auto calc(50% - 330px) 0 calc(50% - 330px)}} +.mx-sheet>p{margin:0} + +/* the sketch board beside a skill's exercise (static/math-board.js): a desktop screen with a mouse or a pen only */ +.mx-shacts{display:flex;align-items:center;gap:6px} +.mx-board{display:none} /* the buttons that open it show everywhere: beside the exercise on a desktop, full screen on a phone */ +.mx-board-btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:none;color:var(--muted);font:700 14px/1 var(--f-body);padding:7px 12px;border-radius:999px;cursor:pointer} +.mx-board-btn .mx-ic{width:16px;height:16px} +/* the board's icons: one line-drawn set in the button's own colour */ +.mx-ic{width:20px;height:20px;flex:none;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} +[dir="rtl"] .mx-ic-flip{transform:scaleX(-1)} /* back and undo point to the start of a right-to-left line */ +.mx-board-btn[aria-pressed="true"]{border-color:var(--mx-accent);background:var(--mx-accent-soft);color:var(--ink)} +@media (min-width:1000px) and (any-pointer:fine){ + .mx-sheet.with-board{inset:16px 16px 16px auto;width:min(600px,42vw);max-height:none;border-radius:20px} + .mx-board{display:flex;flex-direction:column;position:fixed;z-index:62;top:16px;bottom:16px;left:16px;right:clamp(16px,var(--door,100vw),calc(min(600px,42vw) + 32px));transition:right .28s ease; + background:var(--surface);border:1px solid var(--line);border-radius:20px;overflow:hidden;box-shadow:0 6px 30px rgb(0 0 0/.25)} +} +.mx-board-bar{display:flex;align-items:center;gap:6px;padding:8px 10px;border-bottom:1px solid var(--line);flex-wrap:wrap} +.mx-board-bar button{display:inline-flex;align-items:center;justify-content:center;gap:6px;border:1px solid transparent;background:none;color:var(--muted); + font:500 14px/1 var(--f-body);padding:0 7px;border-radius:10px;cursor:pointer;height:36px;min-width:36px} +.mx-board-bar button:hover{color:var(--ink);background:var(--surface-2)} +.mx-board-bar button[hidden]{display:none} +.mx-board-bar button[aria-pressed="true"]{color:var(--ink);border-color:var(--mx-accent);background:var(--mx-accent-soft)} +@media (max-width:1600px){.mx-board-bar button span{display:none}} /* a narrower board: icons only, names stay as tooltips */ +.mx-board-group{display:inline-flex;align-items:center;gap:3px} +/* the inks and the eraser's sizes sit on a strip of the paper's colour, so each ink shows as it will be drawn + (the black one too); the chosen one has a ring, not the tools' outline. The sizes take the inks' place with + the eraser, so the bar keeps its shape. */ +.mx-board-inks,.mx-board-sizes{background:#F8F7F2;border-radius:12px;padding:2px;gap:2px} +.mx-board-bar .mx-board-inks button,.mx-board-bar .mx-board-sizes button{width:34px;min-width:0;height:32px;padding:0;border:0;border-radius:9px;background:none} +.mx-board-bar .mx-board-inks button:hover,.mx-board-bar .mx-board-sizes button:hover{background:rgb(27 33 64/.08)} +.mx-board-inks button::before,.mx-board-sizes button::before{content:"";border-radius:50%} +.mx-board-inks button::before{width:18px;height:18px;background:var(--dot)} +.mx-board-sizes button::before{width:var(--d);height:var(--d);background:#8A93B8} +.mx-board-bar .mx-board-inks button[aria-pressed="true"],.mx-board-bar .mx-board-sizes button[aria-pressed="true"]{background:none} +.mx-board-inks button[aria-pressed="true"]::before{box-shadow:0 0 0 2px #F8F7F2,0 0 0 4px #1B2140} +.mx-board-sizes button[aria-pressed="true"]::before{background:#1B2140;box-shadow:0 0 0 2px #F8F7F2,0 0 0 4px #1B2140} +.mx-board:not([data-tool="eraser"]) .mx-board-sizes,.mx-board[data-tool="eraser"] .mx-board-inks{display:none} +.mx-board-acts{margin-inline-start:auto} /* the page's actions at the far end, apart from the tools */ +.mx-board-bar .mx-board-close{position:relative;margin-inline-start:9px} /* close, kept apart from clear by a line */ +.mx-board-close::before{content:"";position:absolute;inset-inline-start:-8px;top:8px;bottom:8px;width:1px;background:var(--line)} +.mx-board-row{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid var(--line)} +.mx-board-row[hidden]{display:none} +.mx-board-pages{display:flex;align-items:center;gap:4px;flex:1;color:var(--muted);font-size:13px} +.mx-board-pages span{margin-inline-end:4px} +.mx-board-pages button{min-width:30px;height:28px;border:1px solid var(--line);background:none;color:var(--muted);border-radius:8px;font:700 13px/1 var(--f-body);cursor:pointer} +.mx-board-pages button.has{color:var(--ink)} +.mx-board-pages button[aria-selected="true"]{border-color:var(--mx-accent);background:var(--mx-accent-soft);color:var(--ink)} +.mx-board-stage{position:relative;flex:1;min-height:0} +/* a pen held still on an iPad is a long press: no text selection, no Copy bubble and no magnifier on the board. + The angle's words and the typed math are still fields to type in. */ +.mx-board{-webkit-user-select:none;user-select:none;-webkit-touch-callout:none} +.mx-board input,.mx-board math-field{-webkit-user-select:text;user-select:text;-webkit-touch-callout:default} +.mx-board button{touch-action:manipulation} /* two quick taps on a button: two taps, not a zoom */ +.mx-board canvas{position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:none;cursor:crosshair; + background-color:#F8F7F2;background-image:linear-gradient(rgb(27 33 64/.07) 1px,transparent 1px),linear-gradient(90deg,rgb(27 33 64/.07) 1px,transparent 1px); + background-size:28px 28px} +.mx-board-del,.mx-board-top{display:inline-flex;align-items:center;gap:5px} +.mx-board-del .mx-ic,.mx-board-top .mx-ic{width:16px;height:16px} +.mx-board-del{position:absolute;z-index:1;border:1px solid #E7B3BB;background:#FFF1F3;color:#B4233A;font:700 13px/1 var(--f-body); + padding:7px 11px;border-radius:999px;cursor:pointer;box-shadow:0 2px 8px rgb(27 33 64/.15)} +.mx-board-del[hidden]{display:none} +.mx-calc{position:absolute;z-index:2;inset-block-end:12px;inset-inline-start:12px;width:min(340px,calc(100% - 24px));max-height:calc(100% - 24px);overflow:auto; + padding:12px;border:1px solid #2A2F45;border-radius:18px;background:#3A3F55;color:#fff;box-shadow:0 8px 24px rgb(27 33 64/.35);display:flex;flex-direction:column;gap:10px} +.mx-calc[hidden]{display:none} +/* the closet door's handle on the board's right edge (a desktop screen): tap or drag it to slide the board over the exercise */ +.mx-board-door{display:none} +@media (min-width:1000px) and (any-pointer:fine){ + .mx-board-door{display:flex;align-items:center;justify-content:center;position:absolute;z-index:3;right:0;top:50%;transform:translateY(-50%); + width:22px;height:110px;padding:0;border:1px solid var(--line);border-right:0;border-radius:12px 0 0 12px;background:var(--surface-2);cursor:ew-resize;touch-action:none} + .mx-board-door::before{content:"";width:5px;height:56px;border-radius:3px;background:var(--muted);opacity:.6} + .mx-board-door:hover::before{opacity:1;background:var(--mx-accent)} + .mx-board.wide{z-index:63} /* over the exercise it slid onto */ + .mx-board.sliding{transition:none} + .mx-board.full .mx-board-door{display:none} +} +@media (prefers-reduced-motion:reduce){.mx-board{transition:none}} +/* the bar that drags the calculator: wide enough for a finger, with a grip in the middle */ +.mx-calc-grip{height:22px;margin:-6px -4px -4px;border-radius:10px;cursor:grab;touch-action:none;display:flex;align-items:center;justify-content:center} +.mx-calc-grip::before{content:"";width:48px;height:5px;border-radius:3px;background:rgb(255 255 255/.45)} +.mx-calc-grip:hover::before{background:rgb(255 255 255/.75)} +.mx-calc.moving{box-shadow:0 14px 34px rgb(27 33 64/.45)} +.mx-calc.moving .mx-calc-grip{cursor:grabbing} +.mx-calc-screen{position:relative;background:#C9D3B4;color:#1E2418;border-radius:8px;padding:16px 10px 6px;text-align:right;display:flex;flex-direction:column;box-shadow:inset 0 2px 5px rgb(0 0 0/.3)} +.mx-calc-flags{position:absolute;top:3px;left:8px;font:700 10px/1 var(--f-body);letter-spacing:.08em} +.mx-calc-expr{font:500 17px/1.3 ui-monospace,Menlo,Consolas,monospace;overflow-x:auto;white-space:nowrap;scrollbar-width:none;min-height:22px} +.mx-calc-screen output{font:700 24px/1.3 ui-monospace,Menlo,Consolas,monospace;overflow-x:auto;white-space:nowrap;scrollbar-width:none} +.mx-calc-screen output.live{opacity:.55} +.mx-calc-keys{display:grid;grid-template-columns:repeat(5,1fr);gap:14px 6px} +.mx-calc-keys button{position:relative;height:38px;padding:0;border:0;border-radius:8px;font:700 15px/1 var(--f-body);cursor:pointer;color:#fff;background:#5A5F78;box-shadow:0 2px 0 #1E2233} +.mx-calc-keys button i{position:absolute;top:-11px;left:0;right:0;font:600 10px/1 var(--f-body);font-style:normal;color:#F2C94C;pointer-events:none} +.mx-calc-keys button.num{background:#F4F5FA;color:#1B2140} +.mx-calc-keys button.fn{background:#2E3247;font-size:13px} +.mx-calc-keys button.op{background:#5A5F78} +.mx-calc-keys button.del{background:#D3455B} +.mx-calc-keys button.eq{grid-column:span 2;background:#2563D9} +.mx-calc-keys button.shift{background:#F2C94C;color:#1B2140} +.mx-calc-keys button.shift[aria-pressed="true"]{box-shadow:0 0 0 3px #fff} +.mx-calc-keys button.shifted:not(.shift){} +.mx-calc-keys button:active{transform:translateY(1px);filter:brightness(.9)} +.mx-calc-keys{padding-top:10px} + +.mx-board-send .mx-ic{width:18px;height:18px} +.mx-board-send{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--mx-accent);background:var(--mx-accent);color:var(--mx-on-accent); + font:700 14px/1 var(--f-body);padding:8px 14px;border-radius:999px;cursor:pointer} +.mx-board-send[hidden]{display:none} +.mx-board-send:disabled{opacity:.7;cursor:progress} +.mx-board-top{position:absolute;z-index:1;top:8px;left:50%;transform:translateX(-50%);border:1px solid #C5CBDF;background:#fff;color:#1B2140; + font:700 13px/1 var(--f-body);padding:7px 12px;border-radius:999px;cursor:pointer;box-shadow:0 2px 8px rgb(27 33 64/.15)} +.mx-board-top[hidden]{display:none} +.mx-uq-q{scroll-margin-top:90px} /* a question scrolled to from the board's tabs shows below the quiz's sticky head */ + +/* the board full screen (a phone or a tablet, and the phone's answer to a photo request) */ +.mx-board-head{display:none} +.mx-board.full{display:flex;flex-direction:column;position:fixed;inset:0;z-index:1100;border:0;border-radius:0;box-shadow:none;background:var(--surface); + padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)} +.mx-board.full .mx-board-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 12px;border-bottom:1px solid var(--line);color:var(--ink)} +.mx-board-back{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--mx-accent);background:var(--mx-accent-soft);color:var(--ink);font:700 14px/1 var(--f-body);padding:9px 14px;border-radius:999px;cursor:pointer} +.mx-board.full .mx-board-bar{flex-wrap:wrap;row-gap:4px} /* every tool in sight: two rows on a phone rather than hidden off the edge */ +.mx-board.full .mx-board-bar [data-do="hide"]{display:none} /* the head's "back" does it */ /* the head's "back" does it */ +.mx-board.full .mx-board-bar button{height:40px;min-width:40px} +.mx-board.full .mx-board-bar .mx-board-inks button,.mx-board.full .mx-board-bar .mx-board-sizes button{height:36px;width:40px} + +/* typing math on the board: a bar over the board's top; MathLive's keyboard sits above everything, the board too */ +body{--keyboard-zindex:3000} +.mx-board-mathedit{position:absolute;z-index:2;top:8px;left:8px;right:8px;display:flex;align-items:center;gap:6px;padding:6px; + background:#fff;border:1.5px solid var(--mx-accent);border-radius:12px;box-shadow:0 4px 16px rgb(27 33 64/.18)} +.mx-board-mathedit math-field{flex:1;min-width:0;font-size:24px;border:0;background:none;color:#1B2140;--caret-color:#2563D9;--selection-background-color:#DCE6FF} +.mx-board-mathedit math-field::part(virtual-keyboard-toggle),.mx-board-mathedit math-field::part(menu-toggle){display:none} +.mx-board-mathedit button{flex:none;width:40px;height:40px;border-radius:10px;border:1px solid #C5CBDF;background:#F4F6FC;color:#1B2140;font:700 18px/1 var(--f-body);cursor:pointer} +.mx-board-mathedit button[data-math="ok"]{background:var(--mx-accent);border-color:var(--mx-accent);color:var(--mx-on-accent)} +/* an angle's words, typed in a box where they will sit */ +.mx-board-angleedit{position:absolute;z-index:2;display:flex;flex-direction:column;gap:4px;padding:4px;background:#fff;border:1px solid #C5CBDF;border-radius:12px; + box-shadow:0 2px 10px rgb(27 33 64/.2)} +.mx-board-anglein{width:80px;height:34px;box-sizing:border-box;padding:0 6px;border:1.5px solid #2563D9;border-radius:9px; + background:#fff;color:#1B2140;font:500 17px/1 "STIX Two Text","Cambria Math","Times New Roman",serif;text-align:center;outline:none} +.mx-board-angleedit button{width:34px;height:34px;border:1px solid #C5CBDF;border-radius:9px;background:#F4F6FC;color:#1B2140; + font:500 18px/1 "STIX Two Text","Cambria Math","Times New Roman",serif;cursor:pointer} +.mx-board-angleedit button:hover{background:#DCE6FF;border-color:#2563D9} +.mx-board-arcs{display:flex;gap:4px;padding-inline-start:4px;border-inline-start:1px solid #C5CBDF} +.mx-board-arcs button{display:inline-flex;align-items:center;justify-content:center;padding:0} +.mx-board-arcs button[aria-pressed="true"]{background:#DCE6FF;border-color:#2563D9} +.mx-board-anglerow{display:flex;align-items:center;gap:4px} +.mx-board-anglerow .mx-board-anglein{flex:1} +.mx-board-anglerow > .mx-board-arcs{border:0;padding:0} /* first in its row: no line before it */ +.mx-board-colors{display:flex;gap:4px;padding-inline-start:4px;border-inline-start:1px solid #C5CBDF} +.mx-board-colors button{display:inline-flex;align-items:center;justify-content:center;padding:0;background:none} +.mx-board-colors button::before{content:"";width:18px;height:18px;border-radius:50%;background:var(--dot)} +.mx-board-colors button[aria-pressed="true"]{background:none;border-color:transparent} +.mx-board-colors button[aria-pressed="true"]::before{box-shadow:0 0 0 2px #fff,0 0 0 4px var(--dot)} +.mx-board-anglein::placeholder{color:#8A93B8} +.mx-board-mathwait{flex:1;color:#5B6694;font:500 14px/1.3 var(--f-body);padding:8px} diff --git a/mathly2/static/collection.js b/mathly2/static/collection.js new file mode 100644 index 0000000000000000000000000000000000000000..78fdd7e51ef0b1005ec2b64314852e72e92db4ef --- /dev/null +++ b/mathly2/static/collection.js @@ -0,0 +1,26 @@ +// What the student achieved: each completed lesson as a constellation, each mastered skill as a star (faded ones dimmed), and the comets. +import { api } from "./api.js"; +import { esc } from "./math.js"; +import { showCard } from "./comets.js"; +import { constellationSvg } from "./sky.js"; +import { tabs } from "./ui.js"; + +export async function show(view) { + const [{ skills, lessons }, { comets, caught, total }] = await Promise.all([api("/api/collection"), api("/api/comets")]); + view(`${tabs("collection")}

האוסף שלי

+

קבוצות כוכבים (${lessons.length})

+ ${lessons.length ? `
${lessons.map(l => `
+ ${constellationSvg(l.id, l.name, l.skills)}
${esc(l.name)}${l.skills} כוכבים
`).join("")}
` + : `

עוד אין. קבוצת כוכבים מופיעה כשכל המיומנויות של שיעור נשלטות.

`} +

מיומנויות שנשלטו (${skills.length})

+ ${skills.length ? `` + : `

עוד אין. מיומנות נשלטת אחרי 3 תשובות נכונות ברצף, בלי עזרה, בשני ימים שונים.

`} +

שביטים נדירים (${caught} מתוך ${total})

+
${comets.map(c => c.caught + ? `` + : ``).join("")}
`); + document.getElementById("comets").addEventListener("click", event => { + const tile = event.target.closest("[data-comet]"); + if (tile) showCard(comets.find(c => c.id === tile.dataset.comet), { heading: "שביט נדיר" }); + }); +} diff --git a/mathly2/static/comets.js b/mathly2/static/comets.js new file mode 100644 index 0000000000000000000000000000000000000000..d807110888b7cf1546b97272b8f6de7873a5606a --- /dev/null +++ b/mathly2/static/comets.js @@ -0,0 +1,54 @@ +// Comets on screen: the crossing comet (or, with reduced motion, one still button), the catch, and the card with the fact. +import { api } from "./api.js"; +import { esc } from "./math.js"; +import { cometCard, cometSvg } from "./sky.js"; + +const reducedMotion = () => window.matchMedia?.("(prefers-reduced-motion: reduce)").matches; + +/** A small dialog with a comet's card and fact (or a hint for one not caught yet). Closed by its button or Escape; focus returns. */ +export function showCard(comet, { heading = "שביט" } = {}) { + const back = document.activeElement; + const box = document.createElement("div"); + box.className = "comet-dialog"; + box.innerHTML = `
`; + document.body.append(box); + const close = () => { box.remove(); document.removeEventListener("keydown", onKey); back?.focus?.(); }; + const onKey = event => { if (event.key === "Escape") close(); }; + box.addEventListener("click", event => { if (event.target.closest("[data-close]")) close(); }); + document.addEventListener("keydown", onKey); + box.querySelector("button").focus(); + return close; +} + +/** A comet is due: it crosses `host` for about 4 seconds, or, with reduced motion, one still button stays until the next question. + * A tap catches it (the server picks which one) and shows the card. `onDone` runs when it is caught or gone. */ +export function cross({ feedback, onDone = () => {} } = {}) { + document.getElementById("comet")?.remove(); + const button = document.createElement("button"); + button.type = "button"; + button.id = "comet"; + const still = reducedMotion(); + button.className = still ? "comet still" : "comet"; + button.setAttribute("aria-label", "שביט! לחצו כדי לתפוס אותו"); + button.innerHTML = still ? "☄ שביט!" : cometSvg(); + (still ? feedback : document.body).append(button); // a still button sits under the feedback; a moving comet crosses the whole screen + const gone = () => { if (button.isConnected) { button.remove(); onDone(false); } }; + button.addEventListener("animationend", gone); + button.addEventListener("click", async () => { + button.remove(); + try { + const { comet } = await api("/api/comets/catch", { method: "POST" }); + showCard({ ...comet, caught: true }, { heading: "תפסתם שביט נדיר!" }); + onDone(true); + } catch { onDone(false); } + }); + return button; +} + +/** Take a crossing comet away (the sheet closed or the person left). */ +export const clear = () => document.getElementById("comet")?.remove(); diff --git a/mathly2/static/developer.js b/mathly2/static/developer.js new file mode 100644 index 0000000000000000000000000000000000000000..df74e40c09ef25cfa7f2ab4136ce23fb21f56bb6 --- /dev/null +++ b/mathly2/static/developer.js @@ -0,0 +1,9 @@ +// The developer's home. Every permission is already there (the other roles' chips open their screens); the tools come later. +import { esc } from "./math.js"; + +export async function show(me, view) { + view(`

מפתח

+

יש לך את כל ההרשאות: אפשר לפתוח את המסכים של כל התפקידים מהכפתורים למעלה.

+

כלי המפתח (פרומפטר, מעבדה, עלות ה־AI) יתווספו בשלבים הבאים.

+

${esc(me.email)}

`); +} diff --git a/mathly2/static/exercise.js b/mathly2/static/exercise.js new file mode 100644 index 0000000000000000000000000000000000000000..b6ddc769625327e34245572ea69625d80ef2a2bf --- /dev/null +++ b/mathly2/static/exercise.js @@ -0,0 +1,266 @@ +// The exercise screen: one skill, one question at a time, as a dialog over the path (mathly1's sheet). +// Tap a choice and the server grades it; a wrong answer names the mistake and never marks the right choice. +import { api, ApiError } from "./api.js"; +import { figures } from "./figures.js"; +import { clear as clearComet, cross as crossComet } from "./comets.js"; +import { esc, fmt } from "./math.js"; +import { PATH, shuffled } from "./ui.js"; + + +const COUNTDOWN = 3; // seconds before the next question after a right answer +let layer = null, skill = null, timer = null, helped = false, boardReady = null; + +const script = src => new Promise((ok, no) => { + const s = document.createElement("script"); + s.src = src; s.onload = ok; s.onerror = no; + document.head.append(s); +}); + +/** The board and its styles load the first time a sheet opens, not with the app. If they cannot load, the sheet works without it. */ +export function loadBoard() { + return boardReady ||= new Promise(done => { + const link = Object.assign(document.createElement("link"), { rel: "stylesheet", href: "/static/board.css" }); + link.onload = () => script("/static/board-math.js").then(() => script("/static/math-board.js")).then(done, done); + link.onerror = () => done(); + document.head.append(link); + }); +} + +const q = selector => layer?.querySelector(selector); +const stop = () => { clearTimeout(timer); timer = null; }; + +export const isOpen = () => !!layer; + +/** Open (or switch to) a skill's sheet. */ +export async function open(id) { + stop(); + const [data] = await Promise.all([api(`/api/skills/${encodeURIComponent(id)}`), loadBoard()]); + skill = data; + if (!layer) { + layer = document.createElement("div"); + layer.className = "mx-layer"; + document.body.append(layer); + layer.addEventListener("click", onClick); + } + layer.innerHTML = `
`; + render(); + q(".mx-x")?.focus({ preventScroll: true }); +} + +/** Close the sheet: stop timers, bring the board back from full screen, and remove everything. */ +export function close() { + if (!layer) return; + stop(); + clearComet(); + window.MathlyBoard?.closeFull?.(); + layer.remove(); + layer = skill = null; +} + +const heading = () => `
${fmt(skill.lesson.name)} +

${fmt(skill.name)}${skill.state === "mastered" ? ' ✓ נשלטה' : ""}

+
${window.MathlyBoard?.button() || ""} + +
`; + +/** Where the student is in the round: "question n of N" and a dot per question (filled for right, marked ✗ for wrong, empty when not answered). */ +const dots = round => Array.from({ length: round.total }, (_, i) => { + const result = round.results[i]; + return `${result === false ? "✗" : ""}`; +}).join(""); +const countText = round => round.done ? "הסבב הסתיים" : `שאלה ${Math.min(round.answered + 1, round.total)} מתוך ${round.total}`; +const dotsLabel = round => `נענו ${round.answered} מתוך ${round.total}, ${round.results.filter(Boolean).length} נכונות`; +const progress = () => { + const round = skill.round; + return round.total ? `
${countText(round)} + ${dots(round)}
` : ""; +}; + +/** The round's result: how it went and the mistakes, never the right answers. */ +function roundResult() { + const { result } = skill.round; + return `

סיכום הסבב

+

${result.right} מתוך ${result.total}

+ ${skill.state === "mastered" ? `

🎉 המיומנות נשלטה!

` : ""} + ${result.missed.length ? `

מה כדאי לחזק

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

    + ${m.mistake ? `

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

    ` : ""} + ${m.back ? `

    כדאי לחזור אל: ${fmt(m.back.name)}

    ` : ""}
  2. `).join("")}
` + : `

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

`} +

`; +} + +const helpBox = () => { + const ex = skill.help.solved_example; + return ``; +}; + +const related = () => { + const chips = (title, items) => items.length ? `` : ""; + return chips("דורשת:", skill.requires) + chips("פותחת:", skill.opens); +}; + +function questionHtml() { + const question = skill.question; + if (!question && skill.round.done) return roundResult(); + if (!question) return `

אין עדיין שאלות תרגול למיומנות הזו.

`; + return `

${fmt(question.question)}

${figures(question)} +
${shuffled(question.choices).map(c => + ``).join("")}
+
`; +} + +/** Mount the board for the question on screen: each question keeps its own sketch. */ +function mountBoard() { + const key = skill.question ? `${skill.id}:${skill.question.key}` : `${skill.id}:none`; + window.MathlyBoard?.mount(layer, key, { question: () => q("#ex-q") }); +} + +function render(notice = "") { + q(".mx-sheet").innerHTML = `${heading()}

${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", ``); + } +} + +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 = ``; + 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.correct_in_row} ${result.correct_in_row === 1 ? "תשובה נכונה" : "תשובות נכונות"} ברצף (מתוך 3) + ${result.mastered_now ? `

🎉 המיומנות נשלטה!

` : ""} + ${result.next_question ? `
` + : `

סיימתם את הסבב.

`}
`; + q("#ex-results")?.addEventListener("click", next); + if (result.comet) crossComet({ feedback }); + if (result.next_question) { + q("#ex-skip").addEventListener("click", next); + q("#ex-pause").addEventListener("click", () => { stop(); q("#ex-countdown").textContent = ""; q("#ex-pause").remove(); }); + countdown(next); + } + } else { + button.classList.add("wrong"); // only the chosen one is marked, with a symbol and a word (not colour alone); the right choice is never shown + button.insertAdjacentHTML("beforeend", ' לא נכון'); + const m = result.mistake; + feedback.innerHTML = `
${esc(m?.name || "תשובה לא נכונה")}${m?.tip ? `

${fmt(m.tip)}

` : ""} + ${m?.back && m.back_name ? `

כדאי לחזור אל: ${fmt(m.back_name)}

` : ""} +
`; // a wrong question does not come back in the round + q("#ex-other").addEventListener("click", next); + } +} + +async function openHelp() { + const box = q("#ex-helpbox"), button = q("[data-help]"); + const opening = box.hidden; + box.hidden = !opening; + button.setAttribute("aria-expanded", String(opening)); + if (opening && skill.question && !helped && !q("#ex-fb").children.length) { // help before answering: this answer will not count + helped = true; + try { await api(`/api/skills/${encodeURIComponent(skill.id)}/help`, { method: "POST" }); } catch { helped = false; } + } +} + +function onClick(event) { + const target = event.target; + if (target.closest("[data-close]")) { location.hash = PATH; return; } + if (target.closest("[data-board-toggle]")) { window.MathlyBoard?.toggle(); return; } + if (target.closest("[data-help]")) { openHelp(); return; } + if (target.closest("#ex-newround")) { newRound(); return; } + const choice = target.closest(".ex-choice"); + if (choice && !choice.disabled) answer(choice); +} + +window.addEventListener("mathly:leave", close); // another role's screen opened, or the person signed out + +document.addEventListener("keydown", event => { + if (event.key === "Escape" && layer && !document.querySelector(".mx-board.full")) location.hash = PATH; +}); diff --git a/mathly2/static/figures.js b/mathly2/static/figures.js new file mode 100644 index 0000000000000000000000000000000000000000..12854ab796901dfd9c3b344e068ad1d034d20661 --- /dev/null +++ b/mathly2/static/figures.js @@ -0,0 +1,97 @@ +// Drawing for exercise-bank questions that have a `figure` (geometry) or a `graph` (a function's points). +// Ported from the current app's static/math.js (figure() and plot()), unchanged except that the marks use class +// "mk" (the new app already uses "m" for formulas). The syntax of `figure` is described below. +import { esc } from "./math.js"; + +/* A geometry question's figure (`figure` in app/math_algebra9.json, checked by app/math_skills.py), one statement per ";": + A=x,y[@dir] a point (y up; "_P" is not named, @n/s/e/w/ne/nw/se/sw places its name) · poly A B C · line A B · dash A B + dot A · len A B text (lenx: on the other side) · ang P V Q text (ang2/ang3: two or three arcs) · right P V Q + tick A B n (equal sides) · par A B n (parallel arrows) · text x,y words · note words (a line under the figure) + grid (a coordinate plane) */ +function figure(src){ + const P={}, ops=[]; let grid=false; + for(const st of src.split(";").map(s=>s.trim()).filter(Boolean)){ + const m=st.match(/^([A-Za-z_][\w']*)=(-?[\d.]+),(-?[\d.]+)(?:@(\w+))?$/); + if(m){ P[m[1]]={x:+m[2],y:+m[3],dir:m[4]}; continue; } + if(st==="grid"){ grid=true; continue; } + const [op,...a]=st.split(/\s+/); ops.push([op,a]); + } + const under=ops.filter(([op])=>op==="note").map(([,a])=>`

${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="")=>`${esc(words)}`; + // a label beside a point: one beside a side grows away from it, so a long label never covers the side + const beside=(x,y,[nx,ny],gap,words,cls)=>Math.abs(nx)>0.8?txt(x+nx*(gap-6),y+ny*gap,words,cls,nx>0?"start":"end"):txt(x+nx*gap,y+ny*gap,words,cls); + let back="", shapes="", marks="", words=""; + if(grid){ + for(let x=x0;x<=x1;x++){ back+=``; + if(x&&x>x0&&x`; + if(y&&y>y0&&y`; + } + const side=(a,b,flip)=>{const [ax,ay]=at(a),[bx,by]=at(b),u=unit([bx-ax,by-ay]),mx=(ax+bx)/2,my=(ay+by)/2; + let n=[-u[1],u[0]]; if((n[0]*(mx-cx)+n[1]*(my-cy)<0)!==!!flip) n=[-n[0],-n[1]]; return {u,n,mx,my};}; + for(const [op,a] of ops){ + if(op==="poly") shapes+=``; + else if(op==="line"||op==="dash"){ const [p,q]=[at(a[0]),at(a[1])]; shapes+=``; } + else if(op==="len"||op==="lenx"){ const {n,mx,my}=side(a[0],a[1],op==="lenx"); words+=beside(mx,my,n,14,a.slice(2).join(" "),"q"); } + else if(/^ang[23]?$/.test(op)){ + const v=at(a[1]), u1=unit([at(a[0])[0]-v[0],at(a[0])[1]-v[1]]), u2=unit([at(a[2])[0]-v[0],at(a[2])[1]-v[1]]); + let d=Math.atan2(u2[1],u2[0])-Math.atan2(u1[1],u1[0]); while(d>Math.PI)d-=2*Math.PI; while(d<=-Math.PI)d+=2*Math.PI; + const arcs=+(op[3]||1), deg=Math.abs(d)*180/Math.PI; + for(let i=0;i`; } + const b=unit([u1[0]+u2[0],u1[1]+u2[1]]), r=16+(arcs-1)*4+13+Math.max(0,(45-deg)*0.45); + if(a.length>3) words+=txt(v[0]+b[0]*r,v[1]+b[1]*r,a.slice(3).join(" "),"q"); + } + else if(op==="right"){ const v=at(a[1]), u1=unit([at(a[0])[0]-v[0],at(a[0])[1]-v[1]]), u2=unit([at(a[2])[0]-v[0],at(a[2])[1]-v[1]]), k=10; + marks+=``; } + else if(op==="tick"||op==="par"){ const {u,n,mx,my}=side(a[0],a[1]), k=+(a[2]||1); + // arrows step aside from the equal-side marks of the same side + const shift=op==="par"&&ops.some(([o,b])=>o==="tick"&&[b[0],b[1]].sort().join()===[a[0],a[1]].sort().join())?14:0; + for(let i=0;i` + :``; } } + else if(op==="dot") a.forEach(n=>{const [x,y]=at(n);shapes+=``;}); + } + const dirs={n:[0,-1],s:[0,1],e:[1,0],w:[-1,0],ne:[1,-1],nw:[-1,-1],se:[1,1],sw:[-1,1]}; + for(const n of named){ const [x,y]=at(n), d=unit(dirs[P[n].dir]||(Math.hypot(x-cx,y-cy)<1?[1,-1]:[x-cx,y-cy])); words+=txt(x+d[0]*14,y+d[1]*14,n,"v"); } + notes.forEach(t=>{words+=txt(X(t.x),Y(t.y),t.words,"t");}); + return `
${back}${shapes}${marks}${words}${under}השרטוט להמחשה ואינו בקנה מידה
`; +} + +// a function's graph through the given points: monotone cubic (Fritsch-Carlson), so it never passes the marked extrema +function plot(g){ + const W=320, H=210, PAD=24, [x0,x1]=g.x, [y0,y1]=g.y; + const sx=x=>PAD+(x-x0)/(x1-x0)*(W-2*PAD), sy=y=>H-PAD-(y-y0)/(y1-y0)*(H-2*PAD); + const xs=g.points.map(p=>p[0]), ys=g.points.map(p=>p[1]), k=xs.length; + const d=xs.slice(0,-1).map((x,i)=>(ys[i+1]-ys[i])/(xs[i+1]-x)); + const m=xs.map((_,i)=>i===0?d[0]:i===k-1?d[k-2]:d[i-1]*d[i]<=0?0:(d[i-1]+d[i])/2); + d.forEach((di,i)=>{ if(di===0){ m[i]=m[i+1]=0; return; } const a=m[i]/di, b=m[i+1]/di, s=a*a+b*b; + if(s>9){ const t=3/Math.sqrt(s); m[i]=t*a*di; m[i+1]=t*b*di; } }); + let line=""; + for(let i=0;i`; + if(x) ticks+=`${x}`; } + for(let y=Math.ceil(y0);y<=y1;y++){ grid+=``; + if(y) ticks+=`${y}`; } + const dots=g.points.map(([x,y])=>``).join(""); + return `
${grid} + + ${ticks}${dots}
`; +} + +/** The drawings a bank question needs, as HTML: its graph and/or its figure; empty for a plain question. */ +export const figures = q => `${q.graph ? plot(q.graph) : ""}${q.figure ? figure(q.figure) : ""}`; diff --git a/mathly2/static/grades.js b/mathly2/static/grades.js new file mode 100644 index 0000000000000000000000000000000000000000..2cf842a7ce452d7ece205233bd2c130985abb397 --- /dev/null +++ b/mathly2/static/grades.js @@ -0,0 +1,30 @@ +// The student's grades: each lesson's best quiz grade, and each real test's exercise tests and simulation (best grade, tries, last date). +// Assignments will add their rows later. +import { api } from "./api.js"; +import { esc, fmt } from "./math.js"; +import { shortDate, tabs } from "./ui.js"; + +const day = iso => iso ? new Date(iso).toLocaleDateString("he-IL", { day: "numeric", month: "numeric" }) : ""; +const tries = n => `${n} ${n === 1 ? "ניסיון" : "ניסיונות"}`; + +function row({ attrs, href, title, best, attempts, last }) { + return `
  • ${title} + ${best} + + ${tries(attempts)}${last ? ` · האחרון ב־${day(last)}` : ""}
  • `; +} + +const testTitle = (t, suffix) => `מבחן ב־${shortDate(t.date)}: ${suffix}${t.removed ? " (הוסר)" : ""}`; + +export async function show(view) { + const { quizzes, exercise_tests: exercises = [], simulations = [] } = await api("/api/grades"); + const none = !quizzes.length && !exercises.length && !simulations.length; + view(`${tabs("grades")}

    הציונים שלי

    + ${none ? `

    עוד אין ציונים. הבוחן של כל שיעור מחכה בסוף השיעור במסלול.

    ` : ""} + ${quizzes.length ? `

    בחנים

      ${quizzes.map(g => row({ attrs: `data-lesson="${esc(g.lesson.id)}"`, href: `#/quiz/${esc(g.lesson.id)}`, + title: fmt(g.lesson.name), best: g.best, attempts: g.attempts, last: g.last })).join("")}
    ` : ""} + ${exercises.length ? `

    מבחני תרגול

      ${exercises.map(g => row({ attrs: `data-test="${g.test.id}" data-number="${g.number}"`, + href: `#/test/${g.test.id}`, title: testTitle(g.test, `מבחן תרגול ${g.number}`), best: g.best, attempts: g.attempts, last: g.last })).join("")}
    ` : ""} + ${simulations.length ? `

    מבחני סימולציה

      ${simulations.map(g => row({ attrs: `data-test="${g.test.id}"`, + href: `#/test/${g.test.id}`, title: testTitle(g.test, "מבחן סימולציה"), best: g.best, attempts: g.attempts, last: g.last })).join("")}
    ` : ""}
    `); +} diff --git a/mathly2/static/home.js b/mathly2/static/home.js new file mode 100644 index 0000000000000000000000000000000000000000..352d70eadaeb2e1b0ab4687e97c8b5c0191404dd --- /dev/null +++ b/mathly2/static/home.js @@ -0,0 +1,55 @@ +// The student's home for a subject: the nearest test with its readiness and one task for today, the required simulation, +// the other tests, and a button that continues the path. +import { api } from "./api.js"; +import { esc, fmt } from "./math.js"; +import { PATH, backToSubjects, daysText, shortDate, tabs } from "./ui.js"; + +const part = (label, name, value) => `${label} ${name} ${value === null ? "—" : value}`; + +/** The readiness number as a level bar with its three parts under it; before the simulation it says the bar is capped. */ +export function readinessBar(r) { + return `
    +

    ${esc(r.label)}

    +
    +

    ${part("M", "שליטה", r.parts.M)} ${part("E", "מבחני תרגול", r.parts.E)} ${part("S", "סימולציה", r.parts.S)}

    + ${r.waiting_for_simulation ? `

    עוד לא עשיתם מבחן סימולציה, ולכן המדד לא עובר את ${80}.

    ` : ""}
    `; +} + +/** Today's task as {label, href}. */ +function taskLink(task, test, next) { + const skill = id => `#/skill/${encodeURIComponent(id)}`; + switch (task.kind) { + case "path": return { label: task.skill ? `לסיים את המסלול: ${task.skill_name}` : "לסיים את המסלול", href: task.skill ? skill(task.skill) : PATH }; + case "ex1": case "ex2": return { label: `מבחן תרגול ${task.kind === "ex1" ? 1 : 2}`, href: `#/exam/${test.id}/${task.kind === "ex1" ? 1 : 2}` }; + case "sim": return { label: "מבחן סימולציה", href: `#/sim/${test.id}` }; + case "review": return { label: `חזרה על ${task.skill_name}`, href: skill(task.skill) }; + case "mixed_review": return task.skill ? { label: `חזרה קלה: ${task.skill_name}`, href: skill(task.skill) } : { label: "חזרה קלה במסלול", href: PATH }; + default: return next ? { label: `להמשיך במסלול: ${next.name}`, href: skill(next.id) } : { label: "למסלול", href: PATH }; + } +} + +const lessonsOf = test => test.lessons.map(l => fmt(l.name)).join(", "); + +function nearest(test, task, next) { + const t = taskLink(task, test, next); + return `
    +

    המבחן הבא: ${shortDate(test.date)} (${daysText(test.days_left)})

    +

    ${lessonsOf(test)}${test.note ? ` · ${esc(test.note)}` : ""}

    + ${readinessBar(test.readiness)} +

    המשימה להיום${esc(t.label)}

    +

    כל התוכנית והמבחנים

    `; +} + +export async function show(view) { + const data = await api("/api/home"); + const [first, ...others] = data.tests; + const required = data.tests.filter(t => t.simulation.required); + view(`${tabs("home")}${backToSubjects()} + ${first ? nearest(first, data.task, data.next_skill) : `

    הבית

    +

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

    `} + ${required.map(t => `חובה מבחן סימולציה למבחן ב־${shortDate(t.date)}`).join("")} +

    ${data.next_skill ? `להמשיך במסלול: ${fmt(data.next_skill.name)} ` + : `למסלול: כל הכוכבים פתוחים לתרגול `}

    + ${others.length ? `

    מבחנים נוספים

    ` : ""}`); +} diff --git a/mathly2/static/icons/icon-192.png b/mathly2/static/icons/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..ccc4d04f64f39cdcc5d665f41b7eeceafacaef8f --- /dev/null +++ b/mathly2/static/icons/icon-192.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4f12034ecaac9a0af98a05a42a0e03e3a8d105025f72e29d78fb0f5f515b157 +size 9300 diff --git a/mathly2/static/icons/icon-512.png b/mathly2/static/icons/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..802e5b8b67609a3583e04cea853678a6f1ae8fd3 --- /dev/null +++ b/mathly2/static/icons/icon-512.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77f27b79ee2ff2182a2db413cf6e5f74950ca21b1e42a5b96aa246f6360fb153 +size 15837 diff --git a/mathly2/static/icons/icon-maskable-512.png b/mathly2/static/icons/icon-maskable-512.png new file mode 100644 index 0000000000000000000000000000000000000000..bbf7540261522da13421e59f8567eab4453698ba --- /dev/null +++ b/mathly2/static/icons/icon-maskable-512.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baa210c0719ed498b7ae289963f7806b9f9ee27831a9af63cdc0c3d350e7d0e3 +size 12089 diff --git a/mathly2/static/index.html b/mathly2/static/index.html index 1d5633b083f766268eb785bea321c2c0ae6ecb57..508657d8e7a10f5eb459129e0c0f8e3b505759e4 100644 --- a/mathly2/static/index.html +++ b/mathly2/static/index.html @@ -3,8 +3,9 @@ - + Mathly + diff --git a/mathly2/static/logo.svg b/mathly2/static/logo.svg new file mode 100644 index 0000000000000000000000000000000000000000..a31746aaf22decd3aa7d6a5883a22f7942c5e661 --- /dev/null +++ b/mathly2/static/logo.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + +לומדים +בכיף +המורה הפרטי שלך + diff --git a/mathly2/static/manager.js b/mathly2/static/manager.js new file mode 100644 index 0000000000000000000000000000000000000000..260413afb9749f5a6c232282b4bb3107ad54574c --- /dev/null +++ b/mathly2/static/manager.js @@ -0,0 +1,115 @@ +// The manager's screens: every class (make, change, delete) and every student. A manager sees no learning data. +import { api } from "./api.js"; +import { esc } from "./math.js"; + +let draw, lessons = [], tab = "classes", editing = null, draft = null, flash = { message: "", error: "" }; +// draft: what was typed in the editor when a save was refused, so the form keeps it and the person can fix one thing + +const note = () => `${flash.error && tab !== "edit" ? `` : ""}${flash.message ? `

    ${esc(flash.message)}

    ` : ""}`; +const tabs = () => `
    + ${[["classes", "כיתות"], ["edit", editing ? "עריכת כיתה" : "כיתה חדשה"], ["students", "תלמידים"]].map(([id, label]) => + ``).join("")}
    `; + +async function render() { + const body = tab === "classes" ? await classesView() : tab === "students" ? await studentsView() : editorView(); + draw(`

    מנהל כיתות

    ${tabs()}${note()}${body}
    `); + document.getElementById("mgr-tabs").addEventListener("click", event => { + const next = event.target.closest("[data-tab]")?.dataset.tab; + if (!next) return; + if (next === "edit" && tab !== "edit") editing = null; + draft = null; + go(next); + }); + if (tab === "classes") wireClasses(); + if (tab === "edit") wireEditor(); + if (tab === "edit" && flash.error) { // the form is long: bring the reason into view, next to the buttons that were pressed + const reason = document.getElementById("form-error"); + reason.scrollIntoView({ block: "center" }); + reason.focus(); + } + flash = { message: "", error: "" }; +} + +const go = next => { tab = next; return render(); }; + +async function classesView() { + const classes = await api("/api/classes"); + const names = Object.fromEntries(lessons.map(l => [l.id, l.name])); + return `
    + ${classes.length} כיתות
    + ${classes.length ? `
    ${classes.map(c => `
    +

    ${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} בדיקות ביום

    `).join("")}
    ` + : `

    עוד אין כיתות. פתחו כיתה ראשונה, בחרו את השיעורים והוסיפו את התלמידים.

    `}`; +} + +function wireClasses() { + document.getElementById("new-class").addEventListener("click", () => { editing = null; draft = null; go("edit"); }); + document.getElementById("classes")?.addEventListener("click", async event => { + const edit = event.target.closest("[data-edit]")?.dataset.edit, del = event.target.closest("[data-delete]")?.dataset.delete; + if (edit) { editing = await api(`/api/classes/${edit}`); draft = null; return go("edit"); } + if (del) { + const card = event.target.closest("article"); + if (!confirm(`למחוק את הכיתה "${card.querySelector("h3").textContent}"? ההתקדמות של התלמידים נשמרת.`)) return; + try { await api(`/api/classes/${del}`, { method: "DELETE" }); flash.message = "הכיתה נמחקה."; } + catch (e) { flash.error = e.message; } + go("classes"); + } + }); +} + +function editorView() { + const c = editing, d = draft; // a refused save keeps what was typed + const chosen = new Set(d ? d.lessons : c?.lessons || []); + const value = (typed, saved, fallback = "") => d ? (typed ?? fallback) : (saved ?? fallback); + return `

    ${c ? `עריכת ${esc(c.name)}` : "כיתה חדשה"}

    + + +
    ${lessons.map(l => ``).join("")}
    + + + + +
    +
    +

    ה־AI כבוי עד שבית הספר מאשר שהמשפחות מסכימות. רק אחרי זה מפעילים אותו.

    + ${flash.error ? `` : ""} +
    `; +} + +function wireEditor() { + document.getElementById("c-cancel").addEventListener("click", () => { editing = null; draft = null; go("classes"); }); + document.getElementById("class-form").addEventListener("submit", async event => { + event.preventDefault(); + const body = { + name: document.getElementById("c-name").value, + lessons: [...document.querySelectorAll("#c-lessons input:checked")].map(i => i.value), + teacher_email: document.getElementById("c-teacher").value.trim() || null, + students: document.getElementById("c-students").value, + ai_enabled: document.getElementById("c-ai").checked, + ai_daily_checks: Number(document.getElementById("c-budget").value), + }; + try { + const saved = editing ? await api(`/api/classes/${editing.id}`, { method: "PUT", body }) : await api("/api/classes", { method: "POST", body }); + flash.message = `${editing ? "השינויים נשמרו" : "הכיתה נפתחה"}: ${saved.name}.${saved.invalid?.length ? ` לא נראה כמו מייל: ${saved.invalid.join(", ")}` : ""}`; + editing = null; draft = null; + go("classes"); + } catch (e) { draft = body; flash.error = e.message; go("edit"); } + }); +} + +async function studentsView() { + const students = await api("/api/students"); + return `
    + ${students.length ? students.map(s => ``).join("") + : ``}
    תלמידכיתות
    ${esc(s.email)}${s.classes.map(esc).join(" · ")}
    עדיין לא נוספו תלמידים לכיתות.
    `; +} + +export async function show(me, view) { + draw = view; + tab = "classes"; editing = null; + lessons = await api("/api/classes/lessons"); + await render(); +} diff --git a/mathly2/static/math-board.js b/mathly2/static/math-board.js new file mode 100644 index 0000000000000000000000000000000000000000..ddd79dfd12f783e46a4b79bd8691267f56b1b595 --- /dev/null +++ b/mathly2/static/math-board.js @@ -0,0 +1,931 @@ +/* Mathly's sketch board. On a desktop screen it sits beside the exercise (the student turns it on from the sheet's + header; this browser remembers the choice). On a phone or a tablet it opens full screen over the exercise, from + the same button, and closes back to the question. Used by a skill's exercise, the practice exam, the unit quiz, + and the phone's answer to a photo request from the computer (openFull). Each question keeps its own sketch for + as long as the page is open. Nothing is sent anywhere unless the student hands it in. + + Everything on the board is an element that can be moved or erased: a pen stroke (with a pen's pressure), + a straight line, a circle (dragged from the center), an angle's arc with its words (the angle tool: pointing at a + corner where two lines meet shows the arc; a click adds it and asks for its words, and a number gets a degree + sign), typed math (the math keyboard, static/board-math.js), and a + copy of the question (its text and figures). + Line ends and circle centers snap to the ends and centers already drawn, so a triangle closes neatly; + lines that meet that way move together. The eraser removes the lines and circles it touches and cuts pen strokes; + it leaves the question's copy alone (select it and delete it instead). + The paper is endless downwards and to the right (what was written while the board was slid open stays in reach + when it slides back): the mouse wheel over the board scrolls it (sideways with Shift or a trackpad), and so do + two fingers on a touch screen in any direction (one finger draws), and so does dragging empty paper with the move tool. Once a pen has touched the screen, + a single finger is ignored: a hand resting on it. While the pen writes (and for a moment after it lifts) every + touch is ignored, so a palm neither scrolls the paper nor takes back the stroke, and a wide contact is a palm too. + A sheet can let the board hand in a question's answer (the unit quiz): the sketch becomes a picture. */ +(()=>{ +const PREF="mathly.board"; +const isOn=()=>{ try{ return localStorage.getItem(PREF)==="on"; }catch{ return false; } }; +const setOn=on=>{ try{ localStorage.setItem(PREF,on?"on":"off"); }catch{} }; + +const INKS=[["#1B2140","שחור"],["#2563D9","כחול"],["#D3455B","אדום"]]; +const ERASERS=[[16,"קטן"],[40,"בינוני"],[90,"גדול"]]; +const TOOLS=[["move","הזזה"],["pen","עט"],["line","קו ישר"],["circle","עיגול"],["angle","זווית"],["math","נוסחה"],["eraser","מחק"]]; +/* one line-drawn icon set (24×24, the button's text colour), so every button looks alike on every device and + follows the button's hover and pressed colours; "flip" icons point the other way in a right-to-left page */ +const DOT='fill="currentColor" stroke="none"'; +const ICONS={ + move:'', + pen:'', + line:``, + circle:``, + angle:'', + math:'', + eraser:'', + question:'', + undo:'', + clear:'', + close:'', + send:'', + done:'', + back:'', + top:'', + calc:''}; +const FLIP=new Set(["undo","back"]); +const ic=n=>``; +const MATH_SIZE=26; +const GREEK=["α","β","γ"], ARC_GAP=4; // the angle box's letters; how far apart a double or triple arc's arcs are +const ARCS=[[1,"קשת אחת"],[2,"קשת כפולה"],[3,"קשת משולשת"],["right","זווית ישרה (ריבוע)"]]; +// a corner with one, two or three arcs: equal angles are marked alike +const arcsIcon=n=>n==="right"?'' + :``; +const ANGLE_FONT='500 18px "STIX Two Text","Cambria Math","Times New Roman",serif', CORNER=32, CORNER_TOUCH=40; // how near a corner the angle tool reaches: about as far as an arc +const ON=3; // how close a point is to count as on a line: where an angle's corner is, and what moves with what +const PEN=2.6, SHAPE=2.4, SNAP=12, GRAB=9, STEP=2, HISTORY=100; +const PAPER="#F8F7F2", PAPER_INK="#1B2140", PAPER_FAINT="#C5CBDF", SELECT="#2563D9"; +const FONT='500 17px Rubik, system-ui, "Segoe UI", sans-serif', LINE_H=27, CARD_PAD=14; + +/* sketch key -> {marks, past}: marks are drawn in order; past holds copies of marks for undo */ +const sketches=new Map(), images=new Map(); +let el=null, canvas=null, ctx=null, key="", base="", pages=0, page=0, layer=null, source=null, hand=null, onPage=null; +let tool="pen", ink=INKS[0][0], eraser=ERASERS[1][0], sendLabel=""; +let draft=null, drag=null, rub=null, slide=null, selection=[]; // slide: the move tool dragging empty paper, which scrolls it +let paper=PAPER; // the paper's colour: the board's, or white in the picture handed in +let naming=null, hover=null; // naming: an angle's words being typed {mark, node, input, fresh, was, key}; hover: the corner the angle tool points at +let editing=null; // the formula being typed: {mark (null for a new one), at, node, field, key} +let full=null; // the board open full screen: {saved: the context to go back to, done: called when it closes} +const touches=new Map(); let pan=null, penSeen=false; +// a hand resting on the screen while a pen writes: its touches are ignored until they lift +const palms=new Set(); let pensDown=0, penUpAt=-1e9; +const PALM_AFTER_PEN=500, PALM_SIZE=60; // ms after the pen lifts; a contact this wide (css px) is a palm, not a finger +const desk=()=>matchMedia("(min-width:1000px) and (any-pointer:fine)").matches; // the same test as math.css +const context=()=>({layer,base,pages,page,source,hand,onPage,sendLabel,key}); +function restore(c){ ({layer,base,pages,page,source,hand,onPage,sendLabel,key}=c); } + +const sketch=()=>{ if(!sketches.has(key)) sketches.set(key,{marks:[],past:[],x:0,y:0}); return sketches.get(key); }; // x, y: how far right and down the paper is scrolled +const scrollTo=(x,y)=>{ const s=sketch(); s.x=Math.max(0,x); s.y=Math.max(0,y); paint(); }; // never left of or above the paper's corner +const marks=()=>sketch().marks; +const copy=list=>JSON.parse(JSON.stringify(list)); +function remember(before=copy(marks())){ const s=sketch(); s.past.push(before); if(s.past.length>HISTORY) s.past.shift(); } +const shown=()=>!!el?.isConnected&&canvas.clientWidth>0; +const dist=(a,b)=>Math.hypot(a[0]-b[0],a[1]-b[1]); +const same=(a,b)=>dist(a,b)<.5; + +/* The calculator: a scientific one in the layout of the Casio fx-991ES PLUS, on a panel over the paper's corner + (the toolbar's calculator button). SHIFT gives the second function printed above a key (sin⁻¹, 10ˣ, x³, nCr, ...), + DEG/RAD/GRA is the angle unit, S⇔D turns an answer into a fraction and back, Ans is the last answer. + The expression is read by a small parser, never evaluated as code. */ +// [label, what it types (or an @command), shift label, what shift types, class] +const CALC_KEYS=[ + ["SHIFT","@shift",,,"fn shift"],["DEG","@mode",,,"fn"],["S⇔D","@sd",,,"fn"],["nPr","nPr","nCr","nCr","fn"],["%","%",,,"fn"], + ["sin","sin(","sin⁻¹","sin⁻¹(","fn"],["cos","cos(","cos⁻¹","cos⁻¹(","fn"],["tan","tan(","tan⁻¹","tan⁻¹(","fn"],["log","log(","10ˣ","10^(","fn"],["ln","ln(","eˣ","e^(","fn"], + ["(","(",,,"fn"],[")",")",,,"fn"],["x²","^2","x³","^3","fn"],["xʸ","^",,,"fn"],["√","√(","³√","³√(","fn"], + ["x⁻¹","^(−1)","x!","!","fn"],["|x|","Abs(",,,"fn"],["π","π","e","e","fn"],["(−)","−",,,"fn"],["Ans","Ans",,,"fn"], + ["7","7"],["8","8"],["9","9"],["DEL","@del",,,"del"],["AC","@ac",,,"del"], + ["4","4"],["5","5"],["6","6"],["×","×",,,"op"],["÷","÷",,,"op"], + ["1","1"],["2","2"],["3","3"],["+","+",,,"op"],["−","−",,,"op"], + ["0","0"],[".","."],["ᴇ","ᴇ",,,"fn"],["=","@eq",,,"eq"]]; +const cs={expr:"",res:null,done:false,shift:false,mode:"DEG",ans:0,frac:false}; +const CALC_FUNS=["sin⁻¹(","cos⁻¹(","tan⁻¹(","sin(","cos(","tan(","log(","ln(","³√(","√(","Abs("]; +const CALC_NAMES=[...CALC_FUNS,"Ans","nPr","nCr","π"]; +function calcTrig(k,x,inv){ + const d=cs.mode, full=d==="DEG"?360:d==="GRA"?400:2*Math.PI, f={s:"sin",c:"cos",t:"tan"}[k]; + if(inv){ const r=Math[`a${f}`](x); return d==="DEG"?r*180/Math.PI:d==="GRA"?r*200/Math.PI:r; } + if(d!=="RAD"){ // whole turns, halves and quarters give exact answers (sin 180 is 0, not 1.2e-16) + const q=((x%full)+full)%full, half=full/2, quarter=full/4; + if(k==="s"){ if(q%half===0) return 0; if(q===quarter) return 1; if(q===3*quarter) return -1; } + if(k==="c"){ if(q===0) return 1; if(q===half) return -1; if(q===quarter||q===3*quarter) return 0; } + if(k==="t"){ if(q%half===0) return 0; if(q%half===quarter) throw 0; } + } + return Math[f](d==="DEG"?x*Math.PI/180:d==="GRA"?x*Math.PI/200:x); +} +const calcFact=n=>{ if(!Number.isInteger(n)||n<0||n>170) throw 0; let r=1; for(let k=2;k<=n;k++) r*=k; return r; }; +function calcValue(text){ + const T=[], src=text.replace(/\s+/g,"").replace(/-/g,"−").replace(/\*/g,"×").replace(/\//g,"÷"); + for(let i=0;ir.startsWith(x))||("+−×÷()^!%e".includes(r[0])?r[0]:null); + if(!nm) throw 0; T.push(nm); i+=nm.length; + } + let p=0; const nx=()=>T[p]; + const starts=t=>t!==undefined&&(typeof t==="object"||t==="("||t==="e"||t==="π"||t==="Ans"||CALC_FUNS.includes(t)); + const close=()=>{ if(nx()===")") p++; else if(pv) throw 0; + v=calcFact(v)/calcFact(v-r)/(c?calcFact(r):1); } return v; } + function prod(){ let v=perm(); for(;;){ const t=nx(); + if(t==="×"){ p++; v*=perm(); } else if(t==="÷"){ p++; v/=perm(); } else if(starts(t)) v*=perm(); else return v; } } // 2π and 2(3+4) multiply + function sum(){ let v=prod(); for(;;){ if(nx()==="+"){ p++; v+=prod(); } else if(nx()==="−"){ p++; v-=prod(); } else return v; } } + const v=sum(); if(pString(+v.toPrecision(10)).replace("e+","ᴇ").replace("e-","ᴇ−").replace("-","−"); +function calcFrac(v){ // a decimal answer as a fraction with a denominator up to 10000, when it is one + if(!Number.isFinite(v)||Number.isInteger(v)) return null; + const x=Math.abs(v); let h0=0,h1=1,k0=1,k1=0,b=x; + for(let n=0;n<24;n++){ + const a=Math.floor(b), h2=a*h1+h0, k2=a*k1+k0; h0=h1; h1=h2; k0=k1; k1=k2; + if(k1>10000) return null; + if(Math.abs(x-h1/k1)<1e-11*Math.max(1,x)) return `${v<0?"−":""}${h1}/${k1}`; + const f=b-a; if(f<1e-14) return null; b=1/f; + } + return null; +} +function calcDraw(){ + const box=el.querySelector(".mx-calc"), ex=box.querySelector("[data-calc-expr]"), out=box.querySelector("[data-calc-out]"); + let text="", cls=""; + if(cs.res?.err) text="שגיאה"; + else if(cs.res){ text=(cs.frac&&calcFrac(cs.res.v))||calcShow(cs.res.v); } + else if(cs.expr){ try{ if(/[^0-9.]/.test(cs.expr)) text=calcShow(calcValue(cs.expr)); }catch{} cls="live"; } + ex.textContent=cs.expr||"0"; ex.scrollLeft=ex.scrollWidth; + out.textContent=text||" "; out.className=cls; + box.querySelector("[data-calc-flags]").textContent=[cs.shift?"S":"",cs.mode==="DEG"?"D":cs.mode==="RAD"?"R":"G"].filter(Boolean).join(" "); + box.querySelector('[data-calc-do="mode"]').textContent=cs.mode; + box.querySelectorAll("[data-calc]").forEach(b=>b.classList.toggle("shifted",cs.shift)); + box.querySelector(".shift").setAttribute("aria-pressed",cs.shift); +} +function calcAct(act){ + if(act==="@shift"){ cs.shift=!cs.shift; return calcDraw(); } + cs.shift=false; + if(act==="@mode"){ cs.mode=cs.mode==="DEG"?"RAD":cs.mode==="RAD"?"GRA":"DEG"; if(cs.res&&!cs.res.err&&cs.done) calcAct("@eq"); return calcDraw(); } + if(act==="@sd"){ if(cs.res&&!cs.res.err&&calcFrac(cs.res.v)) cs.frac=!cs.frac; return calcDraw(); } + if(act==="@ac"){ cs.expr=""; cs.res=null; cs.done=false; cs.frac=false; return calcDraw(); } + if(act==="@del"){ + if(cs.done){ cs.done=false; cs.res=null; } + else cs.expr=cs.expr.replace(/(?:sin⁻¹\(|cos⁻¹\(|tan⁻¹\(|sin\(|cos\(|tan\(|log\(|ln\(|³√\(|√\(|Abs\(|Ans|nPr|nCr|.)$/u,""); + return calcDraw(); + } + if(act==="@eq"){ + if(!cs.expr) return calcDraw(); + try{ const v=calcValue(cs.expr); cs.res={v}; cs.ans=v; }catch{ cs.res={err:true}; } + cs.done=true; cs.frac=false; return calcDraw(); + } + if(cs.done){ cs.expr=/^(?:\^|!|%|nPr|nCr|[+−×÷])/.test(act)?"Ans"+act:act; cs.done=false; cs.res=null; cs.frac=false; } // an operator goes on from the answer + else cs.expr+=act; + calcDraw(); +} +/* the calculator's bar on top drags it anywhere over the paper; it keeps its place while the page is open, + and stays whole inside the board when the board gets smaller */ +let calcAt=null; // {x, y}: its corner in the board's stage; null: the corner it starts in +function calcPlace(){ + const box=el?.querySelector(".mx-calc"); if(!box||box.hidden||!calcAt) return; + const st=box.parentElement, x=Math.max(0,Math.min(calcAt.x,st.clientWidth-box.offsetWidth)), y=Math.max(0,Math.min(calcAt.y,st.clientHeight-box.offsetHeight)); + box.style.inset="auto"; box.style.left=x+"px"; box.style.top=y+"px"; // inset first: it would undo left and top +} +function calcGrip(){ + const box=el.querySelector(".mx-calc"), grip=box.querySelector(".mx-calc-grip"); let from=null; + grip.addEventListener("pointerdown",e=>{ + e.preventDefault(); try{ grip.setPointerCapture(e.pointerId); }catch{} + from={id:e.pointerId,x:e.clientX-box.offsetLeft,y:e.clientY-box.offsetTop}; box.classList.add("moving"); + }); + grip.addEventListener("pointermove",e=>{ if(from?.id!==e.pointerId) return; calcAt={x:e.clientX-from.x,y:e.clientY-from.y}; calcPlace(); }); + const end=e=>{ if(from?.id===e.pointerId){ from=null; box.classList.remove("moving"); } }; + grip.addEventListener("pointerup",end); grip.addEventListener("pointercancel",end); + new ResizeObserver(calcPlace).observe(box.parentElement); +} +function calcPress(i){ const [,ins,,sins]=CALC_KEYS[i]; calcAct(cs.shift&&sins!==undefined?sins:ins); } +const calcKeysHtml=()=>CALC_KEYS.map(([label,,sl,,cls="num"],i)=> + ``).join(""); +function toggleCalc(){ + const box=el.querySelector(".mx-calc"), on=box.hidden; + box.hidden=!on; el.querySelector('[data-do="calc"]').setAttribute("aria-pressed",on); + if(on){ calcDraw(); calcPlace(); box.querySelector("button").focus({preventScroll:true,focusVisible:false}); } +} +document.addEventListener("keydown",e=>{ + const box=el?.querySelector(".mx-calc"); + if(!box||box.hidden||!box.contains(document.activeElement)||e.ctrlKey||e.metaKey||e.altKey) return; + const k={"*":"×","/":"÷","-":"−"}[e.key]||e.key; + if(/^[0-9.+−×÷()^!%]$/.test(k)) calcAct(k); + else if(k==="Enter"||k==="=") calcAct("@eq"); + else if(k==="Backspace") calcAct("@del"); + else if(k==="Escape"&&(cs.expr||cs.res)) calcAct("@ac"); + else return; + e.preventDefault(); e.stopImmediatePropagation(); +},true); + +function build(){ + el=document.createElement("aside"); el.className="mx-board"; el.setAttribute("aria-label","לוח טיוטה"); + el.innerHTML=`
    לוח טיוטה
    + +
    +
    +
    + + +
    `; + canvas=el.querySelector("canvas"); ctx=canvas.getContext("2d"); + calcGrip(); doorGrip(); + el.addEventListener("click",e=>{ + const b=e.target.closest("button"); if(!b) return; + if(b.dataset.tool) setTool(b.dataset.tool); + if(b.dataset.ink){ ink=b.dataset.ink; if(tool==="eraser"||tool==="move") setTool("pen"); pressed("[data-ink]",b); } + if(b.dataset.eraser){ eraser=+b.dataset.eraser; setTool("eraser"); pressed("[data-eraser]",b); } + if(b.dataset.page){ turn(+b.dataset.page); onPage?.(page); } + const act=b.dataset.do; + if(act==="undo") undo(); + if(act==="clear"&&marks().length){ remember(); marks().length=0; select([]); paint(); drawPages(); } + if(act==="delete") removeSelection(); + if(act==="question") copyQuestion(); + if(act==="send") send(); + if(b.dataset.calc) calcPress(+b.dataset.calc); + if(act==="calc") toggleCalc(); + if(act==="top") scrollTo(0,0); + if(act==="door"&&!doorDragged) setDoor(doorOpen()?null:DOOR_OPEN); + doorDragged=false; + if(act==="hide") full?closeFull():toggle(); + }); + canvas.addEventListener("pointerdown",down); + canvas.addEventListener("pointermove",move); + canvas.addEventListener("pointerup",up); + canvas.addEventListener("pointercancel",up); + canvas.addEventListener("contextmenu",e=>e.preventDefault()); + // Safari on an iPad: a pen or a finger held still on the paper would select the page's text and offer to copy it + canvas.addEventListener("touchstart",e=>e.preventDefault(),{passive:false}); + el.addEventListener("selectstart",e=>{ if(!e.target.closest?.("input,math-field,[contenteditable]")) e.preventDefault(); }); + canvas.addEventListener("dblclick",e=>{ const m=hit(at(e)); if(m?.kind==="math") editMath(m,at(e)); else if(m?.kind==="angle") startAngle(at(e),0); }); + canvas.addEventListener("pointerleave",()=>{ if(hover){ hover=null; paint(); } }); // typed math is edited where it is // the pen's side button: no browser menu over the board + canvas.addEventListener("wheel",e=>{ // endless paper: scrolls down as far as needed, never above the top + if(e.ctrlKey) return; // the browser's zoom + e.preventDefault(); const s=sketch(), k=e.deltaMode===1?24:e.deltaMode===2?canvas.clientHeight:1; + let dx=e.deltaX*k, dy=e.deltaY*k; if(e.shiftKey&&!dx){ dx=dy; dy=0; } // Shift and the wheel: sideways + scrollTo(s.x+dx,s.y+dy); + },{passive:false}); + new ResizeObserver(fit).observe(canvas); + setTool(tool); +} +/* the board's right edge slides like a closet door: a tap on its handle opens the board over the exercise and + closes it back; dragging the handle stops it anywhere between. The CSS keeps it between the two + (--door: the gap on the board's right, in px). It stays as it was left while the page is open. */ +const DOOR_OPEN=16; +const doorShut=()=>Math.min(600,innerWidth*.42)+32; // the gap beside the exercise: the same sum as math.css +const doorOpen=()=>innerWidth-el.getBoundingClientRect().right{ + e.preventDefault(); try{ b.setPointerCapture(e.pointerId); }catch{} + from={id:e.pointerId,x:e.clientX,r:innerWidth-el.getBoundingClientRect().right,moved:false}; + }); + b.addEventListener("pointermove",e=>{ + if(from?.id!==e.pointerId) return; const dx=e.clientX-from.x; + if(!from.moved&&Math.abs(dx)<6) return; + if(!from.moved){ from.moved=true; el.classList.add("sliding"); } + setDoor(Math.max(DOOR_OPEN,Math.min(doorShut(),from.r-dx))); + }); + const end=e=>{ + if(from?.id!==e.pointerId) return; const f=from; from=null; el.classList.remove("sliding"); + if(!f.moved) return; doorDragged=true; // the click that follows is not a tap + const r=innerWidth-el.getBoundingClientRect().right; + setDoor(r>=doorShut()-24?null:r<=DOOR_OPEN+24?DOOR_OPEN:r); // near either end: all the way + }; + b.addEventListener("pointerup",end); b.addEventListener("pointercancel",end); +} +function pressed(sel,b){ el.querySelectorAll(sel).forEach(x=>x.setAttribute("aria-pressed",x===b)); } +function reset(){ draft=drag=rub=slide=null; hover=null; select([]); if(editing) finishMath(false); if(naming) finishAngle(true); } +function setTool(t){ + tool=t; if(hover){ hover=null; paint(); } el.querySelectorAll("[data-tool]").forEach(x=>x.setAttribute("aria-pressed",x.dataset.tool===t)); + el.dataset.tool=t; if(t!=="move"&&selection.length){ select([]); paint(); } + // the eraser's cursor is a ring its own size, so the student sees what it will wipe + const r=eraser/2, svg=``; + canvas.style.cursor=t==="eraser"?`url("data:image/svg+xml,${svg.replace(//g,"%3E")}") ${r+1} ${r+1}, cell`:t==="move"?"grab":""; +} +function select(list){ selection=list; } +function turn(p){ if(editing) finishMath(true); if(naming) finishAngle(true); page=p; key=`${base}:${page}`; reset(); drawPages(); drawSend(); paint(); } +function drawSend(){ + const b=el.querySelector(".mx-board-send"); b.hidden=!hand; el.querySelector(".mx-board-row").hidden=pages<2&&!hand; if(!hand) return; + b.disabled=false; b.innerHTML=`${ic("send")}${sendLabel||`הגשה לשאלה ${page+1}`}`; b.title=sendLabel||`הגשת הלוח כתשובה לשאלה ${page+1}`; +} +function drawPages(){ + const box=el.querySelector(".mx-board-pages"); el.querySelector(".mx-board-row").hidden=pages<2&&!hand; + box.innerHTML=pages<2?"":`שאלה${Array.from({length:pages},(_,i)=>{ + const has=(sketches.get(`${base}:${i}`)?.marks||[]).length>0; + return ``; }).join("")}`; +} + +/* ---------- drawing ---------- */ +function fit(){ + if(!shown()) return; + const d=devicePixelRatio||1, w=Math.round(canvas.clientWidth*d), h=Math.round(canvas.clientHeight*d); + if(canvas.width!==w||canvas.height!==h){ canvas.width=w; canvas.height=h; } + paint(); +} +function paint(){ + if(!ctx) return; + const d=devicePixelRatio||1, {x,y}=sketch(); ctx.setTransform(1,0,0,1,0,0); ctx.clearRect(0,0,canvas.width,canvas.height); ctx.setTransform(d,0,0,d,-x*d,-y*d); + canvas.style.backgroundPosition=`${-x}px ${-y}px`; // the grid scrolls with the paper + el.querySelector(".mx-board-top").hidden=x<1&&y<1; + marks().forEach(draw); + if(draft?.kind==="circle") guide(draft); + if(hover&&!naming) aimed(hover); + if(selection.length) outline(selection); + const del=el.querySelector(".mx-board-del"); del.hidden=!selection.length||!!drag?.before; + if(selection.length){ const [x0,y0]=edges(selection); del.style.left=`${Math.max(4,x0)}px`; const top=y0-y; del.style.top=`${top>40?top-36:Math.max(4,top+4)}px`; } +} +function draw(m){ + ctx.save(); ctx.strokeStyle=m.color; ctx.lineCap="round"; ctx.lineJoin="round"; + if(m.kind==="line"){ ctx.lineWidth=SHAPE; ctx.beginPath(); ctx.moveTo(...m.a); ctx.lineTo(...m.b); ctx.stroke(); } + else if(m.kind==="circle"){ ctx.lineWidth=SHAPE; ctx.beginPath(); ctx.arc(m.a[0],m.a[1],dist(m.a,m.b),0,Math.PI*2); ctx.stroke(); } + else if(m.kind==="angle") angleMark(m); + else if(m.kind==="card") card(m); + else if(m.kind==="math"){ const L=mathBox(m); if(L){ ctx.fillStyle=m.color; ctx.direction="ltr"; ctx.textAlign="left"; ctx.textBaseline="alphabetic"; L.paint(ctx,m.x,m.y+L.a); } } + else{ for(let i=1;inaming?.mark===m?naming.arcs:m.arcs||1; // while its box is open: the arcs picked there +// a right angle is marked with a little square in its corner: its sides along the edges, its far corner on the line splitting the angle +const square=m=>{ + const k=Math.max(8,Math.min(14,arcR(m)*.5)), u=[Math.cos(m.s),Math.sin(m.s)], w=[Math.cos(m.s+m.w),Math.sin(m.s+m.w)]; + return [[m.v[0]+k*u[0],m.v[1]+k*u[1]],[m.v[0]+k*(u[0]+w[0]),m.v[1]+k*(u[1]+w[1])],[m.v[0]+k*w[0],m.v[1]+k*w[1]]]; +}; +const rim=m=>arcsOf(m)==="right"?dist(square(m)[1],m.v):arcR(m)+ARC_GAP*(arcsOf(m)-1); // how far out the mark reaches +const colorOf=m=>naming?.mark===m?naming.color:m.color; // while its box is open: the colour picked there +function angleMark(m){ + ctx.lineWidth=1.8; ctx.strokeStyle=colorOf(m); + if(arcsOf(m)==="right"){ const [a,b,c]=square(m); ctx.beginPath(); ctx.moveTo(...a); ctx.lineTo(...b); ctx.lineTo(...c); ctx.stroke(); } + else for(let k=0;kctx.fillText(line,m.x+m.w-CARD_PAD,m.y+CARD_PAD+i*LINE_H+4)); + for(const f of m.figs){ const img=picture(f.src); if(img.complete&&img.naturalWidth) ctx.drawImage(img,m.x+f.x,m.y+f.y,f.w,f.h); } +} +function picture(src){ + if(!images.has(src)){ const img=new Image(); img.onload=()=>paint(); img.src=src; images.set(src,img); } + return images.get(src); +} +const mathBox=m=>window.MathlyBoardMath?.layout(m.latex,m.size||MATH_SIZE); +function box(m){ + if(m.kind==="card") return [m.x,m.y,m.x+m.w,m.y+m.h]; + if(m.kind==="math"){ const L=mathBox(m)||{w:0,a:0,d:0}; return [m.x,m.y,m.x+L.w,m.y+L.a+L.d]; } + if(m.kind==="angle"){ const [x,y,w]=labelAt(m), r=rim(m); return [Math.min(m.v[0]-r,x-w/2),Math.min(m.v[1]-r,y-10),Math.max(m.v[0]+r,x+w/2),Math.max(m.v[1]+r,y+10)]; } + if(m.kind==="circle"){ const r=dist(m.a,m.b); return [m.a[0]-r,m.a[1]-r,m.a[0]+r,m.a[1]+r]; } + const pts=m.kind==="line"?[m.a,m.b]:m.pts, xs=pts.map(p=>p[0]), ys=pts.map(p=>p[1]); + return [Math.min(...xs),Math.min(...ys),Math.max(...xs),Math.max(...ys)]; +} +// the box around the elements, a little outside their ink +function edges(list){ const bs=list.map(box); return [Math.min(...bs.map(b=>b[0]))-6,Math.min(...bs.map(b=>b[1]))-6,Math.max(...bs.map(b=>b[2]))+6,Math.max(...bs.map(b=>b[3]))+6]; } +function outline(list){ + const [x0,y0,x1,y1]=edges(list); + ctx.save(); ctx.strokeStyle=SELECT; ctx.lineWidth=1.5; ctx.setLineDash([6,4]); ctx.strokeRect(x0,y0,x1-x0,y1-y0); ctx.restore(); +} + +/* ---------- geometry ---------- */ +function nearestOn(p,a,b){ + const dx=b[0]-a[0], dy=b[1]-a[1], l=dx*dx+dy*dy, t=l?Math.max(0,Math.min(1,((p[0]-a[0])*dx+(p[1]-a[1])*dy)/l)):0; + return [a[0]+t*dx,a[1]+t*dy]; +} +const toSegment=(p,a,b)=>dist(p,nearestOn(p,a,b)); +// how far p is from the element's ink +function reach(m,p){ + if(m.kind==="line") return toSegment(p,m.a,m.b); + if(m.kind==="circle") return Math.min(Math.abs(dist(p,m.a)-dist(m.a,m.b)),dist(p,m.a)); + if(m.kind==="angle"&&arcsOf(m)==="right"){ const [a,b,c]=square(m); return Math.min(toSegment(p,a,b),toSegment(p,b,c),toWords(m,p)); } + if(m.kind==="angle") return Math.min(inWedge(Math.atan2(p[1]-m.v[1],p[0]-m.v[0]),m.s,m.w)?Math.max(0,Math.abs(dist(p,m.v)-(arcR(m)+rim(m))/2)-(rim(m)-arcR(m))/2):Infinity,toWords(m,p)); + if(m.kind==="card"||m.kind==="math"){ const [x0,y0,x1,y1]=box(m), dx=Math.max(x0-p[0],0,p[0]-x1), dy=Math.max(y0-p[1],0,p[1]-y1); + return m.kind==="card"?(dx||dy?Infinity:0):Math.hypot(dx,dy); } + if(m.pts.length===1) return dist(p,m.pts[0]); + let d=Infinity; for(let i=1;i{ const all=marks(); for(let i=all.length-1;i>=0;i--) if(reach(all[i],p)<=GRAB) return all[i]; return null; }; +const joints=m=>m.kind==="line"?[m.a,m.b]:m.kind==="circle"?[m.a]:m.kind==="angle"?[m.v]:[]; // an angle moves with its corner +// an element and everything joined to it by a shared end or center: a triangle moves as one +function group(m){ + const out=new Set([m]), todo=[m]; + while(todo.length){ const cur=todo.pop(); + for(const o of marks()) if(!out.has(o)&&linked(cur,o)){ out.add(o); todo.push(o); } } + return [...out]; +} +// joined: a shared end or center, a line's end on another line (drawn from a side), or an angle on a line through it +const lies=(m,o)=>o.kind==="line"&&(m.kind==="line"||m.kind==="angle")&&joints(m).some(p=>toSegment(p,o.a,o.b)<=ON); +const linked=(m,o)=>joints(m).some(p=>joints(o).some(q=>same(p,q)))||lies(m,o)||lies(o,m); +// a line's ends and a circle's center pull to the ends and centers already on the board, or else onto a line +function snap(p,skip){ + let best=null, d=SNAP; + for(const m of marks()){ if(m===skip) continue; for(const q of joints(m)){ const k=dist(p,q); if(k{ p[0]+=dx; p[1]+=dy; }; + if(m.kind==="card"||m.kind==="math"){ m.x+=dx; m.y+=dy; } else if(m.kind==="free") m.pts.forEach(by); else if(m.kind==="angle") by(m.v); else { by(m.a); by(m.b); } +} +// the eraser at p: lines, circles and typed math it touches go; pen strokes are cut; the question's copy stays +function rubOut(p){ + const r=eraser/2, all=marks(); let changed=false; + for(let i=all.length-1;i>=0;i--){ const m=all[i]; + if(m.kind==="line"||m.kind==="circle"||m.kind==="math"||m.kind==="angle"){ if(reach(m,p)<=r+SHAPE/2){ all.splice(i,1); changed=true; } continue; } + if(m.kind!=="free") continue; + const gone=m.pts.map(q=>dist(p,q)<=r+PEN); if(!gone.some(Boolean)) continue; + const runs=[]; let run=[]; m.pts.forEach((q,k)=>{ if(gone[k]){ if(run.length) runs.push(run); run=[]; } else run.push(q); }); if(run.length) runs.push(run); + all.splice(i,1,...runs.map(pts=>({kind:"free",color:m.color,pts}))); changed=true; + } + return changed; +} +/* ---------- angles at corners ---------- */ +const TAU=Math.PI*2, turnOf=a=>(a%TAU+TAU)%TAU, inWedge=(t,s,w)=>turnOf(t-s)<=w; +const gap=(a,b)=>Math.abs(turnOf(a-b+Math.PI)-Math.PI); +// where two lines cross, or null (an end on the other line counts) +function cross(m,o){ + const r=[m.b[0]-m.a[0],m.b[1]-m.a[1]], q=[o.b[0]-o.a[0],o.b[1]-o.a[1]], den=r[0]*q[1]-r[1]*q[0]; + if(Math.abs(den)<1e-9) return null; + const ex=o.a[0]-m.a[0], ey=o.a[1]-m.a[1], t=(ex*q[1]-ey*q[0])/den, u=(ex*r[1]-ey*r[0])/den, k=.01; + return t>=-k&&t<=1+k&&u>=-k&&u<=1+k?[m.a[0]+t*r[0],m.a[1]+t*r[1]]:null; +} +// the points where lines meet: shared ends, an end partway along another line, and crossings +function meets(){ + const lines=marks().filter(m=>m.kind==="line"), out=lines.flatMap(m=>[m.a,m.b]); + lines.forEach((m,i)=>lines.slice(i+1).forEach(o=>{ const c=cross(m,o); if(c) out.push(c); })); + return out; +} +// every line through v, as rays going out of v: one for a line ending there, two for a line passing through +function raysAt(v){ + const rays=[], add=b=>{ + if(dist(b,v)<=ON) return; + const t=turnOf(Math.atan2(b[1]-v[1],b[0]-v[0])), len=dist(v,b), twin=rays.find(r=>gap(r.t,t)<.02); + if(twin) twin.len=Math.min(twin.len,len); else rays.push({t,len}); + }; + for(const m of marks()) if(m.kind==="line"){ + if(dist(m.a,v)<=ON) add(m.b); else if(dist(m.b,v)<=ON) add(m.a); else if(toSegment(v,m.a,m.b)<=ON){ add(m.a); add(m.b); } + } + return rays.sort((a,b)=>a.t-b.t); +} +/* A corner near p where lines meet, and the angle (under half a turn) between two of its rays that p points into: + the inside of a triangle's corner, either side of a line drawn from a side, or the smallest one when p is on the + corner itself. Pointing along a line that splits an angle picks the whole angle, its arc a little wider, and + its words go in the widest gap the inner lines leave. */ +function corner(p,near){ + let v=null, d=near; + for(const q of meets()){ const k=dist(p,q); if(krays.forEach(n=>{ + const w=turnOf(n.t-r.t); if(r===n||w<.02||w>Math.PI-.01) return; + wedges.push({s:r.t,w,len:Math.min(r.len,n.len),inner:rays.filter(x=>x!==r&&x!==n&&turnOf(x.t-r.t)a.w-b.w); + const t=Math.atan2(p[1]-v[1],p[0]-v[0]), far=dist(p,v)>6, along=far&&rays.find(r=>gap(r.t,t)<.1); + const off=x=>inWedge(t,x.s,x.w)?0:Math.min(gap(t,x.s),gap(t,x.s+x.w))+(x.inner.length?1:0); // outside them all: the nearest + const w=(along&&wedges.find(x=>x.inner.includes(along)))||(far&&wedges.reduce((a,b)=>off(b)turnOf(x.t-w.s)).sort((a,b)=>a-b),w.w]; + let f=w.w/2, g=w.w; + if(w.inner.length){ g=0; for(let k=1;kg){ g=cuts[k]-cuts[k-1]; f=(cuts[k]+cuts[k-1])/2; } } + return {v:[v[0],v[1]],s:w.s,w:w.w,r:Math.max(12,Math.min(30,w.len*.3))+10*w.inner.length,f:w.s+f}; +} +// what the angle tool would act on at p: an angle already there (to retype its words), or a corner to add one to +// (an angle's words come first; then the corner decides, so pointing along a middle line over a half's arc still +// gives the whole angle; an arc whose corner is gone is still there to retype) +function aim(p,near){ + const all=marks().filter(m=>m.kind==="angle").reverse(), as=m=>({mark:m,v:m.v,s:m.s,w:m.w,r:arcR(m)}); + const named=all.find(m=>toWords(m,p)<=4); if(named) return as(named); + const c=corner(p,near); + if(c){ c.mark=all.find(m=>dist(m.v,c.v)<=ON&&gap(m.s,c.s)<.05&&Math.abs(m.w-c.w)<.05)||null; if(c.mark) c.r=arcR(c.mark); return c; } + const old=all.find(m=>reach(m,p)<=GRAB); return old?as(old):null; +} +// how far p is from an angle's words +function toWords(m,p){ + if(!m.text) return Infinity; + const [x,y,w]=labelAt(m); return Math.hypot(Math.max(Math.abs(p[0]-x)-w/2,0),Math.max(Math.abs(p[1]-y)-10,0)); +} +// where an angle's words sit: on the line splitting the angle, just past the arc, and far enough out to clear the edges +// (right by the arc, even in a narrow angle: they are drawn over a line's ink with a rim of paper) +function labelAt(m,text=m.text){ + ctx.save(); ctx.font=ANGLE_FONT; const w=text?ctx.measureText(text).width:0; ctx.restore(); + const f=m.f??m.s+m.w/2, out=Math.abs(w/2*Math.cos(f))+Math.abs(10*Math.sin(f)), c=Math.cos(f), s=Math.sin(f); // f: the words' way + // words of an angle beside it at the same corner, added before it: these move out until they are clear of them + const all=marks(), i=all.indexOf(m), mine=inside(m); + const near=i<0?[]:all.slice(0,i).filter(o=>o.kind==="angle"&&o.text&&dist(o.v,m.v)<=ON&&!mine.includes(o)&&!inside(o).includes(m)).map(o=>labelAt(o)); + let d=rim(m)+5+out; + for(let k=0;k<30&&near.some(([x,y,ow])=>Math.abs(m.v[0]+d*c-x)<(w+ow)/2+4&&Math.abs(m.v[1]+d*s-y)<20);k++) d+=3; + return [m.v[0]+d*c,m.v[1]+d*s,w,out]; +} +// the angles inside m at its corner (the halves of an angle a line splits) +const inside=m=>marks().filter(o=>o!==m&&o.kind==="angle"&&dist(o.v,m.v)<=ON&&o.wv.trim().replace(/(?NAMES[w.toLowerCase()]).replace(TERM,"$1$2°"); +const bare=t=>t.replace(TERM,"$1$2"); // for retyping: the signs degrees() puts back by itself +// adds the angle at p (or opens one already there), with a box over its words +function startAngle(p,near){ + const c=aim(p,near); if(!c) return; + hover=null; + let m=c.mark; const fresh=!m; + if(fresh){ remember(); m={kind:"angle",color:ink,v:c.v,s:c.s,w:c.w,r:c.r,f:c.f,text:""}; marks().push(m); } + // the box for the words, with the usual names of a triangle's angles a tap away + const node=document.createElement("div"); node.className="mx-board-angleedit"; + // two rows, to fit a phone: the words and the letters; the arcs and the colour + node.innerHTML=`
    ${GREEK.map(g=>``).join("")}
    +
    ${ARCS.map(([n,name])=>``).join("")} + ${INKS.map(([c,name])=>``).join("")}
    `; + const input=node.querySelector("input"); input.value=bare(m.text); + naming={mark:m,node,input,fresh,was:m.text,arcs:m.arcs||1,color:m.color,key}; + input.addEventListener("keydown",ev=>{ + if(ev.key==="Enter"){ ev.preventDefault(); finishAngle(true); } + else if(ev.key==="Escape"){ ev.preventDefault(); ev.stopPropagation(); finishAngle(false); } + }); + input.addEventListener("blur",()=>naming?.node===node&&finishAngle(true)); + // a letter's button types it where the cursor is ("β+90" takes a tap and a few keys); the box keeps its focus + node.querySelectorAll("[data-letter]").forEach(b=>b.addEventListener("pointerdown",ev=>{ + ev.preventDefault(); input.setRangeText(b.textContent,input.selectionStart??input.value.length,input.selectionEnd??input.value.length,"end"); + })); + // one, two or three arcs: shown at once, kept with the words + node.querySelectorAll("[data-arcs]").forEach(b=>b.addEventListener("pointerdown",ev=>{ + ev.preventDefault(); naming.arcs=b.dataset.arcs==="right"?"right":+b.dataset.arcs; node.querySelectorAll("[data-arcs]").forEach(x=>x.setAttribute("aria-pressed",x===b)); paint(); + })); + // the angle's colour, its arcs and words together: shown at once on the arcs and in the box, kept with the words + const tint=()=>{ input.style.color=naming.color; paint(); }; + node.querySelectorAll("[data-color]").forEach(b=>b.addEventListener("pointerdown",ev=>{ + ev.preventDefault(); naming.color=b.dataset.color; node.querySelectorAll("[data-color]").forEach(x=>x.setAttribute("aria-pressed",x===b)); tint(); + })); + input.style.color=m.color; + el.querySelector(".mx-board-stage").append(node); + const [x,y]=labelAt(m,"000°"), W=canvas.clientWidth, bw=node.offsetWidth; + node.style.left=`${Math.max(4,Math.min(W-4-bw,x-sketch().x-bw/2))}px`; node.style.top=`${Math.max(4,y-sketch().y-21)}px`; + paint(); input.focus({preventScroll:true}); + if(pages>1) drawPages(); +} +// keep: the words go in (a new angle with none keeps just its arc); otherwise a new angle is taken back +function finishAngle(keep){ + const n=naming; if(!n) return; naming=null; n.node.remove(); + const s=sketches.get(n.key), m=n.mark; if(!s) return; + if(keep){ + const t=degrees(n.input.value); if(!n.fresh&&(t!==n.was||n.arcs!==(m.arcs||1)||n.color!==m.color)) remember(); + m.text=t; m.color=n.color; if(n.arcs!==1) m.arcs=n.arcs; else delete m.arcs; // 2, 3, or "right" + } + else if(n.fresh){ const i=s.marks.indexOf(m); if(i>=0){ s.marks.splice(i,1); s.past.pop(); } } + paint(); if(pages>1) drawPages(); +} + +// points along a to b, close enough that nothing between two of them is skipped +function along(a,b,step){ const n=Math.max(1,Math.ceil(dist(a,b)/step)), out=[]; for(let k=1;k<=n;k++) out.push([a[0]+(b[0]-a[0])*k/n,a[1]+(b[1]-a[1])*k/n,a[2]+((b[2]??a[2])-a[2])*k/n]); return out; } + +/* ---------- the pointer ---------- */ +const at=e=>{ const r=canvas.getBoundingClientRect(); return [e.clientX-r.left+sketch().x,e.clientY-r.top+sketch().y,e.pointerType==="pen"?e.pressure:.5]; }; // a point on the paper, not on the screen +const capture=id=>{ try{ canvas.setPointerCapture(id); }catch{} }; // a pointer the browser no longer knows: draw anyway +const fingers=()=>{ let x=0,y=0; touches.forEach(p=>{ x+=p[0]; y+=p[1]; }); return [x/touches.size,y/touches.size]; }; // where the fingers are, together +// a second finger came down: what the first one started is taken back, and the two scroll the paper +function stopLive(){ + const s=sketch(); + if(draft){ s.marks.splice(s.marks.indexOf(draft),1); s.past.pop(); draft=null; } + if(rub){ s.marks=rub.before; rub=null; } + if(drag){ if(drag.before) s.marks=s.past.pop(); drag=null; select([]); } + slide=null; paint(); +} +function down(e){ + if(e.pointerType==="pen"){ + penSeen=true; pensDown++; + if(touches.size){ // the hand came down first: whatever it started is taken back, and it is a palm now + stopLive(); touches.forEach((_,id)=>palms.add(id)); touches.clear(); pan=null; + } + } + if(e.pointerType==="touch"&&penSeen&&(pensDown||performance.now()-penUpAt=PALM_SIZE)){ + palms.add(e.pointerId); e.preventDefault(); return; + } + if(e.pointerType==="touch"){ + touches.set(e.pointerId,[e.clientX,e.clientY]); capture(e.pointerId); e.preventDefault(); + if(touches.size===2){ stopLive(); pan={at:fingers(),x:sketch().x,y:sketch().y}; return; } + if(touches.size>2||pan||penSeen) return; // a hand resting on the screen while a pen writes + } + if(e.button!==0&&e.button!==5) return; // 5: the pen's eraser end + const p=at(e), use=e.button===5||(e.buttons&32)>0?"eraser":tool; + if(editing){ e.preventDefault(); return finishMath(true); } // a tap beside the formula being typed: it is done + if(naming){ e.preventDefault(); return finishAngle(true); } // the same for an angle's words + if(use==="angle"){ e.preventDefault(); return startAngle(p,e.pointerType==="mouse"?CORNER:CORNER_TOUCH); } + if(use==="math"){ e.preventDefault(); const m=hit(p); return editMath(m?.kind==="math"?m:null,p); } + capture(e.pointerId); e.preventDefault(); + if(use==="move"){ + const m=hit(p); + if(!m){ select([]); slide={id:e.pointerId,at:[e.clientX,e.clientY],x:sketch().x,y:sketch().y}; canvas.style.cursor="grabbing"; return paint(); } // empty paper: scroll it + if(!selection.includes(m)) select(group(m)); + drag={id:e.pointerId,last:p,before:null}; return paint(); + } + if(use==="eraser"){ rub={id:e.pointerId,last:p,before:copy(marks()),changed:rubOut(p)}; return paint(); } + remember(); + draft=use==="pen"?{kind:"free",color:ink,pts:[p]}:{kind:use,color:ink,a:snap(p),b:null}; + if(draft.b===null) draft.b=[...draft.a]; + draft.id=e.pointerId; marks().push(draft); paint(); +} +function move(e){ + if(palms.has(e.pointerId)) return; + if(touches.has(e.pointerId)){ + touches.set(e.pointerId,[e.clientX,e.clientY]); + if(pan){ if(touches.size>=2){ const [fx,fy]=fingers(); scrollTo(pan.x-(fx-pan.at[0]),pan.y-(fy-pan.at[1])); } return; } + } + if(slide&&e.pointerId===slide.id) return scrollTo(slide.x-(e.clientX-slide.at[0]),slide.y-(e.clientY-slide.at[1])); + if(tool==="move"&&!drag&&!e.buttons) canvas.style.cursor=hit(at(e))?"move":"grab"; + if(tool==="angle"&&!e.buttons&&e.pointerType!=="touch"){ // a mouse or a pen over a corner: its arc, dashed + const c=naming?null:aim(at(e),CORNER), was=hover; hover=c; canvas.style.cursor=c?"pointer":""; + if(c?.v[0]!==was?.v[0]||c?.v[1]!==was?.v[1]||c?.s!==was?.s) paint(); + return; + } + if(drag&&e.pointerId===drag.id){ + const p=at(e), dx=p[0]-drag.last[0], dy=p[1]-drag.last[1]; if(!dx&&!dy) return; + if(!drag.before){ drag.before=true; remember(); } + selection.forEach(m=>shift(m,dx,dy)); drag.last=p; return paint(); + } + if(rub&&e.pointerId===rub.id){ + const p=at(e); for(const q of along(rub.last,p,eraser/4)) rub.changed=rubOut(q)||rub.changed; + rub.last=p; return paint(); + } + if(!draft||e.pointerId!==draft.id) return; + if(draft.kind==="free"){ + const all=e.getCoalescedEvents?.(); + for(const c of all?.length?all:[e]){ const p=at(c); draft.pts.push(...along(draft.pts.at(-1),p,STEP)); } + ctx.save(); ctx.strokeStyle=draft.color; ctx.lineCap=ctx.lineJoin="round"; + for(let i=Math.max(1,draft.drawn||1);i1&&drawPages(); } + if(!draft||e.pointerId!==draft.id) return; + const m=draft; draft=null; delete m.id; delete m.drawn; + if(m.kind!=="free"&&dist(m.a,m.b)<3){ marks().pop(); sketch().past.pop(); } // a tap, not a shape + paint(); if(pages>1) drawPages(); +} +function undo(){ const s=sketch(); if(!s.past.length) return; s.marks=s.past.pop(); reset(); paint(); if(pages>1) drawPages(); } +function removeSelection(){ + if(!selection.length) return; + remember(); const all=marks(); for(const m of selection) all.splice(all.indexOf(m),1); + select([]); paint(); if(pages>1) drawPages(); +} + +/* ---------- the question's copy ---------- */ +// the question's words, with each piece of math kept left to right and in one piece +function words(node){ + const out=[]; let word=""; + const flush=()=>{ if(word) out.push(word); word=""; }; + (function walk(n){ + for(const c of n.childNodes){ + if(c.nodeType===3){ for(const ch of c.textContent){ if(/\s/.test(ch)) flush(); else word+=ch; } } + else if(c.nodeName==="BR"){ flush(); out.push("\n"); } + else if(c.classList?.contains("m")) word+="⁦"+c.textContent.trim()+"⁩"; // math kept left to right, stuck to the brackets and marks around it + else walk(c); + } + })(node); + flush(); return out; +} +function wrap(tokens,width){ + ctx.save(); ctx.font=FONT; ctx.direction="rtl"; + const lines=[]; let line=""; + for(const t of tokens){ + if(t==="\n"){ lines.push(line); line=""; continue; } + const next=line?line+" "+t:t; + if(line&&ctx.measureText(next).width>width){ lines.push(line); line=t; } else line=next; + } + if(line) lines.push(line); ctx.restore(); return lines; +} +// a figure drawn for the dark sheet, redrawn in ink for the white board +function paperColor(c){ + const m=String(c).match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/); if(!m) return c; + if(m[4]!==undefined&&+m[4]===0) return "none"; + const l=(.299*m[1]+.587*m[2]+.114*m[3])/255; + return l>.55?PAPER_INK:l<.3?PAPER_FAINT:c; +} +const STYLE=["fill","stroke","stroke-width","stroke-dasharray","stroke-linecap","stroke-linejoin","opacity","font-size","font-family","font-weight","font-style","text-anchor","dominant-baseline"]; +function paperFigure(svg){ + const r=svg.getBoundingClientRect(); if(!r.width||!r.height) return null; + const clone=svg.cloneNode(true), from=[svg,...svg.querySelectorAll("*")], to=[clone,...clone.querySelectorAll("*")]; + from.forEach((n,i)=>{ const cs=getComputedStyle(n); + for(const prop of STYLE){ let v=cs.getPropertyValue(prop); if(prop==="fill"||prop==="stroke") v=paperColor(v); if(v) to[i].style.setProperty(prop,v); } }); + clone.setAttribute("xmlns","http://www.w3.org/2000/svg"); clone.setAttribute("width",r.width); clone.setAttribute("height",r.height); + clone.removeAttribute("class"); clone.style.background="none"; + return {src:"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(new XMLSerializer().serializeToString(clone)),w:r.width,h:r.height}; +} +function copyQuestion(){ + const q=source?.(page); if(!q||!shown()) return; + const text=q.querySelector(".mx-uq-text")||q.querySelector(":scope > p"); + const W=Math.min(canvas.clientWidth-32,600), inner=W-2*CARD_PAD; + const lines=text?wrap(words(text),inner):[]; + let y=CARD_PAD+lines.length*LINE_H+(lines.length?6:0); + const figs=[]; + for(const svg of q.querySelectorAll("svg")){ + if(svg.closest("button")) continue; // the answers' buttons are not part of the question + const f=paperFigure(svg); if(!f) continue; + const s=Math.min(1,inner/f.w), w=f.w*s, h=f.h*s; + figs.push({src:f.src,x:(W-w)/2,y,w,h}); y+=h+8; + } + if(!lines.length&&!figs.length) return; + remember(); + const m={kind:"card",x:sketch().x+canvas.clientWidth-16-W,y:sketch().y+16,w:W,h:y+CARD_PAD-(figs.length?8:0),lines,figs}; + marks().push(m); setTool("move"); select([m]); paint(); if(pages>1) drawPages(); +} + +/* ---------- typed math ---------- */ +// a bar over the board's top with the math field; the math keyboard opens with it +async function editMath(mark,p){ + const M=window.MathlyBoardMath; if(!M||editing) return; + const node=document.createElement("div"); node.className="mx-board-mathedit"; node.dir="ltr"; + node.innerHTML='טוענים את מקלדת המתמטיקה…'; + el.querySelector(".mx-board-stage").append(node); + const e=editing={mark,at:p,node,field:null,key}; + try{ await M.load(); } + catch{ node.querySelector("span").textContent="לא הצלחנו לטעון את מקלדת המתמטיקה. נסו שוב."; return setTimeout(()=>editing===e&&finishMath(false),2500); } + if(editing!==e) return; + node.innerHTML=` + `; + const f=e.field=node.querySelector("math-field"); + f.mathVirtualKeyboardPolicy="manual"; + f.value=mark?.latex||""; + f.addEventListener("change",()=>editing===e&&finishMath(true)); // the keyboard's return key, Enter, or leaving the field + f.addEventListener("focusin",()=>window.mathVirtualKeyboard?.show()); + // the buttons keep the field's focus, so leaving it does not count as done before the tap is read + node.querySelectorAll("button").forEach(b=>b.addEventListener("pointerdown",ev=>{ ev.preventDefault(); finishMath(b.dataset.math==="ok"); })); + f.focus(); window.mathVirtualKeyboard?.show(); +} +function finishMath(keep){ + const e=editing; if(!e) return; editing=null; + const latex=keep&&e.field?String(e.field.getValue?.("latex")??e.field.value??"").trim():null; + try{ window.mathVirtualKeyboard?.hide(); }catch{} + e.node.remove(); + if(latex===null||e.key!==key) return; // cancelled, or another page by now + const all=marks(); + if(e.mark){ + if(!all.includes(e.mark)||latex===e.mark.latex) return; + remember(); if(latex) e.mark.latex=latex; else all.splice(all.indexOf(e.mark),1); // emptied: gone + }else if(latex){ + const L=window.MathlyBoardMath.layout(latex,MATH_SIZE), W=canvas.clientWidth; + remember(); + all.push({kind:"math",latex,color:ink,size:MATH_SIZE,x:Math.max(8,Math.min(e.at[0],sketch().x+W-8-L.w)),y:Math.max(0,e.at[1]-(L.a+L.d)/2)}); + }else return; + paint(); if(pages>1) drawPages(); +} +if(window.MathlyBoardMath) window.MathlyBoardMath.onFonts=()=>el&&paint(); + +/* ---------- handing in ---------- */ +// the whole sketch as a picture on white paper: as wide as the board (wider when it was written further right), as tall as what is drawn +function snapshot(){ + const all=marks(); if(!all.some(m=>m.kind!=="card")) return null; + const [,y0,x1,y1]=edges(all), top=Math.max(0,y0-24), W=Math.min(Math.max(canvas.clientWidth,x1+24),8000), H=Math.min(y1+24-top,8000), k=2; + const out=document.createElement("canvas"); out.width=W*k; out.height=Math.round(H*k); + const keep=ctx; ctx=out.getContext("2d"); paper="#fff"; + try{ ctx.fillStyle="#fff"; ctx.fillRect(0,0,out.width,out.height); ctx.setTransform(k,0,0,k,0,-top*k); all.forEach(draw); } + finally{ ctx=keep; paper=PAPER; } + return new Promise(ok=>out.toBlob(ok,"image/png")); +} +async function send(){ + const b=el.querySelector(".mx-board-send"), p=page, say=t=>{ if(page===p) b.innerHTML=t; }; + const blob=await snapshot(); + if(!blob){ say(`הלוח ריק: אין מה להגיש`); return setTimeout(()=>page===p&&drawSend(),2500); } + b.disabled=true; say(`מגישים…`); + let r; try{ r=await hand(p,blob); }catch(e){ r={error:e.message}; } + b.disabled=false; say(r?.error?`⚠ ${r.error}`:`${ic("done")}${sendLabel?"נשלחה":`הוגשה לשאלה ${p+1}`}`); + if(r?.close&&full) return setTimeout(closeFull,900); // done: back to the window that asked + setTimeout(()=>page===p&&!b.disabled&&drawSend(),3000); +} + +document.addEventListener("keydown",e=>{ + if(editing&&e.key==="Escape"){ e.preventDefault(); e.stopImmediatePropagation(); return finishMath(false); } + if(full&&e.key==="Escape"){ e.preventDefault(); e.stopImmediatePropagation(); return closeFull(); } // back to the question, not out of it + if(!shown()||editing||e.target.closest?.("input,textarea,[contenteditable],math-field")) return; + if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==="z"&&!e.shiftKey){ e.preventDefault(); undo(); } + else if((e.key==="Delete"||e.key==="Backspace")&&selection.length){ e.preventDefault(); removeSelection(); } +}); + +/* Shows the board in the sheet's layer when the student has it on (a desktop screen), and takes it away when not. + sketchKey names the sketch; with pages>1 (a sheet with several questions at once) the board has a tab per question. + question(page) gives the element the question is shown in, for the board's copy of it; submit(page, picture) + hands a page in and resolves to {error} or {}; turned(page) is told when the student picks another tab. + On a phone nothing shows until the header's button opens the board full screen. */ +function mount(sheetLayer,sketchKey,{pages:n=1,question=null,submit=null,turned=null,sendLabel:label=""}={}){ + const was=full?full.saved:context(), same=sketchKey===was.base&&n===was.pages; + const next={layer:sheetLayer,source:question,hand:submit,onPage:turned,sendLabel:label, + base:sketchKey,pages:n,page:same?was.page:0}; + next.key=next.pages>1?`${next.base}:${next.page}`:next.base; + if(full){ full.saved=next; return; } // the sheet changed under the full-screen board: it is where the board goes back to + restore(next); + const sheet=layer.querySelector(".mx-sheet"), on=isOn()&&desk(); + layer.querySelector("[data-board-toggle]")?.setAttribute("aria-pressed",on); + sheet?.classList.toggle("with-board",on); + if(on) sheet?.removeAttribute("aria-modal"); else sheet?.setAttribute("aria-modal","true"); // the board is outside the dialog: still reachable + if(!on){ el?.remove(); return; } + if(!el) build(); + reset(); drawPages(); drawSend(); layer.append(el); fit(); +} +const again=()=>mount(layer,base,{pages,question:source,submit:hand,turned:onPage,sendLabel}); +const here=p=>({host:layer,key:base,pages,page:p,question:source,submit:hand,turned:onPage}); +function toggle(){ + if(!desk()) return layer&&openFull(here(page)); // a phone: the board over the exercise + setOn(!isOn()); if(layer) again(); +} +// opens the board on one question's page (the unit quiz's own button under each question) +function show(p){ + if(!desk()) return layer&&openFull(here(p)); + setOn(true); if(!layer) return; again(); if(pages>1&&p!==page) turn(p); +} +/* The board full screen over everything in host, until the student goes back. Options as mount's, and: + title (the head's words), sendLabel (the hand-in button's words), done (called when it closes). + A submit answer with close:true closes it after the hand-in. */ +function openFull({host,key:k,pages:n=1,page:p=0,question=null,submit=null,turned=null,title="לוח טיוטה",sendLabel:label="",done=null}){ + if(!el) build(); + if(full) full.done=done; else full={saved:context(),done}; + restore({layer:host,base:k,pages:n,page:p,source:question,hand:submit,onPage:turned,sendLabel:label,key:n>1?`${k}:${p}`:k}); + el.querySelector("[data-title]").textContent=title; + el.classList.add("full"); el.setAttribute("role","dialog"); el.setAttribute("aria-modal","true"); + reset(); drawPages(); drawSend(); host.append(el); fit(); + el.querySelector(".mx-board-back").focus({preventScroll:true,focusVisible:false}); // reachable by keyboard, without a ring on a tap +} +function closeFull(){ + if(!full) return; if(editing) finishMath(true); if(naming) finishAngle(true); const f=full; full=null; + el.classList.remove("full"); el.removeAttribute("role"); el.removeAttribute("aria-modal"); el.remove(); + restore(f.saved); f.done?.(); + if(layer?.isConnected&&desk()) again(); +} +// the header's switch: beside the exercise on a desktop screen, full screen on a phone +const button=()=>``; + +window.MathlyBoard={button,mount,toggle,show,openFull,closeFull,isOn,desk}; +})(); diff --git a/mathly2/static/path.js b/mathly2/static/path.js new file mode 100644 index 0000000000000000000000000000000000000000..933000e7d053f3fac1845f8128cee000fce5e390 --- /dev/null +++ b/mathly2/static/path.js @@ -0,0 +1,74 @@ +// The path: a trail of lessons. Each lesson is a hub with its skills as numbered stars in a ring around it; the owl perches on the +// suggested next skill. Every star is a link to its exercise screen (#/skill/) and says its state in a symbol and a word. +import { api } from "./api.js"; +import { esc, fmt } from "./math.js"; +import { owl, ringSvg, spark } from "./sky.js"; +import { HOME, backToSubjects, goalBar, tabs } from "./ui.js"; + +export const STATES = { + not_started: { symbol: "○", word: "לא התחלת" }, + learning: { symbol: "◐", word: "בלמידה" }, + mastered: { symbol: "✓", word: "נשלטה" }, +}; +const NEXT = "ממשיכים כאן"; +const FADING = "דועך"; +const plain = text => String(text ?? "").replace(/\$/g, ""); + +function star(skill, i, n, isNext) { + const t = (-90 + 360 * i / n) * Math.PI / 180, base = STATES[skill.state] || STATES.not_started; + const symbol = skill.faded ? `${base.symbol} ◌` : base.symbol, word = skill.faded ? `${base.word}, ${FADING}` : base.word; + return ` + ${spark()}${isNext ? `${owl(30)}` : ""} + ${fmt(skill.short)} ${word}${isNext ? " · " + NEXT : ""}`; +} + +/** The lesson's quiz, a node on the trail after its ring: always open, its state in words. */ +function quizNode(l) { + const { best, open } = l.quiz || {}; + const state = [best !== null && best !== undefined ? `✓ הציון: ${best}` : "○ עוד לא נעשה", open ? "◐ בוחן פתוח" : ""].filter(Boolean).join(" · "); + return `בוחן${state}`; +} + +function lesson(l, next) { + const n = l.skills.length; + return `
    +
    ${ringSvg(l.skills.map(s => s.state))} +

    ${fmt(l.name)}

    ${l.mastered} מתוך ${n} נשלטו${l.completed ? " ✓" : ""}
    + ${l.skills.map((s, i) => star(s, i, n, s.id === next)).join("")}
    ${quizNode(l)}`; +} + +export function pathHtml(path) { + return `${tabs("path")}${backToSubjects()} +

    המסלול שלי

    +

    כל השיעורים פתוחים, בכל סדר. הינשוף מציע איפה להמשיך, אבל אפשר ללחוץ על כל כוכב.

    ${goalBar(path.today, path.streak)}
    +
    +
    ${owl(44)}התחלה
    + ${path.lessons.map(l => lesson(l, path.next)).join("")} +
    סוף המסלול
    `; +} + +/** Draw the path. `scroll`: bring the next skill to the middle of the screen (when the path opens); a refresh keeps the place. */ +export async function show(view, { scroll = true } = {}) { + const path = await api("/api/path"); + const place = window.scrollY; + view(pathHtml(path)); + if (scroll) document.querySelector(".star.next")?.scrollIntoView({ block: "center" }); + else window.scrollTo(0, place); + return path; +} + +/** The first screen: a card per subject of the student's classes. Math is the only subject today; its bar counts mastered skills. */ +export async function showSubjects(view) { + const path = await api("/api/path"); + const total = path.lessons.reduce((n, l) => n + l.skills.length, 0), lit = path.lessons.reduce((n, l) => n + l.mastered, 0); + view(`
    +

    במה נתרגל היום?

    + + מתמטיקה + + ${lit} מתוך ${total} מיומנויות
    `); + return path; +} diff --git a/mathly2/static/quiz.js b/mathly2/static/quiz.js new file mode 100644 index 0000000000000000000000000000000000000000..3637d9e3435f4715af535392b0d6d3022fb2092d --- /dev/null +++ b/mathly2/static/quiz.js @@ -0,0 +1,213 @@ +// A lesson quiz: 10 multiple-choice questions on a server timer, as a dialog over the path (the same sheet as the exercise screen). +// A tap saves the choice on the server; nothing says whether it is right. After the submit (or when time ends) the result shows the +// grade, the skills that lost points and the mistakes' names and tips, never the right answers. +import { api, ApiError } from "./api.js"; +import { loadBoard } from "./exercise.js"; +import { figures } from "./figures.js"; +import { esc, fmt } from "./math.js"; +import { PATH, shuffled } from "./ui.js"; + +const LIVE_AT = new Set([300, 60, 10, 0]); // seconds left at which the timer is announced to a screen reader + +let layer = null, attempt = null, at = 0, timer = null, deadline = 0, orders = {}, warned = false; + +const q = selector => layer?.querySelector(selector); +export const isOpen = () => !!layer; + +const clock = secs => `${String(Math.floor(secs / 60)).padStart(2, "0")}:${String(secs % 60).padStart(2, "0")}`; + +function stopTimer() { clearInterval(timer); timer = null; } + +/** Open the sheet for an attempt that the server already has (`#/quiz//`). */ +export async function open(attemptId) { + const [data] = await Promise.all([api(`/api/attempts/${encodeURIComponent(attemptId)}`), loadBoard()]); + show(data); +} + +/** The student opened a lesson's quiz: the server resumes the open attempt or draws a new one; the address then names the attempt. */ +export async function start(lessonId) { + const data = await api(`/api/lessons/${encodeURIComponent(lessonId)}/quiz/start`, { method: "POST" }); + location.replace(`#/quiz/${encodeURIComponent(lessonId)}/${encodeURIComponent(data.id)}`); +} + +/** An exercise test (1 or 2) of a real test, or its simulation: the same, with the attempt's id put in the address. */ +export async function startExam(testId, number) { + const data = await api(`/api/tests/${encodeURIComponent(testId)}/exercise/${encodeURIComponent(number)}/start`, { method: "POST" }); + location.replace(`#/exam/${encodeURIComponent(testId)}/${encodeURIComponent(number)}/${encodeURIComponent(data.id)}`); +} + +export async function startSimulation(testId) { + const data = await api(`/api/tests/${encodeURIComponent(testId)}/simulation/start`, { method: "POST" }); + location.replace(`#/sim/${encodeURIComponent(testId)}/${encodeURIComponent(data.id)}`); +} + +/** What the sheet is called, who it is about and where closing it leads, by kind. */ +const names = a => a.kind === "exercise_test" ? { title: `מבחן תרגול ${a.test.number}`, again: "מבחן חוזר" } + : a.kind === "simulation" ? { title: "מבחן סימולציה", again: "" } : { title: "בוחן", again: "בוחן חוזר" }; +const chip = a => a.kind === "quiz" ? fmt(a.lesson.name) : a.test.lessons.map(fmt).join(", "); +const leaveTo = () => !attempt || attempt.kind === "quiz" ? PATH : `#/test/${attempt.test.id}`; + +function ensureLayer() { + if (!layer) { + layer = document.createElement("div"); + layer.className = "mx-layer"; + document.body.append(layer); + layer.addEventListener("click", onClick); + } + layer.innerHTML = `
    `; +} + +function show(data) { + stopTimer(); + if (!attempt || attempt.id !== data.id) at = 0; // a different attempt starts at its first question + attempt = data; + warned = false; + ensureLayer(); + if (data.state === "open") { + if (!(data.id in orders)) orders = { [data.id]: {} }; + at = Math.min(at, data.questions.length - 1); + deadline = performance.now() + Math.max(0, new Date(data.due_at) - new Date(data.now)); // the server's clock, not the device's + renderQuestion(); + timer = setInterval(tick, 1000); + tick(); + } else { + renderResult(); + } + q(".mx-x")?.focus({ preventScroll: true }); +} + +export function close() { + if (!layer) return; + stopTimer(); + window.MathlyBoard?.closeFull?.(); + layer.remove(); + layer = attempt = null; + at = 0; +} + +const left = () => Math.max(0, Math.ceil((deadline - performance.now()) / 1000)); + +async function tick() { + if (!layer || attempt?.state !== "open") return; + const secs = left(); + const label = q("#qz-timer"); + if (label) label.textContent = clock(secs); + if (LIVE_AT.has(secs) && q("#qz-live")) q("#qz-live").textContent = secs === 0 ? "הזמן נגמר" : `נשארו ${secs >= 60 ? `${secs / 60} דקות` : `${secs} שניות`}`; + if (secs === 0) { + stopTimer(); + await finish(false); + } +} + +/** Ask the server for the attempt: past the deadline it has been settled already, before it a submit settles it. */ +async function finish(submit) { + const id = attempt.id; + try { + const data = submit ? await api(`/api/attempts/${id}/submit`, { method: "POST" }) : await api(`/api/attempts/${id}`); + if (data.state === "open") { setTimeout(() => layer && finish(false), 1000); return; } // a hair early on the device: ask again + show(data); + } catch (error) { + if (q("#qz-fb")) q("#qz-fb").innerHTML = ``; + } +} + +const heading = (title) => `
    ${chip(attempt)}

    ${title}

    +
    ${attempt.state === "open" ? (window.MathlyBoard?.button() || "") : ""} +
    `; + +function choicesOf(question) { + const order = (orders[attempt.id] ||= {}); + order[question.key] ||= shuffled(question.choices).map(c => c.index); + return order[question.key].map(i => question.choices.find(c => c.index === i)); +} + +function renderQuestion() { + const total = attempt.questions.length, question = attempt.questions[at], saved = attempt.answers[question.key]; + const answered = Object.keys(attempt.answers).length; + q(".mx-sheet").innerHTML = `${heading(names(attempt).title)} +
    ${clock(left())} + שאלה ${at + 1} מתוך ${total}
    + +
    ${attempt.questions.map((x, i) => + ``).join("")}
    +

    ${fmt(question.question)}

    ${figures(question)} +
    ${choicesOf(question).map(c => + ``).join("")}
    +
    +
    + +
    +
    `; + window.MathlyBoard?.mount(layer, `quiz:${attempt.id}:${question.key}`, { question: () => q("#qz-q") }); +} + +async function choose(button) { + const question = attempt.questions[at], index = Number(button.dataset.i), before = attempt.answers[question.key]; + attempt.answers[question.key] = index; + layer.querySelectorAll(".qz-choice").forEach(b => { const on = Number(b.dataset.i) === index; b.classList.toggle("picked", on); b.setAttribute("aria-pressed", String(on)); }); + q(`.qz-dot[data-go="${at}"]`)?.classList.add("done"); + try { + await api(`/api/attempts/${attempt.id}/answers`, { method: "PUT", body: { key: question.key, choice: index } }); + } catch (error) { + if (error instanceof ApiError && error.status === 409) return finish(false); // time ran out: the server already submitted + if (before === undefined) delete attempt.answers[question.key]; else attempt.answers[question.key] = before; + renderQuestion(); + q("#qz-fb").innerHTML = ``; + } +} + +function submit() { + const missing = attempt.questions.filter(x => attempt.answers[x.key] === undefined).length; + if (missing && !warned) { + warned = true; + q("#qz-warn").innerHTML = ``; + q("#qz-back").focus(); + return; + } + finish(true); +} + +function renderResult() { + const r = attempt; + stopTimer(); + q(".mx-sheet").innerHTML = `${heading(`תוצאת ${names(r).title}`)} +

    ${r.grade}מתוך 100

    +

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

    +

    ${r.kind === "simulation" ? `

    מבחן סימולציה אפשר לעשות פעם אחת.

    ` : ""}
    + ${r.lost_skills.length ? `

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

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

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

    ` : `

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

    `} + ${r.missed.length ? `

    הטעויות

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

      + ${m.picked ? `

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

      ` : `

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

      `} + ${m.mistake ? `

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

      ` : ""}
    2. `).join("")}
    ` : ""} +

    ${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", ``); }); + } +} + +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 ``; + }; + const arcs = states.slice(0, -1).map((state, k) => arc(angle(k) + gap, angle(k + 1) - gap, state === "not_started" ? "" : "on")).join(""); + const back = n > 2 ? arc(angle(n - 1) + gap, angle(n) - gap, "back") : ""; + return ``; +} + +/* ---------- constellations and comets (ported from mathly1) ---------- */ +const SPARK = "M12 1.5C13.1 9 15 10.9 22.5 12C15 13.1 13.1 15 12 22.5C10.9 15 9 13.1 1.5 12C9 10.9 10.9 9 12 1.5Z"; +const curve=(f,n=48)=>Array.from({length:n+1},(_,i)=>f(i/n)); +const SHAPES={ + t:{name:"הקערה",aspect:.9,pts:curve(s=>[1-s,1-(2*s-1)**2])}, + t2:{name:"המדרגות",aspect:.75,corners:1,pts:[[1,1],[1,.5],[.5,.5],[.5,0],[0,0]]}, + k:{name:"הדלתון",aspect:1.15,closed:1,corners:1,pts:[[.5,0],[1,.36],[.5,1],[0,.36]],inner:[[[.5,0],[.5,1]],[[0,.36],[1,.36]]]}, + i:{name:"המשולש",aspect:.9,closed:1,corners:1,pts:[[.5,0],[1,1],[0,1]],inner:[[[.5,0],[.5,1]]]}, + q:{name:"הקשת",aspect:.75,pts:curve(s=>[1-s,(2*s-1)**2])}, + q2:{name:"הפרבולה",aspect:.85,pts:curve(s=>[1-s,1-(2*s-1)**2]),inner:[[[.5,0],[.5,1]]]}, + a:{name:"הזווית",aspect:.7,closed:1,corners:1,pts:[[1,0],[1,1],[0,1]]}, + l:{name:"המשולש הישר",aspect:.75,closed:1,corners:1,pts:[[1,0],[1,1],[0,1]]}, + z:{name:"הטרפז",aspect:.6,closed:1,corners:1,pts:[[.72,0],[1,1],[0,1],[.28,0]]}, + z2:{name:"הטרפז הישר",aspect:.6,closed:1,corners:1,pts:[[.6,0],[1,1],[0,1],[0,0]]}, + e:{name:"הגבעה",aspect:.55,pts:curve(s=>[1-s,1-Math.sin(Math.PI*s)])}, + v:{name:"החץ",aspect:.8,corners:1,pts:[[0,0],[1,.5],[0,1]]}, + g:{name:"המקבילית",aspect:.6,closed:1,corners:1,pts:[[1,0],[.72,1],[0,1],[.28,0]]}, + r:{name:"ההיפרבולה",aspect:.9,pts:curve(s=>{const x=.06+.94*(1-s);return [x,Math.min(1,.06/x)]})}, + m:{name:"המלבן",aspect:.62,closed:1,corners:1,pts:[[1,0],[1,1],[0,1],[0,0]],inner:[[[1,0],[0,1]]]}, + h:{name:"הקובייה",aspect:1.1,closed:1,corners:1,pts:[[.5,0],[1,.25],[1,.75],[.5,1],[0,.75],[0,.25]],inner:[[[.5,.5],[.5,1]],[[.5,.5],[0,.25]],[[.5,.5],[1,.25]]]}, + s:{name:"המפגש",aspect:.75,pts:curve(s=>[1-s,(2*s-1)**2]),inner:[[[1,.12],[0,.88]]]}, + n:{name:"הגל",aspect:.5,pts:curve(s=>[1-s,.5-.5*Math.sin(2*Math.PI*s)])}, + b:{name:"המעוין",aspect:1.25,closed:1,corners:1,pts:[[.5,0],[1,.5],[.5,1],[0,.5]],inner:[[[.5,0],[.5,1]],[[0,.5],[1,.5]]]}, + c:{name:"הריבוע",aspect:1,closed:1,corners:1,pts:[[1,0],[1,1],[0,1],[0,0]],inner:[[[1,0],[0,1]],[[0,0],[1,1]]]}, + o:{name:"התיכון",aspect:.8,closed:1,corners:1,pts:[[1,0],[1,1],[0,1]],inner:[[[1,1],[.5,.5]]]}, + p:{name:"הרקטה",aspect:1,pts:curve(s=>{const x=1-s;return [x,1-(Math.pow(40,x)-1)/39]})}, + w:{name:"הברק",aspect:.6,corners:1,pts:[[1,1],[.75,0],[.5,.75],[.25,0],[0,1]]}, + d:{name:"המשולשים הדומים",aspect:.9,closed:1,corners:1,pts:[[.5,0],[1,1],[0,1]],inner:[[[.25,.5],[.75,.5]]]}, +}; +const FALLBACK={aspect:.7,corners:1,pts:[[1,.15],[.68,.85],[.36,.1],[0,.75]]}; +const W=360, X0=60, X1=300, TOP=52, BOTTOM=64; +const lerp=(a,b,t)=>[a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t]; +const dist=(a,b)=>Math.hypot(b[0]-a[0],b[1]-a[1]); +function segments(pts,closed){ const out=[]; for(let i=0;is+dist(a,b),0); + const at=d=>{ for(const [a,b] of segs){ const l=dist(a,b); if(d<=l+1e-9) return lerp(a,b,l?d/l:0); d-=l; } return segs[segs.length-1][1]; }; + if(n<=0) return []; + if(closed) return Array.from({length:n},(_,i)=>at(L*i/n)); + if(n===1) return [at(L/2)]; + return Array.from({length:n},(_,i)=>at(L*i/(n-1))); +} +function onCorners(pts,closed,n){ + const segs=segments(pts,closed), extra=segs.map(()=>0); + for(let k=0;k{ if(dist(a,b)/(extra[i]+1)>dist(...segs[best])/(extra[best]+1)) best=i; }); extra[best]++; } + const out=[]; + segs.forEach(([a,b],i)=>{ out.push(a); for(let j=1;j<=extra[i];j++) out.push(lerp(a,b,j/(extra[i]+1))); }); + if(!closed) out.push(pts[pts.length-1]); + return out; +} +/* The drawing of unit `id` with `n` stars, in a box W wide and H high: the stars in the path's order, the outline's + segments, and the inner lines. A unit with many stars is drawn taller so that they keep apart. */ +export function shape(id,n,name){ + const S=SHAPES[id]||{...FALLBACK,name}; + const w=X1-X0, h=Math.round(Math.max(w*S.aspect,n>6?(n-1)*36:0)), H=TOP+h+BOTTOM; + const map=([x,y])=>[X0+x*w,TOP+y*h]; + const pts=S.pts.map(map); + const stars=(S.corners&&n>=pts.length?onCorners(pts,!!S.closed,n):along(pts,!!S.closed,n)); + return {name:S.name||name,H,stars,lines:segments(pts,!!S.closed),inner:(S.inner||[]).map(l=>l.map(map))}; +} + +/** A completed lesson's constellation: its outline and inner lines, and its stars as small gold sparks, in the shape its lesson id gives + * (a zig-zag when none is defined). Stars are numbered in the lesson's order for the screen reader only. */ +export function constellationSvg(lessonId, name, count) { + const shp = shape(lessonId, count, name); + const line = ([a, b]) => ``; + const stars = shp.stars.map(([x, y]) => ``).join(""); + return `${[...shp.lines, ...shp.inner].map(line).join("")}${stars}`; +} + +/** The comet that crosses the screen: a gold tail and a spark. */ +export const cometSvg = () => ``; + +/** A caught comet's card: its symbol and name (the fact is written under it by the screen). */ +export const cometCard = c => `
    ${esc(c.sym)}${esc(c.name)}
    `; diff --git a/mathly2/static/student.js b/mathly2/static/student.js index 3dfd1f894e9000fa5f31eee8999fbe162ba66cfd..5f82f000509f238bb81eff56a593c1b36f23d359 100644 --- a/mathly2/static/student.js +++ b/mathly2/static/student.js @@ -1,14 +1,69 @@ -import { api } from "./api.js"; +// The student's screens, switched by the address after "#": "/" the subjects, "/subject/math" the home, "/subject/math/path" the path, "/skill/" a skill's sheet over the path, "/collection". import { esc } from "./math.js"; +import * as exercise from "./exercise.js"; +import * as home from "./home.js"; +import * as path from "./path.js"; +import * as quiz from "./quiz.js"; +import { route as onRoute } from "./router.js"; export async function show(me, view) { - if (!me.class) { + if (!me.classes.length && me.roles.every(r => r === "student")) { view(`

    עוד לא בכיתה

    -

    המורה עוד לא הוסיפה אותך לכיתה. בקשו מהמורה להוסיף את כתובת המייל שבה נכנסתם:

    +

    עוד לא הוסיפו אותך לכיתה. בקשו מהמורה או ממנהל הכיתות להוסיף את כתובת המייל שבה נכנסתם:

    ${esc(me.email)}

    `); return; } - const lessons = await api("/api/lessons"); - view(`

    שלום

    הכיתה: ${esc(me.class.name)}. השיעורים (${lessons.length}) יפתחו כאן בהמשך.

    -
      ${lessons.map(l => `
    • ${esc(l.name)}${l.skills.length} מיומנויות
    • `).join("")}
    `); + let lastSkill = ""; + async function route() { + const raw = location.hash.replace(/^#/, ""); + const where = raw.startsWith("/") ? raw : "/"; // no address, or the sign-in service's "#access_token=…": the first screen + try { + if (where.startsWith("/skill/")) { + quiz.close(); + lastSkill = decodeURIComponent(where.slice(7)); + if (!document.getElementById("path")) await path.show(view); // a link or a reload: the path first, then the sheet over it + await exercise.open(lastSkill); + } else if (where.startsWith("/quiz/")) { + exercise.close(); + const [lesson, attempt] = where.slice(6).split("/").map(decodeURIComponent); + if (!document.getElementById("path")) await path.show(view); // a link or a reload: the path first, then the sheet + if (attempt) await quiz.open(attempt); else await quiz.start(lesson); // the node starts or resumes; the address then names the attempt + } else if (where.startsWith("/exam/") || where.startsWith("/sim/")) { + exercise.close(); + const [kind, ...rest] = where.slice(1).split("/").map(decodeURIComponent); + const [test, second, third] = rest; + const attempt = kind === "exam" ? third : second; + if (!document.getElementById("path") && !document.getElementById("test-card")) await (await import("./testcard.js")).show(view, test); // a link or a reload: the test's card first + if (attempt) await quiz.open(attempt); + else if (kind === "exam") await quiz.startExam(test, second); + else await quiz.startSimulation(test); + } else if (where.startsWith("/test/")) { + exercise.close(); quiz.close(); + await (await import("./testcard.js")).show(view, decodeURIComponent(where.slice(6))); + } else if (where === "/grades") { + exercise.close(); quiz.close(); + await (await import("./grades.js")).show(view); + } else if (where === "/") { + exercise.close(); quiz.close(); + await path.showSubjects(view); + } else if (where === "/subject/math") { + exercise.close(); quiz.close(); + await home.show(view); + } else if (where === "/collection") { + exercise.close(); quiz.close(); + await (await import("./collection.js")).show(view); + } else { // "/subject/math/path", and any unknown address + const wasOpen = exercise.isOpen() || quiz.isOpen(); + exercise.close(); quiz.close(); + await path.show(view, { scroll: !wasOpen }); // closing a sheet refreshes the stars and keeps the place + if (wasOpen && lastSkill) document.querySelector(`.star[data-skill="${CSS.escape(lastSkill)}"]`)?.focus({ preventScroll: true }); + } + } catch (error) { + if (error.status === 401) throw error; + view(`
    `); + } + if (!where.startsWith("/skill/") && !exercise.isOpen()) { /* the path scrolls itself */ } + } + onRoute(route); + await route(); } diff --git a/mathly2/static/teacher.js b/mathly2/static/teacher.js index f98200df6f1cb780c475e9b05f60de409650c0b2..6a39a3455aeadfc717f999f25a17c4d79d085923 100644 --- a/mathly2/static/teacher.js +++ b/mathly2/static/teacher.js @@ -1,78 +1,142 @@ -// Teacher screens: my classes, and one class with its students. +// The teacher's home: the classes I teach, each with its students; I add (a pasted list) and remove students of my own classes. import { api } from "./api.js"; -import { esc } from "./math.js"; +import { esc, fmt } from "./math.js"; +import { daysText, shortDate } from "./ui.js"; let draw; // the app's view() function -const note = (text, kind = "muted") => text ? `

    ${text}

    ` : ""; +const tabs = active => `
    + +
    `; -async function showClasses(message = "", error = "") { - const classes = await api("/api/classes"); - draw(`

    הכיתות שלי

    - ${classes.length ? `
      ${classes.map(c => - `
    • ${esc(c.name)}${c.students} תלמידים
    • `).join("")}
    ` - : `

    עוד אין כיתות. אפשר ליצור את הראשונה כאן.

    `}
    -

    כיתה חדשה

    ${note(esc(error), "error")}${note(esc(message))} -
    - -

    `); - document.getElementById("new-class").addEventListener("submit", async event => { - event.preventDefault(); - try { - const created = await api("/api/classes", { method: "POST", body: { name: document.getElementById("class-name").value } }); - await showClasses(`הכיתה "${created.name}" נוצרה`); - } catch (e) { await showClasses("", e.message); } - }); +function wireTabs() { + document.querySelectorAll("#teacher-tabs [data-tab]").forEach(b => b.addEventListener("click", () => (b.dataset.tab === "tests" ? showTests() : showClasses()))); } function report(result) { const lines = []; if (result.added.length) lines.push(`נוספו ${result.added.length} תלמידים.`); if (result.already_here.length) lines.push(`${result.already_here.length} כבר היו בכיתה.`); - for (const x of result.elsewhere) - lines.push(`${esc(x.email)} כבר שייך/ת לכיתה "${esc(x.class_name)}" ולא נוסף/ה. תלמיד יכול להיות רק בכיתה אחת.`); + if (result.teacher.length) lines.push(`${result.teacher.map(esc).join(", ")}: מורה הכיתה לא יכול להיות גם תלמיד בה.`); if (result.invalid.length) lines.push(`לא נראה כמו מייל: ${result.invalid.map(esc).join(", ")}`); return lines; } -async function showClass(id, lines = [], error = "") { - const cls = await api(`/api/classes/${id}`); - draw(`

    ← הכיתות שלי

    -

    ${esc(cls.name)}

    - ${cls.students.length ? `
      ${cls.students.map(s => - `
    • ${esc(s.email)}${s.signed_in ? "נכנס/ה" : "עוד לא נכנס/ה"} -
    • `).join("")}
    ` - : `

    עוד אין תלמידים בכיתה.

    `}
    -

    הוספת תלמידים

    ${note(esc(error), "error")} -
    ${lines.map(l => `

    ${l}

    `).join("")}
    -
    - -

    `); - document.getElementById("add").addEventListener("submit", async event => { +async function showClasses(notes = {}) { + const classes = await api("/api/teaching"); + draw(`${tabs("classes")}

    הכיתות שלי

    + ${classes.length ? `
    ${classes.map(c => `
    +

    ${esc(c.name)}

    ${c.students.length} תלמידים
    +

    ${c.ai_enabled ? "AI פועל" : "AI כבוי: מנהל הכיתות מפעיל"}

    + ${c.students.length ? `
      ${c.students.map(s => `
    • ${esc(s.email)} + ${s.signed_in ? "נכנס/ה" : "עוד לא נכנס/ה"} +
    • `).join("")}
    ` + : `

    עוד אין תלמידים בכיתה.

    `} +
    + +
    ${(notes[c.id]?.lines || []).map(l => `

    ${l}

    `).join("")}
    + ${notes[c.id]?.error ? `` : ""} +

    `).join("")}
    ` + : `

    עוד לא שייכו אותך ככיתה. מנהל הכיתות קובע מי מלמד/ת כל כיתה.

    `}
    `); + wireTabs(); + document.querySelectorAll(".class-card").forEach(card => { + const id = Number(card.dataset.id); + card.querySelector("form").addEventListener("submit", async event => { + event.preventDefault(); + try { + const result = await api(`/api/classes/${id}/students`, { method: "POST", body: { emails: card.querySelector(".emails").value } }); + await showClasses({ [id]: { lines: report(result) } }); + } catch (e) { await showClasses({ [id]: { error: e.message } }); } + }); + card.addEventListener("click", async event => { + const email = event.target.closest("[data-remove]")?.dataset.remove; + if (!email) return; + try { + await api(`/api/classes/${id}/students/${encodeURIComponent(email)}`, { method: "DELETE" }); + await showClasses({ [id]: { lines: [`${esc(email)} הוסר/ה מהכיתה.`] } }); + } catch (e) { await showClasses({ [id]: { error: e.message } }); } + }); + }); +} + +// ---- the tests tab: set a test for a class, change or remove it, see who took the simulation ---- + +const today = () => new Date().toISOString().slice(0, 10); + +function testForm(c, test = null) { + const id = test ? `edit-${test.id}` : `new-${c.id}`; + const chosen = new Set(test ? test.lessons.map(l => l.id) : c.lessons.map(l => l.id)); + return `
    + +
    השיעורים שהמבחן כולל${c.lessons.map(l => ``).join("")}
    + +
    +
    + +

    ${test ? ` ` : ""}

    `; +} + +function testCard(c, t) { + const open = t.days_left > 0; + return `

    מבחן ב־${shortDate(t.date)} (${daysText(t.days_left)})

    + ${t.simulation.taken} מתוך ${t.simulation.total} עשו סימולציה
    +

    ${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 ? `
    + ${t.students.map(s => ` + `).join("")}
    תלמידמוכנותשליטהתרגולסימולציה
    ${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 ? ` ` : ""}

    +
    `; +} + +async function showTests() { + const classes = await api("/api/teaching/tests"); + draw(`${tabs("tests")}

    מבחנים

    + ${classes.length ? classes.map(({ class: c, tests }) => `

    ${esc(c.name)}

    + ${tests.length ? tests.map(t => testCard(c, t)).join("") : `

    עוד לא נקבע מבחן לכיתה.

    `} +
    קביעת מבחן${testForm(c)}
    `).join("") + : `

    עוד לא שייכו אותך ככיתה. מנהל הכיתות קובע מי מלמד/ת כל כיתה.

    `}
    `); + wireTabs(); + const byId = new Map(classes.flatMap(({ class: c, tests }) => tests.map(t => [t.id, { c, t }]))); + const root = document.getElementById("tests"); + root.addEventListener("submit", async event => { + const form = event.target.closest(".test-form"); + if (!form) return; event.preventDefault(); + const data = new FormData(form), error = form.querySelector(".form-error"); + const body = { date: data.get("date"), lessons: data.getAll("lessons"), note: data.get("note") || "", questions: Number(data.get("questions")), minutes: Number(data.get("minutes")) }; + error.hidden = true; try { - const result = await api(`/api/classes/${id}/students`, { method: "POST", body: { emails: document.getElementById("emails").value } }); - await showClass(id, report(result)); - } catch (e) { await showClass(id, [], e.message); } + if (form.dataset.test) await api(`/api/tests/${form.dataset.test}`, { method: "PUT", body }); + else await api(`/api/classes/${form.dataset.class}/tests`, { method: "POST", body }); + await showTests(); + } catch (e) { + error.textContent = e.message; + error.hidden = false; + error.scrollIntoView({ block: "nearest" }); // the form keeps what was typed + } }); - document.getElementById("students")?.addEventListener("click", async event => { - const email = event.target.closest("[data-remove]")?.dataset.remove; - if (!email) return; - try { - await api(`/api/classes/${id}/students/${encodeURIComponent(email)}`, { method: "DELETE" }); - await showClass(id, [`${esc(email)} הוסר/ה מהכיתה.`]); - } catch (e) { await showClass(id, [], e.message); } + root.addEventListener("click", async event => { + const edit = event.target.closest("[data-edit]")?.dataset.edit; + if (edit) { + const { c, t } = byId.get(Number(edit)); + root.querySelector(`[data-slot="${edit}"]`).innerHTML = testForm(c, t); + return; + } + if (event.target.closest("[data-cancel]")) { event.target.closest(".edit-slot").innerHTML = ""; return; } + const remove = event.target.closest("[data-remove-test]"); + if (remove) { // two steps, so a slip does not remove a test + remove.outerHTML = ` `; + return; + } + if (event.target.closest("[data-cancel-remove]")) { await showTests(); return; } + const confirm = event.target.closest("[data-confirm-remove]")?.dataset.confirmRemove; + if (confirm) { await api(`/api/tests/${confirm}`, { method: "DELETE" }); await showTests(); } }); } -async function route() { - const match = location.hash.match(/^#class\/(\d+)$/); - try { await (match ? showClass(Number(match[1])) : showClasses()); } - catch (e) { draw(`

    ← הכיתות שלי

    `); } -} - export async function show(me, view) { draw = view; - addEventListener("hashchange", route); - await route(); + await showClasses(); } diff --git a/mathly2/static/testcard.js b/mathly2/static/testcard.js new file mode 100644 index 0000000000000000000000000000000000000000..1631c119ba5526f1a21c62ee8c5eedd69c46fad5 --- /dev/null +++ b/mathly2/static/testcard.js @@ -0,0 +1,45 @@ +// One real test: its plan with the recommended days, the readiness bar, the two exercise tests, the simulation and what to practise first. +import { api } from "./api.js"; +import { esc, fmt } from "./math.js"; +import { readinessBar } from "./home.js"; +import { HOME, daysText, shortDate, tabs } from "./ui.js"; + +const STEP_NAMES = { path: "לסיים את המסלול של השיעורים", ex1: "מבחן תרגול 1", ex2: "מבחן תרגול 2", sim: "מבחן סימולציה", review: "חזרה על מה שנפל בסימולציה" }; + +function planList(test) { + return `
      ${test.plan.map(step => { + const when = step.id === "path" ? `עד ${step.until} ימים לפני` : step.id === "review" ? `${step.day} ימים לפני ועד המבחן` : `בערך ${step.day} ימים לפני`; + return `
    1. + ${STEP_NAMES[step.id]}
      ${when} · ${step.done ? "בוצע" : "עוד לא"}
    2. `; + }).join("")}

    הימים הם המלצה: אפשר להתחיל כל שלב קודם או אחר כך.

    `; +} + +function exercises(test) { + return ``; +} + +function simulation(test) { + const s = test.simulation; + const lead = s.taken ? `

    הציון: ${s.grade}

    ${s.review.length ? `

    מיומנויות לחזרה:

    ` : `

    אין מיומנויות לחזרה. כל הכבוד!

    `} +

    לתוצאה

    ` + : s.open_now ? `

    חובה המבחן פתוח עד יום המבחן. אפשר לעשות אותו פעם אחת.

    +

    ${s.in_progress ? "להמשיך" : "התחלה"}

    ` + : `

    מבחן הסימולציה ייפתח ב־${shortDate(s.opens_on)} (בעוד ${s.opens_in_days} ימים). אפשר לעשות אותו פעם אחת.

    `; + return `
    ${lead}
    `; +} + +export async function show(view, id) { + const test = await api(`/api/tests/${encodeURIComponent(id)}`); + view(`${tabs("home")}

    ‹ הבית

    +

    מבחן ב־${shortDate(test.date)} (${daysText(test.days_left)})

    +

    ${test.lessons.map(l => fmt(l.name)).join(", ")}${test.note ? ` · ${esc(test.note)}` : ""}
    ${test.questions} שאלות · ${test.minutes} דקות

    + ${readinessBar(test.readiness)}
    +

    התוכנית

    ${planList(test)}
    +

    מבחני תרגול

    ${exercises(test)} + ${test.practice_first.length ? `

    כדאי לתרגל קודם: ${test.practice_first.map(s => `${fmt(s.name)}`).join(" ")}

    +

    אלה מיומנויות שעוד לא התחלתם, ולכן אין להן שאלות במבחני התרגול.

    ` : ""}
    +

    מבחן סימולציה

    ${simulation(test)}
    `); +} diff --git a/mathly2/static/ui.js b/mathly2/static/ui.js new file mode 100644 index 0000000000000000000000000000000000000000..eba960f4dd10e78efc58a688731e8a875074c5fc --- /dev/null +++ b/mathly2/static/ui.js @@ -0,0 +1,43 @@ +// Small pieces shared by the student screens. +import { esc } from "./math.js"; + +const STATES = { mastered: ["✓", "נשלטה"], learning: ["◐", "בלמידה"], not_started: ["○", "לא התחלת"] }; + +/** A skill's state as a symbol and a word, so it never depends on colour alone. */ +export const stateTag = state => { + const [symbol, word] = STATES[state] || STATES.not_started; + return ` ${word}`; +}; + +/** The subject's home and its path: the card on the subjects screen opens the home; the tab bar leads to the rest. */ +export const HOME = "#/subject/math"; +export const PATH = "#/subject/math/path"; + +/** The student's tab bar, fixed at the bottom of the screen (the CSS places it): home, path, grades, collection. */ +export const tabs = active => ``; + +export const shortDate = iso => { const [, m, d] = iso.split("-"); return `${Number(d)}.${Number(m)}`; }; +export const daysText = n => n === 0 ? "היום" : n === 1 ? "מחר" : `בעוד ${n} ימים`; + +/** The way back from a subject's screens to the subjects. */ +export const backToSubjects = () => `

    ‹ המקצועות

    `; + +export const goalBar = (today, streak) => `
    +
    יעד יומי: ${today.done} מתוך ${today.goal}${today.reached ? " ✓" : ""} +
    +
    + ${streak === undefined ? "" : `
    🔥 רצף: ${streak} ${streak === 1 ? "יום" : "ימים"}
    `}
    `; + +/** A copy in random order; the items keep their own `index`, so the server still grades by the bank's position. */ +export const shuffled = items => { + const copy = [...items]; + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [copy[i], copy[j]] = [copy[j], copy[i]]; + } + return copy; +}; diff --git a/mathly2/static/vendor/mathlive/LICENSE.txt b/mathly2/static/vendor/mathlive/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..97ba1353dc3d2a84eb6e064a39b3e92664d7f09c --- /dev/null +++ b/mathly2/static/vendor/mathlive/LICENSE.txt @@ -0,0 +1,19 @@ +Copyright (c) 2017 - present Arno Gourdol. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_AMS-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_AMS-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..0acaaff03d4bb7606de02a827aeee338e5a86910 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_AMS-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Bold.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..f390922eceffe1f6dfb81a3dc086a92d98171b02 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Bold.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..75344a1f98e37e2c631e178065854c3a81fb842f Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Caligraphic-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Bold.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..395f28beac23c7b0f7f3a1e714bd8dac253dd3bc Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Bold.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..735f6948d63c8cc7f8233735bb9c8d843c83d804 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Fraktur-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Bold.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..ab2ad21da6fbe6c171bb869240954d0ead8f68fd Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Bold.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-BoldItalic.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-BoldItalic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..5931794de4a2a485fa70099bf2659b145976d043 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-BoldItalic.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Italic.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b50920e138807f385d0b0359f4f0f09891f18406 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Italic.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..eb24a7ba282b03d830fa6c63ee897d92a5188736 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Main-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-BoldItalic.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-BoldItalic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..29657023adc09956249f6295746c8ce4469b50d3 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-BoldItalic.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-Italic.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..215c143fd7805a5c2b222bd7892a1a2b09610020 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Math-Italic.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Bold.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Bold.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..cfaa3bda59246b49e94298478d6de3b3208066c8 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Bold.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Italic.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Italic.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..349c06dc609f896392fd5bc8b364d3bc3efc9330 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Italic.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..a90eea85f6f7bded69ff5d40114447a6d8b48cfe Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_SansSerif-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Script-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Script-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..b3048fc115681ee6c1bc86b0aa158cfbbf59daa3 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Script-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Size1-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size1-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..c5a8462fbfe2c39a7c1857b9e296e62500a8a8a5 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size1-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Size2-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size2-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..e1bccfe2403a4ed770c1697ae7c15b9e1cd9bc4e Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size2-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Size3-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size3-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..249a28662218a7a17ad8bd1fe072169ecb666a49 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size3-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Size4-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size4-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..680c13085076a2f6c5a7e695935ec3f21cddb65f Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Size4-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/fonts/KaTeX_Typewriter-Regular.woff2 b/mathly2/static/vendor/mathlive/fonts/KaTeX_Typewriter-Regular.woff2 new file mode 100644 index 0000000000000000000000000000000000000000..771f1af705f5cef5f578b3a1e7d8eff66f9b76b0 Binary files /dev/null and b/mathly2/static/vendor/mathlive/fonts/KaTeX_Typewriter-Regular.woff2 differ diff --git a/mathly2/static/vendor/mathlive/mathlive.min.js b/mathly2/static/vendor/mathlive/mathlive.min.js new file mode 100644 index 0000000000000000000000000000000000000000..089bfe29f3b5aa18af421cc8c99870a23f9683cf --- /dev/null +++ b/mathly2/static/vendor/mathlive/mathlive.min.js @@ -0,0 +1,3229 @@ +/** MathLive 0.111.1 */ + (function(global,factory){typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'],factory):(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MathLive = {}));})(this, (function (exports) { 'use strict'; +var MathLive=(()=>{var Wo=Object.defineProperty,of=Object.defineProperties,af=Object.getOwnPropertyDescriptor,sf=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertyNames,Ho=Object.getOwnPropertySymbols;var il=Object.prototype.hasOwnProperty,pu=Object.prototype.propertyIsEnumerable;var hu=(t,e,r)=>e in t?Wo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,h=(t,e)=>{for(var r in e||(e={}))il.call(e,r)&&hu(t,r,e[r]);if(Ho)for(var r of Ho(e))pu.call(e,r)&&hu(t,r,e[r]);return t},g=(t,e)=>of(t,sf(e));var nl=t=>typeof t=="symbol"?t:t+"",Ti=(t,e)=>{var r={};for(var i in t)il.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&Ho)for(var i of Ho(t))e.indexOf(i)<0&&pu.call(t,i)&&(r[i]=t[i]);return r};var cf=(t,e)=>{for(var r in e)Wo(t,r,{get:e[r],enumerable:!0})},uf=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lf(e))!il.call(t,n)&&n!==r&&Wo(t,n,{get:()=>e[n],enumerable:!(i=af(e,n))||i.enumerable});return t};var df=t=>uf(Wo({},"__esModule",{value:!0}),t);var Yy={};cf(Yy,{MathDivElement:()=>Fo,MathSpanElement:()=>No,MathfieldElement:()=>lt,_renderMathInElement:()=>mu,convertAsciiMathToLatex:()=>eu,convertLatexToAsciiMath:()=>by,convertLatexToMarkup:()=>pe,convertLatexToMathMl:()=>Bo,convertLatexToSpeakableText:()=>Ko,globalMathLive:()=>At,initVirtualKeyboardInCurrentBrowsingContext:()=>vo,renderMathInDocument:()=>Jy,renderMathInElement:()=>Qs,setKeyboardLayout:()=>Ou,setKeyboardLayoutLocale:()=>Bu,validateLatex:()=>gy,version:()=>Zy});function Le(){return"window"in globalThis&&"document"in globalThis}function Uo(){return"matchMedia"in window?window.matchMedia("(pointer: coarse)").matches:"ontouchstart"in window||navigator.maxTouchPoints>0}function fu(){try{return window.self!==window.top}catch(t){return!0}}function Di(){return typeof navigator.vibrate=="function"}function Et(){var e,r;if(!Le())return"other";let t=(r=(e=navigator.userAgentData)==null?void 0:e.platform)!=null?r:navigator.platform;return/^mac/i.test(t)?navigator.maxTouchPoints===5?"ios":"macos":/^win/i.test(t)?"windows":/android/i.test(navigator.userAgent)?"android":/iphone|ipod|ipad/i.test(navigator.userAgent)?"ios":/\bcros\b/i.test(navigator.userAgent)?"chromeos":"other"}function gu(){if(!Le())return!0;if(/firefox/i.test(navigator.userAgent)){let t=navigator.userAgent.match(/firefox\/(\d+)/i);return t?parseInt(t[1])>=78:!1}if(/trident/i.test(navigator.userAgent))return!1;if(/edge/i.test(navigator.userAgent)){let t=navigator.userAgent.match(/edg\/(\d+)/i);return t?parseInt(t[1])>=79:!1}return!0}function ol(){return HTMLElement.prototype.hasOwnProperty("popover")}var bu={id:"dvorak",locale:"en",displayName:"Dvorak",virtualLayout:"dvorak",platform:"",score:0,mapping:{KeyA:["a","A","\xE5","\xC5"],KeyB:["x","X","\u2248","\u02DB"],KeyC:["j","J","\u2206","\xD4"],KeyD:["e","E","\xB4","\xB4"],KeyE:[".",">","\u2265","\u02D8"],KeyF:["u","U","\xA8","\xA8"],KeyG:["i","I","\u02C6","\u02C6"],KeyH:["d","D","\u2202","\xCE"],KeyI:["c","C","\xE7","\xC7"],KeyJ:["h","H","\u02D9","\xD3"],KeyK:["t","T","\u2020","\u02C7"],KeyL:["n","N","\u02DC","\u02DC"],KeyM:["m","M","\xB5","\xC2"],KeyN:["b","B","\u222B","\u0131"],KeyO:["r","R","\xAE","\u2030"],KeyP:["l","L","\xAC","\xD2"],KeyQ:["'",'"',"\xE6","\xC6"],KeyR:["p","P","\u03C0","\u220F"],KeyS:["o","O","\xF8","\xD8"],KeyT:["y","Y","\xA5","\xC1"],KeyU:["g","G","\xA9","\u02DD"],KeyV:["k","K","\u02DA","\uF8FF"],KeyW:[",","<","\u2264","\xAF"],KeyX:["q","Q","\u0153","\u0152"],KeyY:["f","F","\u0192","\xCF"],KeyZ:[";",":","\u2026","\xDA"],Digit1:["1","!","\xA1","\u2044"],Digit2:["2","@","\u2122","\u20AC"],Digit3:["3","#","\xA3","\u2039"],Digit4:["4","$","\xA2","\u203A"],Digit5:["5","%","\u221E","\uFB01"],Digit6:["6","^","\xA7","\uFB02"],Digit7:["7","&","\xB6","\u2021"],Digit8:["8","*","\u2022","\xB0"],Digit9:["9","(","\xAA","\xB7"],Digit0:["0",")","\xBA","\u201A"],Space:[" "," "," "," "],Minus:["[","{","\u201C","\u201D"],Equal:["]","}","\u2018","\u2019"],BracketLeft:["/","?","\xF7","\xBF"],BracketRight:["=","+","\u2260","\xB1"],Backslash:["\\","|","\xAB","\xBB"],Semicolon:["s","S","\xDF","\xCD"],Quote:["-","_","\u2013","\u2014"],Backquote:["`","~","`","`"],Comma:["w","W","\u2211","\u201E"],Period:["v","V","\u221A","\u25CA"],Slash:["z","Z","\u03A9","\xB8"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],Numpad1:["1","1","1","1"],Numpad2:["2","2","2","2"],Numpad3:["3","3","3","3"],Numpad4:["4","4","4","4"],Numpad5:["5","5","5","5"],Numpad6:["6","6","6","6"],Numpad7:["7","7","7","7"],Numpad8:["8","8","8","8"],Numpad9:["9","9","9","9"],Numpad0:["0","0","0","0"],NumpadDecimal:[".",".",".","."],IntlBackslash:["\xA7","\xB1","\xA7","\xB1"],NumpadEqual:["=","=","=","="],AudioVolumeUp:["","=","","="]}};var Go={id:"apple.en-intl",displayName:"English (international)",virtualLayout:"qwerty",platform:"apple",locale:"en",score:0,mapping:{KeyA:["a","A","\xE5","\xC5"],KeyB:["b","B","\u222B","\u0131"],KeyC:["c","C","\xE7","\xC7"],KeyD:["d","D","\u2202","\xCE"],KeyE:["e","E","\xB4","\xB4"],KeyF:["f","F","\u0192","\xCF"],KeyG:["g","G","\xA9","\u02DD"],KeyH:["h","H","\u02D9","\xD3"],KeyI:["i","I","\u02C6","\u02C6"],KeyJ:["j","J","\u2206","\xD4"],KeyK:["k","K","\u02DA","\uF8FF"],KeyL:["l","L","\xAC","\xD2"],KeyM:["m","M","\xB5","\xC2"],KeyN:["n","N","\u02DC","\u02DC"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\u03C0","\u220F"],KeyQ:["q","Q","\u0153","\u0152"],KeyR:["r","R","\xAE","\u2030"],KeyS:["s","S","\xDF","\xCD"],KeyT:["t","T","\u2020","\u02C7"],KeyU:["u","U","\xA8","\xA8"],KeyV:["v","V","\u221A","\u25CA"],KeyW:["w","W","\u2211","\u201E"],KeyX:["x","X","\u2248","\u02DB"],KeyY:["y","Y","\xA5","\xC1"],KeyZ:["z","Z","\u03A9","\xB8"],Digit1:["1","!","\xA1","\u2044"],Digit2:["2","@","\u2122","\u20AC"],Digit3:["3","#","\xA3","\u2039"],Digit4:["4","$","\xA2","\u203A"],Digit5:["5","%","\u221E","\uFB01"],Digit6:["6","^","\xA7","\uFB02"],Digit7:["7","&","\xB6","\u2021"],Digit8:["8","*","\u2022","\xB0"],Digit9:["9","(","\xAA","\xB7"],Digit0:["0",")","\xBA","\u201A"],Space:[" "," "," "," "],Minus:["-","_","\u2013","\u2014"],Equal:["=","+","\u2260","\xB1"],BracketLeft:["[","{","\u201C","\u201D"],BracketRight:["]","}","\u2018","\u2019"],Backslash:["\\","|","\xAB","\xBB"],Semicolon:[";",":","\u2026","\xDA"],Quote:["'",'"',"\xE6","\xC6"],Backquote:["`","\u02DC","`","`"],Comma:[",","<","\u2264","\xAF"],Period:[".",">","\u2265","\u02D8"],Slash:["/","?","\xF7","\xBF"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],Numpad1:["1","1","1","1"],Numpad2:["2","2","2","2"],Numpad3:["3","3","3","3"],Numpad4:["4","4","4","4"],Numpad5:["5","5","5","5"],Numpad6:["6","6","6","6"],Numpad7:["7","7","7","7"],Numpad8:["8","8","8","8"],Numpad9:["9","9","9","9"],Numpad0:["0","0","0","0"],NumpadDecimal:[".",".",".","."],IntlBackslash:["\xA7","\xB1","\xA7","\xB1"],NumpadEqual:["=","=","=","="],AudioVolumeUp:["","=","","="]}},al={id:"windows.en-intl",displayName:"English (international)",platform:"windows",virtualLayout:"qwerty",locale:"en",score:0,mapping:{KeyA:["a","A","\xE1","\xC1"],KeyB:["b","B","",""],KeyC:["c","C","\xA9","\xA2"],KeyD:["d","D","\xF0","\xD0"],KeyE:["e","E","\xE9","\xC9"],KeyF:["f","F","",""],KeyG:["g","G","",""],KeyH:["h","H","",""],KeyI:["i","I","\xED","\xCD"],KeyJ:["j","J","",""],KeyK:["k","K","",""],KeyL:["l","L","\xF8","\xD8"],KeyM:["m","M","\xB5",""],KeyN:["n","N","\xF1","\xD1"],KeyO:["o","O","\xF3","\xD3"],KeyP:["p","P","\xF6","\xD6"],KeyQ:["q","Q","\xE4","\xC4"],KeyR:["r","R","\xAE",""],KeyS:["s","S","\xDF","\xA7"],KeyT:["t","T","\xFE","\xDE"],KeyU:["u","U","\xFA","\xDA"],KeyV:["v","V","",""],KeyW:["w","W","\xE5","\xC5"],KeyX:["x","X","",""],KeyY:["y","Y","\xFC","\xDC"],KeyZ:["z","Z","\xE6","\xC6"],Digit1:["1","!","\xA1","\xB9"],Digit2:["2","@","\xB2",""],Digit3:["3","#","\xB3",""],Digit4:["4","$","\xA4","\xA3"],Digit5:["5","%","\u20AC",""],Digit6:["6","^","\xBC",""],Digit7:["7","&","\xBD",""],Digit8:["8","*","\xBE",""],Digit9:["9","(","\u2018",""],Digit0:["0",")","\u2019",""],Space:[" "," ","",""],Minus:["-","_","\xA5",""],Equal:["=","+","\xD7","\xF7"],BracketLeft:["[","{","\xAB",""],BracketRight:["]","}","\xBB",""],Backslash:["\\","|","\xAC","\xA6"],Semicolon:[";",":","\xB6","\xB0"],Quote:["'",'"',"\xB4","\xA8"],Backquote:["`","~","",""],Comma:[",","<","\xE7","\xC7"],Period:[".",">","",""],Slash:["/","?","\xBF",""],NumpadDivide:["/","/","",""],NumpadMultiply:["*","*","",""],NumpadSubtract:["-","-","",""],NumpadAdd:["+","+","",""],IntlBackslash:["\\","|","",""]}},sl={id:"linux.en",displayName:"English",platform:"linux",virtualLayout:"qwerty",locale:"en",score:0,mapping:{KeyA:["a","A","a","A"],KeyB:["b","B","b","B"],KeyC:["c","C","c","C"],KeyD:["d","D","d","D"],KeyE:["e","E","e","E"],KeyF:["f","F","f","F"],KeyG:["g","G","g","G"],KeyH:["h","H","h","H"],KeyI:["i","I","i","I"],KeyJ:["j","J","j","J"],KeyK:["k","K","k","K"],KeyL:["l","L","l","L"],KeyM:["m","M","m","M"],KeyN:["n","N","n","N"],KeyO:["o","O","o","O"],KeyP:["p","P","p","P"],KeyQ:["q","Q","q","Q"],KeyR:["r","R","r","R"],KeyS:["s","S","s","S"],KeyT:["t","T","t","T"],KeyU:["u","U","u","U"],KeyV:["v","V","v","V"],KeyW:["w","W","w","W"],KeyX:["x","X","x","X"],KeyY:["y","Y","y","Y"],KeyZ:["z","Z","z","Z"],Digit1:["1","!","1","!"],Digit2:["2","@","2","@"],Digit3:["3","#","3","#"],Digit4:["4","$","4","$"],Digit5:["5","%","5","%"],Digit6:["6","^","6","^"],Digit7:["7","&","7","&"],Digit8:["8","*","8","*"],Digit9:["9","(","9","("],Digit0:["0",")","0",")"],Space:[" "," "," "," "],Minus:["-","_","-","_"],Equal:["=","+","=","+"],BracketLeft:["[","{","[","{"],BracketRight:["]","}","]","}"],Backslash:["\\","|","\\","|"],Semicolon:[";",":",";",":"],Quote:["'",'"',"'",'"'],Backquote:["`","~","`","~"],Comma:[",","<",",","<"],Period:[".",">",".",">"],Slash:["/","?","/","?"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],Numpad1:["1","1","1","1"],Numpad2:["2","2","2","2"],Numpad3:["3","3","3","3"],Numpad4:["4","4","4","4"],Numpad5:["5","5","5","5"],Numpad6:["6","6","6","6"],Numpad7:["7","7","7","7"],Numpad8:["8","8","8","8"],Numpad9:["9","9","9","9"],Numpad0:["0","0","0","0"],NumpadDecimal:["",".","","."],IntlBackslash:["<",">","|","\xA6"],NumpadEqual:["=","=","=","="],NumpadComma:[".",".",".","."],NumpadParenLeft:["(","(","(","("],NumpadParenRight:[")",")",")",")"]}};var yu={id:"apple.french",locale:"fr",displayName:"French",platform:"apple",virtualLayout:"azerty",score:0,mapping:{KeyA:["q","Q","\u2021","\u03A9"],KeyB:["b","B","\xDF","\u222B"],KeyC:["c","C","\xA9","\xA2"],KeyD:["d","D","\u2202","\u2206"],KeyE:["e","E","\xEA","\xCA"],KeyF:["f","F","\u0192","\xB7"],KeyG:["g","G","\uFB01","\uFB02"],KeyH:["h","H","\xCC","\xCE"],KeyI:["i","I","\xEE","\xEF"],KeyJ:["j","J","\xCF","\xCD"],KeyK:["k","K","\xC8","\xCB"],KeyL:["l","L","\xAC","|"],KeyM:[",","?","\u221E","\xBF"],KeyN:["n","N","~","\u0131"],KeyO:["o","O","\u0153","\u0152"],KeyP:["p","P","\u03C0","\u220F"],KeyQ:["a","A","\xE6","\xC6"],KeyR:["r","R","\xAE","\u201A"],KeyS:["s","S","\xD2","\u2211"],KeyT:["t","T","\u2020","\u2122"],KeyU:["u","U","\xBA","\xAA"],KeyV:["v","V","\u25CA","\u221A"],KeyW:["z","Z","\xC2","\xC5"],KeyX:["x","X","\u2248","\u2044"],KeyY:["y","Y","\xDA","\u0178"],KeyZ:["w","W","\u2039","\u203A"],Digit1:["&","1","\uF8FF","\xB4"],Digit2:["\xE9","2","\xEB","\u201E"],Digit3:['"',"3","\u201C","\u201D"],Digit4:["'","4","\u2018","\u2019"],Digit5:["(","5","{","["],Digit6:["\xA7","6","\xB6","\xE5"],Digit7:["\xE8","7","\xAB","\xBB"],Digit8:["!","8","\xA1","\xDB"],Digit9:["\xE7","9","\xC7","\xC1"],Digit0:["\xE0","0","\xF8","\xD8"],Space:[" "," "," "," "],Minus:[")","\xB0","}","]"],Equal:["-","_","\u2014","\u2013"],BracketLeft:["^","\xA8","\xF4","\xD4"],BracketRight:["$","*","\u20AC","\xA5"],Backslash:["`","\xA3","@","#"],Semicolon:["m","M","\xB5","\xD3"],Quote:["\xF9","%","\xD9","\u2030"],Backquote:["<",">","\u2264","\u2265"],Comma:[";",".","\u2026","\u2022"],Period:[":","/","\xF7","\\"],Slash:["=","+","\u2260","\xB1"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],NumpadDecimal:[",",".",",","."],IntlBackslash:["@","#","\u2022","\u0178"],NumpadEqual:["=","=","=","="]}},xu={id:"windows.french",locale:"fr",displayName:"French",virtualLayout:"azerty",platform:"windows",score:0,mapping:{KeyA:["q","Q","",""],KeyB:["b","B","",""],KeyC:["c","C","",""],KeyD:["d","D","",""],KeyE:["e","E","\u20AC",""],KeyF:["f","F","",""],KeyG:["g","G","",""],KeyH:["h","H","",""],KeyI:["i","I","",""],KeyJ:["j","J","",""],KeyK:["k","K","",""],KeyL:["l","L","",""],KeyM:[",","?","",""],KeyN:["n","N","",""],KeyO:["o","O","",""],KeyP:["p","P","",""],KeyQ:["a","A","",""],KeyR:["r","R","",""],KeyS:["s","S","",""],KeyT:["t","T","",""],KeyU:["u","U","",""],KeyV:["v","V","",""],KeyW:["z","Z","",""],KeyX:["x","X","",""],KeyY:["y","Y","",""],KeyZ:["w","W","",""],Digit1:["&","1","",""],Digit2:["\xE9","2","~",""],Digit3:['"',"3","#",""],Digit4:["'","4","{",""],Digit5:["(","5","[",""],Digit6:["-","6","|",""],Digit7:["\xE8","7","`",""],Digit8:["_","8","\\",""],Digit9:["\xE7","9","^",""],Digit0:["\xE0","0","@",""],Space:[" "," ","",""],Minus:[")","\xB0","]",""],Equal:["=","+","}",""],BracketLeft:["^","\xA8","",""],BracketRight:["$","\xA3","\xA4",""],Backslash:["*","\xB5","",""],Semicolon:["m","M","",""],Quote:["\xF9","%","",""],Backquote:["\xB2","","",""],Comma:[";",".","",""],Period:[":","/","",""],Slash:["!","\xA7","",""],NumpadDivide:["/","/","",""],NumpadMultiply:["*","*","",""],NumpadSubtract:["-","-","",""],NumpadAdd:["+","+","",""],IntlBackslash:["<",">","",""]}},vu={id:"linux.french",locale:"fr",displayName:"French",virtualLayout:"azerty",platform:"linux",score:0,mapping:{KeyA:["q","Q","@","\u03A9"],KeyB:["b","B","\u201D","\u2019"],KeyC:["c","C","\xA2","\xA9"],KeyD:["d","D","\xF0","\xD0"],KeyE:["e","E","\u20AC","\xA2"],KeyF:["f","F","\u0111","\xAA"],KeyG:["g","G","\u014B","\u014A"],KeyH:["h","H","\u0127","\u0126"],KeyI:["i","I","\u2192","\u0131"],KeyJ:["j","J","\u0309","\u031B"],KeyK:["k","K","\u0138","&"],KeyL:["l","L","\u0142","\u0141"],KeyM:[",","?","\u0301","\u030B"],KeyN:["n","N","n","N"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\xFE","\xDE"],KeyQ:["a","A","\xE6","\xC6"],KeyR:["r","R","\xB6","\xAE"],KeyS:["s","S","\xDF","\xA7"],KeyT:["t","T","\u0167","\u0166"],KeyU:["u","U","\u2193","\u2191"],KeyV:["v","V","\u201C","\u2018"],KeyW:["z","Z","\xAB","<"],KeyX:["x","X","\xBB",">"],KeyY:["y","Y","\u2190","\xA5"],KeyZ:["w","W","\u0142","\u0141"],Digit1:["&","1","\xB9","\xA1"],Digit2:["\xE9","2","~","\u215B"],Digit3:['"',"3","#","\xA3"],Digit4:["'","4","{","$"],Digit5:["(","5","[","\u215C"],Digit6:["-","6","|","\u215D"],Digit7:["\xE8","7","`","\u215E"],Digit8:["_","8","\\","\u2122"],Digit9:["\xE7","9","^","\xB1"],Digit0:["\xE0","0","@","\xB0"],Enter:["\r","\r","\r","\r"],Escape:["\x1B","\x1B","\x1B","\x1B"],Backspace:["\b","\b","\b","\b"],Tab:[" ",""," ",""],Space:[" "," "," "," "],Minus:[")","\xB0","]","\xBF"],Equal:["=","+","}","\u0328"],BracketLeft:["\u0302","\u0308","\u0308","\u030A"],BracketRight:["$","\xA3","\xA4","\u0304"],Backslash:["*","\xB5","\u0300","\u0306"],Semicolon:["m","M","\xB5","\xBA"],Quote:["\xF9","%","\u0302","\u030C"],Backquote:["\xB2","~","\xAC","\xAC"],Comma:[";",".","\u2500","\xD7"],Period:[":","/","\xB7","\xF7"],Slash:["!","\xA7","\u0323","\u0307"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],NumpadDecimal:["",".","","."],IntlBackslash:["<",">","|","\xA6"]}};var _u={id:"apple.german",locale:"de",displayName:"German",virtualLayout:"qwertz",platform:"apple",score:0,mapping:{KeyA:["a","A","\xE5","\xC5"],KeyB:["b","B","\u222B","\u2039"],KeyC:["c","C","\xE7","\xC7"],KeyD:["d","D","\u2202","\u2122"],KeyE:["e","E","\u20AC","\u2030"],KeyF:["f","F","\u0192","\xCF"],KeyG:["g","G","\xA9","\xCC"],KeyH:["h","H","\xAA","\xD3"],KeyI:["i","I","\u2044","\xDB"],KeyJ:["j","J","\xBA","\u0131"],KeyK:["k","K","\u2206","\u02C6"],KeyL:["l","L","@","\uFB02"],KeyM:["m","M","\xB5","\u02D8"],KeyN:["n","N","~","\u203A"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\u03C0","\u220F"],KeyQ:["q","Q","\xAB","\xBB"],KeyR:["r","R","\xAE","\xB8"],KeyS:["s","S","\u201A","\xCD"],KeyT:["t","T","\u2020","\u02DD"],KeyU:["u","U","\xA8","\xC1"],KeyV:["v","V","\u221A","\u25CA"],KeyW:["w","W","\u2211","\u201E"],KeyX:["x","X","\u2248","\xD9"],KeyY:["z","Z","\u03A9","\u02C7"],KeyZ:["y","Y","\xA5","\u2021"],Digit1:["1","!","\xA1","\xAC"],Digit2:["2",'"',"\u201C","\u201D"],Digit3:["3","\xA7","\xB6","#"],Digit4:["4","$","\xA2","\xA3"],Digit5:["5","%","[","\uFB01"],Digit6:["6","&","]","^"],Digit7:["7","/","|","\\"],Digit8:["8","(","{","\u02DC"],Digit9:["9",")","}","\xB7"],Digit0:["0","=","\u2260","\xAF"],Space:[" "," "," "," "],Minus:["\xDF","?","\xBF","\u02D9"],Equal:["\xB4","`","'","\u02DA"],BracketLeft:["\xFC","\xDC","\u2022","\xB0"],BracketRight:["+","*","\xB1","\uF8FF"],Backslash:["#","'","\u2018","\u2019"],Semicolon:["\xF6","\xD6","\u0153","\u0152"],Quote:["\xE4","\xC4","\xE6","\xC6"],Backquote:["<",">","\u2264","\u2265"],Comma:[",",";","\u221E","\u02DB"],Period:[".",":","\u2026","\xF7"],Slash:["-","_","\u2013","\u2014"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],NumpadDecimal:[",",",",".","."],IntlBackslash:["^","\xB0","\u201E","\u201C"],NumpadEqual:["=","=","=","="]}},Mu={id:"windows.german",locale:"de",displayName:"German",platform:"windows",virtualLayout:"qwertz",score:0,mapping:{KeyA:["a","A","",""],KeyB:["b","B","",""],KeyC:["c","C","",""],KeyD:["d","D","",""],KeyE:["e","E","\u20AC",""],KeyF:["f","F","",""],KeyG:["g","G","",""],KeyH:["h","H","",""],KeyI:["i","I","",""],KeyJ:["j","J","",""],KeyK:["k","K","",""],KeyL:["l","L","",""],KeyM:["m","M","\xB5",""],KeyN:["n","N","",""],KeyO:["o","O","",""],KeyP:["p","P","",""],KeyQ:["q","Q","@",""],KeyR:["r","R","",""],KeyS:["s","S","",""],KeyT:["t","T","",""],KeyU:["u","U","",""],KeyV:["v","V","",""],KeyW:["w","W","",""],KeyX:["x","X","",""],KeyY:["z","Z","",""],KeyZ:["y","Y","",""],Digit1:["1","!","",""],Digit2:["2",'"',"\xB2",""],Digit3:["3","\xA7","\xB3",""],Digit4:["4","$","",""],Digit5:["5","%","",""],Digit6:["6","&","",""],Digit7:["7","/","{",""],Digit8:["8","(","[",""],Digit9:["9",")","]",""],Digit0:["0","=","}",""],Space:[" "," ","",""],Minus:["\xDF","?","\\","\u1E9E"],Equal:["\xB4","`","",""],BracketLeft:["\xFC","\xDC","",""],BracketRight:["+","*","~",""],Backslash:["#","'","",""],Semicolon:["\xF6","\xD6","",""],Quote:["\xE4","\xC4","",""],Backquote:["^","\xB0","",""],Comma:[",",";","",""],Period:[".",":","",""],Slash:["-","_","",""],NumpadDivide:["/","/","",""],NumpadMultiply:["*","*","",""],NumpadSubtract:["-","-","",""],NumpadAdd:["+","+","",""],IntlBackslash:["<",">","|",""]}},wu={id:"linux.german",locale:"de",displayName:"German",platform:"windows",virtualLayout:"qwertz",score:0,mapping:{KeyA:["a","A","\xE6","\xC6"],KeyB:["b","B","\u201C","\u2018"],KeyC:["c","C","\xA2","\xA9"],KeyD:["d","D","\xF0","\xD0"],KeyE:["e","E","\u20AC","\u20AC"],KeyF:["f","F","\u0111","\xAA"],KeyG:["g","G","\u014B","\u014A"],KeyH:["h","H","\u0127","\u0126"],KeyI:["i","I","\u2192","\u0131"],KeyJ:["j","J","\u0323","\u0307"],KeyK:["k","K","\u0138","&"],KeyL:["l","L","\u0142","\u0141"],KeyM:["m","M","\xB5","\xBA"],KeyN:["n","N","\u201D","\u2019"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\xFE","\xDE"],KeyQ:["q","Q","@","\u03A9"],KeyR:["r","R","\xB6","\xAE"],KeyS:["s","S","\u017F","\u1E9E"],KeyT:["t","T","\u0167","\u0166"],KeyU:["u","U","\u2193","\u2191"],KeyV:["v","V","\u201E","\u201A"],KeyW:["w","W","\u0142","\u0141"],KeyX:["x","X","\xAB","\u2039"],KeyY:["z","Z","\u2190","\xA5"],KeyZ:["y","Y","\xBB","\u203A"],Digit1:["1","!","\xB9","\xA1"],Digit2:["2",'"',"\xB2","\u215B"],Digit3:["3","\xA7","\xB3","\xA3"],Digit4:["4","$","\xBC","\xA4"],Digit5:["5","%","\xBD","\u215C"],Digit6:["6","&","\xAC","\u215D"],Digit7:["7","/","{","\u215E"],Digit8:["8","(","[","\u2122"],Digit9:["9",")","]","\xB1"],Digit0:["0","=","}","\xB0"],Enter:["\r","\r","\r","\r"],Escape:["\x1B","\x1B","\x1B","\x1B"],Backspace:["\b","\b","\b","\b"],Tab:[" ",""," ",""],Space:[" "," "," "," "],Minus:["\xDF","?","\\","\xBF"],Equal:["\u0301","\u0300","\u0327","\u0328"],BracketLeft:["\xFC","\xDC","\u0308","\u030A"],BracketRight:["+","*","~","\xAF"],Backslash:["#","'","\u2019","\u0306"],Semicolon:["\xF6","\xD6","\u030B","\u0323"],Quote:["\xE4","\xC4","\u0302","\u030C"],Backquote:["\u0302","\xB0","\u2032","\u2033"],Comma:[",",";","\xB7","\xD7"],Period:[".",":","\u2026","\xF7"],Slash:["-","_","\u2013","\u2014"],PrintScreen:["","","",""],PageUp:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],Numpad1:["","1","","1"],Numpad2:["","2","","2"],Numpad3:["","3","","3"],Numpad4:["","4","","4"],Numpad5:["","5","","5"],Numpad6:["","6","","6"],Numpad7:["","7","","7"],Numpad8:["","8","","8"],Numpad9:["","9","","9"],Numpad0:["","0","","0"],NumpadDecimal:["",",","",","],IntlBackslash:["<",">","|","\u0331"],AltRight:["\r","\r","\r","\r"],MetaRight:[".",".",".","."]}};var Su={id:"apple.spanish",locale:"es",displayName:"Spanish ISO",platform:"apple",virtualLayout:"qwerty",score:0,mapping:{KeyA:["a","A","\xE5","\xC5"],KeyB:["b","B","\xDF",""],KeyC:["c","C","\xA9"," "],KeyD:["d","D","\u2202","\u2206"],KeyE:["e","E","\u20AC","\u20AC"],KeyF:["f","F","\u0192","\uFB01"],KeyG:["g","G","\uF8FF","\uFB02"],KeyH:["h","H","\u2122"," "],KeyI:["i","I"," "," "],KeyJ:["j","J","\xB6","\xAF"],KeyK:["k","K","\xA7","\u02C7"],KeyL:["l","L"," ","\u02D8"],KeyM:["m","M","\xB5","\u02DA"],KeyN:["n","N"," ","\u02D9"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\u03C0","\u220F"],KeyQ:["q","Q","\u0153","\u0152"],KeyR:["r","R","\xAE"," "],KeyS:["s","S","\u222B"," "],KeyT:["t","T","\u2020","\u2021"],KeyU:["u","U"," "," "],KeyV:["v","V","\u221A","\u25CA"],KeyW:["w","W","\xE6","\xC6"],KeyX:["x","X","\u2211","\u203A"],KeyY:["y","Y","\xA5"," "],KeyZ:["z","Z","\u03A9","\u2039"],Digit1:["1","!","|","\u0131"],Digit2:["2",'"',"@","\u02DD"],Digit3:["3","\xB7","#","\u2022"],Digit4:["4","$","\xA2","\xA3"],Digit5:["5","%","\u221E","\u2030"],Digit6:["6","&","\xAC"," "],Digit7:["7","/","\xF7","\u2044"],Digit8:["8","(","\u201C","\u2018"],Digit9:["9",")","\u201D","\u2019"],Digit0:["0","=","\u2260","\u2248"],Space:[" "," "," "," "],Minus:["'","?","\xB4","\xB8"],Equal:["\xA1","\xBF","\u201A","\u02DB"],BracketLeft:["`","^","[","\u02C6"],BracketRight:["+","*","]","\xB1"],Backslash:["\xE7","\xC7","}","\xBB"],Semicolon:["\xF1","\xD1","~","\u02DC"],Quote:["\xB4","\xA8","{","\xAB"],Backquote:["<",">","\u2264","\u2265"],Comma:[",",";","\u201E",""],Period:[".",":","\u2026","\u2026"],Slash:["-","_","\u2013","\u2014"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],Numpad1:["1","1","1","1"],Numpad2:["2","2","2","2"],Numpad3:["3","3","3","3"],Numpad4:["4","4","4","4"],Numpad5:["5","5","5","5"],Numpad6:["6","6","6","6"],Numpad7:["7","7","7","7"],Numpad8:["8","8","8","8"],Numpad9:["9","9","9","9"],Numpad0:["0","0","0","0"],NumpadDecimal:[",",",",",",","],IntlBackslash:["\xBA","\xAA","\\","\xB0"]}},ku={id:"windows.spanish",locale:"es",displayName:"Spanish",platform:"windows",virtualLayout:"qwerty",score:0,mapping:{KeyA:["a","A","",""],KeyB:["b","B","",""],KeyC:["c","C","",""],KeyD:["d","D","",""],KeyE:["e","E","\u20AC",""],KeyF:["f","F","",""],KeyG:["g","G","",""],KeyH:["h","H","",""],KeyI:["i","I","",""],KeyJ:["j","J","",""],KeyK:["k","K","",""],KeyL:["l","L","",""],KeyM:["m","M","",""],KeyN:["n","N","",""],KeyO:["o","O","",""],KeyP:["p","P","",""],KeyQ:["q","Q","",""],KeyR:["r","R","",""],KeyS:["s","S","",""],KeyT:["t","T","",""],KeyU:["u","U","",""],KeyV:["v","V","",""],KeyW:["w","W","",""],KeyX:["x","X","",""],KeyY:["y","Y","",""],KeyZ:["z","Z","",""],Digit1:["1","!","|",""],Digit2:["2",'"',"@",""],Digit3:["3","\xB7","#",""],Digit4:["4","$","~",""],Digit5:["5","%","\u20AC",""],Digit6:["6","&","\xAC",""],Digit7:["7","/","",""],Digit8:["8","(","",""],Digit9:["9",")","",""],Digit0:["0","=","",""],Space:[" "," ","",""],Minus:["'","?","",""],Equal:["\xA1","\xBF","",""],BracketLeft:["`","^","[",""],BracketRight:["+","*","]",""],Backslash:["\xE7","\xC7","}",""],Semicolon:["\xF1","\xD1","",""],Quote:["\xB4","\xA8","{",""],Backquote:["\xBA","\xAA","\\",""],Comma:[",",";","",""],Period:[".",":","",""],Slash:["-","_","",""],NumpadDivide:["/","/","",""],NumpadMultiply:["*","*","",""],NumpadSubtract:["-","-","",""],NumpadAdd:["+","+","",""],IntlBackslash:["<",">","",""]}},Lu={id:"linux.spanish",locale:"es",displayName:"Spanish",platform:"linux",virtualLayout:"qwerty",score:0,mapping:{KeyA:["a","A","\xE6","\xC6"],KeyB:["b","B","\u201D","\u2019"],KeyC:["c","C","\xA2","\xA9"],KeyD:["d","D","\xF0","\xD0"],KeyE:["e","E","\u20AC","\xA2"],KeyF:["f","F","\u0111","\xAA"],KeyG:["g","G","\u014B","\u014A"],KeyH:["h","H","\u0127","\u0126"],KeyI:["i","I","\u2192","\u0131"],KeyJ:["j","J","\u0309","\u031B"],KeyK:["k","K","\u0138","&"],KeyL:["l","L","\u0142","\u0141"],KeyM:["m","M","\xB5","\xBA"],KeyN:["n","N","n","N"],KeyO:["o","O","\xF8","\xD8"],KeyP:["p","P","\xFE","\xDE"],KeyQ:["q","Q","@","\u03A9"],KeyR:["r","R","\xB6","\xAE"],KeyS:["s","S","\xDF","\xA7"],KeyT:["t","T","\u0167","\u0166"],KeyU:["u","U","\u2193","\u2191"],KeyV:["v","V","\u201C","\u2018"],KeyW:["w","W","\u0142","\u0141"],KeyX:["x","X","\xBB",">"],KeyY:["y","Y","\u2190","\xA5"],KeyZ:["z","Z","\xAB","<"],Digit1:["1","!","|","\xA1"],Digit2:["2",'"',"@","\u215B"],Digit3:["3","\xB7","#","\xA3"],Digit4:["4","$","~","$"],Digit5:["5","%","\xBD","\u215C"],Digit6:["6","&","\xAC","\u215D"],Digit7:["7","/","{","\u215E"],Digit8:["8","(","[","\u2122"],Digit9:["9",")","]","\xB1"],Digit0:["0","=","}","\xB0"],Enter:["\r","\r","\r","\r"],Escape:["\x1B","\x1B","\x1B","\x1B"],Backspace:["\b","\b","\b","\b"],Tab:[" ",""," ",""],Space:[" "," "," "," "],Minus:["'","?","\\","\xBF"],Equal:["\xA1","\xBF","\u0303","~"],BracketLeft:["\u0300","\u0302","[","\u030A"],BracketRight:["+","*","]","\u0304"],Backslash:["\xE7","\xC7","}","\u0306"],Semicolon:["\xF1","\xD1","~","\u030B"],Quote:["\u0301","\u0308","{","{"],Backquote:["\xBA","\xAA","\\","\\"],Comma:[",",";","\u2500","\xD7"],Period:[".",":","\xB7","\xF7"],Slash:["-","_","\u0323","\u0307"],NumpadDivide:["/","/","/","/"],NumpadMultiply:["*","*","*","*"],NumpadSubtract:["-","-","-","-"],NumpadAdd:["+","+","+","+"],NumpadEnter:["\r","\r","\r","\r"],Numpad1:["","1","","1"],Numpad2:["","2","","2"],Numpad3:["","3","","3"],Numpad4:["","4","","4"],Numpad5:["","5","","5"],Numpad6:["","6","","6"],Numpad7:["","7","","7"],Numpad8:["","8","","8"],Numpad9:["","9","","9"],Numpad0:["","0","","0"],NumpadDecimal:["",".","","."],IntlBackslash:["<",">","|","\xA6"],NumpadEqual:["=","=","=","="],NumpadComma:[".",".",".","."],NumpadParenLeft:["(","(","(","("],NumpadParenRight:[")",")",")",")"]}};function ll(t){let e=t.split("+"),r={shift:!1,alt:!1,cmd:!1,win:!1,meta:!1,ctrl:!1,key:e.pop()};return e.includes("shift")&&(r.shift=!0),e.includes("alt")&&(r.alt=!0),e.includes("ctrl")&&(r.ctrl=!0),e.includes("cmd")&&(r.cmd=!0),e.includes("win")&&(r.win=!0),e.includes("meta")&&(r.meta=!0),r}function Zr(t){let e="";return t.shift&&(e+="shift+"),t.alt&&(e+="alt+"),t.ctrl&&(e+="ctrl+"),t.cmd&&(e+="cmd+"),t.win&&(e+="win+"),t.meta&&(e+="meta+"),e+t.key}var mf={enter:"[Enter]",escape:"[Escape]",backspace:"[Backspace]",tab:"[Tab]",space:"[Space]",pausebreak:"[Pause]",insert:"[Insert]",home:"[Home]",pageup:"[PageUp]",delete:"[Delete]",end:"[End]",pagedown:"[PageDown]",right:"[ArrowRight]",left:"[ArrowLeft]",down:"[ArrowDown]",up:"[ArrowUp]",numpad0:"[Numpad0]",numpad1:"[Numpad1]",numpad2:"[Numpad2]",numpad3:"[Numpad3]",numpad4:"[Numpad4]",numpad5:"[Numpad5]",numpad6:"[Numpad6]",numpad7:"[Numpad7]",numpad8:"[Numpad8]",numpad9:"[Numpad9]",numpad_divide:"[NumpadDivide]",numpad_multiply:"[NumpadMultiply]",numpad_subtract:"[NumpadSubtract]",numpad_add:"[NumpadAdd]",numpad_decimal:"[NumpadDecimal]",numpad_separator:"[NumpadComma]",capslock:"[Capslock]",f1:"[F1]",f2:"[F2]",f3:"[F3]",f4:"[F4]",f5:"[F5]",f6:"[F6]",f7:"[F7]",f8:"[F8]",f9:"[F9]",f10:"[F10]",f11:"[F11]",f12:"[F12]",f13:"[F13]",f14:"[F14]",f15:"[F15]",f16:"[F16]",f17:"[F17]",f18:"[F18]",f19:"[F19]"},Oi=[],Yt;function cl(){switch(Et()){case"macos":case"ios":return"apple";case"windows":return"windows"}return"linux"}function Je(t){(!t.platform||t.platform===cl())&&Oi.push(t)}function Au(t,e){var i;let r={shift:!1,alt:!1,cmd:!1,win:!1,meta:!1,ctrl:!1,key:""};if(!t)return r;for(let[n,o]of Object.entries(e.mapping)){if(o[0]===t)return r.key=`[${n}]`,r;if(o[1]===t)return r.shift=!0,r.key=`[${n}]`,r;if(o[2]===t)return r.alt=!0,r.key=`[${n}]`,r;if(o[3]===t)return r.shift=!0,r.alt=!0,r.key=`[${n}]`,r}return r.key=(i=mf[t])!=null?i:"",r}function Cu(t){if(t.code)return t;let e=Object.entries(yr().mapping),r=!1,i=!1,n="";for(let o=0;o<4;o++){for(let[a,s]of e)if(s[o]===t.key){n=a,o===3?(r=!0,i=!0):o===2?r=!0:o===1&&(i=!0);break}if(n)break}return new KeyboardEvent(t.type,g(h({},t),{altKey:r,shiftKey:i,code:n}))}function Eu(t){var r,i;if(!t||t.key==="Unidentified"||t.key==="Dead")return;let e=t.shiftKey&&t.altKey?3:t.altKey?2:t.shiftKey?1:0;for(let n of Oi)((r=n.mapping[t.code])==null?void 0:r[e])===t.key?n.score+=1:(i=n.mapping[t.code])!=null&&i[e]&&(n.score=0);Oi.sort((n,o)=>o.score-n.score)}function jo(t){Yt=Oi.find(e=>t.startsWith(e.locale))}function Tu(t){return Yt=Oi.find(e=>e.id===t),Yt}function yr(){return Yt!=null?Yt:Oi[0]}function Du(){switch(cl()){case"apple":return Go;case"windows":return al;case"linux":return sl}return Go}switch(cl()){case"apple":Je(Go),Je(yu),Je(Su),Je(_u);break;case"windows":Je(al),Je(xu),Je(ku),Je(Mu);break;case"linux":Je(sl),Je(vu),Je(Lu),Je(wu);break}Je(bu);function Ou(t){Tu(t)}function Bu(t){jo(t)}function ee(t){return Array.isArray(t)}var Ku={en:{"keyboard.tooltip.symbols":"Symbols","keyboard.tooltip.greek":"Greek Letters","keyboard.tooltip.numeric":"Numeric","keyboard.tooltip.alphabetic":"Roman Letters","tooltip.copy to clipboard":"Copy to Clipboard","tooltip.cut to clipboard":"Cut to Clipboard","tooltip.paste from clipboard":"Paste from Clipboard","tooltip.redo":"Redo","tooltip.toggle virtual keyboard":"Toggle Virtual Keyboard","tooltip.menu":"Menu","tooltip.undo":"Undo","menu.borders":"Borders","menu.insert matrix":"Insert Matrix","menu.array.add row above":"Add Row Before","menu.array.add row below":"Add Row After","menu.array.add column after":"Add Column After","menu.array.add column before":"Add Column Before","menu.array.delete row":"Delete Row","menu.array.delete rows":"Delete Selected Rows","menu.array.delete column":"Delete Column","menu.array.delete columns":"Delete Selected Columns","menu.mode":"Mode","menu.mode-math":"Math","menu.mode-text":"Text","menu.mode-latex":"LaTeX","menu.insert":"Insert","menu.insert.abs":"Absolute Value","menu.insert.abs-template":"\\left|x\\right|","menu.insert.nth-root":"nth Root","menu.insert.nth-root-template":"\\sqrt[n]{x}","menu.insert.log-base":"Logarithm base a","menu.insert.log-base-template":"\\log_a(x)","menu.insert.heading-calculus":"Calculus","menu.insert.derivative":"Derivative","menu.insert.derivative-template":"\\dfrac{\\mathrm{d}}{\\mathrm{d}x}f(x)\\bigm|_{x=a}","menu.insert.nth-derivative":"nth derivative","menu.insert.nth-derivative-template":"\\dfrac{\\mathrm{d}^n}{\\mathrm{d}x^n}f(x)\\bigm|_{x=a}","menu.insert.integral":"Integral","menu.insert.integral-template":"$\\int_a^b f(x)\\,\\mathrm{d}x$","menu.insert.sum":"Sum","menu.insert.sum-template":"$\\sum_{i=1}^n x_i$","menu.insert.product":"Product","menu.insert.product-template":"\\prod_{i=1}^n x_i","menu.insert.heading-complex-numbers":"Complex Numbers","menu.insert.modulus":"Modulus","menu.insert.modulus-template":"\\lvert z \\rvert","menu.insert.argument":"Argument","menu.insert.argument-template":"\\arg(z)","menu.insert.real-part":"Real Part","menu.insert.real-part-template":"\\Re(z)","menu.insert.imaginary-part":"Imaginary Part","menu.insert.imaginary-part-template":"\\Im(z)","menu.insert.conjugate":"Conjugate","menu.insert.conjugate-template":"\\overline{z}","tooltip.blackboard":"Blackboard","tooltip.bold":"Bold","tooltip.italic":"Italic","tooltip.fraktur":"Fraktur","tooltip.script":"Script","tooltip.caligraphic":"Caligraphic","tooltip.typewriter":"Typewriter","tooltip.roman-upright":"Roman Upright","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Font Style","menu.accent":"Accent","menu.decoration":"Decoration","menu.color":"Color","menu.background-color":"Background","menu.cut":"Cut","menu.copy":"Copy","menu.copy-as-latex":"Copy as LaTeX","menu.copy-as-typst":"Copy as Typst","menu.copy-as-ascii-math":"Copy as ASCII Math","menu.copy-as-mathml":"Copy as MathML","menu.paste":"Paste","menu.select-all":"Select All","color.red":"Red","color.orange":"Orange","color.yellow":"Yellow","color.lime":"Lime","color.green":"Green","color.teal":"Teal","color.cyan":"Cyan","color.blue":"Blue","color.indigo":"Indigo","color.purple":"Purple","color.magenta":"Magenta","color.black":"Black","color.dark-grey":"Dark Grey","color.grey":"Grey","color.light-grey":"Light Grey","color.white":"White"},ar:{"keyboard.tooltip.symbols":"\u062D\u0631\u0641 \u0627\u0648 \u0631\u0645\u0632","keyboard.tooltip.greek":"\u062D\u0631\u0648\u0641 \u064A\u0648\u0646\u0627\u0646\u064A\u0629","keyboard.tooltip.numeric":"\u0627\u0644\u0631\u0642\u0645\u064A\u0629","keyboard.tooltip.alphabetic":"\u0631\u0645\u0648\u0632 \u0627\u0644\u0627\u062D\u0631\u0641 \u0627\u0644\u0631\u0648\u0645\u0627\u0646\u064A\u0629","tooltip.copy to clipboard":"\u0646\u0633\u062E \u0625\u0644\u0649 \u0627\u0644\u062D\u0627\u0641\u0638\u0629","tooltip.cut to clipboard":"\u0642\u0635 \u0625\u0644\u0649 \u0627\u0644\u062D\u0627\u0641\u0638\u0629","tooltip.paste from clipboard":"\u0644\u0635\u0642 \u0645\u0646 \u0627\u0644\u062D\u0627\u0641\u0638\u0629","tooltip.redo":"\u0627\u0644\u0625\u0639\u0627\u062F\u0629","tooltip.toggle virtual keyboard":"\u062A\u0628\u062F\u064A\u0644 \u0644\u0648\u062D\u0629 \u0627\u0644\u0645\u0641\u0627\u062A\u064A\u062D \u0627\u0644\u0625\u0641\u062A\u0631\u0627\u0636\u064A\u0629","tooltip.undo":"\u0625\u0644\u063A\u0627\u0621","menu.insert matrix":"\u0623\u062F\u062E\u0644 \u0627\u0644\u0645\u0635\u0641\u0648\u0641\u0629","menu.borders":"\u0645\u062D\u062F\u062F\u0627\u062A \u0627\u0644\u0645\u0635\u0641\u0648\u0641\u0629","menu.array.add row above":"\u0623\u0636\u0641 \u0635\u0641\u064B\u0627 \u0628\u0639\u062F \u0630\u0644\u0643","menu.array.add row below":"\u0623\u0636\u0641 \u0627\u0644\u0635\u0641 \u0642\u0628\u0644","menu.array.add column after":"\u0623\u0636\u0641 \u0627\u0644\u0639\u0645\u0648\u062F \u0628\u0639\u062F \u0630\u0644\u0643","menu.array.add column before":"\u0623\u0636\u0641 \u0627\u0644\u0639\u0645\u0648\u062F \u0642\u0628\u0644","menu.array.delete row":"\u0627\u062D\u0630\u0641 \u0635\u0641","menu.array.delete rows":"\u062D\u0630\u0641 \u0627\u0644\u0635\u0641\u0648\u0641 \u0627\u0644\u0645\u062D\u062F\u062F\u0629","menu.array.delete column":"\u062D\u0630\u0641 \u0627\u0644\u0639\u0645\u0648\u062F","menu.array.delete columns":"\u062D\u0630\u0641 \u0627\u0644\u0623\u0639\u0645\u062F\u0629 \u0627\u0644\u0645\u062D\u062F\u062F\u0629","menu.mode":"\u0648\u0636\u0639","menu.mode-math":"\u0631\u064A\u0627\u0636\u064A\u0627\u062A","menu.mode-text":"\u0646\u0635","menu.mode-latex":"\u0644\u0627\u062A\u0643\u0633","tooltip.blackboard":"\u0633\u0628\u0648\u0631\u0629","tooltip.bold":"\u0639\u0631\u064A\u0636","tooltip.italic":"\u0645\u0627\u0626\u0644","tooltip.fraktur":"\u0641\u0631\u0627\u0643\u062A\u0648\u0631","tooltip.script":"\u0633\u0643\u0631\u064A\u0628\u062A","tooltip.caligraphic":"\u0643\u0627\u0644\u064A\u062C\u0631\u0627\u0641\u064A\u0643","tooltip.typewriter":"\u0622\u0644\u0629 \u0643\u0627\u062A\u0628\u0629","tooltip.roman-upright":"\u0631\u0648\u0645\u0627\u0646\u064A \u0645\u0633\u062A\u0642\u064A\u0645","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u0646\u0645\u0637 \u0627\u0644\u062E\u0637","menu.accent":"\u062A\u0634\u0643\u064A\u0644","menu.decoration":"\u0632\u062E\u0631\u0641\u0629","menu.color":"\u0644\u0648\u0646","menu.background-color":"\u0627\u0644\u062E\u0644\u0641\u064A\u0629","menu.cut":"\u0642\u0635","menu.copy":"\u0646\u0633\u062E","menu.copy-as-latex":"\u0646\u0633\u062E \u0643\u0640 LaTeX","menu.copy-as-ascii-math":"\u0646\u0633\u062E \u0643\u0640 ASCII Math","menu.copy-as-mathml":"\u0646\u0633\u062E \u0643\u0640 MathML","menu.paste":"\u0644\u0635\u0642","menu.select-all":"\u062A\u062D\u062F\u064A\u062F \u0627\u0644\u0643\u0644","color.red":"\u0623\u062D\u0645\u0631","color.orange":"\u0628\u0631\u062A\u0642\u0627\u0644\u064A","color.yellow":"\u0623\u0635\u0641\u0631","color.lime":"\u0644\u064A\u0645\u0648\u0646\u064A","color.green":"\u0623\u062E\u0636\u0631","color.teal":"\u0633\u0645\u0627\u0648\u064A","color.cyan":"\u0633\u0645\u0627\u0648\u064A \u0641\u0627\u062A\u062D","color.blue":"\u0623\u0632\u0631\u0642","color.indigo":"\u0646\u064A\u0644\u064A","color.purple":"\u0628\u0646\u0641\u0633\u062C\u064A","color.magenta":"\u0623\u0631\u062C\u0648\u0627\u0646\u064A","color.black":"\u0623\u0633\u0648\u062F","color.dark-grey":"\u0631\u0645\u0627\u062F\u064A \u063A\u0627\u0645\u0642","color.grey":"\u0631\u0645\u0627\u062F\u064A","color.light-grey":"\u0631\u0645\u0627\u062F\u064A \u0641\u0627\u062A\u062D","color.white":"\u0623\u0628\u064A\u0636"},de:{"keyboard.tooltip.symbols":"Symbole","keyboard.tooltip.greek":"Griechische Buchstaben","keyboard.tooltip.numeric":"Numerisch","keyboard.tooltip.alphabetic":"R\xF6mische Buchstaben","tooltip.copy to clipboard":"In die Zwischenablage kopieren","tooltip.redo":"Wiederholen","tooltip.toggle virtual keyboard":"Virtuelle Tastatur umschalten","tooltip.undo":"Widerrufen","menu.insert matrix":"Matrix einf\xFCgen","menu.borders":"Matrixtrennzeichen","menu.array.add row above":"Zeile hinzuf\xFCgen nach","menu.array.add row below":"Zeile hinzuf\xFCgen vor","menu.array.add column after":"Spalte hinzuf\xFCgen nach","menu.array.add column before":"Spalte hinzuf\xFCgen vor","menu.array.delete row":"Zeile l\xF6schen","menu.array.delete rows":"Ausgew\xE4hlte Zeilen l\xF6schen","menu.array.delete column":"Spalte l\xF6schen","menu.array.delete columns":"Ausgew\xE4hlte Spalten l\xF6schen","menu.mode":"Modus","menu.mode-math":"Mathematik","menu.mode-text":"Text","menu.mode-latex":"LaTeX","tooltip.blackboard":"Tafel","tooltip.bold":"Fett","tooltip.italic":"Kursiv","tooltip.fraktur":"Fraktur","tooltip.script":"Skript","tooltip.caligraphic":"Kalligraphie","tooltip.typewriter":"Schreibmaschine","tooltip.roman-upright":"R\xF6misch aufrecht","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Schriftstil","menu.accent":"Akzent","menu.decoration":"Dekoration","menu.color":"Farbe","menu.background-color":"Hintergrund","menu.cut":"Ausschneiden","menu.copy":"Kopieren","menu.copy-as-latex":"Als LaTeX kopieren","menu.copy-as-ascii-math":"Als ASCII Math kopieren","menu.copy-as-mathml":"Als MathML kopieren","menu.paste":"Einf\xFCgen","menu.select-all":"Alles ausw\xE4hlen","color.red":"Rot","color.orange":"Orange","color.yellow":"Gelb","color.lime":"Limette","color.green":"Gr\xFCn","color.teal":"Blaugr\xFCn","color.cyan":"Cyan","color.blue":"Blau","color.indigo":"Indigo","color.purple":"Lila","color.magenta":"Magenta","color.black":"Schwarz","color.dark-grey":"Dunkelgrau","color.grey":"Grau","color.light-grey":"Hellgrau","color.white":"Wei\xDF"},el:{"keyboard.tooltip.symbols":"\u03C3\u03CD\u03BC\u03B2\u03BF\u03BB\u03B1","keyboard.tooltip.greek":"\u03B5\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC \u03B3\u03C1\u03AC\u03BC\u03BC\u03B1\u03C4\u03B1","keyboard.tooltip.numeric":"\u0391\u03C1\u03B9\u03B8\u03BC\u03B7\u03C4\u03B9\u03BA\u03CC\u03C2","keyboard.tooltip.alphabetic":"\u03A1\u03C9\u03BC\u03B1\u03CA\u03BA\u03AC \u03B3\u03C1\u03AC\u03BC\u03BC\u03B1\u03C4\u03B1","tooltip.copy to clipboard":"\u0391\u03BD\u03C4\u03B9\u03B3\u03C1\u03B1\u03C6\u03AE \u03C3\u03C4\u03BF \u03C0\u03C1\u03CC\u03C7\u03B5\u03B9\u03C1\u03BF","tooltip.redo":"\u039E\u03B1\u03BD\u03B1\u03BA\u03AC\u03BD\u03C9","tooltip.toggle virtual keyboard":"\u0395\u03BD\u03B1\u03BB\u03BB\u03B1\u03B3\u03AE \u03B5\u03B9\u03BA\u03BF\u03BD\u03B9\u03BA\u03BF\u03CD \u03C0\u03BB\u03B7\u03BA\u03C4\u03C1\u03BF\u03BB\u03BF\u03B3\u03AF\u03BF\u03C5","tooltip.undo":"\u039E\u03B5\u03BA\u03AC\u03BD\u03C9","menu.insert matrix":"\u0395\u03B9\u03C3\u03B1\u03B3\u03C9\u03B3\u03AE \u03BC\u03AE\u03C4\u03C1\u03B1","menu.borders":"\u039F\u03C1\u03B9\u03BF\u03B8\u03AD\u03C4\u03B5\u03C2 \u03BC\u03AE\u03C4\u03C1\u03B1","menu.array.add row above":"\u03A0\u03C1\u03BF\u03C3\u03B8\u03AE\u03BA\u03B7 \u03C3\u03B5\u03B9\u03C1\u03AC\u03C2 \u03BC\u03B5\u03C4\u03AC","menu.array.add row below":"\u03A0\u03C1\u03BF\u03C3\u03B8\u03AE\u03BA\u03B7 \u03C3\u03B5\u03B9\u03C1\u03AC\u03C2 \u03C0\u03C1\u03B9\u03BD","menu.array.add column after":"\u03A0\u03C1\u03BF\u03C3\u03B8\u03AE\u03BA\u03B7 \u03C3\u03C4\u03AE\u03BB\u03B7\u03C2 \u03BC\u03B5\u03C4\u03AC","menu.array.add column before":"\u03A0\u03C1\u03BF\u03C3\u03B8\u03AE\u03BA\u03B7 \u03C3\u03C4\u03AE\u03BB\u03B7\u03C2 \u03C0\u03C1\u03B9\u03BD","menu.array.delete row":"\u0394\u03B9\u03B1\u03B3\u03C1\u03B1\u03C6\u03AE \u03C3\u03B5\u03B9\u03C1\u03AC\u03C2","menu.array.delete rows":"\u0394\u03B9\u03B1\u03B3\u03C1\u03B1\u03C6\u03AE \u03B5\u03C0\u03B9\u03BB\u03B5\u03B3\u03BC\u03AD\u03BD\u03C9\u03BD \u03C3\u03B5\u03B9\u03C1\u03CE\u03BD","menu.array.delete column":"\u0394\u03B9\u03B1\u03B3\u03C1\u03B1\u03C6\u03AE \u03C3\u03C4\u03AE\u03BB\u03B7\u03C2","menu.array.delete columns":"\u0394\u03B9\u03B1\u03B3\u03C1\u03B1\u03C6\u03AE \u03B5\u03C0\u03B9\u03BB\u03B5\u03B3\u03BC\u03AD\u03BD\u03C9\u03BD \u03C3\u03C4\u03B7\u03BB\u03CE\u03BD","menu.mode":"\u039B\u03B5\u03B9\u03C4\u03BF\u03C5\u03C1\u03B3\u03AF\u03B1","menu.mode-math":"\u039C\u03B1\u03B8\u03B7\u03BC\u03B1\u03C4\u03B9\u03BA\u03AC","menu.mode-text":"\u039A\u03B5\u03AF\u03BC\u03B5\u03BD\u03BF","menu.mode-latex":"LaTeX","tooltip.blackboard":"\u03A0\u03AF\u03BD\u03B1\u03BA\u03B1\u03C2","tooltip.bold":"\u0388\u03BD\u03C4\u03BF\u03BD\u03B7","tooltip.italic":"\u03A0\u03BB\u03AC\u03B3\u03B9\u03B1","tooltip.fraktur":"\u03A6\u03C1\u03AC\u03BA\u03C4\u03BF\u03C5\u03C1","tooltip.script":"\u03A3\u03B5\u03BD\u03AC\u03C1\u03B9\u03BF","tooltip.caligraphic":"\u039A\u03B1\u03BB\u03BB\u03B9\u03B3\u03C1\u03B1\u03C6\u03B9\u03BA\u03AE","tooltip.typewriter":"\u039C\u03B7\u03C7\u03B1\u03BD\u03AE \u03B3\u03C1\u03B1\u03C6\u03AE\u03C2","tooltip.roman-upright":"\u03A1\u03C9\u03BC\u03B1\u03CA\u03BA\u03CC \u039A\u03B1\u03C4\u03B1\u03BA\u03CC\u03C1\u03C5\u03C6\u03BF","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u03A3\u03C4\u03C5\u03BB \u03B3\u03C1\u03B1\u03BC\u03BC\u03B1\u03C4\u03BF\u03C3\u03B5\u03B9\u03C1\u03AC\u03C2","menu.accent":"\u03A4\u03CC\u03BD\u03BF\u03C2","menu.decoration":"\u0394\u03B9\u03B1\u03BA\u03CC\u03C3\u03BC\u03B7\u03C3\u03B7","menu.color":"\u03A7\u03C1\u03CE\u03BC\u03B1","menu.background-color":"\u03A7\u03C1\u03CE\u03BC\u03B1 \u03C6\u03CC\u03BD\u03C4\u03BF\u03C5","menu.cut":"\u0391\u03C0\u03BF\u03BA\u03BF\u03C0\u03AE","menu.copy":"\u0391\u03BD\u03C4\u03B9\u03B3\u03C1\u03B1\u03C6\u03AE","menu.copy-as-latex":"\u0391\u03BD\u03C4\u03B9\u03B3\u03C1\u03B1\u03C6\u03AE \u03C9\u03C2 LaTeX","menu.copy-as-ascii-math":"\u0391\u03BD\u03C4\u03B9\u03B3\u03C1\u03B1\u03C6\u03AE \u03C9\u03C2 ASCII Math","menu.copy-as-mathml":"\u0391\u03BD\u03C4\u03B9\u03B3\u03C1\u03B1\u03C6\u03AE \u03C9\u03C2 MathML","menu.paste":"\u0395\u03C0\u03B9\u03BA\u03CC\u03BB\u03BB\u03B7\u03C3\u03B7","menu.select-all":"\u0395\u03C0\u03B9\u03BB\u03BF\u03B3\u03AE \u03CC\u03BB\u03C9\u03BD","color.red":"\u039A\u03CC\u03BA\u03BA\u03B9\u03BD\u03BF","color.orange":"\u03A0\u03BF\u03C1\u03C4\u03BF\u03BA\u03B1\u03BB\u03AF","color.yellow":"\u039A\u03AF\u03C4\u03C1\u03B9\u03BD\u03BF","color.lime":"\u039B\u03B1\u03C7\u03B1\u03BD\u03AF","color.green":"\u03A0\u03C1\u03AC\u03C3\u03B9\u03BD\u03BF","color.teal":"\u039A\u03C5\u03B1\u03BD\u03CC","color.cyan":"\u0393\u03B1\u03BB\u03AC\u03B6\u03B9\u03BF","color.blue":"\u039C\u03C0\u03BB\u03B5","color.indigo":"\u0399\u03BD\u03B4\u03B9\u03BA\u03CC","color.purple":"\u039C\u03C9\u03B2","color.magenta":"\u039C\u03B1\u03C4\u03B6\u03AD\u03BD\u03C4\u03B1","color.black":"\u039C\u03B1\u03CD\u03C1\u03BF","color.dark-grey":"\u03A3\u03BA\u03BF\u03CD\u03C1\u03BF \u0393\u03BA\u03C1\u03B9","color.grey":"\u0393\u03BA\u03C1\u03B9","color.light-grey":"\u0391\u03BD\u03BF\u03B9\u03C7\u03C4\u03CC \u0393\u03BA\u03C1\u03B9","color.white":"\u039B\u03B5\u03C5\u03BA\u03CC"},es:{"keyboard.tooltip.symbols":"S\xEDmbolos","keyboard.tooltip.greek":"Letras griegas","keyboard.tooltip.numeric":"Num\xE9rico","keyboard.tooltip.alphabetic":"Letras romanas","tooltip.copy to clipboard":"Copiar al portapapeles","tooltip.redo":"Rehacer","tooltip.toggle virtual keyboard":"Alternar teclado virtual","tooltip.undo":"Deshacer","menu.insert matrix":"A\xF1adir Matriz","menu.borders":"Delimitadores de Matriz","menu.array.add row above":"A\xF1adir L\xEDnea Antes","menu.array.add row below":"A\xF1adir L\xEDnea Despues","menu.array.add column after":"A\xF1adir Columna Despues","menu.array.add column before":"A\xF1adir Columna Antes","menu.array.delete row":"Borrar L\xEDnea","menu.array.delete rows":"Borrar L\xEDneas Seleccionadas","menu.array.delete column":"Borrar Columna","menu.array.delete columns":"Borrar Columnas Seleccionadas","menu.mode":"Modo","menu.mode-math":"Matem\xE1ticas","menu.mode-text":"Texto","menu.mode-latex":"LaTeX","tooltip.blackboard":"Pizarra","tooltip.bold":"Negrita","tooltip.italic":"Cursiva","tooltip.fraktur":"Fraktur","tooltip.script":"Script","tooltip.caligraphic":"Caligr\xE1fico","tooltip.typewriter":"M\xE1quina de escribir","tooltip.roman-upright":"Romano Vertical","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Estilo de fuente","menu.accent":"Acento","menu.decoration":"Decoraci\xF3n","menu.color":"Color","menu.background-color":"Fondo","menu.cut":"Cortar","menu.copy":"Copiar","menu.copy-as-latex":"Copiar como LaTeX","menu.copy-as-ascii-math":"Copiar como ASCII Math","menu.copy-as-mathml":"Copiar como MathML","menu.paste":"Pegar","menu.select-all":"Seleccionar todo","color.red":"Rojo","color.orange":"Naranja","color.yellow":"Amarillo","color.lime":"Lima","color.green":"Verde","color.teal":"Verde azulado","color.cyan":"Cian","color.blue":"Azul","color.indigo":"\xCDndigo","color.purple":"Morado","color.magenta":"Magenta","color.black":"Negro","color.dark-grey":"Gris oscuro","color.grey":"Gris","color.light-grey":"Gris claro","color.white":"Blanco"},fr:{"keyboard.tooltip.symbols":"Symboles","keyboard.tooltip.greek":"Lettres grecques","keyboard.tooltip.numeric":"Num\xE9rique","keyboard.tooltip.alphabetic":"Lettres romaines","tooltip.menu":"Menu","tooltip.copy to clipboard":"Copier dans le presse-papiers","tooltip.redo":"R\xE9tablir","tooltip.toggle virtual keyboard":"Afficher/Masquer le clavier virtuel","tooltip.undo":"Annuler","menu.insert matrix":"Ins\xE9rer une Matrice","menu.borders":"Bords","menu.array.add row above":"Ajouter une Ligne Avant","menu.array.add row below":"Ajouter une Ligne Apr\xE8s","menu.array.add column before":"Ajouter une Colonne Avant","menu.array.add column after":"Ajouter une Colonne Apr\xE8s","menu.array.delete row":"Enlever une Ligne","menu.array.delete rows":"Enlever les Lignes S\xE9lection\xE9es","menu.array.delete column":"Enlever une Colone","menu.array.delete columns":"Enlever les Colonnes S\xE9lection\xE9es","menu.mode":"Mode","menu.mode-math":"Math","menu.mode-text":"Text","menu.mode-latex":"LaTeX","tooltip.blackboard":"Tableau noir","tooltip.bold":"Gras","tooltip.italic":"Italique","tooltip.fraktur":"Fraktur","tooltip.script":"Script","tooltip.caligraphic":"Calligraphique","tooltip.typewriter":"Machine \xE0 \xE9crire","tooltip.roman-upright":"Romain droit","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Style de police","menu.accent":"Accent","menu.decoration":"D\xE9coration","menu.color":"Couleur","menu.background-color":"Arri\xE8re-plan","menu.cut":"Couper","menu.copy":"Copier","menu.copy-as-latex":"Copier en LaTeX","menu.copy-as-ascii-math":"Copier en ASCII Math","menu.copy-as-mathml":"Copier en MathML","menu.paste":"Coller","menu.select-all":"S\xE9lectionner tout","color.red":"Rouge","color.orange":"Orange","color.yellow":"Jaune","color.lime":"Citron vert","color.green":"Vert","color.teal":"Turquoise","color.cyan":"Cyan","color.blue":"Bleu","color.indigo":"Indigo","color.purple":"Violet","color.magenta":"Magenta","color.black":"Noir","color.dark-grey":"Gris fonc\xE9","color.grey":"Gris","color.light-grey":"Gris clair","color.white":"Blanc"},he:{"keyboard.tooltip.symbols":"\u05E1\u05DE\u05DC\u05D9\u05DD","keyboard.tooltip.greek":"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA \u05D9\u05D5\u05D5\u05E0\u05D9\u05D5\u05EA","keyboard.tooltip.numeric":"\u05DE\u05E1\u05E4\u05E8\u05D9","keyboard.tooltip.alphabetic":"\u05DE\u05DB\u05EA\u05D1\u05D9\u05DD \u05E8\u05D5\u05DE\u05D9\u05D9\u05DD","tooltip.copy to clipboard":"\u05D4\u05E2\u05EA\u05E7 \u05DC\u05DC\u05D5\u05D7","tooltip.redo":"\u05DC\u05B7\u05E2\u05B2\u05E9\u05C2\u05D5\u05B9\u05EA \u05E9\u05C1\u05D5\u05BC\u05D1","tooltip.toggle virtual keyboard":"\u05D4\u05D7\u05DC\u05E3 \u05D0\u05EA \u05D4\u05DE\u05E7\u05DC\u05D3\u05EA \u05D4\u05D5\u05D5\u05D9\u05E8\u05D8\u05D5\u05D0\u05DC\u05D9\u05EA","tooltip.undo":"\u05DC\u05D1\u05D8\u05DC","menu.insert matrix":"\u05D4\u05DB\u05E0\u05E1 \u05DE\u05D8\u05E8\u05D9\u05E7\u05E1","menu.borders":"\u05DE\u05E4\u05E8\u05D9\u05D3\u05D9 \u05DE\u05D8\u05E8\u05D9\u05E7\u05E1","menu.array.add row above":"\u05D4\u05D5\u05E1\u05E3 \u05E9\u05D5\u05E8\u05D4 \u05D0\u05D7\u05E8\u05D9","menu.array.add row below":"\u05D4\u05D5\u05E1\u05E3 \u05E9\u05D5\u05E8\u05D4 \u05DC\u05E4\u05E0\u05D9","menu.array.add column after":"\u05D4\u05D5\u05E1\u05E3 \u05E2\u05DE\u05D5\u05D3\u05D4 \u05D0\u05D7\u05E8\u05D9","menu.array.add column before":"\u05D4\u05D5\u05E1\u05E3 \u05E2\u05DE\u05D5\u05D3\u05D4 \u05DC\u05E4\u05E0\u05D9","menu.array.delete row":"\u05DE\u05D7\u05E7 \u05E9\u05D5\u05E8\u05D4","menu.array.delete rows":"\u05DE\u05D7\u05E7 \u05E9\u05D5\u05E8\u05D5\u05EA \u05E9\u05E0\u05D1\u05D7\u05E8\u05D5","menu.array.delete column":"\u05DE\u05D7\u05E7 \u05E2\u05DE\u05D5\u05D3\u05D4","menu.array.delete columns":"\u05DE\u05D7\u05E7 \u05E2\u05DE\u05D5\u05D3\u05D5\u05EA \u05E9\u05E0\u05D1\u05D7\u05E8\u05D5","menu.mode":"\u05DE\u05E6\u05D1","menu.mode-math":"\u05DE\u05EA\u05DE\u05D8\u05D9\u05E7\u05D4","menu.mode-text":"\u05D8\u05E7\u05E1\u05D8","menu.mode-latex":"LaTeX","tooltip.blackboard":"\u05DC\u05D5\u05D7 \u05E9\u05D7\u05D5\u05E8","tooltip.bold":"\u05DE\u05D5\u05D3\u05D2\u05E9","tooltip.italic":"\u05E0\u05D8\u05D5\u05D9","tooltip.fraktur":"\u05E4\u05E8\u05E7\u05D8\u05D5\u05E8","tooltip.script":"\u05DB\u05EA\u05D1","tooltip.caligraphic":"\u05E7\u05DC\u05D9\u05D2\u05E8\u05E4\u05D9","tooltip.typewriter":"\u05DE\u05DB\u05D5\u05E0\u05EA \u05DB\u05EA\u05D9\u05D1\u05D4","tooltip.roman-upright":"\u05E8\u05D5\u05DE\u05D9 \u05D9\u05E9\u05E8","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u05E1\u05D2\u05E0\u05D5\u05DF \u05D2\u05D5\u05E4\u05DF","menu.accent":"\u05E6\u05DC\u05D9\u05DC","menu.decoration":"\u05E7\u05D9\u05E9\u05D5\u05D8","menu.color":"\u05E6\u05D1\u05E2","menu.background-color":"\u05E8\u05E7\u05E2","menu.cut":"\u05D2\u05D6\u05D5\u05E8","menu.copy":"\u05D4\u05E2\u05EA\u05E7","menu.copy-as-latex":"\u05D4\u05E2\u05EA\u05E7 \u05DB\u05BELaTeX","menu.copy-as-ascii-math":"\u05D4\u05E2\u05EA\u05E7 \u05DB\u05BEASCII Math","menu.copy-as-mathml":"\u05D4\u05E2\u05EA\u05E7 \u05DB\u05BEMathML","menu.paste":"\u05D4\u05D3\u05D1\u05E7","menu.select-all":"\u05D1\u05D7\u05E8 \u05D4\u05DB\u05DC","color.red":"\u05D0\u05D3\u05D5\u05DD","color.orange":"\u05DB\u05EA\u05D5\u05DD","color.yellow":"\u05E6\u05D4\u05D5\u05D1","color.lime":"\u05D9\u05E8\u05D5\u05E7 \u05DC\u05D9\u05D9\u05DD","color.green":"\u05D9\u05E8\u05D5\u05E7","color.teal":"\u05D8\u05D9\u05DC","color.cyan":"\u05E6\u05D9\u05D0\u05DF","color.blue":"\u05DB\u05D7\u05D5\u05DC","color.indigo":"\u05D0\u05D9\u05E0\u05D3\u05D9\u05D2\u05D5","color.purple":"\u05E1\u05D2\u05D5\u05DC","color.magenta":"\u05DE\u05D2\u05E0\u05D8\u05D4","color.black":"\u05E9\u05D7\u05D5\u05E8","color.dark-grey":"\u05D0\u05E4\u05D5\u05E8 \u05DB\u05D4\u05D4","color.grey":"\u05D0\u05E4\u05D5\u05E8","color.light-grey":"\u05D0\u05E4\u05D5\u05E8 \u05D1\u05D4\u05D9\u05E8","color.white":"\u05DC\u05D1\u05DF"},it:{"keyboard.tooltip.symbols":"Simboli","keyboard.tooltip.greek":"Lettere greche","keyboard.tooltip.numeric":"Numerico","keyboard.tooltip.alphabetic":"Lettere romane","tooltip.copy to clipboard":"Copia negli appunti","tooltip.cut to clipboard":"Taglia negli appunti","tooltip.paste from clipboard":"Incolla dagli appunti","tooltip.redo":"Ripeti","tooltip.toggle virtual keyboard":"Attiva/disattiva tastiera virtuale","tooltip.menu":"Menu","tooltip.undo":"Annulla","menu.borders":"Delimitatori","menu.insert matrix":"Inserisci matrice","menu.array.add row above":"Aggiungi riga sopra","menu.array.add row below":"Aggiungi riga sotto","menu.array.add column after":"Aggiungi colonna dopo","menu.array.add column before":"Aggiungi colonna prima","menu.array.delete row":"Elimina riga","menu.array.delete rows":"Elimina righe selezionate","menu.array.delete column":"Elimina colonna","menu.array.delete columns":"Elimina colonne selezionate","menu.mode":"Modalit\xE0","menu.mode-math":"Matematica","menu.mode-text":"Testo","menu.mode-latex":"LaTeX","menu.insert":"Inserisci","menu.insert.abs":"Valore assoluto","menu.insert.abs-template":"\\left|x\\right|","menu.insert.nth-root":"Radice n-esima","menu.insert.nth-root-template":"\\sqrt[n]{x}","menu.insert.log-base":"Logaritmo in base a","menu.insert.log-base-template":"\\log_a(x)","menu.insert.heading-calculus":"Calcolo","menu.insert.derivative":"Derivata","menu.insert.derivative-template":"\\dfrac{\\mathrm{d}}{\\mathrm{d}x}f(x)\\bigm|_{x=a}","menu.insert.nth-derivative":"Derivata n-esima","menu.insert.nth-derivative-template":"\\dfrac{\\mathrm{d}^n}{\\mathrm{d}x^n}f(x)\\bigm|_{x=a}","menu.insert.integral":"Integrale","menu.insert.integral-template":"$\\int_a^b f(x)\\,\\mathrm{d}x$","menu.insert.sum":"Somma","menu.insert.sum-template":"$\\sum_{i=1}^n x_i$","menu.insert.product":"Prodotto","menu.insert.product-template":"\\prod_{i=1}^n x_i","menu.insert.heading-complex-numbers":"Numeri complessi","menu.insert.modulus":"Modulo","menu.insert.modulus-template":"\\lvert z \\rvert","menu.insert.argument":"Argomento","menu.insert.argument-template":"\\arg(z)","menu.insert.real-part":"Parte reale","menu.insert.real-part-template":"\\Re(z)","menu.insert.imaginary-part":"Parte immaginaria","menu.insert.imaginary-part-template":"\\Im(z)","menu.insert.conjugate":"Coniugato","menu.insert.conjugate-template":"\\overline{z}","tooltip.blackboard":"Lavagna","tooltip.bold":"Grassetto","tooltip.italic":"Corsivo","tooltip.fraktur":"Fraktur","tooltip.script":"Script","tooltip.caligraphic":"Calligrafico","tooltip.typewriter":"Macchina da scrivere","tooltip.roman-upright":"Romano diritto","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Stile carattere","menu.accent":"Accento","menu.decoration":"Decorazione","menu.color":"Colore","menu.background-color":"Sfondo","menu.cut":"Taglia","menu.copy":"Copia","menu.copy-as-latex":"Copia come LaTeX","menu.copy-as-ascii-math":"Copia come ASCII Math","menu.copy-as-mathml":"Copia come MathML","menu.paste":"Incolla","menu.select-all":"Seleziona tutto","color.red":"Rosso","color.orange":"Arancione","color.yellow":"Giallo","color.lime":"Lime","color.green":"Verde","color.teal":"Verde acqua","color.cyan":"Ciano","color.blue":"Blu","color.indigo":"Indaco","color.purple":"Viola","color.magenta":"Magenta","color.black":"Nero","color.dark-grey":"Grigio scuro","color.grey":"Grigio","color.light-grey":"Grigio chiaro","color.white":"Bianco"},ja:{"keyboard.tooltip.symbols":"\u8A18\u53F7","keyboard.tooltip.greek":"\u30AE\u30EA\u30B7\u30A2\u6587\u5B57","keyboard.tooltip.numeric":"\u6570\u5024","keyboard.tooltip.alphabetic":"\u30ED\u30FC\u30DE\u5B57","tooltip.copy to clipboard":"\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u30B3\u30D4\u30FC","tooltip.cut to clipboard":"\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u306B\u5207\u308A\u53D6\u308A","tooltip.paste from clipboard":"\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u304B\u3089\u8CBC\u308A\u4ED8\u3051","tooltip.redo":"\u3084\u308A\u76F4\u3057","tooltip.toggle virtual keyboard":"\u4EEE\u60F3\u30AD\u30FC\u30DC\u30FC\u30C9\u306E\u5207\u308A\u66FF\u3048","tooltip.menu":"\u30E1\u30CB\u30E5\u30FC","tooltip.undo":"\u5143\u306B\u623B\u3059","menu.borders":"\u884C\u5217\u306E\u533A\u5207\u308A\u6587\u5B57","menu.insert matrix":"\u884C\u5217\u3092\u633F\u5165","menu.array.add row above":"\u5F8C\u306B\u884C\u3092\u8FFD\u52A0","menu.array.add row below":"\u524D\u306B\u884C\u3092\u8FFD\u52A0","menu.array.add column after":"\u5F8C\u306B\u5217\u3092\u8FFD\u52A0","menu.array.add column before":"\u524D\u306B\u5217\u3092\u8FFD\u52A0","menu.array.delete row":"\u884C\u3092\u524A\u9664","menu.array.delete rows":"\u9078\u629E\u3057\u305F\u884C\u3092\u524A\u9664","menu.array.delete column":"\u5217\u3092\u524A\u9664","menu.array.delete columns":"\u9078\u629E\u3057\u305F\u5217\u3092\u524A\u9664","menu.mode":"\u30E2\u30FC\u30C9","menu.mode-math":"\u6570\u5F0F","menu.mode-text":"\u30C6\u30AD\u30B9\u30C8","menu.mode-latex":"LaTeX","menu.insert":"\u633F\u5165","menu.insert.abs":"\u7D76\u5BFE\u5024","menu.insert.nth-root":"n \u4E57\u6839","menu.insert.log-base":"\u5E95\u304C a \u306E\u5BFE\u6570","menu.insert.heading-calculus":"\u5FAE\u7A4D\u5206","menu.insert.derivative":"\u5C0E\u95A2\u6570","menu.insert.nth-derivative":"n \u968E\u5C0E\u95A2\u6570","menu.insert.integral":"\u7A4D\u5206","menu.insert.sum":"\u7DCF\u548C","menu.insert.product":"\u7DCF\u7A4D","menu.insert.heading-complex-numbers":"\u8907\u7D20\u6570","menu.insert.modulus":"\u7D76\u5BFE\u5024","menu.insert.argument":"\u504F\u89D2","menu.insert.real-part":"\u5B9F\u90E8","menu.insert.imaginary-part":"\u865A\u90E8","menu.insert.conjugate":"\u5171\u5F79\u8907\u7D20\u6570","tooltip.blackboard":"\u9ED2\u677F","tooltip.bold":"\u592A\u5B57","tooltip.italic":"\u30A4\u30BF\u30EA\u30C3\u30AF\u4F53","tooltip.fraktur":"\u30D5\u30E9\u30AF\u30C8\u30A5\u30FC\u30EB","tooltip.script":"\u30B9\u30AF\u30EA\u30D7\u30C8","tooltip.caligraphic":"\u30AB\u30EA\u30B0\u30E9\u30D5\u30A3\u30C3\u30AF","tooltip.typewriter":"\u30BF\u30A4\u30D7\u30E9\u30A4\u30BF\u30FC","tooltip.roman-upright":"\u30ED\u30FC\u30DE\u76F4\u7ACB","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u30D5\u30A9\u30F3\u30C8\u30B9\u30BF\u30A4\u30EB","menu.accent":"\u30A2\u30AF\u30BB\u30F3\u30C8","menu.decoration":"\u88C5\u98FE","menu.color":"\u8272","menu.background-color":"\u80CC\u666F","menu.cut":"\u5207\u308A\u53D6\u308A","menu.copy":"\u30B3\u30D4\u30FC","menu.copy-as-latex":"LaTeX \u3068\u3057\u3066\u30B3\u30D4\u30FC","menu.copy-as-typst":"Typst \u3068\u3057\u3066\u30B3\u30D4\u30FC","menu.copy-as-ascii-math":"ASCII Math \u3068\u3057\u3066\u30B3\u30D4\u30FC","menu.copy-as-mathml":"MathML \u3068\u3057\u3066\u30B3\u30D4\u30FC","menu.paste":"\u8CBC\u308A\u4ED8\u3051","menu.select-all":"\u3059\u3079\u3066\u9078\u629E","color.red":"\u8D64","color.orange":"\u30AA\u30EC\u30F3\u30B8","color.yellow":"\u9EC4\u8272","color.lime":"\u30E9\u30A4\u30E0","color.green":"\u7DD1","color.teal":"\u30C6\u30A3\u30FC\u30EB","color.cyan":"\u30B7\u30A2\u30F3","color.blue":"\u9752","color.indigo":"\u30A4\u30F3\u30C7\u30A3\u30B4","color.purple":"\u7D2B","color.magenta":"\u30DE\u30BC\u30F3\u30BF","color.black":"\u9ED2","color.dark-grey":"\u6FC3\u3044\u30B0\u30EC\u30FC","color.grey":"\u30B0\u30EC\u30FC","color.light-grey":"\u8584\u3044\u30B0\u30EC\u30FC","color.white":"\u767D"},ko:{"keyboard.tooltip.symbols":"\uAE30\uD638","keyboard.tooltip.greek":"\uADF8\uB9AC\uC2A4 \uBB38\uC790","keyboard.tooltip.numeric":"\uC22B\uC790","keyboard.tooltip.alphabetic":"\uB85C\uB9C8 \uBB38\uC790","tooltip.copy to clipboard":"\uD074\uB9BD \uBCF4\uB4DC\uC5D0 \uBCF5\uC0AC","tooltip.redo":"\uB2E4\uC2DC \uC2E4\uD589","tooltip.toggle virtual keyboard":"\uAC00\uC0C1 \uD0A4\uBCF4\uB4DC \uC804\uD658","tooltip.undo":"\uC2E4\uD589 \uCDE8\uC18C","menu.insert matrix":"\uD589\uB82C \uC0BD\uC785","menu.borders":"\uD589\uB82C \uAD6C\uBD84 \uAE30\uD638","menu.array.add row above":"\uB4A4\uC5D0 \uD589 \uCD94\uAC00","menu.array.add row below":"\uC55E\uC5D0 \uD589 \uCD94\uAC00","menu.array.add column after":"\uB4A4\uC5D0 \uC5F4 \uCD94\uAC00","menu.array.add column before":"\uC55E\uC5D0 \uC5F4 \uCD94\uAC00","menu.array.delete row":"\uD589 \uC0AD\uC81C","menu.array.delete rows":"\uC120\uD0DD\uD55C \uD589 \uC0AD\uC81C","menu.array.delete column":"\uC5F4 \uC0AD\uC81C","menu.array.delete columns":"\uC120\uD0DD\uD55C \uC5F4 \uC0AD\uC81C","menu.mode":"\uBAA8\uB4DC","menu.mode-math":"\uC218\uC2DD","menu.mode-text":"\uD14D\uC2A4\uD2B8","menu.mode-latex":"LaTeX","tooltip.blackboard":"\uCE60\uD310","tooltip.bold":"\uAD75\uAC8C","tooltip.italic":"\uC774\uD0E4\uB9AD","tooltip.fraktur":"\uD504\uB799\uD22C\uC5B4","tooltip.script":"\uCCA8\uC790","tooltip.caligraphic":"\uD544\uAE30\uCCB4","tooltip.typewriter":"\uD0C0\uC790\uAE30","tooltip.roman-upright":"\uC77C\uBC18 \uB85C\uB9C8\uC790","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\uAE00\uAF34 \uC2A4\uD0C0\uC77C","menu.accent":"\uBC1C\uC74C \uAE30\uD638","menu.decoration":"\uC7A5\uC2DD","menu.color":"\uC0C9\uC0C1","menu.background-color":"\uBC30\uACBD","menu.cut":"\uC798\uB77C\uB0B4\uAE30","menu.copy":"\uBCF5\uC0AC","menu.copy-as-latex":"LaTeX\uB85C \uBCF5\uC0AC","menu.copy-as-ascii-math":"ASCIIMath\uB85C \uBCF5\uC0AC","menu.copy-as-mathml":"MathML\uB85C \uBCF5\uC0AC","menu.paste":"\uBD99\uC5EC\uB123\uAE30","menu.select-all":"\uBAA8\uB450 \uC120\uD0DD","color.red":"\uBE68\uAC15","color.orange":"\uC8FC\uD669","color.yellow":"\uB178\uB791","color.lime":"\uB77C\uC784","color.green":"\uCD08\uB85D","color.teal":"\uCCAD\uB85D","color.cyan":"\uCCAD\uC0C9","color.blue":"\uD30C\uB791","color.indigo":"\uB0A8\uC0C9","color.purple":"\uBCF4\uB77C","color.magenta":"\uC790\uD64D","color.black":"\uAC80\uC815","color.dark-grey":"\uC9C4\uD55C \uD68C\uC0C9","color.grey":"\uD68C\uC0C9","color.light-grey":"\uC5F0\uD55C \uD68C\uC0C9","color.white":"\uD770\uC0C9"},pl:{"keyboard.tooltip.symbols":"Symbolika","keyboard.tooltip.greek":"Litery greckie","keyboard.tooltip.numeric":"Numeryczne","keyboard.tooltip.alphabetic":"Litery rzymskie","tooltip.copy to clipboard":"Kopiuj do Schowka","tooltip.cut to clipboard":"Wytnij ze Schowka","tooltip.paste from clipboard":"Wklej ze Schowka","tooltip.redo":"Przywr\xF3\u0107","tooltip.toggle virtual keyboard":"Prze\u0142\u0105cz klawiatur\u0119 wirtualn\u0105","tooltip.menu":"Menu","tooltip.undo":"Cofnij","menu.borders":"Ograniczniki macierzy","menu.insert matrix":"Wstaw macierz","menu.array.add row above":"Dodaj wiersz przed","menu.array.add row below":"Dodaj wiersz po","menu.array.add column after":"Dodaj kolumn\u0119 po","menu.array.add column before":"Dodaj kolumn\u0119 przed","menu.array.delete row":"Usu\u0144 wiersz","menu.array.delete rows":"Usu\u0144 wybrane wiersze","menu.array.delete column":"Usu\u0144 kolumn\u0119","menu.array.delete columns":"Usu\u0144 wybrane kolumny","menu.mode":"Tryb","menu.mode-math":"Formu\u0142a","menu.mode-text":"Tekst","menu.mode-latex":"LaTeX","menu.insert":"Wstaw","menu.insert.abs":"Warto\u015B\u0107 bezwzgl\u0119dna","menu.insert.abs-template":"\\left|x\\right|","menu.insert.nth-root":"Pierwiastek n-tego stopnia","menu.insert.nth-root-template":"\\sqrt[n]{x}","menu.insert.log-base":"Logarytm o podstawie a","menu.insert.log-base-template":"\\log_a(x)","menu.insert.heading-calculus":"Rachunek r\xF3\u017Cniczkowy i ca\u0142kowy","menu.insert.derivative":"Pochodna","menu.insert.derivative-template":"\\dfrac{\\mathrm{d}}{\\mathrm{d}x}f(x)\\bigm|_{x=a}","menu.insert.nth-derivative":"Pochodna n-tego rz\u0119du","menu.insert.nth-derivative-template":"\\dfrac{\\mathrm{d}^n}{\\mathrm{d}x^n}f(x)\\bigm|_{x=a}","menu.insert.integral":"Ca\u0142ka","menu.insert.integral-template":"$\\int_a^b f(x)\\,\\mathrm{d}x$","menu.insert.sum":"Suma","menu.insert.sum-template":"$\\sum_{i=1}^n x_i$","menu.insert.product":"Iloczyn","menu.insert.product-template":"\\prod_{i=1}^n x_i","menu.insert.heading-complex-numbers":"Liczby zespolone","menu.insert.modulus":"Modu\u0142","menu.insert.modulus-template":"\\lvert z \\rvert","menu.insert.argument":"Argument","menu.insert.argument-template":"\\arg(z)","menu.insert.real-part":"Cz\u0119\u015B\u0107 rzeczywista","menu.insert.real-part-template":"\\Re(z)","menu.insert.imaginary-part":"Cz\u0119\u015B\u0107 urojona","menu.insert.imaginary-part-template":"\\Im(z)","menu.insert.conjugate":"Sprz\u0119\u017Cenie","menu.insert.conjugate-template":"\\overline{z}","tooltip.blackboard":"Tablica","tooltip.bold":"Pogrubienie","tooltip.italic":"Kursywa","tooltip.fraktur":"Fraktura","tooltip.script":"Skrypt","tooltip.caligraphic":"Kaligraficzny","tooltip.typewriter":"Maszynowy","tooltip.roman-upright":"Rzymski prosto","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Styl czcionki","menu.accent":"Akcent","menu.decoration":"Dekoracja","menu.color":"Kolor","menu.background-color":"T\u0142o","menu.cut":"Wytnij","menu.copy":"Kopiuj","menu.copy-as-latex":"Kopiuj jako LaTeX","menu.copy-as-ascii-math":"Kopiuj jako ASCII Math","menu.copy-as-mathml":"Kopiuj jako MathML","menu.paste":"Wklej","menu.select-all":"Zaznacz wszystko","color.red":"Czerwony","color.orange":"Pomara\u0144czowy","color.yellow":"\u017B\xF3\u0142ty","color.lime":"Limetkowy","color.green":"Zielony","color.teal":"Turkusowy","color.cyan":"Cyjan","color.blue":"Niebieski","color.indigo":"Indygo","color.purple":"Fioletowy","color.magenta":"Magenta","color.black":"Czarny","color.dark-grey":"Ciemnoszary","color.grey":"Szary","color.light-grey":"Jasnoszary","color.white":"Bia\u0142y"},pt:{"keyboard.tooltip.symbols":"S\xEDmbolos","keyboard.tooltip.greek":"Letras gregas","keyboard.tooltip.numeric":"Num\xE9rico","keyboard.tooltip.alphabetic":"Letras romanas","tooltip.copy to clipboard":"Copiar para \xE1rea de transfer\xEAncia","tooltip.redo":"Refazer","tooltip.toggle virtual keyboard":"Alternar teclado virtual","tooltip.undo":"Desfazer","menu.insert matrix":"Inserir Matriz","menu.borders":"Delimitadores de matriz","menu.array.add row above":"Adicionar linha depois","menu.array.add row below":"Adicionar linha antes","menu.array.add column after":"Adicionar coluna depois","menu.array.add column before":"Adicionar coluna antes","menu.array.delete row":"Excluir linha","menu.array.delete rows":"Excluir linhas selecionadas","menu.array.delete column":"Apagar Coluna","menu.array.delete columns":"Excluir Colunas Selecionadas","menu.mode":"Modo","menu.mode-math":"F\xF3rmula","menu.mode-text":"Texto","menu.mode-latex":"LaTeX","tooltip.blackboard":"Quadro Negro","tooltip.bold":"Negrito","tooltip.italic":"It\xE1lico","tooltip.fraktur":"Fraktur","tooltip.script":"Script","tooltip.caligraphic":"Caligr\xE1fico","tooltip.typewriter":"M\xE1quina de Escrever","tooltip.roman-upright":"Romano Vertical","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"Estilo da Fonte","menu.accent":"Acento","menu.decoration":"Decora\xE7\xE3o","menu.color":"Cor","menu.background-color":"Cor de Fundo","menu.cut":"Recortar","menu.copy":"Copiar","menu.copy-as-latex":"Copiar como LaTeX","menu.copy-as-ascii-math":"Copiar como ASCII Math","menu.copy-as-mathml":"Copiar como MathML","menu.paste":"Colar","menu.select-all":"Selecionar Tudo","color.red":"Vermelho","color.orange":"Laranja","color.yellow":"Amarelo","color.lime":"Verde Lima","color.green":"Verde","color.teal":"Verde-azulado","color.cyan":"Ciano","color.blue":"Azul","color.indigo":"\xCDndigo","color.purple":"Roxo","color.magenta":"Magenta","color.black":"Preto","color.dark-grey":"Cinza Escuro","color.grey":"Cinza","color.light-grey":"Cinza Claro","color.white":"Branco"},uk:{"keyboard.tooltip.symbols":"\u0421\u0438\u043C\u0432\u043E\u043B\u0438","keyboard.tooltip.greek":"\u0413\u0440\u0435\u0446\u044C\u043A\u0456 \u043B\u0456\u0442\u0435\u0440\u0438","keyboard.tooltip.numeric":"\u0427\u0438\u0441\u043B\u043E\u0432\u0438\u0439","keyboard.tooltip.alphabetic":"\u0420\u0438\u043C\u0441\u044C\u043A\u0456 \u043B\u0456\u0442\u0435\u0440\u0438","tooltip.copy to clipboard":"\u041A\u043E\u043F\u0456\u044E\u0432\u0430\u0442\u0438 \u0432 \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0456\u043D\u0443","tooltip.cut to clipboard":"\u0412\u0438\u0440\u0456\u0437\u0430\u0442\u0438 \u0432 \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0456\u043D\u0443","tooltip.paste from clipboard":"\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u0438 \u0437 \u0431\u0443\u0444\u0435\u0440\u0430 \u043E\u0431\u043C\u0456\u043D\u0443","tooltip.redo":"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u0438","tooltip.toggle virtual keyboard":"\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438 \u0432\u0456\u0440\u0442\u0443\u0430\u043B\u044C\u043D\u0443 \u043A\u043B\u0430\u0432\u0456\u0430\u0442\u0443\u0440\u0443","tooltip.menu":"\u041C\u0435\u043D\u044E","tooltip.undo":"\u0421\u043A\u0430\u0441\u0443\u0432\u0430\u0442\u0438","menu.borders":"\u041C\u0435\u0436\u0456","menu.insert matrix":"\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u0438 \u043C\u0430\u0442\u0440\u0438\u0446\u044E","menu.array.add row above":"\u0414\u043E\u0434\u0430\u0442\u0438 \u0440\u044F\u0434\u043E\u043A \u043F\u0435\u0440\u0435\u0434","menu.array.add row below":"\u0414\u043E\u0434\u0430\u0442\u0438 \u0440\u044F\u0434\u043E\u043A \u043F\u0456\u0441\u043B\u044F","menu.array.add column after":"\u0414\u043E\u0434\u0430\u0442\u0438 \u0441\u0442\u043E\u0432\u043F\u0435\u0446\u044C \u043F\u0456\u0441\u043B\u044F","menu.array.add column before":"\u0414\u043E\u0434\u0430\u0442\u0438 \u0441\u0442\u043E\u0432\u043F\u0435\u0446\u044C \u043F\u0435\u0440\u0435\u0434","menu.array.delete row":"\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438 \u0440\u044F\u0434\u043E\u043A","menu.array.delete rows":"\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438 \u0432\u0438\u0431\u0440\u0430\u043D\u0456 \u0440\u044F\u0434\u043A\u0438","menu.array.delete column":"\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438 \u0441\u0442\u043E\u0432\u043F\u0435\u0446\u044C","menu.array.delete columns":"\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438 \u0432\u0438\u0431\u0440\u0430\u043D\u0456 \u0441\u0442\u043E\u0432\u043F\u0446\u0456","menu.mode":"\u0420\u0435\u0436\u0438\u043C","menu.mode-math":"\u041C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u043A\u0430","menu.mode-text":"\u0422\u0435\u043A\u0441\u0442","menu.mode-latex":"LaTeX","menu.insert":"\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u0438","menu.insert.abs":"\u0410\u0431\u0441\u043E\u043B\u044E\u0442\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F","menu.insert.abs-template":"\\left|x\\right|","menu.insert.nth-root":"\u041A\u043E\u0440\u0456\u043D\u044C n-\u0433\u043E \u0441\u0442\u0435\u043F\u0435\u043D\u044F","menu.insert.nth-root-template":"\\sqrt[n]{x}","menu.insert.log-base":"\u041B\u043E\u0433\u0430\u0440\u0438\u0444\u043C \u0437\u0430 \u043E\u0441\u043D\u043E\u0432\u043E\u044E a","menu.insert.log-base-template":"\\log_a(x)","menu.insert.heading-calculus":"\u041E\u0431\u0447\u0438\u0441\u043B\u0435\u043D\u043D\u044F","menu.insert.derivative":"\u041F\u043E\u0445\u0456\u0434\u043D\u0430","menu.insert.derivative-template":"\\dfrac{\\mathrm{d}}{\\mathrm{d}x}f(x)\\bigm|_{x=a}","menu.insert.nth-derivative":"\u041F\u043E\u0445\u0456\u0434\u043D\u0430 n-\u0433\u043E \u043F\u043E\u0440\u044F\u0434\u043A\u0443","menu.insert.nth-derivative-template":"\\dfrac{\\mathrm{d}^n}{\\mathrm{d}x^n}f(x)\\bigm|_{x=a}","menu.insert.integral":"\u0406\u043D\u0442\u0435\u0433\u0440\u0430\u043B","menu.insert.integral-template":"$\\int_a^b f(x)\\,\\mathrm{d}x$","menu.insert.sum":"\u0421\u0443\u043C\u0430","menu.insert.sum-template":"$\\sum_{i=1}^n x_i$","menu.insert.product":"\u0414\u043E\u0431\u0443\u0442\u043E\u043A","menu.insert.product-template":"\\prod_{i=1}^n x_i","menu.insert.heading-complex-numbers":"\u041A\u043E\u043C\u043F\u043B\u0435\u043A\u0441\u043D\u0456 \u0447\u0438\u0441\u043B\u0430","menu.insert.modulus":"\u041C\u043E\u0434\u0443\u043B\u044C","menu.insert.modulus-template":"\\lvert z \\rvert","menu.insert.argument":"\u0410\u0440\u0433\u0443\u043C\u0435\u043D\u0442","menu.insert.argument-template":"\\arg(z)","menu.insert.real-part":"\u0414\u0456\u0439\u0441\u043D\u0430 \u0447\u0430\u0441\u0442\u0438\u043D\u0430","menu.insert.real-part-template":"\\Re(z)","menu.insert.imaginary-part":"\u0423\u044F\u0432\u043D\u0430 \u0447\u0430\u0441\u0442\u0438\u043D\u0430","menu.insert.imaginary-part-template":"\\Im(z)","menu.insert.conjugate":"\u0421\u043F\u0440\u044F\u0436\u0435\u043D\u0435 \u0447\u0438\u0441\u043B\u043E","menu.insert.conjugate-template":"\\overline{z}","tooltip.blackboard":"\u0414\u043E\u0448\u043A\u0430","tooltip.bold":"\u0416\u0438\u0440\u043D\u0438\u0439","tooltip.italic":"\u041A\u0443\u0440\u0441\u0438\u0432","tooltip.fraktur":"\u0424\u0440\u0430\u043A\u0442\u0443\u0440\u043D\u0438\u0439","tooltip.script":"\u0420\u0443\u043A\u043E\u043F\u0438\u0441\u043D\u0438\u0439","tooltip.caligraphic":"\u041A\u0430\u043B\u0456\u0433\u0440\u0430\u0444\u0456\u0447\u043D\u0438\u0439","tooltip.typewriter":"\u0414\u0440\u0443\u043A\u0430\u0440\u0441\u044C\u043A\u0438\u0439","tooltip.roman-upright":"\u041F\u0440\u044F\u043C\u0438\u0439 \u0440\u0438\u043C\u0441\u044C\u043A\u0438\u0439","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u0421\u0442\u0438\u043B\u044C \u0448\u0440\u0438\u0444\u0442\u0443","menu.accent":"\u0410\u043A\u0446\u0435\u043D\u0442","menu.decoration":"\u041E\u0444\u043E\u0440\u043C\u043B\u0435\u043D\u043D\u044F","menu.color":"\u041A\u043E\u043B\u0456\u0440","menu.background-color":"\u0424\u043E\u043D","menu.cut":"\u0412\u0438\u0440\u0456\u0437\u0430\u0442\u0438","menu.copy":"\u041A\u043E\u043F\u0456\u044E\u0432\u0430\u0442\u0438","menu.copy-as-latex":"\u041A\u043E\u043F\u0456\u044E\u0432\u0430\u0442\u0438 \u044F\u043A LaTeX","menu.copy-as-ascii-math":"\u041A\u043E\u043F\u0456\u044E\u0432\u0430\u0442\u0438 \u044F\u043A ASCII Math","menu.copy-as-mathml":"\u041A\u043E\u043F\u0456\u044E\u0432\u0430\u0442\u0438 \u044F\u043A MathML","menu.paste":"\u0412\u0441\u0442\u0430\u0432\u0438\u0442\u0438","menu.select-all":"\u0412\u0438\u0431\u0440\u0430\u0442\u0438 \u0432\u0441\u0435","color.red":"\u0427\u0435\u0440\u0432\u043E\u043D\u0438\u0439","color.orange":"\u041F\u043E\u043C\u0430\u0440\u0430\u043D\u0447\u0435\u0432\u0438\u0439","color.yellow":"\u0416\u043E\u0432\u0442\u0438\u0439","color.lime":"\u041B\u0430\u0439\u043C\u043E\u0432\u0438\u0439","color.green":"\u0417\u0435\u043B\u0435\u043D\u0438\u0439","color.teal":"\u0411\u0456\u0440\u044E\u0437\u043E\u0432\u0438\u0439","color.cyan":"\u0421\u0438\u043D\u044C\u043E-\u0437\u0435\u043B\u0435\u043D\u0438\u0439","color.blue":"\u0421\u0438\u043D\u0456\u0439","color.indigo":"\u0406\u043D\u0434\u0438\u0433\u043E","color.purple":"\u0424\u0456\u043E\u043B\u0435\u0442\u043E\u0432\u0438\u0439","color.magenta":"\u041F\u0443\u0440\u043F\u0443\u0440\u043D\u0438\u0439","color.black":"\u0427\u043E\u0440\u043D\u0438\u0439","color.dark-grey":"\u0422\u0435\u043C\u043D\u043E-\u0441\u0456\u0440\u0438\u0439","color.grey":"\u0421\u0456\u0440\u0438\u0439","color.light-grey":"\u0421\u0432\u0456\u0442\u043B\u043E-\u0441\u0456\u0440\u0438\u0439","color.white":"\u0411\u0456\u043B\u0438\u0439"},"zh-cn":{"keyboard.tooltip.symbols":"\u7B26\u53F7","keyboard.tooltip.greek":"\u5E0C\u814A\u5B57\u6BCD","keyboard.tooltip.numeric":"\u6570\u5B57","keyboard.tooltip.alphabetic":"\u7F57\u9A6C\u5B57\u6BCD","tooltip.copy to clipboard":"\u590D\u5236\u5230\u526A\u8D34\u677F","tooltip.redo":"\u91CD\u505A","tooltip.toggle virtual keyboard":"\u5207\u6362\u865A\u62DF\u952E\u76D8","tooltip.undo":"\u64A4\u6D88","menu.insert matrix":"\u63D2\u5165\u77E9\u9635","menu.borders":"\u77E9\u9635\u5206\u9694\u7B26","menu.array.add row above":"\u5728\u540E\u9762\u6DFB\u52A0\u884C","menu.array.add row below":"\u5728\u524D\u9762\u6DFB\u52A0\u884C","menu.array.add column after":"\u5728\u540E\u9762\u6DFB\u52A0\u5217r","menu.array.add column before":"\u5728\u524D\u9762\u6DFB\u52A0\u5217","menu.array.delete row":"\u5220\u9664\u884C","menu.array.delete rows":"\u5220\u9664\u9009\u5B9A\u884C","menu.array.delete column":"\u5220\u9664\u5217","menu.array.delete columns":"\u5220\u9664\u9009\u5B9A\u7684\u5217","menu.mode":"\u6A21\u5F0F","menu.mode-math":"\u6570\u5B66","menu.mode-text":"\u6587\u672C","menu.mode-latex":"LaTeX","tooltip.blackboard":"\u9ED1\u677F","tooltip.bold":"\u7C97\u4F53","tooltip.italic":"\u659C\u4F53","tooltip.fraktur":"Fraktur","tooltip.script":"\u811A\u672C","tooltip.caligraphic":"\u8349\u4E66","tooltip.typewriter":"\u6253\u5B57\u673A","tooltip.roman-upright":"\u7F57\u9A6C\u76F4\u7ACB","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u5B57\u4F53\u6837\u5F0F","menu.accent":"\u91CD\u97F3","menu.decoration":"\u88C5\u9970","menu.color":"\u989C\u8272","menu.background-color":"\u80CC\u666F","menu.cut":"\u526A\u5207","menu.copy":"\u590D\u5236","menu.copy-as-latex":"\u590D\u5236\u4E3A LaTeX","menu.copy-as-ascii-math":"\u590D\u5236\u4E3A ASCII Math","menu.copy-as-mathml":"\u590D\u5236\u4E3A MathML","menu.paste":"\u7C98\u8D34","menu.select-all":"\u5168\u9009","color.red":"\u7EA2\u8272","color.orange":"\u6A59\u8272","color.yellow":"\u9EC4\u8272","color.lime":"\u7EFF\u9EC4\u8272","color.green":"\u7EFF\u8272","color.teal":"\u9752\u8272","color.cyan":"\u84DD\u7EFF\u8272","color.blue":"\u84DD\u8272","color.indigo":"\u975B\u84DD\u8272","color.purple":"\u7D2B\u8272","color.magenta":"\u6D0B\u7EA2\u8272","color.black":"\u9ED1\u8272","color.dark-grey":"\u6DF1\u7070\u8272","color.grey":"\u7070\u8272","color.light-grey":"\u6D45\u7070\u8272","color.white":"\u767D\u8272"},"zh-tw":{"keyboard.tooltip.symbols":"\u7B26\u865F","keyboard.tooltip.greek":"\u5E0C\u81D8\u5B57\u6BCD","keyboard.tooltip.numeric":"\u6578\u5B57","keyboard.tooltip.alphabetic":"\u7F85\u99AC\u5B57\u6BCD","tooltip.copy to clipboard":"\u8907\u88FD\u5230\u526A\u8CBC\u677F","tooltip.redo":"\u91CD\u505A","tooltip.toggle virtual keyboard":"\u5207\u63DB\u865B\u64EC\u9375\u76E4","tooltip.undo":"\u64A4\u6D88","menu.insert matrix":"\u63D2\u5165\u77E9\u9663","menu.borders":"\u77E9\u9663\u5206\u9694\u7B26","menu.array.add row above":"\u5728\u5F8C\u9762\u6DFB\u52A0\u884C","menu.array.add row below":"\u5728\u524D\u9762\u6DFB\u52A0\u884C","menu.array.add column after":"\u5728\u5F8C\u9762\u6DFB\u52A0\u5217","menu.array.add column before":"\u5728\u524D\u9762\u6DFB\u52A0\u5217","menu.array.delete row":"\u522A\u9664\u884C","menu.array.delete rows":"\u522A\u9664\u9078\u5B9A\u884C","menu.array.delete column":"\u522A\u9664\u5217","menu.array.delete columns":"\u522A\u9664\u9078\u5B9A\u7684\u5217","menu.mode":"\u6A21\u5F0F","menu.mode-math":"\u6578\u5B78","menu.mode-text":"\u6587\u672C","menu.mode-latex":"LaTeX","tooltip.blackboard":"\u9ED1\u677F","tooltip.bold":"\u7C97\u9AD4","tooltip.italic":"\u659C\u9AD4","tooltip.fraktur":"Fraktur","tooltip.script":"\u8173\u672C","tooltip.caligraphic":"\u8349\u66F8","tooltip.typewriter":"\u6253\u5B57\u6A5F","tooltip.roman-upright":"\u7F85\u99AC\u76F4\u7ACB","tooltip.row-by-col":"%@ \xD7 %@","menu.font-style":"\u5B57\u9AD4\u6A23\u5F0F","menu.accent":"\u91CD\u97F3","menu.decoration":"\u88DD\u98FE","menu.color":"\u984F\u8272","menu.background-color":"\u80CC\u666F","menu.cut":"\u526A\u4E0B","menu.copy":"\u8907\u88FD","menu.copy-as-latex":"\u8907\u88FD\u70BA LaTeX","menu.copy-as-ascii-math":"\u8907\u88FD\u70BA ASCII Math","menu.copy-as-mathml":"\u8907\u88FD\u70BA MathML","menu.paste":"\u8CBC\u4E0A","menu.select-all":"\u5168\u9078","color.red":"\u7D05\u8272","color.orange":"\u6A59\u8272","color.yellow":"\u9EC3\u8272","color.lime":"\u7DA0\u9EC3\u8272","color.green":"\u7DA0\u8272","color.teal":"\u9752\u8272","color.cyan":"\u85CD\u7DA0\u8272","color.blue":"\u85CD\u8272","color.indigo":"\u975B\u85CD\u8272","color.purple":"\u7D2B\u8272","color.magenta":"\u6D0B\u7D05\u8272","color.black":"\u9ED1\u8272","color.dark-grey":"\u6DF1\u7070\u8272","color.grey":"\u7070\u8272","color.light-grey":"\u6DFA\u7070\u8272","color.white":"\u767D\u8272"}};var F={strings:Ku,_locale:"",_dirty:!1,_subscribers:[],_numberFormatter:void 0,get locale(){return F._locale||(F._locale=Le()?navigator.language.slice(0,5):"en-US"),F._locale},set locale(t){F._locale=t,F._numberFormatter=void 0,F.dirty=!0},get numberFormatter(){if(!F._numberFormatter)try{F._numberFormatter=new Intl.NumberFormat(F.locale)}catch(t){try{F._numberFormatter=new Intl.NumberFormat(F.locale.slice(0,2))}catch(e){F._numberFormatter=new Intl.NumberFormat("en-US")}}return F._numberFormatter},merge(t,e){if(typeof t=="string"&&e)F.strings[t]=h(h({},F.strings[t]),e),F.dirty=!0;else for(let r of Object.keys(t))F.merge(r,t[r])},get dirty(){return F._dirty},set dirty(t){F._dirty||F._dirty===t||(F._dirty=!0,setTimeout(()=>{F._dirty=!1,this._subscribers.forEach(e=>e==null?void 0:e())},0))},subscribe(t){return F._subscribers.push(t),F._subscribers.length-1},unsubscribe(t){t<0||t>=F._subscribers.length||(F._subscribers[t]=void 0)},update(t){let e=t.querySelectorAll("[data-l10n-tooltip]");for(let r of e){let i=r.getAttribute("data-l10n-tooltip");if(i){let n=$(i);n&&r.setAttribute("data-tooltip",n)}}e=t.querySelectorAll("[data-l10n-arial-label]");for(let r of e){let i=r.getAttribute("data-l10n-arial-label");if(i){let n=$(i);n&&r.setAttribute("aria-label",n)}}}};function $(t,...e){if(t===void 0)return;let r="",i=F.locale;F.strings[i]&&(r=F.strings[i][t]);let n=i.slice(0,2);if(!r&&F.strings[n]&&(r=F.strings[n][t]),r||(r=F.strings.en[t]),!r)return;let o=/(%@|%([0-9]+)\$@)/g,a=o.exec(r),s=0;for(;a;){if(e[s++]){let c=a[2]?parseInt(a[2],10)-1:s-1,u=e[c];typeof u=="number"&&(u=F.numberFormatter.format(u)),r=r.replace(a[1],u)}a=o.exec(r)}return r=r.replace(/%%/g,"%"),r}var hf={m0:"#3F3D99",m1:"#993D71",m2:"#998B3D",m3:"#3D9956",m4:"#3D5A99",m5:"#993D90",m6:"#996D3D",m7:"#43993D",m8:"#3D7999",m9:"#843D99"},pf={blue:"#0072BD",orange:"#D95319",yellow:"#EDB120",purple:"#7E2F8E",green:"#77AC30",cyan:"#4DBEEE",red:"#A2142F"},Qt={red:"#fbbbb6",orange:"#ffe0c2",yellow:"#fff1c2",lime:"#d0e8b9",green:"#bceac4",teal:"#b9f1f1",cyan:"#b8e5c9",blue:"#b6d9fb",indigo:"#d1c2f0",purple:"#e3baf8",magenta:"#f9c8e0",black:"#353535","dark-grey":"#8C8C8C",grey:"#D0D0D0","light-grey":"#F0F0F0",white:"#ffffff"},er={red:"#d7170b",orange:"#fe8a2b",yellow:"#ffc02b",lime:"#63b215",green:"#21ba3a",teal:"#17cfcf",cyan:"#13a7ec",blue:"#0d80f2",indigo:"#63c",purple:"#a219e6",magenta:"#eb4799",black:"#000","dark-grey":"#666",grey:"#A6A6A6","light-grey":"#d4d5d2",white:"#ffffff"},Pu={Red:"red",Orange:"orange",Yellow:"yellow",LimeGreen:"lime",Green:"green",TealBlue:"teal",Blue:"blue",Violet:"indigo",Purple:"purple",Magenta:"magenta",Black:"black",Gray:"grey",White:"white"},ff={Apricot:"#FBB982",Aquamarine:"#00B5BE",Bittersweet:"#C04F17",Black:"#221E1F",Blue:"#2D2F92",BlueGreen:"#00B3B8",BlueViolet:"#473992",BrickRed:"#B6321C",Brown:"#792500",BurntOrange:"#F7921D",CadetBlue:"#74729A",CarnationPink:"#F282B4",Cerulean:"#00A2E3",CornflowerBlue:"#41B0E4",Cyan:"#00AEEF",Dandelion:"#FDBC42",DarkOrchid:"#A4538A",Emerald:"#00A99D",ForestGreen:"#009B55",Fuchsia:"#8C368C",Goldenrod:"#FFDF42",Gray:"#949698",Green:"#00A64F",GreenYellow:"#DFE674",JungleGreen:"#00A99A",Lavender:"#F49EC4",Limegreen:"#8DC73E",Magenta:"#EC008C",Mahogany:"#A9341F",Maroon:"#AF3235",Melon:"#F89E7B",MidnightBlue:"#006795",Mulberry:"#A93C93",NavyBlue:"#006EB8",OliveGreen:"#3C8031",Orange:"#F58137",OrangeRed:"#ED135A",Orchid:"#AF72B0",Peach:"#F7965A",Periwinkle:"#7977B8",PineGreen:"#008B72",Plum:"#92268F",ProcessBlue:"#00B0F0",Purple:"#99479B",RawSienna:"#974006",Red:"#ED1B23",RedOrange:"#F26035",RedViolet:"#A1246B",Rhodamine:"#EF559F",RoyalBlue:"#0071BC",RoyalPurple:"#613F99",RubineRed:"#ED017D",Salmon:"#F69289",SeaGreen:"#3FBC9D",Sepia:"#671800",SkyBlue:"#46C5DD",SpringGreen:"#C6DC67",Tan:"#DA9D76",TealBlue:"#00AEB3",Thistle:"#D883B7",Turquoise:"#00B4CE",Violet:"#58429B",VioletRed:"#EF58A0",White:"#FFFFFF",WildStrawberry:"#EE2967",Yellow:"#FFF200",YellowGreen:"#98CC70",YellowOrange:"#FAA21A"};function Yr(t){var u,d,m,p,f,y;let e=t.split("!"),r,i,n,o=255,a=255,s=255,l=-1,c=e.length>0&&e[0].startsWith("-");c&&(e[0]=e[0].slice(1));for(let v=0;v=0&&(o=(1-l)*o+l*r,a=(1-l)*a+l*i,s=(1-l)*s+l*n,l=-1),v+1=0&&(o=l*o+(1-l)*r,a=l*a+(1-l)*i,s=l*s+(1-l)*n),c&&(o=255-o,a=255-a,s=255-s),"#"+("00"+Math.round(o).toString(16)).slice(-2)+("00"+Math.round(a).toString(16)).slice(-2)+("00"+Math.round(s).toString(16)).slice(-2)}function Bi(t){var e,r;return t=t.trim(),(r=(e=Qt[t.toLowerCase()])!=null?e:Qt[Pu[t]])!=null?r:Yr(t)}function gf(t){if(!t||t[0]!=="#")return;t=t.slice(1);let e;return t.length<=4?(e={r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16)},t.length===4&&(e.a=parseInt(t[3]+t[3],16)/255)):(e={r:parseInt(t[0]+t[1],16),g:parseInt(t[2]+t[3],16),b:parseInt(t[4]+t[5],16)},t.length===8&&(e.a=parseInt(t[6]+t[7],16)/255)),e&&e.a===void 0&&(e.a=1),e}function ul(t,e,r){return r<0&&(r+=6),r>=6&&(r-=6),r<1?(e-t)*r+t:r<3?e:r<4?(e-t)*(4-r)+t:t}function bf(t){let[e,r,i]=[t.h,t.s,t.l];e=(e+360)%360/60,i=Math.max(0,Math.min(i,1)),r=Math.max(0,Math.min(r,1));let n=i<=.5?i*(r+1):i+r-i*r,o=i*2-n;return{r:Math.round(255*ul(o,n,e+2)),g:Math.round(255*ul(o,n,e)),b:Math.round(255*ul(o,n,e-2))}}function dl(t){return t<0?0:t>255?255:Math.round(t)}function yf(t){let{r:e,g:r,b:i}=t,n=((1<<24)+(dl(e)<<16)+(dl(r)<<8)+dl(i)).toString(16).slice(1);return n[0]===n[1]&&n[2]===n[3]&&n[4]===n[5]&&n[6]===n[7]&&(n=n[0]+n[2]+n[4]),"#"+n}function xf(t){let{r:e,g:r,b:i}=t;e=e/255,r=r/255,i=i/255;let n=Math.min(e,r,i),o=Math.max(e,r,i),a=o-n,s,l;o===n?s=0:e===o?s=(r-i)/a:r===o?s=2+(i-e)/a:i===o&&(s=4+(e-r)/a),s=Math.min(s*60,360),s<0&&(s+=360);let c=(n+o)/2;return o===n?l=0:c<=.5?l=a/(o+n):l=a/(2-o-n),{h:s,s:l,l:c}}function Ru(t){let e=gf(t);if(!e)return t;let{h:r,s:i,l:n}=xf(e);return i+=.1,n-=.1,yf(bf({h:r,s:i,l:n}))}var hl={60:"\\lt",62:"\\gt",111:"o",38:"\\&",123:"\\lbrace",125:"\\rbrace",91:"\\lbrack",93:"\\rbrack",58:"\\colon",160:"~",172:"\\neg",183:"\\cdot",188:"\\frac{1}{4}",189:"\\frac{1}{2}",190:"\\frac{3}{4}",8304:"^{0}",8305:"^{i}",185:"^{1}",178:"^{2}",179:"^{3}",8224:"\\dagger",8225:"\\ddagger",8230:"\\ldots",8308:"^{4}",8309:"^{5}",8310:"^{6}",8311:"^{7}",8312:"^{8}",8313:"^{9}",8314:"^{+}",8315:"^{-}",8316:"^{=}",8319:"^{n}",8320:"_{0}",8321:"_{1}",8322:"_{2}",8323:"_{3}",8324:"_{4}",8325:"_{5}",8326:"_{6}",8327:"_{7}",8328:"_{8}",8329:"_{9}",8330:"_{+}",8331:"_{-}",8332:"_{=}",8336:"_{a}",8337:"_{e}",8338:"_{o}",8339:"_{x}",8242:"\\prime",39:"\\prime",8592:"\\gets",8594:"\\to",9651:"\\triangle",9661:"\\triangledown",8715:"\\owns",8727:"\\ast",8739:"\\vert",8741:"\\Vert",8743:"\\land",8744:"\\lor",8901:"\\cdot",8904:"\\bowtie",8800:"\\ne",8804:"\\le",8805:"\\ge",8869:"\\bot",10178:"\\perp",10231:"\\biconditional",10232:"\\impliedby",10233:"\\implies",10234:"\\iff",8450:"\\mathbb{C}",8469:"\\mathbb{N}",8473:"\\mathbb{P}",8474:"\\mathbb{Q}",8477:"\\mathbb{R}",8484:"\\mathbb{Z}",8461:"\\mathbb{H}",8476:"\\Re",8465:"\\Im",42:"\\ast",11036:"\\square",9633:"\\square",8720:"\\coprod",8716:"\\not\\ni",9671:"\\diamond",8846:"\\uplus",8851:"\\sqcap",8852:"\\sqcup",8768:"\\wr",8750:"\\oint",8226:"\\textbullet",8722:"-",978:"\\Upsilon"},ml={119893:8462,119965:8492,119968:8496,119969:8497,119971:8459,119972:8464,119975:8466,119976:8499,119981:8475,119994:8495,119996:8458,120004:8500,120070:8493,120075:8460,120076:8465,120085:8476,120093:8488,120122:8450,120127:8461,120133:8469,120135:8473,120136:8474,120137:8477,120145:8484},Iu=[{start:119808,len:26,offset:65,style:"bold"},{start:119834,len:26,offset:97,style:"bold"},{start:120488,len:25,offset:913,style:"bold"},{start:120514,len:25,offset:945,style:"bold"},{start:119860,len:26,offset:65,style:"italic"},{start:119886,len:26,offset:97,style:"italic"},{start:120546,len:25,offset:913,style:"italic"},{start:120572,len:25,offset:945,style:"italic"},{start:119912,len:26,offset:65,style:"bolditalic"},{start:119938,len:26,offset:97,style:"bolditalic"},{start:120604,len:25,offset:913,style:"bolditalic"},{start:120630,len:25,offset:945,style:"bolditalic"},{start:120782,len:10,offset:48,variant:"main",style:"bold"},{start:119964,len:26,offset:65,variant:"script"},{start:119990,len:26,offset:97,variant:"script"},{start:120016,len:26,offset:65,variant:"script",style:"bold"},{start:120042,len:26,offset:97,variant:"script",style:"bold"},{start:120068,len:26,offset:65,variant:"fraktur"},{start:120094,len:26,offset:97,variant:"fraktur"},{start:120172,len:26,offset:65,variant:"fraktur",style:"bold"},{start:120198,len:26,offset:97,variant:"fraktur",style:"bold"},{start:120120,len:26,offset:65,variant:"double-struck"},{start:120146,len:26,offset:97,variant:"double-struck"},{start:120792,len:10,offset:48,variant:"double-struck"},{start:120432,len:26,offset:65,variant:"monospace"},{start:120458,len:26,offset:97,variant:"monospace"},{start:120822,len:10,offset:48,variant:"monospace"},{start:120224,len:26,offset:65,variant:"sans-serif"},{start:120250,len:26,offset:97,variant:"sans-serif"},{start:120276,len:26,offset:65,variant:"sans-serif",style:"bold"},{start:120302,len:26,offset:97,variant:"sans-serif",style:"bold"},{start:120328,len:26,offset:65,variant:"sans-serif",style:"italic"},{start:120354,len:26,offset:97,variant:"sans-serif",style:"italic"},{start:120380,len:26,offset:65,variant:"sans-serif",style:"bolditalic"},{start:120406,len:26,offset:97,variant:"sans-serif",style:"bolditalic"},{start:120662,len:25,offset:913,variant:"sans-serif",style:"bold"},{start:120688,len:25,offset:945,variant:"sans-serif",style:"bold"},{start:120720,len:25,offset:913,variant:"sans-serif",style:"bolditalic"},{start:120746,len:25,offset:945,variant:"sans-serif",style:"bolditalic"},{start:120803,len:10,offset:48,variant:"sans-serif"},{start:120812,len:10,offset:48,variant:"sans-serif",style:"bold"}];function Bn(t,e,r){if(!/[A-Za-z\d]/.test(t)||(r==="up"&&(r=void 0),!e&&!r))return;let i=t.codePointAt(0);if(i===void 0)return t;for(let n of Iu)if((!e||n.variant===e)&&(!r||n.style===r)&&i>=n.offset&&i120831)&&(t<8448||t>8527))return{char:String.fromCodePoint(t)};for(let r in ml)if(ml[r]===t){t=(e=r.codePointAt(0))!=null?e:0;break}for(let r of Iu)if(t>=r.start&&t[]$&*#^_%:'\u02DC".includes(t)||t.length>1)return;let e=(a=t.codePointAt(0))!=null?a:0,r=hl[e];if(r)return r;let{char:i,variant:n,style:o}=vf(e);if(!(!n&&!o)){switch(r=i,n){case"double-struck":r=`\\mathbb{${r}}`;break;case"fraktur":r=`\\mathfrak{${r}}`;break;case"script":r=`\\mathscr{${r}}`;break;case"sans-serif":r=`\\mathsf{${r}}`;break;case"monospace":r=`\\mathtt{${r}}`;break;case"calligraphic":r=`\\mathcal{${r}}`;break}switch(o){case"bold":r=`\\mathbf{${r}}`;break;case"italic":r=`\\mathit{${r}}`;break;case"bolditalic":r=`\\mathbfit{${r}}`;break}return r}}function T(t){return t?Array.isArray(t)?t:typeof t=="object"&&"group"in t?t.group:[]:[]}var Kn={},Xo=h({},hl),Pi={},fl={},_f={darr:"\\downarrow",dArr:"\\Downarrow",Darr:"\\Downarrow",lang:"\\langle",rang:"\\rangle",uarr:"\\uparrow",uArr:"\\Uparrow",Uarr:"\\Uparrow",C:"\\mathbb{C}",H:"\\mathbb{H}",N:"\\mathbb{N}",Q:"\\mathbb{Q}",R:"\\mathbb{R}",Z:"\\mathbb{Z}",alef:"\\aleph",alefsym:"\\aleph",Alpha:"\\mathrm{A}",Beta:"\\mathrm{B}",bull:"\\bullet",Chi:"\\mathrm{X}",clubs:"\\clubsuit",cnums:"\\mathbb{C}",Complex:"\\mathbb{C}",Dagger:"\\ddagger",diamonds:"\\diamondsuit",doublecap:"\\Cap",doublecup:"\\Cup",empty:"\\emptyset",Epsilon:"\\mathrm{E}",Eta:"\\mathrm{H}",exist:"\\exists",hArr:"\\Leftrightarrow",harr:"\\leftrightarrow",Harr:"\\Leftrightarrow",hearts:"\\heartsuit",image:"\\Im",infin:"\\infty",Iota:"\\mathrm{I}",isin:"\\in",Kappa:"\\mathrm{K}",larr:"\\leftarrow",Larr:"\\Leftarrow",lArr:"\\Leftarrow",lrarr:"\\leftrightarrow",Lrarr:"\\Leftrightarrow",lrArr:"\\Leftrightarrow",Mu:"\\mathrm{M}",natnums:"\\mathbb{N}",Nu:"\\mathrm{N}",Omicron:"\\mathrm{O}",part:"\\partial",plusmn:"\\pm",rarr:"\\rightarrow",Rarr:"\\Rightarrow",rArr:"\\Rightarrow",real:"\\Re",reals:"\\mathbb{R}",Reals:"\\mathbb{R}",restriction:"\\upharpoonright",Rho:"\\mathrm{P}",sdot:"\\cdot",sect:"\\S",spades:"\\spadesuit",sub:"\\subset",sube:"\\subseteq",supe:"\\supseteq",Tau:"\\mathrm{T}",thetasym:"\\vartheta",varcoppa:"\\coppa",weierp:"\\wp",Zeta:"\\mathrm{Z}"},Mf={varGamma:"\\mathit{\\Gamma}",varDelta:"\\mathit{\\Delta}",varTheta:"\\mathit{\\Theta}",varLambda:"\\mathit{\\Lambda}",varXi:"\\mathit{\\Xi}",varPi:"\\mathit{\\Pi}",varSigma:"\\mathit{\\Sigma}",varUpsilon:"\\mathit{\\Upsilon}",varPhi:"\\mathit{\\Phi}",varPsi:"\\mathit{\\Psi}",varOmega:"\\mathit{\\Omega}",pmod:{def:"\\quad(\\operatorname{mod}\\ #1)",args:1,expand:!1,captureSelection:!1},mod:{def:"\\quad\\operatorname{mod}\\,\\,#1",args:1,expand:!1},bmod:{def:"\\;\\mathbin{\\operatorname{mod }}",expand:!1}},wf={bra:{def:"\\mathinner{\\langle{#1}|}",args:1,captureSelection:!1},ket:{def:"\\mathinner{|{#1}\\rangle}",args:1,captureSelection:!1},braket:{def:"\\mathinner{\\langle{#1}\\rangle}",args:1,captureSelection:!1},set:{def:"\\mathinner{\\lbrace #1 \\rbrace}",args:1,captureSelection:!1},Bra:{def:"\\left\\langle #1\\right|",args:1,captureSelection:!1},Ket:{def:"\\left|#1\\right\\rangle",args:1,captureSelection:!1},Braket:{def:"\\left\\langle{#1}\\right\\rangle",args:1,captureSelection:!1},Set:{def:"\\left\\lbrace #1 \\right\\rbrace",args:1,captureSelection:!1}},Sf={strut:{primitive:!0,def:"\\phantom{\\rule[0.3\\baselineskip]{0}{0.7\\baselineskip}}",args:0,captureSelection:!0},iff:{primitive:!0,captureSelection:!0,def:"\\;\\Longleftrightarrow\\;"},nicefrac:"^{#1}\\!\\!/\\!_{#2}",phase:{def:"\\enclose{phasorangle}{#1}",args:1,captureSelection:!1},rd:"\\mathrm{d}",rD:"\\mathrm{D}",odif:"\\mathrm{d}",doubleStruckCapitalN:"\\mathbb{N}",doubleStruckCapitalR:"\\mathbb{R}",doubleStruckCapitalQ:"\\mathbb{Q}",doubleStruckCapitalZ:"\\mathbb{Z}",doubleStruckCapitalP:"\\mathbb{P}",scriptCapitalE:"\\mathscr{E}",scriptCapitalH:"\\mathscr{H}",scriptCapitalL:"\\mathscr{L}",gothicCapitalC:"\\mathfrak{C}",gothicCapitalH:"\\mathfrak{H}",gothicCapitalI:"\\mathfrak{I}",gothicCapitalR:"\\mathfrak{R}",imaginaryI:"\\mathrm{i}",imaginaryJ:"\\mathrm{j}",exponentialE:"\\mathrm{e}",differentialD:"\\mathrm{d}",capitalDifferentialD:"\\mathrm{D}",mathstrut:{def:"\\vphantom{(}",primitive:!0},angl:"\\enclose{actuarial}{#1}",angln:"\\enclose{actuarial}{n}",anglr:"\\enclose{actuarial}{r}",anglk:"\\enclose{actuarial}{k}",mathtools:{primitive:!0,package:{ordinarycolon:":",vcentcolon:"\\mathrel{\\mathop\\ordinarycolon}",dblcolon:'{\\mathop{\\char"2237}}',coloneqq:'{\\mathop{\\char"2254}}',Coloneqq:'{\\mathop{\\char"2A74}}',coloneq:'{\\mathop{\\char"2254}}',Coloneq:'{\\mathop{\\char"2A74}}',eqqcolon:'{\\mathop{\\char"2255}}',Eqqcolon:'{\\mathop{\\char"3D\\char"2237}}',eqcolon:'{\\mathop{\\char"2255}}',Eqcolon:'{\\mathop{\\char"3D\\char"2237}}',colonapprox:'{\\mathop{\\char"003A\\char"2248}}',Colonapprox:'{\\mathop{\\char"2237\\char"2248}}',colonsim:'{\\mathop{\\char"3A\\char"223C}}',Colonsim:'{\\mathop{\\char"2237\\char"223C}}',colondash:"\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}",Colondash:"\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}",dashcolon:"\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}",Dashcolon:"\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}"}},ratio:"\\vcentcolon",coloncolon:"\\dblcolon",colonequals:"\\coloneq",coloncolonequals:"\\Coloneq",equalscolon:"\\eqcolon",equalscoloncolon:"\\Eqcolon",colonminus:"\\colondash",coloncolonminus:"\\Colondash",minuscolon:"\\dashcolon",minuscoloncolon:"\\Dashcolon",coloncolonapprox:"\\Colonapprox",coloncolonsim:"\\Colonsim",simcolon:"\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}",Simcolon:"\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}",simcoloncolon:"\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}",approxcolon:"\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}",Approxcolon:"\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}",approxcoloncolon:"\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}",notni:"\\mathrel{\\char`\u220C}",limsup:"\\operatorname*{lim\\,sup}",liminf:"\\operatorname*{lim\\,inf}",injlim:"\\operatorname*{inj\\,lim}",projlim:"\\operatorname*{proj\\,lim}",varlimsup:"\\operatorname*{\\overline{lim}}",varliminf:"\\operatorname*{\\underline{lim}}",varinjlim:"\\operatorname*{\\underrightarrow{lim}}",varprojlim:"\\operatorname*{\\underleftarrow{lim}}",argmin:"\\operatorname*{arg\\,min}",argmax:"\\operatorname*{arg\\,max}",plim:"\\mathop{\\operatorname{plim}}\\limits",tripledash:{def:"\\vphantom{-}\\raise{4mu}{\\mkern1.5mu\\rule{2mu}{1.5mu}\\mkern{2.25mu}\\rule{2mu}{1.5mu}\\mkern{2.25mu}\\rule{2mu}{1.5mu}\\mkern{2mu}}",expand:!0},"braket.sty":{package:wf},"amsmath.sty":{package:Mf,primitive:!0},"texvc.sty":{package:_f,primitive:!1}},Ki={" ":32,"\\!":33,"\\#":35,"\\$":36,"\\%":37,"\\&":38,"\\_":95,"-":45,"\\textunderscore":95,"\\euro":8364,"\\maltese":10016,"\\{":123,"\\}":125,"\\textbraceleft":123,"\\textbraceright":125,"\\lbrace":123,"\\rbrace":125,"\\lbrack":91,"\\rbrack":93,"\\nobreakspace":160,"\\ldots":8230,"\\textellipsis":8230,"\\backslash":92,"`":8216,"'":8217,"``":8220,"''":8221,"\\degree":176,"\\textasciicircum":94,"\\textasciitilde":126,"\\textasteriskcentered":42,"\\textbackslash":92,"\\textbullet":8226,"\\textdollar":36,"\\textsterling":163,"\\textdagger":8224,"\\textdaggerdbl":8225,"\u2013":8211,"\u2014":8212,"\u2018":8216,"\u2019":8217,"\u201C":8220,"\u201D":8221,'"':8221,"\\ss":223,"\\ae":230,"\\oe":339,"\\AE":198,"\\OE":338,"\\O":216,"\\i":305,"\\j":567,"\\aa":229,"\\AA":197},$u=/[\w!@*()-=+{}\[\]\\';:?/.,~<>`|$%#&^" ]/,Zo,Qr;gu()?(Zo=new RegExp("\\p{Letter}","u"),Qr=new RegExp("[0-9\\p{Letter}]","u")):(Zo=/[a-zA-ZаАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяĄąĆćĘꣳŃńÓóŚśŹźŻżàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒößÖẞìíòúÌÍÒÚáñÁÑ]/,Qr=/[\da-zA-ZаАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяĄąĆćĘꣳŃńÓóŚśŹźŻżàâäôéèëêïîçùûüÿæœÀÂÄÔÉÈËÊÏΟÇÙÛÜÆŒößÖẞìíòúÌÍÒÚáñÁÑ]/);function pl(t,e,r="mord",i){e!==void 0&&(Kn[t]={definitionType:"symbol",type:r,variant:i,codepoint:e},Xo[e]||(Xo[e]=t))}function Se(t,e,r){if(typeof t=="string"){for(let i=0;i{var l,c;return a.frequency===s.frequency?a.match.length===s.match.length?a.matcha.match)}function Nu(t){let e="auto",r=t.match(/:([^=]+)/);return r&&(e=r[1].trim()),e}function Yo(t){if(!t)return[];let e=[],r=t.split("]");if(r[0].startsWith("[")){e.push({isOptional:!0,type:Nu(r[0].slice(1))});for(let i=1;i<=r.length;i++)e.push(...Yo(r[i]))}else if(r=t.split("}"),r[0].startsWith("{")){e.push({isOptional:!1,type:Nu(r[0].slice(1))});for(let i=1;i<=r.length;i++)e.push(...Yo(r[i]))}return e}function bl(t){if(!t)return"";let e="",r=!0;for(let i of t)typeof i.value=="string"?e+=i.value:r=!1;return r?e:""}function Tt(t,e,r){typeof t=="string"&&(t=[t]);let n={tabular:!0,rootOnly:!1,params:Yo(e),createAtom:r};for(let o of t)fl[o]=n}function Qo(t,e,r){var n;typeof t=="string"&&(t=[t]);let i={tabular:(n=r==null?void 0:r.tabular)!=null?n:!1,rootOnly:!0,params:[],createAtom:e};for(let o of t)fl[o]=i}function M(t,e,r){var n,o;r||(r={});let i={definitionType:"function",params:Yo(e),ifMode:r.ifMode,isFunction:(n=r.isFunction)!=null?n:!1,applyMode:r.applyMode,infix:(o=r.infix)!=null?o:!1,parse:r.parse,createAtom:r.createAtom,applyStyle:r.applyStyle,serialize:r.serialize,render:r.render};if(typeof t=="string")Pi["\\"+t]=i;else for(let a of t)Pi["\\"+a]=i}var Jo;function Ri(t){return Jo||(Jo=ei(Sf)),t?ei(h(h({},Jo),t)):Jo}function Fu(t,e){var r,i,n,o;if(typeof t=="string"){let a=0,s=t;return/(^|[^\\])#1/.test(s)&&(a=1),/(^|[^\\])#2/.test(s)&&(a=2),/(^|[^\\])#3/.test(s)&&(a=3),/(^|[^\\])#4/.test(s)&&(a=4),/(^|[^\\])#5/.test(s)&&(a=5),/(^|[^\\])#6/.test(s)&&(a=6),/(^|[^\\])#7/.test(s)&&(a=7),/(^|[^\\])#8/.test(s)&&(a=8),/(^|[^\\])#9/.test(s)&&(a=9),{expand:(r=e==null?void 0:e.expand)!=null?r:!0,captureSelection:(i=e==null?void 0:e.captureSelection)!=null?i:!0,args:a,def:s}}return h({expand:(n=e==null?void 0:e.expand)!=null?n:!0,captureSelection:(o=e==null?void 0:e.captureSelection)!=null?o:!0,args:0},t)}function ei(t){if(!t)return{};let e={};for(let r of Object.keys(t)){let i=t[r];if(i==null)delete e[r];else if(typeof i=="object"&&"package"in i)for(let n of Object.keys(i.package))e[n]=Fu(i.package[n],{expand:!i.primitive,captureSelection:i.captureSelection});else e[r]=Fu(i)}return e}function ne(t,e="math"){if(!t||t.length===0)return null;let r=null;if(t.startsWith("\\")){if(r=Pi[t],r)return!r.ifMode||r.ifMode===e?r:null;e==="math"?r=Kn[t]:Ki[t]&&(r={definitionType:"symbol",type:"mord",codepoint:Ki[t]})}else if(e==="math"){if(r=Kn[t],!r&&t.length===1){let i=yl("math",t.codePointAt(0));return i.startsWith("\\")?g(h({},ne(i,"math")),{command:i}):null}}else Ki[t]?r={definitionType:"symbol",type:"mord",codepoint:Ki[t]}:e==="text"&&(r={definitionType:"symbol",type:"mord",codepoint:t.codePointAt(0)});return r!=null?r:null}function ti(t,e){if(!t.startsWith("\\"))return null;let r=t.slice(1);return e[r]}function yl(t,e){if(e===void 0)return"";if(t==="math"&&Xo[e])return Xo[e];if(t==="text"){let r=Object.keys(Ki).find(i=>Ki[i]===e);return r||String.fromCodePoint(e)}return String.fromCodePoint(e)}var tt=[0,.68889,0,0,.72222],ri=[0,.68889,0,0,.66667],xl=[0,.68889,0,0,.77778],ea=[0,.68889,0,0,.61111],Hu=[.16667,.68889,0,0,.77778],Pn=[0,.68889,0,0,.55556],Z=[0,0,0,0,.25],Wu=[0,.825,0,0,2.33334],Uu=[0,.9,0,0,2.33334],ta=[0,.68889,0,0,.54028],vl=[-.03598,.46402,0,0,.5],Be=[-.13313,.36687,0,0,1],ra=[.01354,.52239,0,0,1],Gu=[.01354,.52239,0,0,1.11111],ju=[0,.54986,0,0,1],ia=[0,.69224,0,0,.5],_l=[0,.43056,0,0,1],xr=[.08198,.58198,0,0,.77778],na=[.19444,.69224,0,0,.41667],oa=[.1808,.675,0,0,1],Ju=[.19444,.69224,0,0,.83334],Xu=[.13667,.63667,0,0,1],Zu=[-.064,.437,0,0,1.334],vr=[.08167,.58167,0,0,.77778],Rn=[0,.69224,0,0,.72222],Ml=[0,.69224,0,0,.66667],aa=[-.13313,.36687,0,0,.77778],Yu=[.06062,.54986,0,0,.77778],sa=[0,.69224,0,0,.77778],Ii=[.25583,.75583,0,0,.77778],Dt=[.25142,.75726,0,0,.77778],zi=[.20576,.70576,0,0,.77778],dt=[.30274,.79383,0,0,.77778],In=[.22958,.72958,0,0,.77778],Qu=[.1808,.675,0,0,.77778],Ot=[.13667,.63667,0,0,.77778],qe=[.13597,.63597,0,0,.77778],_r=[.03517,.54986,0,0,.77778],Ni=[0,.675,0,0,.77778],ed=[.19444,.69224,0,0,.61111],td=[0,.54986,0,0,.76042],rd=[0,.54986,0,0,.66667],Mr=[.0391,.5391,0,0,.77778],id=[.03517,.54986,0,0,1.33334],nd=[.38569,.88569,0,0,.77778],la=[.23222,.74111,0,0,.77778],od=[.19444,.69224,0,0,.77778],ad=[0,.37788,0,0,.5],ca=[0,.54986,0,0,.72222],sd=[0,.69224,0,0,.83334],ld=[.11111,.69224,0,0,.66667],Fi=[.26167,.75726,0,0,.77778],cd=[.48256,.98256,0,0,.77778],ud=[.28481,.79383,0,0,.77778],dd=[.08167,.58167,0,0,.22222],md=[.08167,.58167,0,0,.38889],hd=[0,.43056,.04028,0,.66667],pd=[.41951,.91951,0,0,.77778],fd=[.24982,.74947,0,0,.38865],gd=[.08319,.58283,0,0,.75623],bd=[0,.10803,0,0,.27764],wl=[0,.47534,0,0,.50181],zn=[.18906,.47534,0,0,.50181],yd=[0,.69141,0,0,.50181],xd=[.24982,.74947,0,0,.27764],Sl=[0,.69141,0,0,.21471],ua=[.25,.75,0,0,.44722],rt=[0,.64444,0,0,.575],$i=[.08556,.58556,0,0,.89444],da=[0,.69444,0,0,.89444],ma=[0,.68611,0,0,.9],kl=[0,.68611,0,0,.86944],wr=[.25,.75,0,0,.575],ha=[.25,.75,0,0,.31944],ii=[0,.69444,0,0,.63889],Vi=[0,.69444,0,0,.31944],vd=[0,.44444,0,0,.63889],_d=[0,.44444,0,0,.51111],Sr=[0,.69444,0,0,.575],mt=[.13333,.63333,0,0,.89444],Md=[0,.44444,0,0,.31944],wd=[0,.69444,0,0,.86944],Sd=[0,.68611,0,0,.69166],pa=[0,.68611,0,0,.83055],Ll=[0,.68611,0,0,.89444],Al=[0,.69444,0,0,.60278],kd=[.19444,.69444,0,0,.51111],Ld=[0,.69444,0,0,.83055],Bt=[-.10889,.39111,0,0,1.14999],Ad=[.19444,.69444,0,0,.575],Nn=[.19444,.69444,0,0,1.14999],Cd=[.19444,.69444,0,0,.70277],Ed=[.05556,.75,0,0,.575],Cl=[0,.68611,0,0,.95833],Td=[.08556,.58556,0,0,.76666],El=[-.02639,.47361,0,0,.575],Dd=[0,.44444,0,0,.89444],ni=[0,.55556,0,0,.76666],Od=[-.10889,.39111,0,0,.89444],Tl=[.00222,.50222,0,0,.89444],kr=[.19667,.69667,0,0,.89444],Bd=[.08556,.58556,0,0,1.14999],Dl=[0,.69444,0,0,.70277],fa=[-.02778,.47222,0,0,.575],ga=[.25,.75,0,0,.51111],Kd=[-.13889,.36111,0,0,1.14999],Pd=[.19444,.69444,0,0,1.02222],ba=[.12963,.69444,0,0,.89444],Rd=[.19444,.69444,0,0,.44722],Lr=[0,.64444,.13167,0,.59111],Id=[.19444,.64444,.13167,0,.59111],Ol=[0,.68611,.17208,0,.8961],zd=[.19444,.44444,.105,0,.53222],Nd=[0,.44444,.085,0,.82666],Fd=[0,.69444,.06709,0,.59111],ya=[0,.69444,.12945,0,.35555],$d=[0,.69444,0,0,.94888],Bl=[0,.69444,.11472,0,.59111],Vd=[0,.68611,.10778,0,.88555],qd=[0,.69444,.07939,0,.62055],xa=[0,.69444,.12417,0,.30667],Ar=[0,.64444,.13556,0,.51111],Hd=[.19444,.64444,.13556,0,.51111],va=[0,.68333,.16389,0,.74333],Wd=[.19444,.43056,.08847,0,.46],Ud=[0,.43056,.07514,0,.71555],Gd=[0,.69444,.06646,0,.51111],jd=[0,.69444,0,0,.83129],Jd=[0,.69444,.1225,0,.51111],Xd=[0,.68333,.09403,0,.76666],Zd=[0,.68333,.11111,0,.76666],Yd=[0,.69444,.06961,0,.51444],tr=[0,.69444,0,0,.27778],qi=[.25,.75,0,0,.38889],it=[0,.64444,0,0,.5],oi=[0,.69444,0,0,.77778],ai=[0,.68333,0,0,.75],Fn=[0,.68333,0,0,.77778],Qd=[0,.68333,0,0,.68056],$n=[0,.68333,0,0,.72222],rr=[.25,.75,0,0,.5],_a=[.25,.75,0,0,.27778],ke=[0,.69444,0,0,.5],Hi=[0,.69444,0,0,.55556],Kl=[0,.43056,0,0,.44445],Vn=[0,.43056,0,0,.5],em=[.19444,.43056,0,0,.55556],tm=[0,.43056,0,0,.55556],nt=[.08333,.58333,0,0,.77778],rm=[0,.43056,0,0,.27778],im=[0,.66786,0,0,.27778],nm=[0,.69444,0,0,.75],om=[0,.66786,0,0,.5],am=[0,.68333,0,0,.625],Pl=[.19444,.69444,0,0,.44445],qn=[0,.69444,0,0,.72222],sm=[.19444,.69444,0,0,.5],Hn=[.19444,.69444,0,0,1],lm=[.011,.511,0,0,1.126],Rl=[.19444,.69444,0,0,.61111],Il=[.05556,.75,0,0,.5],cm=[0,.68333,0,0,.83334],um=[.0391,.5391,0,0,.66667],zl=[-.05555,.44445,0,0,.5],dm=[0,.43056,0,0,.77778],si=[0,.55556,0,0,.66667],Ma=[-.03625,.46375,0,0,.77778],mm=[-.01688,.48312,0,0,.77778],hm=[.0391,.5391,0,0,1],Cr=[0,.69444,0,0,.61111],wa=[-.03472,.46528,0,0,.5],Sa=[.25,.75,0,0,.44445],pm=[-.14236,.35764,0,0,1],ka=[.244,.744,0,0,.412],fm=[.19444,.69444,0,0,.88889],La=[.12963,.69444,0,0,.77778],gm=[.19444,.69444,0,0,.38889],bm=[.011,.511,0,0,1.638],ym=[.19444,.69444,0,0,0],Aa=[0,.44444,0,0,.575],Wn=[.19444,.44444,0,0,.575],xm=[0,.68611,0,0,.75555],vm=[0,.69444,0,0,.66759],_m=[0,.68611,0,0,.80555],Mm=[0,.68611,.08229,0,.98229],wm=[0,.68611,0,0,.76666],Sm=[0,.44444,0,0,.58472],km=[.19444,.44444,0,0,.6118],Un=[.19444,.43056,0,0,.5],Lm=[0,.68333,.02778,.08334,.76278],Am=[0,.68333,.08125,.05556,.83125],Cm=[0,.43056,0,.05556,.48472],Em=[.19444,.43056,0,.08334,.51702],Tm=[.25,.75,0,0,.42778],Ce=[0,.69444,0,0,.55],ir=[0,.69444,0,0,.73334],Er=[0,.69444,0,0,.79445],Dm=[0,.69444,0,0,.51945],Nl=[0,.69444,0,0,.70278],Om=[0,.69444,0,0,.76389],Bm=[.25,.75,0,0,.34306],Fl=[0,.69444,0,0,.56111],Km=[0,.69444,0,0,.25556],Pm=[.19444,.45833,0,0,.56111],Rm=[0,.45833,0,0,.56111],Ca=[0,.69444,0,0,.30556],Im=[0,.69444,0,0,.58056],zm=[0,.69444,0,0,.67223],$l=[0,.69444,0,0,.85556],Vl=[0,.69444,0,0,.55834],Kt=[0,.65556,.11156,0,.5],ql=[0,.69444,.08094,0,.70834],Hl=[.17014,0,0,0,.44445],Nm=[0,.69444,.0799,0,.5],Fm=[0,.69444,0,0,.73752],$m=[0,.69444,.09205,0,.5],Vm=[0,.69444,.09031,0,.77778],Wl=[0,.69444,.07816,0,.27778],qm=[0,.69444,.00316,0,.5],Hm=[.19444,.69444,0,0,.83334],Wm=[.05556,.75,0,0,.83334],Um=[0,.75,0,0,.5],Gm=[.125,.08333,0,0,.27778],jm=[0,.08333,0,0,.27778],Pt=[0,.65556,0,0,.5],Ul=[0,.69444,0,0,.47222],nr=[0,.69444,0,0,.66667],Jm=[0,.69444,0,0,.59722],Gl=[0,.69444,0,0,.54167],jl=[0,.69444,0,0,.70834],Xm=[.25,.75,0,0,.28889],Jl=[0,.69444,0,0,.51667],Zm=[0,.44444,0,0,.44445],Ym=[.19444,.44444,0,0,.51667],Qm=[0,.44444,0,0,.38333],e0=[0,.44444,0,0,.51667],t0=[0,.69444,0,0,.83334],r0=[.35001,.85,0,0,.45834],i0=[.35001,.85,0,0,.57778],n0=[.35001,.85,0,0,.41667],o0=[.35001,.85,0,0,.58334],Ea=[0,.72222,0,0,.55556],a0=[1e-5,.6,0,0,.66667],s0=[1e-5,.6,0,0,.77778],l0=[.25001,.75,0,0,.94445],c0=[.306,.805,.19445,0,.47222],u0=[.30612,.805,.19445,0,.47222],Wi=[.25001,.75,0,0,.83334],Ui=[.35001,.85,0,0,.47222],Xl=[.25001,.75,0,0,1.11111],d0=[.65002,1.15,0,0,.59722],m0=[.65002,1.15,0,0,.81111],h0=[.65002,1.15,0,0,.47222],p0=[.65002,1.15,0,0,.66667],Ta=[0,.75,0,0,1],f0=[.55001,1.05,0,0,1.27778],g0=[.862,1.36,.44445,0,.55556],b0=[.86225,1.36,.44445,0,.55556],Gi=[.55001,1.05,0,0,1.11111],Da=[.65002,1.15,0,0,.52778],y0=[.65002,1.15,0,0,.61111],Zl=[.55001,1.05,0,0,1.51112],x0=[.95003,1.45,0,0,.73611],v0=[.95003,1.45,0,0,1.04445],_0=[.95003,1.45,0,0,.52778],Oa=[.95003,1.45,0,0,.75],Ba=[0,.75,0,0,1.44445],Ka=[.95003,1.45,0,0,.58334],M0=[1.25003,1.75,0,0,.79167],w0=[1.25003,1.75,0,0,1.27778],S0=[1.25003,1.75,0,0,.58334],Pa=[1.25003,1.75,0,0,.80556],Ra=[0,.825,0,0,1.8889],Ia=[1.25003,1.75,0,0,.63889],za=[.64502,1.155,0,0,.875],k0=[1e-5,.6,0,0,.875],Yl=[-99e-5,.601,0,0,.66667],Na=[.64502,1.155,0,0,.66667],L0=[1e-5,.9,0,0,.88889],A0=[.65002,1.15,0,0,.88889],C0=[.90001,0,0,0,.88889],E0=[-.00499,.605,0,0,1.05556],Fa=[0,.12,0,0,.45],B=[0,.61111,0,0,.525],ht=[.08333,.69444,0,0,.525],T0=[-.08056,.53055,0,0,.525],D0=[-.05556,.55556,0,0,.525],Re=[0,.43056,0,0,.525],Gn=[.22222,.43056,0,0,.525],O0=[0,0,0,0,.525],B0={"AMS-Regular":{32:Z,65:tt,66:ri,67:tt,68:tt,69:ri,70:ea,71:xl,72:xl,73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:xl,76:ri,77:[0,.68889,0,0,.94445],78:tt,79:Hu,80:ea,81:Hu,82:tt,83:Pn,84:ri,85:tt,86:tt,87:[0,.68889,0,0,1],88:tt,89:tt,90:ri,107:Pn,160:Z,165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:Pn,295:ta,710:Wu,732:Uu,770:Wu,771:Uu,989:vr,1008:hd,8245:[0,.54986,0,0,.275],8463:ta,8487:tt,8498:Pn,8502:ri,8503:[0,.68889,0,0,.44445],8504:ri,8513:[0,.68889,0,0,.63889],8592:vl,8594:vl,8602:Be,8603:Be,8606:ra,8608:ra,8610:Gu,8611:Gu,8619:ju,8620:ju,8621:[-.13313,.37788,0,0,1.38889],8622:Be,8624:ia,8625:ia,8630:_l,8631:_l,8634:xr,8635:xr,8638:na,8639:na,8642:na,8643:na,8644:oa,8646:oa,8647:oa,8648:Ju,8649:oa,8650:Ju,8651:ra,8652:ra,8653:Be,8654:Be,8655:Be,8666:Xu,8667:Xu,8669:[-.13313,.37788,0,0,1],8672:Zu,8674:Zu,8705:[0,.825,0,0,.5],8708:Pn,8709:vr,8717:[0,.43056,0,0,.42917],8722:vl,8724:[.08198,.69224,0,0,.77778],8726:vr,8733:sa,8736:Rn,8737:Rn,8738:[.03517,.52239,0,0,.72222],8739:dd,8740:[.25142,.74111,0,0,.27778],8741:md,8742:[.25142,.74111,0,0,.5],8756:Ml,8757:Ml,8764:aa,8765:[-.13313,.37788,0,0,.77778],8769:aa,8770:Ma,8774:dt,8776:mm,8778:vr,8782:Yu,8783:Yu,8785:xr,8786:xr,8787:xr,8790:sa,8791:In,8796:[.08198,.91667,0,0,.77778],8806:Ii,8807:Ii,8808:Dt,8809:Dt,8812:[.25583,.75583,0,0,.5],8814:zi,8815:zi,8816:dt,8817:dt,8818:In,8819:In,8822:Qu,8823:Qu,8828:Ot,8829:Ot,8830:In,8831:In,8832:zi,8833:zi,8840:dt,8841:dt,8842:qe,8843:qe,8847:_r,8848:_r,8858:xr,8859:xr,8861:xr,8862:Ni,8863:Ni,8864:Ni,8865:Ni,8872:[0,.69224,0,0,.61111],8873:Rn,8874:[0,.69224,0,0,.88889],8876:ea,8877:ea,8878:tt,8879:tt,8882:_r,8883:_r,8884:Ot,8885:Ot,8888:[0,.54986,0,0,1.11111],8890:em,8891:ed,8892:ed,8901:[0,.54986,0,0,.27778],8903:vr,8905:vr,8906:vr,8907:sa,8908:sa,8909:[-.03598,.46402,0,0,.77778],8910:td,8911:td,8912:_r,8913:_r,8914:rd,8915:rd,8916:Ml,8918:Mr,8919:Mr,8920:id,8921:id,8922:nd,8923:nd,8926:Ot,8927:Ot,8928:dt,8929:dt,8934:la,8935:la,8936:la,8937:la,8938:zi,8939:zi,8940:dt,8941:dt,8994:od,8995:od,9416:[.15559,.69224,0,0,.90222],9484:ia,9488:ia,9492:ad,9496:ad,9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:Ni,9633:Ni,9650:ca,9651:ca,9654:_r,9660:ca,9661:ca,9664:_r,9674:ld,9733:[.19444,.69224,0,0,.94445],10003:sd,10016:sd,10731:ld,10846:[.19444,.75583,0,0,.61111],10877:Ot,10878:Ot,10885:Ii,10886:Ii,10887:qe,10888:qe,10889:Fi,10890:Fi,10891:cd,10892:cd,10901:Ot,10902:Ot,10933:Dt,10934:Dt,10935:Fi,10936:Fi,10937:Fi,10938:Fi,10949:Ii,10950:Ii,10955:ud,10956:ud,57350:dd,57351:md,57352:vr,57353:hd,57356:Dt,57357:Dt,57358:pd,57359:dt,57360:dt,57361:pd,57366:Dt,57367:Dt,57368:Dt,57369:Dt,57370:qe,57371:qe},"Caligraphic-Regular":{32:Z,65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:Z},"Fraktur-Regular":{32:Z,33:[0,.69141,0,0,.29574],34:Sl,38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:fd,41:fd,42:[0,.62119,0,0,.27764],43:gd,44:bd,45:gd,46:bd,47:[.24982,.74947,0,0,.50181],48:wl,49:wl,50:wl,51:zn,52:zn,53:zn,54:yd,55:zn,56:yd,57:zn,58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:xd,93:xd,94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:Z,8216:Sl,8217:Sl,58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:Z,33:[0,.69444,0,0,.35],34:Al,35:[.19444,.69444,0,0,.95833],36:Ed,37:[.05556,.75,0,0,.95833],38:da,39:Vi,40:ua,41:ua,42:[0,.75,0,0,.575],43:mt,44:[.19444,.15556,0,0,.31944],45:Qm,46:[0,.15556,0,0,.31944],47:wr,48:rt,49:rt,50:rt,51:rt,52:rt,53:rt,54:rt,55:rt,56:rt,57:rt,58:Md,59:[.19444,.44444,0,0,.31944],60:$i,61:Od,62:$i,63:[0,.69444,0,0,.54305],64:da,65:kl,66:[0,.68611,0,0,.81805],67:pa,68:[0,.68611,0,0,.88194],69:xm,70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:ma,73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:Sd,77:[0,.68611,0,0,1.09166],78:ma,79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:kl,89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:ha,92:wr,93:ha,94:Sr,95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:ii,99:_d,100:ii,101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:ii,105:Vi,106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:Vi,109:[0,.44444,0,0,.95833],110:vd,111:Aa,112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:vd,118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:_d,123:wr,124:ha,125:wr,126:[.35,.34444,0,0,.575],160:Z,163:[0,.69444,0,0,.86853],168:Sr,172:[0,.44444,0,0,.76666],176:wd,177:mt,184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:mt,216:[.04861,.73472,0,0,.89444],223:Jm,230:[0,.44444,0,0,.83055],247:mt,248:[.09722,.54167,0,0,.575],305:Md,338:[0,.68611,0,0,1.16944],339:Dd,567:[.19444,.44444,0,0,.35139],710:Sr,711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:Sr,715:Sr,728:Sr,729:Vi,730:wd,732:Sr,733:Sr,915:Sd,916:Cl,920:Ll,923:_m,926:wm,928:ma,931:pa,933:Ll,934:pa,936:Ll,937:pa,8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:Vi,8217:Vi,8220:Al,8221:Al,8224:kd,8225:kd,8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:vm,8465:Ld,8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:Ld,8501:Dl,8592:Bt,8593:Ad,8594:Bt,8595:Ad,8596:Bt,8597:wr,8598:Nn,8599:Nn,8600:Nn,8601:Nn,8636:Bt,8637:Bt,8640:Bt,8641:Bt,8656:Bt,8657:Cd,8658:Bt,8659:Cd,8660:Bt,8661:[.25,.75,0,0,.70277],8704:ii,8706:[0,.69444,.06389,0,.62847],8707:ii,8709:Ed,8711:Cl,8712:Td,8715:Td,8722:mt,8723:mt,8725:wr,8726:wr,8727:fa,8728:El,8729:El,8730:[.18,.82,0,0,.95833],8733:Dd,8734:[0,.44444,0,0,1.14999],8736:Rn,8739:ha,8741:wr,8743:ni,8744:ni,8745:ni,8746:ni,8747:[.19444,.69444,.12778,0,.56875],8764:Od,8768:[.19444,.69444,0,0,.31944],8771:Tl,8776:[.02444,.52444,0,0,.89444],8781:Tl,8801:Tl,8804:kr,8805:kr,8810:Bd,8811:Bd,8826:$i,8827:$i,8834:$i,8835:$i,8838:kr,8839:kr,8846:ni,8849:kr,8850:kr,8851:ni,8852:ni,8853:mt,8854:mt,8855:mt,8856:mt,8857:mt,8866:Dl,8867:Dl,8868:da,8869:da,8900:El,8901:[-.02639,.47361,0,0,.31944],8902:fa,8968:ga,8969:ga,8970:ga,8971:ga,8994:Kd,8995:Kd,9651:Pd,9657:fa,9661:Pd,9667:fa,9711:Nn,9824:ba,9825:ba,9826:ba,9827:ba,9837:[0,.75,0,0,.44722],9838:Rd,9839:Rd,10216:ua,10217:ua,10815:ma,10927:kr,10928:kr,57376:ym},"Main-BoldItalic":{32:Z,33:[0,.69444,.11417,0,.38611],34:qd,35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:ya,40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:Lr,49:Lr,50:Lr,51:Lr,52:Id,53:Lr,54:Lr,55:Id,56:Lr,57:Lr,58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:Bl,64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:Ol,73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:Ol,79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:Fd,95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:zd,104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:zd,114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:Z,168:[0,.69444,.11473,0,.59111],176:$d,184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:Nd,248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:Nd,567:[.19444,.44444,.04611,0,.385],710:Fd,711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:ya,730:$d,732:Bl,733:Bl,915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:Ol,931:[0,.68611,.11431,0,.82666],933:Vd,934:[0,.68611,.05632,0,.82666],936:Vd,937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:ya,8217:ya,8220:[0,.69444,.16772,0,.62055],8221:qd},"Main-Italic":{32:Z,33:xa,34:Yd,35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:xa,40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:Ar,49:Ar,50:Ar,51:Ar,52:Hd,53:Ar,54:Ar,55:Hd,56:Ar,57:Ar,58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:Jd,64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:va,73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:va,79:Xd,80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:va,86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:Gd,95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:Wd,104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:Wd,114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:Z,168:[0,.66786,.10474,0,.51111],176:jd,184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:Ud,248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:Ud,710:Gd,711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:jd,732:[0,.66786,.11585,0,.51111],733:Jd,915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:Xd,923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:va,931:[0,.68333,.12028,0,.71555],933:Zd,934:[0,.68333,.05986,0,.71555],936:Zd,937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:xa,8217:xa,8220:[0,.69444,.1685,0,.51444],8221:Yd,8463:ta},"Main-Regular":{32:Z,33:tr,34:ke,35:Hm,36:Il,37:Wm,38:oi,39:tr,40:qi,41:qi,42:Um,43:nt,44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:rr,48:it,49:it,50:it,51:it,52:it,53:it,54:it,55:it,56:it,57:it,58:rm,59:[.19444,.43056,0,0,.27778],60:Mr,61:aa,62:Mr,63:Ul,64:oi,65:ai,66:[0,.68333,0,0,.70834],67:$n,68:[0,.68333,0,0,.76389],69:Qd,70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:ai,73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:Fn,76:am,77:[0,.68333,0,0,.91667],78:ai,79:Fn,80:Qd,81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:$n,85:ai,86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:ai,89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:_a,92:rr,93:_a,94:ke,95:[.31,.12056,.02778,0,.5],97:Vn,98:Hi,99:Kl,100:Hi,101:Kl,102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:Hi,105:im,106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:tr,109:[0,.43056,0,0,.83334],110:tm,111:Vn,112:em,113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:tm,118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:Kl,123:rr,124:_a,125:rr,126:[.35,.31786,0,0,.5],160:Z,163:[0,.69444,0,0,.76909],167:Pl,168:om,172:[0,.43056,0,0,.66667],176:nm,177:nt,182:Rl,184:Hl,198:[0,.68333,0,0,.90278],215:nt,216:[.04861,.73194,0,0,.77778],223:ke,230:[0,.43056,0,0,.72222],247:nt,248:[.09722,.52778,0,0,.5],305:rm,338:[0,.68333,0,0,1.01389],339:dm,567:[.19444,.43056,0,0,.30556],710:ke,711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:ke,715:ke,728:ke,729:im,730:nm,732:om,733:ke,915:am,916:cm,920:Fn,923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:ai,931:$n,933:Fn,934:$n,936:Fn,937:$n,8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:tr,8217:tr,8220:ke,8221:ke,8224:Pl,8225:Pl,8230:[0,.12,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:ta,8465:qn,8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:qn,8501:Cr,8592:Be,8593:sm,8594:Be,8595:sm,8596:Be,8597:rr,8598:Hn,8599:Hn,8600:Hn,8601:Hn,8614:[.011,.511,0,0,1],8617:lm,8618:lm,8636:Be,8637:Be,8640:Be,8641:Be,8652:[.011,.671,0,0,1],8656:Be,8657:Rl,8658:Be,8659:Rl,8660:Be,8661:[.25,.75,0,0,.61111],8704:Hi,8706:[0,.69444,.05556,.08334,.5309],8707:Hi,8709:Il,8711:cm,8712:um,8715:um,8722:nt,8723:nt,8725:rr,8726:rr,8727:wa,8728:zl,8729:zl,8730:[.2,.8,0,0,.83334],8733:dm,8734:_l,8736:Rn,8739:_a,8741:rr,8743:si,8744:si,8745:si,8746:si,8747:[.19444,.69444,.11111,0,.41667],8764:aa,8768:[.19444,.69444,0,0,.27778],8771:Ma,8773:[-.022,.589,0,0,1],8776:mm,8781:Ma,8784:[-.133,.67,0,0,.778],8801:Ma,8804:qe,8805:qe,8810:hm,8811:hm,8826:Mr,8827:Mr,8834:Mr,8835:Mr,8838:qe,8839:qe,8846:si,8849:qe,8850:qe,8851:si,8852:si,8853:nt,8854:nt,8855:nt,8856:nt,8857:nt,8866:Cr,8867:Cr,8868:oi,8869:oi,8872:[.249,.75,0,0,.867],8900:zl,8901:[-.05555,.44445,0,0,.27778],8902:wa,8904:[.005,.505,0,0,.9],8942:[.03,.9,0,0,.278],8943:[-.19,.31,0,0,1.172],8945:[-.1,.82,0,0,1.282],8968:Sa,8969:Sa,8970:Sa,8971:Sa,8994:pm,8995:pm,9136:ka,9137:ka,9651:fm,9657:wa,9661:fm,9667:wa,9711:Hn,9824:La,9825:La,9826:La,9827:La,9837:[0,.75,0,0,.38889],9838:gm,9839:gm,10216:qi,10217:qi,10222:ka,10223:ka,10229:[.011,.511,0,0,1.609],10230:bm,10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:bm,10815:ai,10927:qe,10928:qe,57376:ym},"Math-BoldItalic":{32:Z,48:Aa,49:Aa,50:Aa,51:Wn,52:Wn,53:Wn,54:rt,55:Wn,56:rt,57:Wn,65:kl,66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:Mm,73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:xm,77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:vm,105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:Sm,112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:Z,915:[0,.68611,.15972,0,.65694],916:Cl,920:[0,.68611,.03194,0,.86722],923:_m,926:[0,.68611,.07458,0,.84125],928:Mm,931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:wm,936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:Sm,960:[0,.44444,.03704,0,.68241],961:km,962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:km,1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:Z,48:Vn,49:Vn,50:Vn,51:Un,52:Un,53:Un,54:it,55:Un,56:it,57:Un,65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:Am,73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:Lm,80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:Cm,112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:Z,915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:Lm,923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:Am,931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:Cm,960:[0,.43056,.03588,0,.57003],961:Em,962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:Em,1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:Z,33:[0,.69444,0,0,.36667],34:Vl,35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:Ca,40:Tm,41:Tm,42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:Ce,49:Ce,50:Ce,51:Ce,52:Ce,53:Ce,54:Ce,55:Ce,56:Ce,57:Ce,58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:Dm,64:ir,65:ir,66:ir,67:Nl,68:Er,69:[0,.69444,0,0,.64167],70:Cr,71:ir,72:Er,73:[0,.69444,0,0,.33056],74:Dm,75:Om,76:Im,77:[0,.69444,0,0,.97778],78:Er,79:Er,80:Nl,81:[.10556,.69444,0,0,.79445],82:Nl,83:Cr,84:ir,85:Om,86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:ir,89:[0,.69444,.0275,0,.73334],90:zm,91:Bm,93:Bm,94:Ce,95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:Fl,99:[0,.45833,0,0,.48889],100:Fl,101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:Fl,105:Km,106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:Km,109:[0,.45833,0,0,.86667],110:Rm,111:[0,.45833,0,0,.55],112:Pm,113:Pm,114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:Rm,118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:Z,168:Ce,176:ir,180:Ce,184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:Ce,711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:Ce,729:Ca,730:ir,732:Ce,733:Ce,915:Im,916:[0,.69444,0,0,.91667],920:$l,923:zm,926:ir,928:Er,931:Er,933:$l,934:Er,936:$l,937:Er,8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:Ca,8217:Ca,8220:Vl,8221:Vl},"SansSerif-Italic":{32:Z,33:[0,.69444,.05733,0,.31945],34:qm,35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:Wl,40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:Gm,45:[0,.44444,.01946,0,.33333],46:jm,47:[.25,.75,.13164,0,.5],48:Kt,49:Kt,50:Kt,51:Kt,52:Kt,53:Kt,54:Kt,55:Kt,56:Kt,57:Kt,58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:nr,66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:ql,73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:Gl,77:[0,.69444,.08094,0,.875],78:ql,79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:Nm,95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:Z,168:[0,.67937,.06385,0,.5],176:Fm,184:Hl,305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:Nm,711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:$m,715:ke,728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:Fm,732:[0,.67659,.08826,0,.5],733:$m,915:[0,.69444,.13372,0,.54167],916:t0,920:[0,.69444,.07555,0,.77778],923:Cr,926:[0,.69444,.12816,0,.66667],928:ql,931:[0,.69444,.11983,0,.72222],933:Vm,934:[0,.69444,.04603,0,.72222],936:Vm,937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:Wl,8217:Wl,8220:[0,.69444,.14205,0,.5],8221:qm},"SansSerif-Regular":{32:Z,33:[0,.69444,0,0,.31945],34:ke,35:Hm,36:Il,37:Wm,38:[0,.69444,0,0,.75834],39:tr,40:qi,41:qi,42:Um,43:nt,44:Gm,45:[0,.44444,0,0,.33333],46:jm,47:rr,48:Pt,49:Pt,50:Pt,51:Pt,52:Pt,53:Pt,54:Pt,55:Pt,56:Pt,57:Pt,58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:Ul,64:nr,65:nr,66:nr,67:ii,68:[0,.69444,0,0,.72223],69:Jm,70:[0,.69444,0,0,.56945],71:nr,72:jl,73:tr,74:Ul,75:[0,.69444,0,0,.69445],76:Gl,77:[0,.69444,0,0,.875],78:jl,79:[0,.69444,0,0,.73611],80:ii,81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:Hi,84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:nr,89:[0,.69444,.025,0,.66667],90:Cr,91:Xm,93:Xm,94:ke,95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:Jl,99:Zm,100:Jl,101:Zm,102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:Jl,105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:e0,111:[0,.44444,0,0,.5],112:Ym,113:Ym,114:[0,.44444,.01389,0,.34167],115:Qm,116:[0,.57143,0,0,.36111],117:e0,118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:Z,168:[0,.67937,0,0,.5],176:nr,184:Hl,305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:ke,711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:ke,715:ke,728:ke,729:[0,.67937,0,0,.27778],730:nr,732:[0,.67659,0,0,.5],733:ke,915:Gl,916:t0,920:oi,923:Cr,926:nr,928:jl,931:qn,933:oi,934:qn,936:oi,937:qn,8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:tr,8217:tr,8220:ke,8221:ke},"Script-Regular":{32:Z,65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:Z},"Size1-Regular":{32:Z,40:r0,41:r0,47:i0,91:n0,92:i0,93:n0,123:o0,125:o0,160:Z,710:Ea,732:Ea,770:Ea,771:Ea,8214:[-99e-5,.601,0,0,.77778],8593:a0,8595:a0,8657:s0,8659:s0,8719:l0,8720:l0,8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:u0,8748:c0,8749:c0,8750:u0,8896:Wi,8897:Wi,8898:Wi,8899:Wi,8968:Ui,8969:Ui,8970:Ui,8971:Ui,9168:Yl,10216:Ui,10217:Ui,10752:Xl,10753:Xl,10754:Xl,10756:Wi,10758:Wi},"Size2-Regular":{32:Z,40:d0,41:d0,47:m0,91:h0,92:m0,93:h0,123:p0,125:p0,160:Z,710:Ta,732:Ta,770:Ta,771:Ta,8719:f0,8720:f0,8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:b0,8748:g0,8749:g0,8750:b0,8896:Gi,8897:Gi,8898:Gi,8899:Gi,8968:Da,8969:Da,8970:Da,8971:Da,10216:y0,10217:y0,10752:Zl,10753:Zl,10754:Zl,10756:Gi,10758:Gi},"Size3-Regular":{32:Z,40:x0,41:x0,47:v0,91:_0,92:v0,93:_0,123:Oa,125:Oa,160:Z,710:Ba,732:Ba,770:Ba,771:Ba,8730:[.95003,1.45,0,0,1],8968:Ka,8969:Ka,8970:Ka,8971:Ka,10216:Oa,10217:Oa},"Size4-Regular":{32:Z,40:M0,41:M0,47:w0,91:S0,92:w0,93:S0,123:Pa,125:Pa,160:Z,710:Ra,732:Ra,770:Ra,771:Ra,8730:[1.25003,1.75,0,0,1],8968:Ia,8969:Ia,8970:Ia,8971:Ia,9115:za,9116:k0,9117:za,9118:za,9119:k0,9120:za,9121:Na,9122:Yl,9123:Na,9124:Na,9125:Yl,9126:Na,9127:L0,9128:A0,9129:C0,9130:[0,.3,0,0,.88889],9131:L0,9132:A0,9133:C0,9143:[.88502,.915,0,0,1.05556],10216:Pa,10217:Pa,57344:E0,57345:E0,57680:Fa,57681:Fa,57682:Fa,57683:Fa},"Typewriter-Regular":{32:O0,33:B,34:B,35:B,36:ht,37:ht,38:B,39:B,40:ht,41:ht,42:[0,.52083,0,0,.525],43:T0,44:[.13889,.125,0,0,.525],45:T0,46:[0,.125,0,0,.525],47:ht,48:B,49:B,50:B,51:B,52:B,53:B,54:B,55:B,56:B,57:B,58:Re,59:[.13889,.43056,0,0,.525],60:D0,61:[-.19549,.41562,0,0,.525],62:D0,63:B,64:B,65:B,66:B,67:B,68:B,69:B,70:B,71:B,72:B,73:B,74:B,75:B,76:B,77:B,78:B,79:B,80:B,81:[.13889,.61111,0,0,.525],82:B,83:B,84:B,85:B,86:B,87:B,88:B,89:B,90:B,91:ht,92:ht,93:ht,94:B,95:[.09514,0,0,0,.525],96:B,97:Re,98:B,99:Re,100:B,101:Re,102:B,103:Gn,104:B,105:B,106:[.22222,.61111,0,0,.525],107:B,108:B,109:Re,110:Re,111:Re,112:Gn,113:Gn,114:Re,115:Re,116:[0,.55358,0,0,.525],117:Re,118:Re,119:Re,120:Re,121:Gn,122:Re,123:ht,124:ht,125:ht,126:B,127:B,160:O0,176:B,184:[.19445,0,0,0,.525],305:Re,567:Gn,711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:B,715:B,728:B,730:B,770:B,771:B,776:B,915:B,916:B,920:B,923:B,926:B,928:B,931:B,933:B,934:B,936:B,937:B,8216:B,8217:B,8242:B,9251:[.11111,.21944,0,0,.525]}};var kf=/[\u3040-\u309F]|[\u30A0-\u30FF]|[\u4E00-\u9FAF]|[\uAC00-\uD7AF]/,Rt=10,Ie=.25,P0=1.2,Xe=.431,Ql={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[Xe,Xe,Xe],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.5,.732,.925],num2:[.394,.384,.5],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[Ie,Ie,Ie],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04]},jn=[0,.5,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],ji=5,K0={"\xA0":" ","\u200B":" ",\u00C5:"A",\u00C7:"C",\u00D0:"D",\u00DE:"o",\u00E5:"a",\u00E7:"c",\u00F0:"d",\u00FE:"o",\u0410:"A",\u0411:"B",\u0412:"B",\u0413:"F",\u0414:"A",\u0415:"E",\u0416:"K",\u0417:"3",\u0418:"N",\u0419:"N",\u041A:"K",\u041B:"N",\u041C:"M",\u041D:"H",\u041E:"O",\u041F:"N",\u0420:"P",\u0421:"C",\u0422:"T",\u0423:"y",\u0424:"O",\u0425:"X",\u0426:"U",\u0427:"h",\u0428:"W",\u0429:"W",\u042A:"B",\u042B:"X",\u042C:"B",\u042D:"3",\u042E:"X",\u042F:"R",\u0430:"a",\u0431:"b",\u0432:"a",\u0433:"r",\u0434:"y",\u0435:"e",\u0436:"m",\u0437:"e",\u0438:"n",\u0439:"n",\u043A:"n",\u043B:"n",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"n",\u0440:"p",\u0441:"c",\u0442:"o",\u0443:"y",\u0444:"b",\u0445:"x",\u0446:"n",\u0447:"n",\u0448:"w",\u0449:"w",\u044A:"a",\u044B:"m",\u044C:"a",\u044D:"e",\u044E:"m",\u044F:"r"};function Tr(t,e){t===void 0&&(t=77);let r=B0[e][t];if(r)return{defaultMetrics:!1,depth:r[0],height:r[1],italic:r[2],skew:r[3],width:r[4]};if(t===11034)return{defaultMetrics:!0,depth:.2,height:.8,italic:0,skew:0,width:.8};let i=String.fromCodePoint(t);if(i in K0)t=K0[i].codePointAt(0);else if(kf.test(i))return t=77,{defaultMetrics:!0,depth:.2,height:.9,italic:0,skew:0,width:1};return{defaultMetrics:!0,depth:.2,height:.7,italic:0,skew:0,width:.8}}var ec={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],longrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],longleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],longleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],longrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],longleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xleftrightarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],longleftrightarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xRightleftharpoons:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],longRightleftharpoons:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xLeftrightharpoons:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716],longLeftrightharpoons:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},tc={widehat1:[1062,239,.24],widehat2:[2364,300,.3],widehat3:[2364,360,.36],widehat4:[2364,420,.42],widecheck1:[1062,239,.24],widecheck2:[2364,300,.3],widecheck3:[2364,360,.36],widecheck4:[2364,420,.42],widetilde1:[600,260,.26],widetilde2:[1033,286,.286],widetilde3:[2339,306,.306],widetilde4:[2340,312,.34],overarc:[1061,159,.3],underarc:[1061,159,.3]},R0={doubleleftarrow:`M262 157 +l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3 + 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28 + 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5 +c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5 + 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87 +-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7 +-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z +m8 0v40h399730v-40zm0 194v40h399730v-40z`,doublerightarrow:`M399738 392l +-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5 + 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88 +-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68 +-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18 +-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782 +c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3 +-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,leftarrow:`M400000 241H110l3-3c68.7-52.7 113.7-120 + 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8 +-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247 +c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208 + 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3 + 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202 + l-3-3h399890zM100 241v40h399900v-40z`,leftbrace:`M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117 +-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7 + 5-6 9-10 13-.7 1-7.3 1-20 1H6z`,leftbraceunder:`M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13 + 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688 + 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7 +-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,overarc:"M529 0c179 0 524 115 524 115 5 1 9 5 9 10 0 1-1 2-1 3l-4 22c-1 5-5 9-11 9h-2s-338-93-512-92c-174 0-513 92-513 92h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13 0 0 342-115 520-115z",underarc:`m 529 160 + c -179 0 -524 -115 -524 -115 + c -5 -1 -9 -5 -9 -10 + c 0 -1 1 -2 1 -3 + l 4 -22 + c 1 -5 5 -9 11 -9 + h 2 + s 338 93 512 92 + c 174 0 513 -92 513 -92 + h 2 + c 5 0 9 4 11 9 + l 5 22 + c 1 6 -2 12 -8 13 + c 0 0 -342 115 -520 115 + z + `,leftgroup:`M400000 80 +H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0 + 435 0h399565z`,leftgroupunder:`M400000 262 +H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219 + 435 219h399565z`,leftharpoon:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3 +-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5 +-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7 +-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,leftharpoonplus:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5 + 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3 +-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7 +-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z +m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333 + 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5 + 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667 +-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,leftharpoondownplus:`M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12 + 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7 +-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0 +v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5 +-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3 +-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21 + 71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:`M40 281 V428 H0 V94 H40 V241 H400000 v40z +M40 281 V428 H0 V94 H40 V241 H400000 v40z`,leftmapsto:`M40 281 V448H0V74H40V241H400000v40z +M40 281 V448H0V74H40V241H400000v40z`,leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23 +-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8 +c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3 + 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:`M0 50 h400000 v40H0z m0 194h40000v40H0z +M0 50 h400000 v40H0z m0 194h40000v40H0z`,midbrace:`M200428 334 +c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14 +-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7 + 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11 + 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,midbraceunder:`M199572 214 +c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14 + 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3 + 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0 +-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,oiintSize1:`M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6 +-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z +m368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8 +60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z`,oiintSize2:`M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8 +-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z +m502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2 +c0 110 84 276 504 276s502.4-166 502.4-276z`,oiiintSize1:`M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6 +-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z +m525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0 +85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z`,oiiintSize2:`M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8 +-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z +m770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1 +c0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z`,rightarrow:`M0 241v40h399891c-47.3 35.3-84 78-110 128 +-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 + 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 + 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85 +-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 + 151.7 139 205zm0 0v40h399900v-40z`,rightbrace:`M400000 542l +-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5 +s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1 +c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,rightbraceunder:`M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3 + 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237 +-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,rightgroup:`M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0 + 3-1 3-3v-38c-76-158-257-219-435-219H0z`,rightgroupunder:`M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18 + 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,rightharpoon:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3 +-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2 +-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 + 69.2 92 94.5zm0 0v40h399900v-40z`,rightharpoonplus:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11 +-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7 + 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z +m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown:`M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8 + 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5 +-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95 +-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,rightharpoondownplus:`M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8 + 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 + 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3 +-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z +m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3 + 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0 +-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21 + 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z +M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`,rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23 + 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32 +-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142 +-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40 + 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69 +-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3 +-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19 +-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101 + 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,twoheadrightarrow:`M400000 167 +c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3 + 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42 + 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333 +-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70 + 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,widetilde1:`M200 55.538c-77 0-168 73.953-177 73.953-3 0-7 +-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0 + 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0 + 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128 +-68.267.847-113-73.952-191-73.952z`,widetilde2:`M344 55.266c-142 0-300.638 81.316-311.5 86.418 +-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9 + 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114 +c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751 + 181.476 676 181.476c-149 0-189-126.21-332-126.21z`,widetilde3:`M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457 +-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0 + 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697 + 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696 + -338 0-409-156.573-744-156.573z`,widetilde4:`M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345 +-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409 + 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9 + 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409 + -175.236-744-175.236z`,vec:`M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5 +3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11 +10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63 +-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1 +-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59 +H213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359 +c-16-25.333-24-45-24-59z`,widehat1:`M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22 +c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,widehat2:`M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat3:`M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat4:`M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widecheck1:`M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1, +-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z`,widecheck2:`M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck3:`M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck4:`M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,baraboveleftarrow:`M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202 +c4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5 +c-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130 +s-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47 +121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6 +s2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11 +c0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z +M100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z`,rightarrowabovebar:`M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32 +-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0 +13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39 +-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5 +-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 +151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z`,baraboveshortleftharpoon:`M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17 +c2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21 +c-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40 +c-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z +M0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z`,rightharpoonaboveshortbar:`M0,241 l0,40c399126,0,399993,0,399993,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z`,shortbaraboveleftharpoon:`M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9, +1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7, +-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z +M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`,shortrightharpoonabovebar:`M53,241l0,40c398570,0,399437,0,399437,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`};function I0(t){if(tc[t]){let[c,u,d]=tc[t],m=``;return`${m}`}let[e,r,i,n]=ec[t],o,a,s=i/1e3;e.length===3?(o=["slice-1-of-3","slice-2-of-3","slice-3-of-3"],a=["xMinYMin","xMidYMin","xMaxYMin"]):e.length===2?(o=["slice-1-of-2","slice-2-of-2"],a=["xMinYMin","xMaxYMin"]):(o=["slice-1-of-1"],a=[n]);let l=e.map((c,u)=>``).join("");return`${l}`}function z0(t){return ec[t]?ec[t][2]/1e3:tc[t][2]}function Lf(t){let e=[];for(let r=0;r=55296&&i<=56319){let n=t.charCodeAt(r+1);if(n>=56320&&n<=57343){let o=i-55296,a=n-56320;i=2**16+o*2**10+a,r++}}e.push(i)}return e}var Va=8205,Af=[[Va,1],[65038,2],[127995,5],[129456,4],[917536,96]],$a,N0=[127462,127487];function F0(t){var e;if($a===void 0){$a={};for(let r of Af)for(let i=r[0];i<=r[0]+r[1]-1;i++)$a[i]=!0}return(e=$a[t])!=null?e:!1}function Cf(t){return t>=N0[0]&&t<=N0[1]}function qa(t){if(/^[\u0020-\u00FF]*$/.test(t))return t;let e=[],r=Lf(t),i=0;for(;i=this.s.length}get(){return this.pos";let e=this.get();if(e==="\\"){if(!this.end()){let r=this.match(/^[a-zA-Z\*]+/);return r?this.match(/^[ \f\n\r\t\v\u00A0\u2028\u2029]*/):r=this.get(),"\\"+r}}else{if(e==="{")return"<{>";if(e==="}")return"<}>";if(e==="^"){if(this.peek()==="^"){this.get();let r=this.match(/^(\^(\^(\^(\^[\da-f])?[\da-f])?[\da-f])?[\da-f])?[\da-f]{2}/);if(r)return String.fromCodePoint(Number.parseInt(r.slice(r.lastIndexOf("^")+1),16))}return e}else if(e==="#"){if(!this.end()){let r=!1;if(/[\d?@]/.test(this.peek())&&(r=!0,this.pos+1"):"<$>"}return e}};function Ef(t,e){var n,o,a,s;let r=[],i=t.next();if(i&&i!=="\\relax"){if(i==="\\noexpand")i=t.next(),i&&r.push(i);else if(i==="\\obeyspaces")t.obeyspaces=!0;else if(i==="\\bgroup")r.push("<{>");else if(i==="\\egroup")r.push("<}>");else if(i==="\\string"){if(i=t.next(),i)if(i.startsWith("\\"))for(let l of i)r.push(l==="\\"?"\\backslash":l);else i==="<{>"?r.push("\\{"):i===""?r.push("~"):i==="<}>"&&r.push("\\}")}else if(i==="\\csname"){for(;t.peek()==="";)t.next();let l="",c=!1,u=[];do{if(u.length===0)if(/^#[\d?@]$/.test(t.peek())){let d=t.get().slice(1);u=Ji((o=(n=e==null?void 0:e(d))!=null?n:e==null?void 0:e("?"))!=null?o:"\\placeholder{}",e),i=u[0]}else i=t.next(),u=i?[i]:[];c=u.length===0,!c&&i==="\\endcsname"&&(c=!0,u.shift()),c||(c=i==="<$>"||i==="<$$>"||i==="<{>"||i==="<}>"||typeof i=="string"&&i.length>1&&i.startsWith("\\")),c||(l+=u.shift())}while(!c);l&&r.push("\\"+l),r.push(...u)}else if(i!=="\\endcsname")if(i.length>1&&i.startsWith("#")){let l=i.slice(1);r.push(...Ji((s=(a=e==null?void 0:e(l))!=null?a:e==null?void 0:e("?"))!=null?s:"\\placeholder{}",e))}else r.push(i)}return r}function Ji(t,e=null){if(!t)return[];let r=[],i="";for(let a of t.toString().split(/\r?\n/)){i&&r.push(i),i=" ";let s=a.match(/((?:\\%)|[^%])*/);s!==null&&r.push(s[0])}let n=new rc(r.join("")),o=[];do o.push(...Ef(n,e));while(!n.end());return o}function R(t){let e="",r=[];for(let i of t)i&&(e&&/^[a-zA-Z\*]/.test(i)&&r.push(e),r.push(i),/^\\[a-zA-Z]+\*?[\"\'][^\ ]+$/.test(i)&&r.push(" "),e=/\\[a-zA-Z]+\*?$/.test(i)?" ":"");return r.join("")}function U(t,...e){return t.startsWith("\\"),e.length===0?t:R([t,...e.map(r=>`{${r}}`)])}function Dr(t){return R(t.map(e=>{var r;return(r={"":" ","<$$>":"$$","<$>":"$","<{>":"{","<}>":"}"}[e])!=null?r:e}))}var li=class li{constructor(e){li._registry[e]=this}static createAtom(e,r,i){return li._registry[e].createAtom(r,ne(r,e),i)}static serialize(e,r){var i;if(!e||e.length===0)return"";if((i=r.skipStyles)!=null&&i){let n=[];for(let o of V0(e)){let a=li._registry[o[0].mode];n.push(...a.serialize(o,r))}return R(n)}return R(Df(e,r))}static getFont(e,r,i){return li._registry[e].getFont(r,i)}};li._registry={};var _e=li;function V0(t){let e=[],r=[],i="NONE";for(let n of t)n.type!=="first"&&(n.mode!==i?(r.length>0&&e.push(r),r=[n],i=n.mode):r.push(n));return r.length>0&&e.push(r),e}function Ha(t){if((t==null?void 0:t.mode)!=="math")return"";let{style:e}=t;return!e||!e.variantStyle?"":e.variantStyle==="bold"||e.variantStyle==="bolditalic"?"bold":""}function Wa(t){if(!t)return"";let{style:e}=t;if(!e)return"";let r=e.variant;return r===void 0&&(r="normal"),!["calligraphic","fraktur","double-struck","script","monospace","sans-serif"].includes(r)&&e.variantStyle&&(r+="-"+e.variantStyle),r}function pt(t,e){let r=[],i=[],n;for(let o of t){if(o.type==="first")continue;let a;e==="variant"?a=Wa(o):e==="bold"?a=Ha(o):a=o.style[e],a===n?i.push(o):(i.length>0&&r.push(i),i=[o],n=a)}return i.length>0&&r.push(i),r}function $0(t,e){var o;let{parent:r}=t[0],i=r==null?void 0:r.style.color,n=[];for(let a of V0(t)){let s=e.defaultMode;for(let l of pt(a,"color")){let c=l[0].style,u=_e._registry[l[0].mode].serialize(l,g(h({},e),{defaultMode:s==="text"?"text":"math"}));!e.skipStyles&&c.color&&c.color!=="none"&&(!r||i!==c.color)?n.push(U("\\textcolor",(o=c.verbatimColor)!=null?o:c.color,R(u))):n.push(R(u))}}return n}function Tf(t,e){let{parent:r}=t[0],i=r==null?void 0:r.style.backgroundColor;return pt(t,"backgroundColor").map(n=>{var o;if(n.length>0||n[0].type!=="box"){let a=n[0].style;if(a.backgroundColor&&a.backgroundColor!=="none"&&(!r||i!==a.backgroundColor))return U("\\colorbox",(o=a.verbatimBackgroundColor)!=null?o:a.backgroundColor,R($0(n,g(h({},e),{defaultMode:"text"}))))}return R($0(n,e))})}function Df(t,e){if(t.length===0)return[];let{parent:r}=t[0],i=r==null?void 0:r.style.fontSize,n=[];for(let o of pt(t,"fontSize")){let a=o[0].style.fontSize,s=Tf(o,e);s&&(a&&a!=="auto"&&(!r||i!==a)?n.push(["","\\tiny","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"][a],...s):n.push(...s))}return n}function Ua(t){return t?{mord:"ord",mbin:"bin",mop:"op",mrel:"rel",mopen:"open",mclose:"close",mpunct:"punct",minner:"inner",spacing:"ignore",latex:"latex",composition:"inner",error:"inner",placeholder:"ord",supsub:"ignore"}[t]:void 0}function ci(t){if(t.length===0)return"ord";let e=Ua(t[0].type),r=Ua(t[t.length-1].type);return e&&e===r?e:"ord"}function Jn(t,e){if(typeof t=="string")return t;if(typeof t=="number"){Number.isFinite(t);let r=Math.ceil(100*t)/100;return r===0?"0":r.toString()+(e!=null?e:"")}return""}var w=class t{constructor(e,r){var n,o,a,s,l;if(typeof e=="number"?this.value=String.fromCodePoint(e):typeof e=="string"?this.value=e:ee(e)?this.children=e.filter(c=>c!==null):e&&e instanceof t&&(this.children=[e]),this.children)for(let c of this.children)c.parent=this;this.type=(n=r==null?void 0:r.type)!=null?n:"ignore",this.isSelected=(r==null?void 0:r.isSelected)===!0,r!=null&&r.caret&&(this.caret=r.caret),this.classes=(o=r==null?void 0:r.classes)!=null?o:"",this.isTight=(a=r==null?void 0:r.isTight)!=null?a:!1,r!=null&&r.attributes&&(this.attributes=r.attributes);let i=r==null?void 0:r.fontFamily;r!=null&&r.style&&this.value&&(i=(l=_e.getFont((s=r.mode)!=null?s:"math",this,g(h({variant:"normal"},r.style),{letterShapeStyle:r.letterShapeStyle})))!=null?l:void 0),i||(i="Main-Regular"),this._height=0,this._depth=0,this._width=0,this.hasExplicitWidth=!1,this.skew=0,this.italic=0,this.maxFontSize=0,this.scale=1,(r==null?void 0:r.maxFontSize)!==void 0&&(this.maxFontSize=r.maxFontSize),Of(this,i)}set atomID(e){e===void 0||e.length===0||(this.id=e)}selected(e){if(this.isSelected!==e&&(this.isSelected=e,this.children))for(let r of this.children)r.selected(e)}setStyle(e,r,i){if(r===void 0)return;let n=Jn(r,i);n.length>0&&(this.cssProperties||(this.cssProperties={}),this.cssProperties[e]=n)}setTop(e){Number.isFinite(e)&&Math.abs(e)>.01&&(this.cssProperties||(this.cssProperties={}),this.cssProperties.top=Jn(e,"em"),this.height-=e,this.depth+=e)}get left(){var e;return(e=this.cssProperties)!=null&&e["margin-left"]?Number.parseFloat(this.cssProperties["margin-left"]):0}set left(e){Number.isFinite(e)&&(e===0?this.cssProperties&&delete this.cssProperties["margin-left"]:(this.cssProperties||(this.cssProperties={}),this.cssProperties["margin-left"]=Jn(e,"em")))}set right(e){Number.isFinite(e)&&(e===0?this.cssProperties&&delete this.cssProperties["margin-right"]:(this.cssProperties||(this.cssProperties={}),this.cssProperties["margin-right"]=Jn(e,"em")))}set bottom(e){Number.isFinite(e)&&(e===0?this.cssProperties&&delete this.cssProperties["margin-bottom"]:(this.cssProperties||(this.cssProperties={}),this.cssProperties["margin-bottom"]=Jn(e,"em")))}get width(){return this._width*this.scale}set width(e){this._width=e,this.hasExplicitWidth=!0}set softWidth(e){}get height(){return this._height*this.scale}set height(e){this._height=e}get depth(){return this._depth*this.scale}set depth(e){this._depth=e}wrap(e){let r=e.parent;if(!r)return this;e.isPhantom&&this.setStyle("opacity",0);let i=e.color;i&&i!==r.color&&this.setStyle("color",i);let o=e.backgroundColor;this.isSelected&&(o=Ru(o)),o&&o!==r.backgroundColor&&(this.setStyle("background-color",o),this.setStyle("--bg-color",o),this.setStyle("display","inline-block"),this.setStyle("position","relative"),this.classes=this.classes?`${this.classes} ML__bg`:"ML__bg");let a=e.scalingFactor;return this.scale=a,this.skew*=a,this.italic*=a,this}toMarkup(){var c,u,d;let e=this.value?Bf(this.value):"";if(this.children)for(let m of this.children)e+=m.toMarkup();let r="";if(this.svgBody)r=I0(this.svgBody);else if(this.svgOverlay){r='',r+=e,r+="",r+=']/g,p=>`&#${p.charCodeAt(0)};`)};`),r+='"',this.svgStyle&&(r+=this.svgStyle),r+=` viewBox="0 0 ${Math.floor(100*this.width)/100} ${Math.floor(100*(this.height+this.depth))/100}"`,r+=`>${this.svgOverlay}`}let i=[],n=this.classes.split(" ");n.push((u={latex:"ML__raw-latex",placeholder:"ML__placeholder",error:"ML__error"}[this.type])!=null?u:""),this.caret==="latex"&&n.push("ML__latex-caret"),this.isSelected&&n.push("ML__selected");let o=n.length===1?n[0]:n.filter((m,p,f)=>m.length>0&&f.indexOf(m)===p).join(" ");if(o.length>0&&i.push(`class=${Xi(`"${o}"`)}`),this.id&&i.push(` data-atom-id=${Xi(this.id)}`),this.cssId&&i.push(` id=${Xi(`"${this.cssId.replace(/ /g,"-")}"`)}`),this.attributes&&i.push(...Object.keys(this.attributes).map(m=>`${ic(m)}=${Xi(this.attributes[m])}`)),this.htmlData){let m=this.htmlData.split(",");for(let p of m){let f=p.match(/([^=]+)=(.+$)/);if(f){let y=ic(f[1]);if(y)if(y==="href"){let v=new URL(f[2]);if(v.protocol!=="http:"&&v.protocol!=="https:")throw new Error(`Invalid URL: ${f[2]}`);i.push(`href="${q0(f[2])}"`)}else i.push(`data-${y}=${Xi(f[2])}`)}else{let y=ic(p);y&&i.push(`data-${y} `)}}}let a=(d=this.cssProperties)!=null?d:{};this.hasExplicitWidth&&a.width===void 0&&(a.width=`${Math.ceil(this._width*100)/100}em`);let s=Object.keys(a).map(m=>`${m}:${a[m]}`);if(this.scale!==void 0&&this.scale!==1&&(e.length>0||r.length>0)&&s.push(`font-size: ${Math.ceil(this.scale*1e4)/100}%`),this.htmlStyle)for(let m of this.htmlStyle.split(";")){let p=m.match(/([^:]+):(.+$)/);if(p){let f=p[1].trim().replace(/ /g,"-");f&&s.push(`${f}:${p[2]}`)}}s.length>0&&i.push(`style=${Xi(s.join(";"))}`);let l="";return i.length>0||r.length>0?l=`${e}${r}`:l=e,this.caret==="text"?l+='':this.caret==="math"&&(l+=''),l}tryCoalesceWith(e){if(this.svgBody||!this.value||e.svgBody||!e.value)return!1;let r=this.children&&this.children.length>0,i=e.children&&e.children.length>0;if(r||i)return!1;if(e.cssProperties||this.cssProperties){for(let l of["border","border-left","border-right","border-right-width","left","margin","margin-left","margin-right","padding","position","width"])if(e.cssProperties&&l in e.cssProperties||this.cssProperties&&l in this.cssProperties)return!1}let n=this.cssProperties?Object.keys(this.cssProperties).length:0,o=e.cssProperties?Object.keys(e.cssProperties).length:0;if(n!==o)return!1;if(n>0){for(let l of Object.keys(this.cssProperties))if(this.cssProperties[l]!==e.cssProperties[l])return!1}let a=this.classes.trim().replace(/\s+/g," ").split(" "),s=e.classes.trim().replace(/\s+/g," ").split(" ");if(a.length!==s.length)return!1;a.sort(),s.sort();for(let[l,c]of a.entries())if(c==="ML__vertical-separator"||c!==s[l])return!1;return this.value+=e.value,this.height=Math.max(this.height,e.height),this.depth=Math.max(this.depth,e.depth),this._width=this._width+e._width,this.maxFontSize=Math.max(this.maxFontSize,e.maxFontSize),this.italic=e.italic,!0}};function nc(t){if(!t||t.length===0)return[];t[0].children=nc(t[0].children);let e=[t[0]];for(let r=1;r0){let i=-1/0,n=-1/0,o=0;for(let a of t.children)a.height>i&&(i=a.height),a.depth>n&&(n=a.depth),o=Math.max(o,(r=a.maxFontSize)!=null?r:0);t.height=i,t.depth=n,t._width=t.children.reduce((a,s)=>a+s.width,0),t.maxFontSize=o}}function Bf(t){return t.replace(/&/g,"&").replace(//g,">")}function ic(t){if(t=t.trim().replace(/ /g,"-"),t.length===0)throw new Error("Invalid empty attribute name");if(/[\x20\x09\x0a\x0c\x0d"'>/=\x00-\x1f]/.test(t))throw new Error(`Invalid attribute name "${t}"`);return t}function q0(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}function Xi(t){if(t=t.trim(),t.length>=2&&(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")))t=t.slice(1,-1);else if(t.length===0)throw new Error("Invalid empty attribute value");return`"${q0(t)}"`}function Kf(t){if("individualShift"in t){let e=t.individualShift,r=e[0];if(r==null)return[null,0];let i=[r],n=-r.shift-r.box.depth,o=n;for(let a=1;a{f.softWidth=c});let u=new w(o,{classes:"ML__vlist"});if(u.softWidth=c,u.height=s,u.setStyle("height",s,"em"),a>=0)return[[new w(u,{classes:"ML__vlist-r"})],s,-a];let d=new w(new w(null),{classes:"ML__vlist"});d.height=-a,d.setStyle("height",-a,"em");let m=new w(8203,{classes:"ML__vlist-s",maxFontSize:0});return m.softWidth=0,m.height=0,m.depth=0,[[new w([u,m],{classes:"ML__vlist-r"}),new w(d,{classes:"ML__vlist-r"})],s,-a]}var te=class extends w{constructor(e,r){var a;let[i,n,o]=Pf(e);super(i.length===1?i[0]:i,{type:r==null?void 0:r.type,classes:((a=r==null?void 0:r.classes)!=null?a:"")+" ML__vlist-t"+(i.length===2?" ML__vlist-t2":"")}),this.height=n,this.depth=o,this.softWidth=i.reduce((s,l)=>Math.max(s,l.width),0)}};function H0(t,e){var c,u,d,m,p;let r=t.metrics,i=new w(e.base),n=(c=e.baseShift)!=null?c:0,o=(u=e.slant)!=null?u:0,a=0,s=0;e.above&&(a=(d=e.aboveShift)!=null?d:Math.max(r.bigOpSpacing1,r.bigOpSpacing3-e.above.depth)),e.below&&(s=(m=e.belowShift)!=null?m:Math.max(r.bigOpSpacing2,r.bigOpSpacing4-e.below.height));let l=null;if(e.below&&e.above){let f=r.bigOpSpacing5+e.below.height+e.below.depth+s+i.depth+n;l=new te({bottom:f,children:[r.bigOpSpacing5,{box:e.below,marginLeft:-o,classes:["ML__center"]},s,{box:i,classes:["ML__center"]},a,{box:e.above,marginLeft:o,classes:["ML__center"]},r.bigOpSpacing5]}).wrap(t)}else if(e.below&&!e.above)l=new te({top:i.height-n,children:[r.bigOpSpacing5,{box:e.below,marginLeft:-o,classes:["ML__center"]},s,{box:i,classes:["ML__center"]}]}).wrap(t);else if(!e.below&&e.above){let f=i.depth+n;l=new te({bottom:f,children:[{box:i,classes:["ML__center"]},a,{box:e.above,marginLeft:o,classes:["ML__center"]},r.bigOpSpacing5]}).wrap(t)}else{let f=i.depth+n;l=new te({bottom:f,children:[{box:i},r.bigOpSpacing5]}).wrap(t)}return new w(l,{type:(p=e.type)!=null?p:"op"})}var Rf=/^-?(\d+|\d*\.\d+)(px|em|rem|ex|ch|pt|pc|cm|mm|in|vw|vh|%)?$/,If=/^([a-zA-Z]+|#[0-9a-fA-F]{3,8}|(rgba?|hsla?)\(\s*[-\d.,%\s/]*\s*\)|var\(--[\w-]+\))$/,zf=/^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/;function oc(t){let e=[],r=0,i="";for(let n of t.trim()){if(n==="("?r+=1:n===")"&&(r-=1),r<0)return;/\s/.test(n)&&r===0?(i&&e.push(i),i=""):i+=n}if(r===0)return i&&e.push(i),e}function ac(t){return Rf.test(t)}function sc(t){return If.test(t)}function W0(t){if(!t)return;let e=t.trim();return ac(e)?e:void 0}function Yi(t){if(!t)return;let e=oc(t);if(!(!e||e.length!==1))return sc(e[0])?e[0]:void 0}function Ga(t){if(!t)return;let e=oc(t);if(!e||e.length===0||e.length>3)return;let r=0,i=0,n=0;for(let o of e)if(ac(o))r+=1;else if(zf.test(o))i+=1;else if(sc(o))n+=1;else return;if(!(r>1||i>1||n>1))return e.join(" ")}function U0(t){if(!t)return;let e=oc(t);if(!e||e.length<2||e.length>4)return;let r=0,i=0;for(let n of e)if(ac(n))r+=1;else if(sc(n))i+=1;else return;if(!(r<2||r>3||i>1))return e.join(" ")}function G0(t){if(!t)return;let e=t.trim();return/^[A-Za-z0-9 _'",-]+$/.test(e)?e:void 0}var ja=7,Zn=6,Yn=5,Kr=4,ui=3,He=2,Pr=1,Ee=0,It=class{constructor(e,r,i){this.id=e,this.sizeDelta=r,this.cramped=i;let n={"-4":2,"-3":1,0:0}[r];this.metrics=Object.keys(Ql).reduce((o,a)=>g(h({},o),{[a]:Ql[a][n]}),{})}getFontSize(e){return Math.max(1,e+this.sizeDelta)}get sup(){return ft[[Ee,Pr,Ee,Pr,He,ui,He,ui][this.id]]}get sub(){return ft[[Ee,Ee,Ee,Ee,He,He,He,He][this.id]]}get fracNum(){return ft[[Ee,Pr,Ee,Pr,He,ui,Kr,Yn][this.id]]}get fracDen(){return ft[[Ee,Ee,Ee,Ee,He,He,Kr,Kr][this.id]]}get cramp(){return ft[[Ee,Ee,He,He,Kr,Kr,Zn,Zn][this.id]]}get isTight(){return this.sizeDelta<0}},Xn={7:new It(ja,0,!1),6:new It(Zn,0,!0),5:new It(Yn,0,!1),4:new It(Kr,0,!0),3:new It(ui,-3,!1),2:new It(He,-3,!0),1:new It(Pr,-4,!1),0:new It(Ee,-4,!0)},ft=g(h({},Xn),{displaystyle:Xn[ja],textstyle:Xn[Yn],scriptstyle:Xn[ui],scriptscriptstyle:Xn[Pr]});function cc(t,e){var i;if(!t)return 0;let r={pt:1,mm:7227/2540,cm:7227/254,ex:35271/8192,px:3/4,em:Rt,bp:803/800,dd:1238/1157,pc:12,in:72.27,mu:10/18}[(i=t.unit)!=null?i:"pt"];if(Number.isFinite(e)){let n=10**e;return Math.round(t.dimension/Rt*r*n)/n}return t.dimension*r}function Ja(t,e){if(t===null)return 0;let r=cc(t)/Rt;if(Number.isFinite(e)){let i=10**e;return Math.round(r*i)/i}return r}function lc(t){var e;return`${t.dimension}${(e=t.unit)!=null?e:"pt"}`}function Nf(t){let e=lc(t.glue);return t.grow&&t.grow.dimension!==0&&(e+=` plus ${lc(t.grow)}`),t.shrink&&t.shrink.dimension!==0&&(e+=` minus ${lc(t.shrink)}`),e}function ge(t){var r,i;if(t==null)return null;let e="";if("dimension"in t&&(e=`${t.dimension}${(r=t.unit)!=null?r:"pt"}`),"glue"in t&&(e=Nf(t)),"number"in t)if(!("base"in t)||t.base==="decimal")e=Number(t.number).toString();else if(t.base==="alpha")e=`\`${String.fromCodePoint(t.number)}`;else{let n=Math.round(t.number)>>>0;t.base==="hexadecimal"?(e=Number(n).toString(16).toUpperCase(),n<=255?e=e.padStart(2,"0"):n<=65535?e=e.padStart(4,"0"):n<=16777215?e=e.padStart(6,"0"):e=e.padStart(8,"0"),e=`"${e}`):t.base==="octal"&&(e=Number(n).toString(8),n<=63?e=e.padStart(2,"0"):n<=30583?e=e.padStart(4,"0"):e=e.padStart(8,"0"),e=`'${e}`)}return"register"in t&&("factor"in t&&(t.factor===-1?e="-":t.factor!==1&&(e=Number(t.factor).toString())),"global"in t&&t.global&&(e+="\\global"),e+=`\\${t.register}`),"string"in t&&(e=t.string),(i=t.relax)!=null&&i&&(e+="\\relax"),e}function gt(t,e){return t==null?null:"number"in t?g(h({},t),{number:t.number*e}):"register"in t?"factor"in t&&t.factor?g(h({},t),{factor:t.factor*e}):g(h({},t),{factor:e}):"dimension"in t?g(h({},t),{dimension:t.dimension*e}):"glue"in t?t.shrink&&t.grow?{glue:gt(t.glue,e),shrink:gt(t.shrink,e),grow:gt(t.grow,e)}:t.shrink?{glue:gt(t.glue,e),shrink:gt(t.shrink,e)}:t.grow?{glue:gt(t.glue,e),grow:gt(t.grow,e)}:{glue:gt(t.glue,e)}:null}var Ff={"p@":{dimension:1},"z@":{dimension:0},maxdimen:{dimension:16383.99999},hfuzz:{dimension:.1},vfuzz:{dimension:.1},overfullrule:{dimension:5},hsize:{dimension:6.5,unit:"in"},vsize:{dimension:8.9,unit:"in"},parindent:{dimension:20},maxdepth:{dimension:4},splitmaxdepth:{register:"maxdimen"},boxmaxdepth:{register:"maxdimen"},delimitershortfall:{dimension:5},nulldelimiterspace:{dimension:1.2,unit:"pt"},scriptspace:{dimension:.5},topskip:{dimension:10},splittopskip:{dimension:10},normalbaselineskip:{dimension:12},normallineskip:{dimension:1},normallineskiplimit:{dimension:0},jot:{dimension:3},doublerulesep:{dimension:2},arrayrulewidth:{dimension:.4},arraycolsep:{dimension:5},fboxsep:{dimension:3},fboxrule:{dimension:.4},"z@skip":{glue:{dimension:0},shrink:{dimension:0},grow:{dimension:0}},hideskip:{glue:{dimension:-1e3},grow:{dimension:1,unit:"fill"}},"@flushglue":{glue:{dimension:0},grow:{dimension:1,unit:"fill"}},parskip:{glue:{dimension:0},grow:{dimension:1}},abovedisplayskip:{glue:{dimension:12},grow:{dimension:3},shrink:{dimension:9}},abovedisplayshortskip:{glue:{dimension:0},grow:{dimension:3}},belowdisplayskip:{glue:{dimension:12},grow:{dimension:3},shrink:{dimension:9}},belowdisplayshortskip:{glue:{dimension:7},grow:{dimension:3},shrink:{dimension:4}},parfillskip:{glue:{dimension:0},grow:{dimension:1,unit:"fil"}},thinmuskip:{glue:{dimension:3,unit:"mu"}},medmuskip:{glue:{dimension:4,unit:"mu"},grow:{dimension:2,unit:"mu"},shrink:{dimension:4,unit:"mu"}},thickmuskip:{glue:{dimension:5,unit:"mu"},grow:{dimension:5,unit:"mu"}},smallskipamount:{glue:{dimension:3},grow:{dimension:1},shrink:{dimension:1}},medskipamount:{glue:{dimension:6},grow:{dimension:2},shrink:{dimension:3}},bigskipamount:{glue:{dimension:12},grow:{dimension:2},shrink:{dimension:4}},pretolerance:100,tolerance:200,hbadness:1e3,vbadness:1e3,linepenalty:10,hyphenpenalty:50,exhyphenpenalty:50,binoppenalty:700,relpenalty:500,clubpenalty:150,widowpenalty:150,displaywidowpenalty:50,brokenpenalty:100,predisplaypenalty:1e4,doublehyphendemerits:1e4,finalhyphendemerits:5e3,adjdemerits:1e4,tracinglostchars:1,uchyph:1,delimiterfactor:901,defaulthyphenchar:"\\-",defaultskewchar:-1,newlinechar:-1,showboxbreadth:5,showboxdepth:3,errorcontextlines:5,interdisplaylinepenalty:100,interfootnotelinepenalty:100,baselineSkip:1.2,arraystretch:1,month:new Date().getMonth()+1,day:new Date().getDate(),year:new Date().getFullYear()};function Xa(){return h({},Ff)}function Qn(){return{registers:Xa(),smartFence:!1,renderPlaceholder:void 0,placeholderSymbol:"\u25A2",letterShapeStyle:F.locale.startsWith("fr")?"french":"tex",minFontScale:0,maxMatrixCols:10,colorMap:Yr,backgroundColorMap:Bi,getMacro:t=>ti(t,Ri())}}var P=class t{constructor(e,r){var o,a,s,l,c,u,d,m,p,f,y,v,b,k,S;let i;e!=null&&e.parent?(this.parent=e.parent,i=e.parent,this.registers={}):(i=h(h({},Qn()),(o=e==null?void 0:e.from)!=null?o:{}),this.registers=i.registers),i.atomIdsSettings&&(this.atomIdsSettings=h({},i.atomIdsSettings)),this.renderPlaceholder=i.renderPlaceholder,this.isPhantom=(l=(s=e==null?void 0:e.isPhantom)!=null?s:(a=this.parent)==null?void 0:a.isPhantom)!=null?l:!1,this.letterShapeStyle=i.letterShapeStyle,this.minFontScale=i.minFontScale,this.maxMatrixCols=i.maxMatrixCols,r!=null&&r.color&&r.color!=="none"?this.color=r.color:this.color=(u=(c=this.parent)==null?void 0:c.color)!=null?u:"",r!=null&&r.backgroundColor&&r.backgroundColor!=="none"?this.backgroundColor=r.backgroundColor:this.backgroundColor=(m=(d=this.parent)==null?void 0:d.backgroundColor)!=null?m:"",r!=null&&r.fontSize&&r.fontSize!=="auto"&&r.fontSize!==((p=this.parent)==null?void 0:p.size)?this.size=r.fontSize:this.size=(y=(f=this.parent)==null?void 0:f.size)!=null?y:ji;let n=(b=(v=this.parent)==null?void 0:v.mathstyle)!=null?b:ft.displaystyle;if(typeof(e==null?void 0:e.mathstyle)=="string"){if(i instanceof t)switch(e.mathstyle){case"cramp":n=n.cramp;break;case"superscript":n=n.sup;break;case"subscript":n=n.sub;break;case"numerator":n=n.fracNum;break;case"denominator":n=n.fracDen;break}switch(e.mathstyle){case"textstyle":n=ft.textstyle;break;case"displaystyle":n=ft.displaystyle;break;case"scriptstyle":n=ft.scriptstyle;break;case"scriptscriptstyle":n=ft.scriptscriptstyle;break;case"":case"auto":break}}this.mathstyle=n,this.smartFence=i.smartFence,this.placeholderSymbol=i.placeholderSymbol,this.colorMap=(k=i.colorMap)!=null?k:(A=>A),this.backgroundColorMap=(S=i.backgroundColorMap)!=null?S:(A=>A),this.getMacro=i.getMacro,this.parent!==void 0||this.registers}makeID(){if(!this.atomIdsSettings)return;if(this.atomIdsSettings.overrideID)return this.atomIdsSettings.overrideID;if(typeof this.atomIdsSettings.seed!="number")return`${Date.now().toString(36).slice(-2)}${Math.floor(Math.random()*1e5).toString(36)}`;let e=this.atomIdsSettings.seed.toString(36);return this.atomIdsSettings.seed+=1,e}scale(e){return e*this.effectiveFontSize}get scalingFactor(){return this.parent?this.effectiveFontSize/this.parent.effectiveFontSize:1}get isDisplayStyle(){return this.mathstyle.id===ja||this.mathstyle.id===Zn}get isCramped(){return this.mathstyle.cramped}get isTight(){return this.mathstyle.isTight}get metrics(){return this.mathstyle.metrics}get effectiveFontSize(){return Math.max(jn[Math.max(1,this.size+this.mathstyle.sizeDelta)],this.minFontScale)}getRegister(e){if(this.registers&&e in this.registers)return this.registers[e];if(this.parent)return this.parent.getRegister(e)}getRegisterAsNumber(e){let r=this.getRegister(e);if(typeof r=="number")return r;if(typeof r=="string")return Number(r)}getRegisterAsGlue(e){if(this.registers&&e in this.registers){let r=this.registers[e];return typeof r=="object"&&"glue"in r?r:typeof r=="object"&&"dimension"in r?{glue:{dimension:r.dimension}}:typeof r=="number"?{glue:{dimension:r}}:void 0}if(this.parent)return this.parent.getRegisterAsGlue(e)}getRegisterAsEm(e,r){return Ja(this.getRegisterAsDimension(e),r)}getRegisterAsDimension(e){if(this.registers&&e in this.registers){let r=this.registers[e];return typeof r=="object"&&"glue"in r?r.glue:typeof r=="object"&&"dimension"in r?r:typeof r=="number"?{dimension:r}:void 0}if(this.parent)return this.parent.getRegisterAsDimension(e)}setRegister(e,r){if(r===void 0){delete this.registers[e];return}this.registers[e]=r}evaluate(e){if(!e||!("register"in e))return e;let r=this;if("global"in e&&e.global)for(;r.parent;)r=r.parent;let i=1;"factor"in e&&e.factor!==1&&e.factor!==void 0&&(i=e.factor);let n=r.getRegister(e.register);if(n===void 0)return;if(typeof n=="string")return{string:Number(n).toString()+n};if(typeof n=="number")return{number:i*n};let o=r.evaluate(n);if(o!==void 0)return"string"in o?{string:Number(n).toString()+o.string}:"number"in o?{number:i*o.number}:"dimension"in o?g(h({},o),{dimension:i*o.dimension}):"glue"in o?g(h({},o),{glue:g(h({},o.glue),{dimension:i*o.glue.dimension}),shrink:o.shrink?g(h({},o.shrink),{dimension:i*o.shrink.dimension}):void 0,grow:o.grow?g(h({},o.grow),{dimension:i*o.grow.dimension}):void 0}):e}toDimension(e){let r=this.evaluate(e);if(r===void 0)return null;if("dimension"in r)return r;if("glue"in r)return r.glue;if("number"in r)return{dimension:r.number};if("string"in r){let i=parseFloat(r.string),n=r.string.match(/(mm|cm|ex|px|em|bp|dd|pc|in|mu)$/);return n?{dimension:i,unit:n[0]}:{dimension:i}}return null}toEm(e,r){if(e===null)return 0;let i=this.toDimension(e);return i===null?0:cc(i,r)/Rt}toNumber(e){if(e===null)return null;let r=this.evaluate(e);return r===void 0?null:"number"in r?r.number:"dimension"in r?r.dimension:"glue"in r?r.glue.dimension:"string"in r?Number(r.string):null}toColor(e){var i,n,o;if(e===null)return null;let r=this.evaluate(e);return r===void 0?null:"string"in r&&(o=(n=(i=this.colorMap)==null?void 0:i.call(this,r.string))!=null?n:Yi(r.string))!=null?o:null}toBackgroundColor(e){var i,n,o;if(e===null)return null;let r=this.evaluate(e);return r===void 0?null:"string"in r&&(o=(n=(i=this.backgroundColorMap)==null?void 0:i.call(this,r.string))!=null?n:Yi(r.string))!=null?o:null}};var Ir=["body","above","below","subscript","superscript"];function Rr(t){return typeof t=="string"&&Ir.includes(t)}function Ze(t){return t!==void 0&&Array.isArray(t)&&t.length===2}var x=class t{constructor(e){this.isRoot=!1;var r,i,n,o,a,s,l;this.type=e.type,typeof e.value=="string"&&(this.value=e.value),this.command=(i=(r=e.command)!=null?r:this.value)!=null?i:"",this.mode=(n=e.mode)!=null?n:"math",e.isFunction&&(this.isFunction=!0),(e.isRoot||this.type==="root")&&(this.isRoot=!0),e.limits&&(this.subsupPlacement=e.limits),this.style=h({},(o=e.style)!=null?o:{}),this.displayContainsHighlight=(a=e.displayContainsHighlight)!=null?a:!1,this.captureSelection=(s=e.captureSelection)!=null?s:!1,this.skipBoundary=(l=e.skipBoundary)!=null?l:!1,e.verbatimLatex!==void 0&&e.verbatimLatex!==null&&(this.verbatimLatex=e.verbatimLatex),e.args&&(this.args=e.args),e.body&&(this.body=e.body),this._changeCounter=0}static createBox(e,r,i){var s;if(!r)return null;let n=$f(r),o=[];for(let l of n){let c=l[0].style,u=Vf(e,l,{style:{color:c.color,backgroundColor:c.backgroundColor,fontSize:c.fontSize}});u&&o.push(u)}if(o.length===0)return null;let a=((s=i==null?void 0:i.classes)!=null?s:"").trim();return o.length===1&&!a&&!(i!=null&&i.type)?o[0].wrap(e):new w(o,{classes:a,type:i==null?void 0:i.type}).wrap(e)}static serialize(e,r){return _e.serialize(e,r)}static commonAncestor(e,r){if(e===r||e.parent===r.parent)return e.parent;let i=new WeakSet,{parent:n}=e;for(;n;)i.add(n),n=n.parent;for(n=r.parent;n;){if(i.has(n))return n;n=n.parent}}static fromJson(e){return typeof e=="string"?new t({type:"mord",value:e,mode:"math"}):new t(e)}toJson(){if(this._json)return this._json;let e={};if(this.type&&(e.type=this.type),this.mode!=="math"&&(e.mode=this.mode),this.command&&this.command!==this.value&&(e.command=this.command),this.value!==void 0&&(e.value=this.value),this.style&&Object.keys(this.style).length>0&&(e.style=h({},this.style)),this.verbatimLatex!==void 0&&(e.verbatimLatex=this.verbatimLatex),this.subsupPlacement&&(e.subsupPlacement=this.subsupPlacement),this.explicitSubsupPlacement&&(e.explicitSubsupPlacement=!0),this.isFunction&&(e.isFunction=!0),this.displayContainsHighlight&&(e.displayContainsHighlight=!0),this.skipBoundary&&(e.skipBoundary=!0),this.captureSelection&&(e.captureSelection=!0),this.args&&(e.args=qf(this.args)),this._branches)for(let r of Object.keys(this._branches))this._branches[r]&&(e[r]=this._branches[r].filter(i=>i.type!=="first").map(i=>i.toJson()));return e.type==="mord"&&Object.keys(e).length===2&&"value"in e?e.value:(this._json=e,e)}get changeCounter(){return this.parent?this.parent.changeCounter:this._changeCounter}set isDirty(e){e&&(this._json=void 0,this.parent||this._changeCounter++,"verbatimLatex"in this&&(this.verbatimLatex=void 0),this._children=void 0,this.parent&&(this.parent.isDirty=!0))}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);return r!=null&&r.serialize?r.serialize(this,e):this.body&&this.command?R([U(this.command,this.bodyToLatex(e)),this.supsubToLatex(e)]):this.body?R([this.bodyToLatex(e),this.supsubToLatex(e)]):!this.value||this.value==="\u200B"?"":this.command}bodyToLatex(e){var i;let r=(i=e.defaultMode)!=null?i:this.mode==="math"?"math":"text";return _e.serialize(this.body,g(h({},e),{defaultMode:r}))}aboveToLatex(e){return _e.serialize(this.above,e)}belowToLatex(e){return _e.serialize(this.below,e)}supsubToLatex(e){let r="";if(e=g(h({},e),{defaultMode:"math"}),this.branch("subscript")!==void 0){let i=_e.serialize(this.subscript,e);i.length===0?r+="_{}":i.length===1?/^[0-9]$/.test(i)?r+=`_${i}`:r+=`_{${i}}`:r+=`_{${i}}`}if(this.branch("superscript")!==void 0){let i=_e.serialize(this.superscript,e);i.length===0?r+="^{}":i.length===1?i==="\u2032"?r+="^\\prime ":i==="\u2033"?r+="^\\doubleprime ":/^[0-9]$/.test(i)?r+=`^${i}`:r+=`^{${i}}`:r+=`^{${i}}`}return r}get treeDepth(){let e=1,r=this.parent;for(;r;)r=r.parent,e+=1;return e}get inCaptureSelection(){let e=this;for(;e;){if(e.captureSelection)return!0;e=e.parent}return!1}get parentPrompt(){let e=this.parent;for(;e;){if(e.type==="prompt"&&!e.captureSelection)return e;e=e.parent}return null}branch(e){if(Rr(e)&&this._branches)return this._branches[e]}get branches(){if(!this._branches)return[];let e=[];for(let r of Ir)this._branches[r]&&e.push(r);return e}createBranch(e){return Rr(e),Rr(e)?(this._branches?this._branches[e]||(this._branches[e]=[this.makeFirstAtom(e)]):this._branches={[e]:[this.makeFirstAtom(e)]},this.isDirty=!0,this._branches[e]):[]}get row(){return Ze(this.parentBranch)?this.parentBranch[0]:-1}get col(){return Ze(this.parentBranch)?this.parentBranch[1]:-1}get body(){var e;return(e=this._branches)==null?void 0:e.body}set body(e){this.setChildren(e,"body")}get superscript(){var e;return(e=this._branches)==null?void 0:e.superscript}set superscript(e){this.setChildren(e,"superscript")}get subscript(){var e;return(e=this._branches)==null?void 0:e.subscript}set subscript(e){this.setChildren(e,"subscript")}get above(){var e;return(e=this._branches)==null?void 0:e.above}set above(e){this.setChildren(e,"above")}get below(){var e;return(e=this._branches)==null?void 0:e.below}set below(e){this.setChildren(e,"below")}applyStyle(e,r){this.isDirty=!0,r!=null&&r.unstyledOnly?(e.color&&!this.style.color&&(this.style.color=e.color),e.backgroundColor&&!this.style.backgroundColor&&(this.style.backgroundColor=e.backgroundColor),e.fontFamily&&!this.style.fontFamily&&(this.style.fontFamily=e.fontFamily),e.fontShape&&!this.style.fontShape&&(this.style.fontShape=e.fontShape),e.fontSeries&&!this.style.fontSeries&&(this.style.fontSeries=e.fontSeries),e.fontSize&&!this.style.fontSize&&(this.style.fontSize=e.fontSize),e.variant&&!this.style.variant&&(this.style.variant=e.variant),e.variantStyle&&!this.style.variantStyle&&(this.style.variantStyle=e.variantStyle)):this.style=h(h({},this.style),e),this.style.fontFamily==="none"&&delete this.style.fontFamily,this.style.fontShape==="auto"&&delete this.style.fontShape,this.style.fontSeries==="auto"&&delete this.style.fontSeries,this.style.color==="none"&&(delete this.style.color,delete this.style.verbatimColor),this.style.backgroundColor==="none"&&(delete this.style.backgroundColor,delete this.style.verbatimBackgroundColor),this.style.fontSize==="auto"&&delete this.style.fontSize;for(let i of this.children)i.applyStyle(e,r)}getInitialBaseElement(){var e,r,i;return this.hasEmptyBranch("body")?this:((e=this.body)==null||e[0].type,(i=(r=this.body[1])==null?void 0:r.getInitialBaseElement())!=null?i:this)}getFinalBaseElement(){return this.hasEmptyBranch("body")?this:this.body[this.body.length-1].getFinalBaseElement()}isCharacterBox(){return this.type==="leftright"||this.type==="genfrac"||this.type==="subsup"||this.type==="delim"||this.type==="array"||this.type==="surd"?!1:this.getFinalBaseElement().type==="mord"}hasEmptyBranch(e){let r=this.branch(e);return r?(r.length>0,r[0].type,r.length===1):!0}setChildren(e,r){var n;if(!e||(Rr(r),!Rr(r)))return;let i=((n=e[0])==null?void 0:n.type)==="first"?[...e]:[this.makeFirstAtom(r),...e];this._branches?this._branches[r]=i:this._branches={[r]:i};for(let o of e)o.parent=this,o.parentBranch=r;this.isDirty=!0}makeFirstAtom(e){let r=new t({type:"first",mode:this.mode});return r.parent=this,r.parentBranch=e,r}addChild(e,r){e.type,this.createBranch(r).push(e),this.isDirty=!0,e.parent=this,e.parentBranch=r}addChildBefore(e,r){r.parentBranch;let i=this.createBranch(r.parentBranch);i.splice(i.indexOf(r),0,e),this.isDirty=!0,e.parent=this,e.parentBranch=r.parentBranch}addChildAfter(e,r){r.parentBranch;let i=this.createBranch(r.parentBranch);i.splice(i.indexOf(r)+1,0,e),this.isDirty=!0,e.parent=this,e.parentBranch=r.parentBranch}addChildren(e,r){let i=this.createBranch(r);for(let n of e)n.parent=this,n.parentBranch=r,i.push(n);this.isDirty=!0}addChildrenAfter(e,r){e.length===0||e[0].type,r.parentBranch;let i=this.createBranch(r.parentBranch);i.splice(i.indexOf(r)+1,0,...e),this.isDirty=!0;for(let n of e)n.parent=this,n.parentBranch=r.parentBranch;return e[e.length-1]}removeBranch(e){let r=this.branch(e);if(Rr(e)&&(this._branches[e]=void 0),!r)return[];for(let o of r)o.parent=void 0,o.parentBranch=void 0;r[0].type;let[i,...n]=r;return this.isDirty=!0,n}removeChild(e){if(e.parent,e.type==="first")return;let r=this.branch(e.parentBranch),i=r.indexOf(e);i>=0,r.splice(i,1),this.isDirty=!0,e.parent=void 0,e.parentBranch=void 0}get siblings(){return this.parent?this.parent.branch(this.parentBranch):[]}get firstSibling(){return this.siblings[0]}get lastSibling(){let{siblings:e}=this;return e[e.length-1]}get isFirstSibling(){return this===this.firstSibling}get isLastSibling(){return this===this.lastSibling}get hasNoSiblings(){return this.siblings.length===1}get leftSibling(){this.parent;let e=this.parent.branch(this.parentBranch);return e[e.indexOf(this)-1]}get rightSibling(){this.parent;let e=this.parent.branch(this.parentBranch);return e[e.indexOf(this)+1]}get hasChildren(){return!!(this._branches&&this.children.length>0)}get firstChild(){return this.hasChildren,this.children[0]}get lastChild(){this.hasChildren;let{children:e}=this;return e[e.length-1]}get children(){if(this._children)return this._children;if(!this._branches)return[];let e=[];for(let r of Ir)if(this._branches[r])for(let i of this._branches[r])e.push(...i.children),e.push(i);return this._children=e,e}render(e){if(this.type==="first"&&!e.atomIdsSettings)return null;let r=ne(this.command,this.mode);if(r!=null&&r.render)return r.render(this,e);let i=new P({parent:e},this.style),n=this.createBox(i,{classes:this.parent?"":"ML__base"});return n?(!this.subsupPlacement&&(this.superscript||this.subscript)&&(n=this.attachSupsub(i,{base:n})),n.wrap(i)):null}attachSupsub(e,r){var f;let i=r.base,n=this.superscript,o=this.subscript;if(!n&&!o)return i;let a=null,s=null,l=(f=r.isCharacterBox)!=null?f:this.isCharacterBox(),c=0;if(n){let y=new P({parent:e,mathstyle:"superscript"});a=t.createBox(y,n),l||(c=i.height-e.metrics.supDrop*y.scalingFactor)}let u=0;if(o){let y=new P({parent:e,mathstyle:"subscript"});s=t.createBox(y,o),l||(u=i.depth+e.metrics.subDrop*y.scalingFactor)}let d;e.isDisplayStyle?d=e.metrics.sup1:e.isCramped?d=e.metrics.sup3:d=e.metrics.sup2;let m=.5/Rt/e.scalingFactor,p=null;if(s&&a){c=Math.max(c,d,a.depth+.25*e.metrics.xHeight),u=Math.max(u,e.metrics.sub2);let y=e.metrics.defaultRuleThickness;if(c-a.depth-(s.height-u)<4*y){u=4*y-(c-a.depth)+s.height;let b=.8*e.metrics.xHeight-(c-a.depth);b>0&&(c+=b,u-=b)}let v=this.type==="extensible-symbol"&&i.italic?-i.italic:0;p=new te({individualShift:[{box:s,shift:u,marginLeft:v},{box:a,shift:-c}]})}else s&&!a?(u=Math.max(u,e.metrics.sub1,s.height-.8*Xe),p=new te({shift:u,children:[{box:s,marginRight:m,marginLeft:this.isCharacterBox()?-i.italic:0}]})):!s&&a&&(c=Math.max(c,d,a.depth+.25*Xe),p=new te({shift:-c,children:[{box:a,marginRight:m}]}));return new w([i,new w(p,{caret:this.caret,isSelected:this.isSelected,classes:"ML__msubsup"})],{type:r.type})}attachLimits(e,r){let i=this.superscript?t.createBox(new P({parent:e,mathstyle:"superscript"},this.style),this.superscript):null,n=this.subscript?t.createBox(new P({parent:e,mathstyle:"subscript"},this.style),this.subscript):null;return!i&&!n?r.base.wrap(e):H0(e,g(h({},r),{above:i,below:n}))}bind(e,r){if(!r||e.isPhantom||this.value==="\u200B")return r;let i=this.parent;for(;i&&!i.captureSelection;)i=i.parent;return i!=null&&i.captureSelection||(this.id||(this.id=e.makeID()),r.atomID=this.id),r}createBox(e,r){var s,l,c,u;let i=(s=this.value)!=null?s:this.body,n=(l=r==null?void 0:r.boxType)!=null?l:Ua(this.type),o=(c=r==null?void 0:r.classes)!=null?c:"";this.mode==="text"&&(o+=" ML__text");let a=typeof i=="string"||i===void 0?new w(i!=null?i:null,{type:n,isSelected:this.isSelected,mode:this.mode,maxFontSize:e.scalingFactor,style:g(h({variant:"normal"},this.style),{fontSize:Math.max(1,e.size+e.mathstyle.sizeDelta)}),letterShapeStyle:e.letterShapeStyle,classes:o}):(u=t.createBox(e,i,{type:n,classes:o}))!=null?u:new w(null);return e.isTight&&(a.isTight=!0),(this.mode!=="math"||this.style.variant==="main")&&(a.italic=0),a.right=a.italic,this.bind(e,a),this.caret&&!this.superscript&&!this.subscript&&(a.caret=this.caret),a}isDigit(){var e;return this.type==="mord"&&this.value?/^[\d,\.]$/.test(this.value):this.type==="group"&&((e=this.body)==null?void 0:e.length)===2?this.body[0].type==="first"&&this.body[1].value===",":!1}asDigit(){var e;return this.type==="mord"&&this.value&&/^[\d,\.]$/.test(this.value)?this.value:this.type==="group"&&((e=this.body)==null?void 0:e.length)===2&&this.body[0].type==="first"&&this.body[1].value===","?".":""}};function $f(t){let e,r=[],i=[];for(let n of t){if(n.type==="first"){i.push(n);continue}if(!e&&!n.style)i.push(n);else{let o=n.style;e&&o.color===e.color&&o.backgroundColor===e.backgroundColor&&o.fontSize===e.fontSize?i.push(n):(i.length>0&&r.push(i),i=[n],e=o)}}return i.length>0&&r.push(i),r}function Vf(t,e,r){var s,l,c,u,d;if(!e||e.length===0)return null;let i=new P({parent:t},r.style),n=!((s=i.atomIdsSettings)!=null&&s.groupNumbers),o=[];if(e.length===1){let m=e[0],p=m.render(i);p&&(n&&m.isSelected&&p.selected(!0),o=[p])}else{let m="",p=!0;for(let f of e){(l=i.atomIdsSettings)!=null&&l.groupNumbers&&m&&(p&&f.isDigit()||!p&&uc(f))&&(i.atomIdsSettings.overrideID=m);let y=f.render(i);i.atomIdsSettings&&(i.atomIdsSettings.overrideID=void 0),y&&((c=i.atomIdsSettings)!=null&&c.groupNumbers&&((f.isDigit()||uc(f))&&(!m||p!==f.isDigit())&&(p=f.isDigit(),m=(u=f.id)!=null?u:""),m&&(!(f.isDigit()||uc(f))||!f.hasEmptyBranch("superscript")||!f.hasEmptyBranch("subscript"))&&(m="")),n&&f.isSelected&&y.selected(!0),o.push(y))}}if(o.length===0)return null;let a=new w(o,g(h({isTight:i.isTight},r),{type:(d=r.type)!=null?d:"lift"}));return a.isSelected=o.every(m=>m.isSelected),a.wrap(i)}function uc(t){return t.mode==="text"}function qf(t){return t.map(e=>e===null?"":Array.isArray(e)&&e[0]instanceof x?{atoms:e.map(r=>r.toJson())}:typeof e=="object"&&"group"in e?{group:e.group.map(r=>r.toJson())}:e)}var We=class t extends x{constructor(e,r,i){super({type:"text",command:e,mode:"text",displayContainsHighlight:!0}),this.value=r,this.verbatimLatex=r,this.applyStyle(i)}static fromJson(e){return new t(e.command,e.value,e.style)}render(e){let r=this.createBox(e);return this.caret&&(r.caret=this.caret),r}_serialize(e){var r;return(r=this.verbatimLatex)!=null?r:yl("text",this.value.codePointAt(0))}};function j0(t,e){if(t.direction===e.direction){let r=t.ranges.length;if(e.ranges.length===r){let i=0;for(;i=":"\\ge","\u2264":"\\le","<=":"\\le","<<":"\\ll",">>":"\\gg","~~":"\\approx","\u2248":"\\approx","?=":"\\questeq","\xF7":"\\div","\xAC":"\\neg",":=":"\\coloneq","::":"\\Colon","(:":"\\langle",":)":"\\rangle",beta:"\\beta",chi:"\\chi",epsilon:"\\epsilon",varepsilon:"\\varepsilon",eta:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\eta"},gamma:"\\gamma",Gamma:"\\Gamma",iota:"\\iota",kappa:"\\kappa",lambda:"\\lambda",Lambda:"\\Lambda",mu:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\mu"},nu:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\nu"},\u00B5:"\\mu",phi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\phi"},Phi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\Phi"},varphi:"\\varphi",psi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\psi"},Psi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\Psi"},rho:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\rho"},sigma:"\\sigma",Sigma:"\\Sigma",tau:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\tau"},vartheta:"\\vartheta",upsilon:"\\upsilon",xi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space",value:"\\xi"},Xi:{after:"nothing+digit+function+frac+surd+binop+relop+punct+array+openfence+closefence+space+text",value:"\\Xi"},zeta:"\\zeta",omega:"\\omega",Omega:"\\Omega",\u03A9:"\\omega",forall:"\\forall",exists:"\\exists","!exists":"\\nexists",":.":"\\therefore",liminf:"\\liminf_{#?}",limsup:"\\limsup_{#?}",argmin:"\\operatorname*{arg~min}_{#?}",argmax:"\\operatorname*{arg~max}_{#?}",det:"\\det",mod:"\\bmod{#?}","(mod":"\\pmod{#?}",max:"\\max",min:"\\min",erf:"\\operatorname{erf}",erfc:"\\operatorname{erfc}",bessel:"\\operatorname{bessel}",mean:"\\operatorname{mean}",median:"\\operatorname{median}",fft:"\\operatorname{fft}",lcm:"\\operatorname{lcm}",gcd:"\\gcd",randomReal:"\\operatorname{randomReal}",randomInteger:"\\operatorname{randomInteger}",Re:"\\operatorname{Re}",Im:"\\operatorname{Im}",mm:{after:"nothing+digit+operator",value:"\\operatorname{mm}"},cm:{after:"nothing+digit+operator",value:"\\operatorname{cm}"},km:{after:"nothing+digit+operator",value:"\\operatorname{km}"},kg:{after:"nothing+digit+operator",value:"\\operatorname{kg}"},ft:{after:"nothing+digit+operator",value:"\\operatorname{ft}"},inch:{after:"nothing+digit+operator",value:"\\operatorname{inch}"},mi:{after:"nothing+digit+operator",value:"\\operatorname{mi}"},"...":"\\ldots","+...":"+\\cdots","-...":"-\\cdots","->...":"\\to\\cdots","-->...":"\\longrightarrow\\cdots","->":"\\to","|->":"\\mapsto","-->":"\\longrightarrow","<--":"\\longleftarrow","=>":"\\Rightarrow","==>":"\\Longrightarrow","<=>":"\\iff","<->":"\\leftrightarrow","(.)":"\\odot","(+)":"\\oplus","(/)":"\\oslash","(*)":"\\otimes","(-)":"\\ominus","||":"\\Vert","*":"\\cdot","**":"\\star","***":"\\ast","//":"\\slash","\\\\":"\\backslash",setminus:"\\backslash","|><":"\\ltimes","><|":"\\rtimes","|><|":"\\bowtie","-:":"\\div",divide:"\\div","@":"\\circ","^^":"\\wedge","^^^":"\\bigwedge",vv:"\\vee",vvv:"\\bigvee",nn:"\\cap",nnn:"\\bigcap",uu:"\\cup",uuu:"\\bigcup","-=":"\\equiv","~=":"\\cong",lt:"<","lt=":"\\leq",gt:">","gt=":"\\geq","-<":"\\prec","-lt":"\\prec","-<=":"\\preceq",">-=":"\\succeq",prop:"\\propto",diamond:"\\diamond",square:"\\square",iff:"\\iff",sub:"\\subset",sup:"\\supset",sube:"\\subseteq",supe:"\\supseteq",uarr:"\\uparrow",darr:"\\downarrow",rarr:"\\rightarrow",rArr:"\\Rightarrow",larr:"\\leftarrow",lArr:"\\Leftarrow",harr:"\\leftrightarrow",hArr:"\\Leftrightarrow",aleph:"\\aleph",and:"\\land",or:"\\lor",not:"\\neg","_|_":"\\bot",TT:"\\top","|--":"\\vdash","|==":"\\models","|__":"\\lfloor","__|":"\\rfloor","|~":"\\lceil","~|":"\\rceil",">->":"\\rightarrowtail","->>":"\\twoheadrightarrow",">->>":"\\twoheadrightarrowtail",times:"\\times",of:"\\circ",infinity:"\\infty",defint:"\\int_{#?}^{#?}",approaches:"\\to",ceil:"\\left\\lceil#?\\right\\rceil",floor:"\\left\\lfloor#?\\right\\rfloor",union:"\\cup",asterisk:"\\ast",frac:"\\frac{#?}{#?}",cbrt:"\\sqrt[3]{#?}",nthroot:"\\sqrt[#?]{#?}"};function or(t,e){var i;let r=(i=e==null?void 0:e.format)!=null?i:"auto";return r==="auto"&&([r,t]=Uf(t)),r==="ascii-math"?(t=t.replace(/\u2061/gu,""),t=t.replace(/\u3016/gu,"{"),t=t.replace(/\u3017/gu,"}"),t=t.replace(/([^\\])sinx/g,"$1\\sin x"),t=t.replace(/([^\\])cosx/g,"$1\\cos x "),t=t.replace(/\u2013/g,"-"),["ascii-math",Ue(t,{inlineShortcuts:e==null?void 0:e.inlineShortcuts})]):["latex",t]}function Ue(t,e){var a;if(t=t.trim(),!t)return"";let r=(a=e.inlineShortcuts)!=null?a:Za;if(t.startsWith("^")||t.startsWith("_")){let{match:s,rest:l}=mi(t.slice(1),{inlineShortcuts:r,noWrap:!0});return`${t[0]}{${s}}${Ue(l,e)}`}let i=t.match(/^(sqrt|\u221A)(.*)/);if(i){let{match:s,rest:l}=mi(i[2],{inlineShortcuts:r,noWrap:!0});return`\\sqrt{${s!=null?s:"\\placeholder{}"}}${Ue(l,e)}`}if(i=t.match(/^(\\cbrt|\u221B)(.*)/),i){let{match:s,rest:l}=mi(i[2],{inlineShortcuts:r,noWrap:!0});return`\\sqrt[3]{${s!=null?s:"\\placeholder{}"}}${Ue(l,e)}`}if(i=t.match(/^abs(.*)/),i){let{match:s,rest:l}=mi(i[1],{inlineShortcuts:r,noWrap:!0});return`\\left|${s!=null?s:"\\placeholder{}"}\\right|${Ue(l,e)}`}if(i=t.match(/^["”“](.*?)["”“](.*)/),i)return`\\text{${i[1]}}${Ue(i[2],e)}`;if(i=t.match(/^([^a-zA-Z0-9\(\{\[\_\^\\\s"]+)(.*)/),i)return`${Z0(i[1],r)}${Ue(i[2],e)}`;if(/^([fgh])[^a-zA-Z]/.test(t)){let{rest:s,match:l}=mi(t.slice(1),{inlineShortcuts:r,noWrap:!0}),c="";return t[1]==="("?c=`${t[0]}\\left(${l}\\right)`:c=t[0]+l,c+Ue(s,e)}if(i=t.match(/^([a-zA-Z]+)(.*)/),i)return Z0(i[1],r)+Ue(i[2],e);let{match:n,rest:o}=mi(t,{inlineShortcuts:r,noWrap:!0});if(n&&o[0]==="/"){let s=mi(o.slice(1),{inlineShortcuts:r,noWrap:!0});if(s.match)return`\\frac{${n}}{${s.match}}${Ue(s.rest,e)}`}else return t.startsWith("(")?"\\left("+n+"\\right)"+Ue(o,e):n+Ue(o,e);return i=t.match(/^(\s+)(.*)$/),i?" "+Ue(i[2],e):t}var X0={"[":"\\lbrack","]":"\\rbrack","{":"\\lbrace","}":"\\rbrace"};function mi(t,e){var a,s;let r="";t=t.trim();let i=t,n=t.charAt(0),o={"(":")","{":"}","[":"]"}[n];if(o){let l=1,c=1;for(;c0;)t[c]===n&&l++,t[c]===o&&l--,c++;if(l===0){let u=Ue(t.substring(1,c-1),e);e.noWrap&&n==="("?r=u:r=`\\left${(a=X0[n])!=null?a:n}${u}\\right${(s=X0[o])!=null?s:o}`,i=t.slice(Math.max(0,c))}else r=t.substring(1,c),i=""}else{let l=t.match(/^([a-zA-Z]+)/);if(l){let c=eo(null,t,e.inlineShortcuts);if(c)return c=c.replace("_{#?}",""),c=c.replace("^{#?}",""),{match:c,rest:t.slice(c.length)}}if(l=t.match(/^([a-zA-Z])/),l)return{match:l[1],rest:t.slice(1)};if(l=t.match(/^(-)?\d+(\.\d*)?/),l)return{match:l[0],rest:t.slice(l[0].length)};/^\\(left|right)/.test(t)||(l=t.match(/^(\\[a-zA-Z]+)/),l&&(i=t.slice(l[1].length),r=l[1]))}return{match:r,rest:i}}function Z0(t,e){let r=eo(null,t,e);return r?(r=r.replace("_{#?}",""),r=r.replace("^{#?}",""),r+=" "):r=t,r}var dc=[["\\[","\\]"],["\\(","\\)"],["$$","$$"],["$","$"],["\\begin{math}","\\end{math}"],["\\begin{displaymath}","\\end{displaymath}"],["\\begin{equation}","\\end{equation}"],["\\begin{equation*}","\\end{equation*}"]];function Ya(t){let e=t.trim();for(let r of dc)if(e.startsWith(r[0])&&e.endsWith(r[1]))return[!0,e.substring(r[0].length,e.length-r[1].length)];return[!1,t]}function Uf(t){if(t=t.trim(),t.length<=1)return["latex",t];let e;return[e,t]=Ya(t),e?["latex",t]:t.startsWith("`")&&t.endsWith("`")?(t=t.substring(1,t.length-1),["ascii-math",t]):t.includes("\\")?["latex",t]:/\$.+\$/.test(t)?["latex",`\\text{${t}}`]:[void 0,t]}var Gf="$$",jf="$$",Y0=(t,e,r)=>(dc.some(i=>e.startsWith(i[0])&&e.endsWith(i[1]))||(e=`${Gf} ${e} ${jf}`),e),en=class en{constructor(e){en._modes[e]=this}static onPaste(e,r,i){var o;if(!r.contentEditable&&r.userSelect==="none")return r.model.announce("plonk"),!1;if(typeof i=="string"){let a=new DataTransfer;a.setData("text/plain",i),i=a}let n=new ClipboardEvent("paste",{clipboardData:i,cancelable:!0});return(o=r.host)!=null&&o.dispatchEvent(n)?en._modes[e].onPaste(r,i):!1}static copyToClipboard(e,r){if(!e.contentEditable&&e.userSelect==="none"){e.model.announce("plonk");return}let i=e.model,n=i.selectionIsCollapsed?[0,i.lastOffset]:de(i.selection),o=i.getValue(n,r);navigator.clipboard.writeText(o).then(()=>{},()=>e.model.announce("plonk"))}static onCopy(e,r){var a;if(!r.clipboardData)return;if(!e.contentEditable&&e.userSelect==="none"){e.model.announce("plonk");return}let i=e.model,n=i.selectionIsCollapsed?[0,i.lastOffset]:de(i.selection),o=i.getAtoms(n);if(o.every(s=>s.mode==="text"||!s.mode))r.clipboardData.setData("text/plain",o.filter(s=>s instanceof We).map(s=>s.value).join(""));else if(o.every(s=>s.mode==="latex"))r.clipboardData.setData("text/plain",i.getAtoms(n,{includeChildren:!0}).map(s=>{var l;return(l=s.value)!=null?l:""}).join(""));else{let s;o.length===1&&o[0].verbatimLatex!==void 0?s=o[0].verbatimLatex:s=i.getValue(n,"latex-expanded"),r.clipboardData.setData("application/x-latex",s);try{r.clipboardData.setData("text/plain",e.options.onExport(e,s,n))}catch(l){}if(o.length===1){let l=o[0];(l.type==="root"||l.type==="group")&&(o=l.body.filter(c=>c.type!=="first"))}try{r.clipboardData.setData("application/json+mathlive",JSON.stringify(o.map(l=>l.toJson())))}catch(l){}if((a=window[Symbol.for("io.cortexjs.compute-engine")])!=null&&a.ComputeEngine){let l=globalThis.MathfieldElement.computeEngine;if(l)try{let c=l.jsonSerializationOptions;l.jsonSerializationOptions={metadata:["latex"]};let u=l.parse(i.getValue(n,"latex-unstyled"));l.jsonSerializationOptions=c;let d=JSON.stringify(u.json);d&&r.clipboardData.setData("application/json",d)}catch(c){}}}r.preventDefault()}static insert(e,r,i={}){var o;let n=i.mode==="auto"?e.mode:(o=i.mode)!=null?o:e.mode;return en._modes[n].insert(e,r,i)}onPaste(e,r){return!1}insert(e,r,i){return!1}};en._modes={};var H=en;var Q0=[{key:"left",command:"moveToPreviousChar"},{key:"right",command:"moveToNextChar"},{key:"up",command:"moveUp"},{key:"down",command:"moveDown"},{key:"shift+[ArrowLeft]",command:"extendSelectionBackward"},{key:"shift+[ArrowRight]",command:"extendSelectionForward"},{key:"shift+[ArrowUp]",command:"extendSelectionUpward"},{key:"shift+[ArrowDown]",command:"extendSelectionDownward"},{key:"[Backspace]",command:"deleteBackward"},{key:"[Delete]",command:"deleteForward"},{key:"shift+[Backspace]",command:"deleteForward"},{key:"alt+[Backspace]",command:"deletePreviousWord"},{key:"alt+[Delete]",command:"deleteNextWord"},{key:"ctrl+[Backspace]",command:"deleteToGroupStart"},{key:"ctrl+[Delete]",command:"deleteToGroupEnd"},{key:"ctrl+shift+[Backspace]",command:"deleteToGroupEnd"},{key:"alt+[ArrowLeft]",command:"moveToPreviousWord"},{key:"alt+[ArrowRight]",command:"moveToNextWord"},{key:"shift+alt+[ArrowLeft]",command:"extendToPreviousWord"},{key:"shift+alt+[ArrowRight]",command:"extendToNextWord"},{key:"ctrl+[ArrowLeft]",command:"moveToGroupStart"},{key:"ctrl+[ArrowRight]",command:"moveToGroupEnd"},{key:"shift+ctrl+[ArrowLeft]",command:"extendToGroupStart"},{key:"shift+ctrl+[ArrowRight]",command:"extendToGroupEnd"},{key:"[Home]",command:"moveToMathfieldStart"},{key:"cmd+[ArrowLeft]",command:"moveToMathfieldStart"},{key:"shift+[Home]",command:"extendToMathFieldStart"},{key:"shift+cmd+[ArrowLeft]",command:"extendToMathFieldStart"},{key:"[End]",command:"moveToMathfieldEnd"},{key:"cmd+[ArrowRight]",command:"moveToMathfieldEnd"},{key:"shift+[End]",command:"extendToMathFieldEnd"},{key:"shift+cmd+[ArrowRight]",command:"extendToMathFieldEnd"},{key:"[Pageup]",command:"moveToGroupStart"},{key:"[Pagedown]",command:"moveToGroupEnd"},{key:"[Tab]",command:"moveToNextGroup"},{key:"shift+[Tab]",command:"moveToPreviousGroup"},{key:"[Escape]",ifMode:"math",command:["switchMode","latex"]},{key:"[Escape]",ifMode:"text",command:["switchMode","latex"]},{key:"[Escape]",ifMode:"latex",command:["complete","complete",{selectItem:"true"}]},{key:"\\",ifMode:"math",command:["switchMode","latex","","\\"]},{key:"[IntlBackslash]",ifMode:"math",command:["switchMode","latex","","\\"]},{key:"[Tab]",ifMode:"latex",command:["complete","accept-suggestion"]},{key:"[Return]",ifMode:"latex",command:["complete","accept-all"]},{key:"[Enter]",ifMode:"latex",command:["complete","accept-all"]},{key:"shift+[Escape]",ifMode:"latex",command:["complete","reject"]},{key:"[ArrowDown]",ifMode:"latex",command:"nextSuggestion"},{key:"[ArrowUp]",ifMode:"latex",command:"previousSuggestion"},{key:"ctrl+a",ifPlatform:"!macos",command:"selectAll"},{key:"cmd+a",command:"selectAll"},{key:"[Cut]",command:"cutToClipboard"},{key:"[Copy]",command:"copyToClipboard"},{key:"[Paste]",command:"pasteFromClipboard"},{key:"[Clear]",command:"deleteBackward"},{key:"[Undo]",command:"undo"},{key:"[Redo]",command:"redo"},{key:"[EraseEof]",command:"deleteToGroupEnd"},{key:"ctrl+x",ifPlatform:"ios",command:"cutToClipboard"},{key:"cmd+x",ifPlatform:"ios",command:"cutToClipboard"},{key:"ctrl+c",ifPlatform:"ios",command:"copyToClipboard"},{key:"cmd+c",ifPlatform:"ios",command:"copyToClipboard"},{key:"ctrl+v",ifPlatform:"ios",command:"pasteFromClipboard"},{key:"cmd+v",ifPlatform:"ios",command:"pasteFromClipboard"},{key:"ctrl+z",ifPlatform:"!macos",command:"undo"},{key:"cmd+z",command:"undo"},{key:"ctrl+y",ifPlatform:"!macos",command:"redo"},{key:"shift+cmd+y",command:"redo"},{key:"shift+ctrl+z",ifPlatform:"!macos",command:"redo"},{key:"shift+cmd+z",command:"redo"},{key:"ctrl+b",ifPlatform:"macos",command:"moveToPreviousChar"},{key:"ctrl+f",ifPlatform:"macos",command:"moveToNextChar"},{key:"ctrl+p",ifPlatform:"macos",command:"moveUp"},{key:"ctrl+n",ifPlatform:"macos",command:"moveDown"},{key:"ctrl+a",ifPlatform:"macos",command:"moveToMathfieldStart"},{key:"ctrl+e",ifPlatform:"macos",command:"moveToMathfieldEnd"},{key:"shift+ctrl+b",ifPlatform:"macos",command:"extendSelectionBackward"},{key:"shift+ctrl+f",ifPlatform:"macos",command:"extendSelectionForward"},{key:"shift+ctrl+p",ifPlatform:"macos",command:"extendSelectionUpward"},{key:"shift+ctrl+n",ifPlatform:"macos",command:"extendSelectionDownward"},{key:"shift+ctrl+a",ifPlatform:"macos",command:"extendToMathFieldStart"},{key:"shift+ctrl+e",ifPlatform:"macos",command:"extendToMathFieldEnd"},{key:"alt+ctrl+b",ifPlatform:"macos",command:"moveToPreviousWord"},{key:"alt+ctrl+f",ifPlatform:"macos",command:"moveToNextWord"},{key:"shift+alt+ctrl+b",ifPlatform:"macos",command:"extendToPreviousWord"},{key:"shift+alt+ctrl+f",ifPlatform:"macos",command:"extendToNextWord"},{key:"ctrl+h",ifPlatform:"macos",command:"deleteBackward"},{key:"ctrl+d",ifPlatform:"macos",command:"deleteForward"},{key:"ctrl+l",ifPlatform:"macos",command:"scrollIntoView"},{key:"ctrl+[Digit2]",ifMode:"math",command:["insert","\\sqrt{#0}"]},{key:"ctrl+[Digit5]",ifMode:"math",command:"moveToOpposite"},{key:"ctrl+[Digit6]",ifMode:"math",command:"moveToSuperscript"},{key:"ctrl+[Return]",ifMode:"math",command:"addRowAfter"},{key:"ctrl+[Enter]",ifMode:"math",command:"addRowAfter"},{key:"cmd+[Return]",ifMode:"math",command:"addRowAfter"},{key:"cmd+[Enter]",ifMode:"math",command:"addRowAfter"},{key:"alt+p",ifMode:"math",command:["insert","\\pi"]},{key:"alt+v",ifMode:"math",command:["insert","\\sqrt{#0}"]},{key:"alt+shift+v",ifMode:"math",command:["insert","\\sqrt[#0]{#1}"]},{key:"alt+o",ifMode:"math",command:["insert","\\emptyset"]},{key:"alt+d",ifMode:"math",command:["insert","\\differentialD"]},{key:"shift+alt+o",ifMode:"math",command:["insert","\\varnothing"]},{key:"shift+alt+d",ifMode:"math",command:["insert","\\partial"]},{key:"alt+[Backslash]",ifMode:"math",command:["insert","\\backslash"]},{key:"[NumpadDivide]",ifMode:"math",command:["insert","\\frac{#@}{#?}"]},{key:"alt+[NumpadDivide]",ifMode:"math",command:["insert","\\frac{#?}{#@}"]},{key:"shift+alt+k",command:"toggleKeystrokeCaption"},{key:"alt+[Space]",command:"toggleContextMenu"},{key:"alt+shift+[Space]",command:"toggleVirtualKeyboard"},{key:"alt+ctrl+[ArrowUp]",command:["speak","all",{withHighlighting:!1}]},{key:"alt+ctrl+[ArrowDown]",command:["speak","selection",{withHighlighting:!1}]},{key:"shift+[Quote]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["switchMode","text","",""]},{key:"shift+[Quote]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"text",command:["switchMode","math","",""]},{key:"shift+alt+[KeyT]",ifMode:"math",command:["switchMode","text"]},{key:"shift+alt+[KeyT]",ifMode:"text",command:["switchMode","math"]},{key:"/",ifMode:"math",command:["insert","\\frac{#@}{#?}"]},{key:"alt+/",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","/"]},{key:"alt+shift+/",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","/"]},{key:"alt+[BracketLeft]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","\\left\\lbrack #0 \\right\\rbrack"]},{key:"ctrl+[Minus]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:"moveToSubscript"},{key:"shift+alt+[BracketLeft]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","\\left\\lbrace #0 \\right\\rbrace"]},{key:"ctrl+;",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:"addRowAfter"},{key:"cmd+;",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:"addRowAfter"},{key:"shift+ctrl+;",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:"addRowBefore"},{key:"shift+cmd+;",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:"addRowBefore"},{key:"alt+[Tab]",ifMode:"math",command:"addColumnAfter"},{key:"shift+alt+[Tab]",ifMode:"math",command:"addColumnBefore"},{key:"alt+[Enter]",ifMode:"math",command:"addRowAfter"},{key:"shift+alt+[Enter]",ifMode:"math",command:"addRowBefore"},{key:"alt+[Return]",ifMode:"math",command:"addRowAfter"},{key:"shift+alt+[Return]",ifMode:"math",command:"addRowBefore"},{key:"shift+[Backspace]",ifMode:"math",command:"removeColumn"},{key:"shift+[Delete]",ifMode:"math",command:"removeRow"},{key:"shift+alt+[Backspace]",ifMode:"math",command:"removeRow"},{key:"alt+[Digit5]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","$\\infty"]},{key:"alt+[Digit9]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","("]},{key:"alt+[Digit0]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert",")"]},{key:"alt+|",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","|"]},{key:"shift+[Backquote]",ifLayout:["apple.en-intl","windows.en-intl","linux.en"],ifMode:"math",command:["insert","\\~"]},{key:"[Backquote]",ifLayout:["windows.french","linux.french"],ifMode:"math",command:["insert","^2"]},{key:"[Backquote]",ifLayout:["windows.german","linux.german"],ifMode:"math",command:["insert","^"]},{key:"[IntlBackslash]",ifLayout:["apple.german"],ifMode:"math",command:["insert","^"]}],eh={"\\sqrt":["alt+v","ctrl+[Digit2]"],"\\pi":"alt+p","\\infty":"alt+[Digit5]","\\differentialD":"alt+d","\\partial":"shift+alt+d","\\frac":"Slash","\\emptyset":"alt+o","\\varnothing":"shift+alt+o","\\~":"~"};function Ye(t){var e;return((e=t.element)==null?void 0:e.mathfield)===t}function Jf(t){var e,r;return(r=(e=t.querySelector(".ML__caret"))!=null?e:t.querySelector(".ML__text-caret"))!=null?r:t.querySelector(".ML__latex-caret")}function tn(t){let e=Jf(t);if(!e)return null;let r=e.getBoundingClientRect();return{x:r.right,y:r.bottom,height:r.height}}function Xf(t){var r;if(!t.parent)return"root";let e=(r=t.parent.id)!=null?r:"";return e+=typeof t.parentBranch=="string"?"-"+t.parentBranch:`-${t.parentBranch[0]}/${t.parentBranch[0]}`,e}function hc(t,e,r){if(!e)return null;let i=t.field.getBoundingClientRect(),n=e.right-e.left,o=e.bottom-e.top,a=Math.ceil(e.left-i.left+t.field.scrollLeft*r),s=Math.ceil(e.top-i.top);return{left:a,right:a+n,top:s,bottom:s+o}}function mc(t){let e=t,r=e.getBoundingClientRect();for(;r.bottom===r.top&&e.parentElement instanceof Element&&(e=e.parentElement,r=e.getBoundingClientRect(),r.bottom===r.top););let i=getComputedStyle(e),n=parseInt(i.marginRight),o=r.right-r.left,a=r.bottom-r.top;if(o===0||!Number.isFinite(o)){let l=parseFloat(i.width);Number.isFinite(l)&&l>0?o=l:e instanceof HTMLElement&&e.offsetWidth>0&&(o=e.offsetWidth)}if(a===0||!Number.isFinite(a)){let l=parseFloat(i.height);Number.isFinite(l)&&l>0?a=l:e instanceof HTMLElement&&e.offsetHeight>0&&(a=e.offsetHeight)}let s={top:r.top-1,bottom:r.top-1+a,left:r.left,right:r.left+o-1+n};if(t.children.length===0||t.tagName.toUpperCase()==="SVG")return s;for(let l of t.children)if(l.nodeType===1&&"atomId"in l.dataset&&!l.classList.contains("ML__pstrut")){let c=mc(l);s.left=Math.min(s.left,c.left),s.right=Math.max(s.right,c.right),s.top=Math.min(s.top,c.top),s.bottom=Math.max(s.bottom,c.bottom)}return s}function ar(t,e){var o,a;if(!e.id)return null;let r=(a=(o=t.atomBoundsCache)==null?void 0:o.get(e.id))!=null?a:null;if(r!==null)return r;let i=t.field.querySelectorAll(`[data-atom-id="${e.id}"]`),n=Array.from(i);if(e.type==="prompt"){for(let s of n)if(s.classList.contains("ML__prompt-atom")){let l=s.querySelector(".ML__prompt");if(l){let c=mc(l);r?(r.left=Math.min(r.left,c.left),r.right=Math.max(r.right,c.right),r.top=Math.min(r.top,c.top),r.bottom=Math.max(r.bottom,c.bottom)):r=c}}}for(let s of n){let l=mc(s);r?(r.left=Math.min(r.left,l.left),r.right=Math.max(r.right,l.right),r.top=Math.min(r.top,l.top),r.bottom=Math.max(r.bottom,l.bottom)):r=l}return t.atomBoundsCache&&(r?t.atomBoundsCache.set(e.id,r):t.atomBoundsCache.delete(e.id)),r!=null?r:null}function th(t,e){let[r,i]=e,n=null;for(let o=r;o<=i;o++){let a=ar(t,t.model.at(o));a&&(n?(n.top=Math.min(n.top,a.top),n.bottom=Math.max(n.bottom,a.bottom),n.left=Math.min(n.left,a.left),n.right=Math.max(n.right,a.right)):n=a)}return n!=null?n:{top:0,bottom:0,left:0,right:0}}function Zf(t,e,r){let i=new Map,n=t.field,o=n.offsetWidth,s=Math.floor(n.getBoundingClientRect().width)/o;s=isNaN(s)?1:s;for(let l of t.model.getAtoms(e,{includeChildren:!0})){if(r!=null&&r.excludeAtomsWithBackground&&l.style.backgroundColor)continue;let c=hc(t,ar(t,l),s);if(c){let u=Xf(l);if(i.has(u)){let d=i.get(u);i.set(u,{left:Math.min(d.left,c.left),right:Math.max(d.right,c.right),top:Math.min(d.top,c.top),bottom:Math.max(d.bottom,c.bottom)})}else i.set(u,c)}}return[...i.values()]}function Qa(t,e){return t.model.selection.ranges.reduce((r,i)=>r.concat(...Zf(t,i,e)),[])}function rn(t,e){return t==="*"||e==="none"?!0:e==="same-origin"?!window.origin||t===window.origin:typeof e=="function"?e(t):!1}function pc(t){let e=0,r=0,i=t.offsetWidth,n=t.offsetHeight;for(;t instanceof HTMLElement;)e+=t.offsetTop,r+=t.offsetLeft,t=t.offsetParent;return new DOMRect(r,e,i,n)}function es(t,e){if(!t)return;let r=t.model.at(e);if(!r)return;let i={},n=ar(t,r);n&&(i.bounds=new DOMRect(n.left,n.top,n.right-n.left,n.bottom-n.top)),i.depth=r.treeDepth-2,i.style=r.style;let o=r;for(;o;){if(o.command==="\\htmlData"&&o.args&&typeof o.args[0]=="string"){let a=o.args[0].split(",");for(let s of a){let l=s.match(/([^=]+)=(.+$)/);if(l){let c=l[1].trim().replace(/ /g,"-");c&&(i.data||(i.data={}),i.data[c]=l[2])}else{let c=s.trim().replace(/ /g,"-");c&&(i.data||(i.data={}),i.data[c]=void 0)}}}(o.command==="\\htmlId"||o.command==="\\cssId")&&!i.id&&o.args&&typeof o.args[0]=="string"&&(i.id=o.args[0]),o=o.parent}return(r.mode==="math"||r.mode==="text")&&(i.latex=x.serialize([r],{defaultMode:"math"})),i}function rh(t,e){let r=t.model.at(e);for(;r;){if(r.command==="\\href"){let i=r.args[0];if(typeof i=="string")return i}r=r.parent}return""}var ih=`@keyframes ML__caret-blink { + 0%, + 100% { + opacity: 1; + } + 50% { + opacity: 0; + } +} +:host { + display: block; +} +.ML__container { + display: inline-flex; + flex-flow: row; + justify-content: space-between; + align-items: flex-end; + min-height: 39px; + /* Need some room for the virtual keyboard toggle */ + width: 100%; + padding: 4px; + box-sizing: border-box; + /* This attribute is necessary to work around a Firefox issue where + where clicking multiple times on the border leads to a focused mathfield that cannot be edited until focus is lost and regained (also fixes the multiple cursor issue on firefox that can occur with the same sequence of events). + */ + pointer-events: auto; + /* Prevent the browser from trying to interpret touch gestures in the field */ + /* "Disabling double-tap to zoom removes the need for browsers to + delay the generation of click events when the user taps the screen." */ + touch-action: none; + --_caret-color: var(--caret-color, hsl(var(--_hue), 40%, 49%)); + --_selection-color: var(--selection-color, #000); + --_selection-background-color: var(--selection-background-color, hsl(var(--_hue), 70%, 85%)); + --_text-highlight-background-color: var(--highlight-text, hsla(var(--_hue), 40%, 50%, 0.1)); + --_contains-highlight-background-color: var(--contains-highlight-background-color, hsl(var(--_hue), 40%, 95%)); + --_smart-fence-color: var(--smart-fence-color, currentColor); + --_smart-fence-opacity: var(--smart-fence-opacity, 0.5); + --_contains-highlight-color: var(--contains-highlight-color, var(--_caret-color)); + --_latex-color: var(--latex-color, hsl(var(--_hue), 80%, 40%)); + --_correct-color: var(--correct-color, #10a000); + --_incorrect-color: var(--incorrect-color, #a01b00); + --_composition-background-color: var(--composition-background-color, #fff1c2); + --_composition-text-color: var(--composition-text-color, black); + --_composition-underline-color: var(--composition-underline-color, transparent); + --_tooltip-border: var(--tooltip-border, 1px solid transparent); + --_tooltip-border-radius: var(--tooltip-border-radius, 8px); + --_tooltip-background-color: var(--tooltip-background-color, #616161); + --_tooltip-color: var(--tooltip-color, #fff); + --_tooltip-box-shadow: var(--tooltip-box-shadow, 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2)); +} +@media (prefers-color-scheme: dark) { + .ML__container { + --_contains-highlight-color: var(--contains-highlight-color, hsl(var(--_hue), 85%, 75%)); + --_caret-color: var(--caret-color, hsl(var(--_hue), 65%, 55%)); + --_selection-color: var(--selection-color, #fff); + --_selection-background-color: var(--selection-background-color, hsl(var(--_hue), 65%, 55%)); + --_text-highlight-background-color: var(--text-highlight-background-color, hsla(var(--_hue), 40%, 50%, 0.6)); + --_contains-highlight-background-color: var(--contains-highlight-background-color, hsl(var(--_hue), 5%, 34%)); + --_latex-color: var(--primary, hsl(var(--_hue), 40%, 50%)); + --_composition-background-color: #69571c; + --_composition-text-color: white; + --_placeholder-color: hsl(var(--_hue), 60%, 69%); + --_smart-fence-color: var(--smart-fence-color, #fff); + --_smart-fence-opacity: var(--smart-fence-opacity, 0.7); + } +} +@media (forced-colors: active) { + .ML__container { + --_caret-color: white; + --_selection-color: white; + --_smart-fence-color: white; + --_latex-color: white; + --_correct-color: white; + --_incorrect-color: white; + --_composition-text-color: white; + } +} +@media (hover: none) and (pointer: coarse) { + :host(:not(:focus)) .ML__container { + pointer-events: none; + } +} +/* This is the actual field content (formula) */ +.ML__content { + display: flex; + align-items: center; + align-self: center; + position: relative; + overflow: hidden; + padding: 2px 3px 2px 1px; + width: 100%; + /* Encourage the browser to use the GPU to render the field. + Weirdly, this is required for prompts to be rendered correctly. + */ + isolation: isolate; + text-shadow: var(--text-shadow); +} +.ML__content .ML__latex { + text-shadow: var(--text-shadow); +} +.ML__content .ML__sqrt-line { + box-shadow: var(--text-shadow); +} +.ML__content .ML__frac-line { + box-shadow: var(--text-shadow); +} +/* Container for the virtual keyboard toggle and menu toggle buttons */ +.ML__toggles { + display: flex; + flex-direction: row; + align-items: flex-start; + gap: 0; + align-self: flex-start; +} +/* Vertical layout modifier */ +.ML__toggles--vertical { + flex-direction: column; + align-items: center; + gap: 4px; +} +.ML__toggles--vertical .ML__virtual-keyboard-toggle, +.ML__toggles--vertical .ML__menu-toggle { + margin-right: 0; +} +.ML__virtual-keyboard-toggle, +.ML__menu-toggle { + box-sizing: border-box; + display: flex; + align-self: center; + align-items: center; + flex-shrink: 0; + flex-direction: column; + justify-content: center; + width: 34px; + height: 34px; + padding: 0; + margin-right: 4px; + cursor: pointer; + /* Avoid some weird blinking with :hover */ + border-radius: 8px; + border: 1px solid transparent; + transition: background 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); + color: hsl(var(--_hue), 40%, 50%); + fill: currentColor; + background: transparent; +} +.ML__virtual-keyboard-toggle:hover, +.ML__menu-toggle:hover { + background: hsla(0, 0%, 70%, 0.3); + color: #333; + fill: currentColor; +} +.ML__virtual-keyboard-toggle > span, +.ML__menu-toggle > span { + display: flex; + align-self: center; + align-items: center; +} +@media (pointer: coarse) { + .ML__virtual-keyboard-toggle, + .ML__menu-toggle { + min-width: 60px; + min-height: 60px; + } +} +/* The invisible element used to capture keyboard events. We're just trying + really hard to make sure it doesn't show. */ +.ML__keyboard-sink { + display: inline-block; + resize: none; + outline: none; + border: none; + pointer-events: none; + /* Need these for Microsoft Edge */ + position: fixed; + clip: rect(0 0 0 0); + /* Need this to prevent iOS Safari from auto-zooming */ + font-size: 1em; + font-family: KaTeX_Main; + line-height: 0.5; + /* On Chromium, if this is 0, no keyboard events are received */ + /* Preferred over clip */ + clip-path: inset(50%); +} +[part='placeholder'] { + color: var(--neutral-400); +} +.ML__composition { + background: var(--_composition-background-color); + color: var(--_composition-text-color); + text-decoration: underline var(--_composition-underline-color); +} +.ML__caret { + display: inline-block; +} +.ML__caret::after { + content: ''; + visibility: hidden; + width: 0; + display: inline-block; + height: 0.76em; + --_caret-width: clamp(2px, 0.08em, 10px); + border: none; + border-radius: calc(var(--_caret-width) / 2); + border-right: var(--_caret-width) solid var(--_caret-color); + margin-right: calc(-1 * var(--_caret-width)); + position: relative; + left: -0.045em; + bottom: -0.05em; + animation: ML__caret-blink 1.05s step-end forwards infinite; +} +.ML__text-caret::after { + content: ''; + visibility: hidden; + width: 0; + display: inline-block; + height: 0.76em; + --_caret-width: clamp(2px, 0.08em, 10px); + border: none; + border-radius: calc(var(--_caret-width) / 2); + border-right: var(--_caret-width) solid var(--_caret-color); + margin-right: calc(-1 * var(--_caret-width)); + position: relative; + left: -0.045em; + bottom: -0.05em; + animation: ML__caret-blink 1.05s step-end forwards infinite; +} +.ML__latex-caret::after { + content: ''; + visibility: hidden; + --_caret-width: clamp(2px, 0.08em, 10px); + border: none; + border-radius: calc(var(--_caret-width) / 2); + border-right: var(--_caret-width) solid var(--_latex-color); + margin-right: calc(-1 * var(--_caret-width)); + position: relative; + left: -0.019em; + animation: ML__caret-blink 1.05s step-end forwards infinite; +} +.ML__focused .ML__latex-caret::after, +.ML__focused .ML__text-caret::after, +.ML__focused .ML__caret::after { + visibility: visible; +} +.ML__focused .ML__text { + background: var(--_text-highlight-background-color); +} +/* When using smartFence, the anticipated closing fence is displayed +with this style */ +.ML__smart-fence__close { + opacity: var(--_smart-fence-opacity); + color: var(--_smart-fence-color); +} +.ML__focused .ML__selected, +.ML__focused .ML__selected .ML__contains-caret, +.ML__focused .ML__selected .ML__smart-fence__close, +.ML__focused .ML__selected .ML__placeholder { + color: var(--_selection-color); + opacity: 1; +} +.ML__empty-line-anchor::after { + content: ''; + position: absolute; + left: 0; + top: 50%; + transform: translateY(-50%); + width: 8px; + height: 20px; + border-radius: 2px; + background: transparent; + opacity: 0; + pointer-events: none; +} +.ML__focused .ML__empty-line-anchor.ML__selected::after { + background: var(--_selection-background-color); + opacity: 1; +} +.ML__selection { + box-sizing: border-box; + background: transparent; +} +:host(:focus) .ML__selection { + background: var(--_selection-background-color) !important; +} +.ML__contains-caret.ML__close, +.ML__contains-caret.ML__open, +.ML__contains-caret > .ML__close, +.ML__contains-caret > .ML__open, +.ML__contains-caret .ML__sqrt-sign, +.ML__contains-caret .ML__sqrt-line { + color: var(--_contains-highlight-color); +} +.ML__contains-highlight { + box-sizing: border-box; + background: transparent; +} +.ML__focused .ML__contains-highlight { + background: var(--_contains-highlight-background-color); +} +.ML__raw-latex { + font-family: 'Berkeley Mono', 'IBM Plex Mono', 'Source Code Pro', Consolas, 'Roboto Mono', Menlo, 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace; + font-weight: 400; + font-size: 0.8em; + letter-spacing: -0.05em; + color: var(--_latex-color); +} +.ML__suggestion { + color: var(--neutral-500); +} +.ML__virtual-keyboard-toggle.is-visible.is-pressed:hover { + background: hsl(var(--_hue), 25%, 35%); + color: #fafafa; + fill: currentColor; +} +.ML__virtual-keyboard-toggle.is-pressed, +.ML__virtual-keyboard-toggle.is-active:hover, +.ML__virtual-keyboard-toggle.is-active { + background: hsl(var(--_hue), 25%, 35%); + color: #fafafa; + fill: currentColor; +} +/* Add an attribute 'data-tooltip' to automatically show a + tooltip over a element on hover. +*/ +[data-tooltip] { + position: relative; +} +[data-tooltip]::after { + content: attr(data-tooltip); + position: absolute; + display: block; + z-index: 2; + pointer-events: none; + right: auto; + top: calc(-100% - 4px); + width: max-content; + max-width: 200px; + padding: 8px 8px; + border-radius: 4px; + background: #616161; + color: #fff; + box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); + text-align: center; + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-style: normal; + font-weight: 400; + font-size: 13px; + /* Phone */ + opacity: 0; + transform: scale(0.5); +} +@media only screen and (max-width: 767px) { + [data-tooltip]::after { + padding: 8px 16px; + font-size: 16px; + } +} +menu [data-tooltip]::after { + left: 100%; + top: 0%; +} +menu .ML__base { + cursor: default; +} +/** Don't display if we're tracking, i.e. have the pointer down */ +.tracking [data-tooltip]:hover::after { + /* Use visibility, not display. Display will remove the after from the DOM, and the override below will not work */ + visibility: hidden; +} +/** But do display if tracking and inside a menu */ +.tracking menu li[data-tooltip]:hover::after, +[data-tooltip]:hover::after { + visibility: visible; + opacity: 1; + transform: scale(1); + transition-property: opacity, scale; + transition-duration: 0.15s; + transition-delay: 1s; + transition-timing-function: cubic-bezier(0.4, 0, 1, 1); +} +.ML__prompt { + border-radius: 2px; +} +.ML__editablePromptBox { + outline: 1px solid #acacac; + border-radius: 2px; + z-index: -1; +} +.ML__focused .ML__focusedPromptBox { + outline: highlight auto 1px; +} +.ML__lockedPromptBox { + background-color: rgba(142, 142, 141, 0.4); + z-index: -1; +} +.ML__correctPromptBox { + outline: 1px solid var(--_correct-color); + box-shadow: 0 0 5px var(--_correct-color); +} +.ML__incorrectPromptBox { + outline: 1px solid var(--_incorrect-color); + box-shadow: 0 0 5px var(--_incorrect-color); +} +.variant-submenu { + display: flex; + flex-direction: column; + padding: 8px; +} +.variant-submenu [part='menu-item'].ML__xl { + font-size: 2rem; + text-align: center; + margin: 0; +} +.ML__center-menu .label { + text-align: center; +} +.insert-matrix-submenu { + /* Grid doesn't work on Safari */ + --_menu-item-size: 25px; + width: calc(5 * var(--_menu-item-size)); + display: flex; + flex-wrap: wrap; + padding: 8px; + align-content: center; + justify-content: center; +} +.insert-matrix-submenu [part='menu-item'] { + width: var(--_menu-item-size); + height: var(--_menu-item-size); + font-size: 21px; + border: none; + border-radius: 0; + line-height: 21px; + text-align: center; + padding: 0; + margin: 0; +} +.border-submenu [part='menu-item'] { + font-size: 2rem; + line-height: 1.2; + text-align: center; +} +.swatches-submenu { + --_swatch-size: 2rem; + --_columns: 4; + display: flex; + flex-flow: wrap; + padding: 8px; + max-width: calc(var(--_columns) * (var(--_swatch-size) + 18px) + 16px); + box-sizing: border-box; +} +.menu-swatch { + display: flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: fit-content; + height: fit-content; + margin: 2px; + padding: 0; + background: var(--neutral-200); +} +.menu-swatch > .label { + padding: 0; + margin: 0; + line-height: 0; +} +.menu-swatch > .label > span { + display: inline-block; + margin: 6px; + min-width: var(--_swatch-size); + min-height: var(--_swatch-size); + border-radius: 50%; +} +.menu-swatch.active { + background: var(--neutral-100); + z-index: 1; + scale: 1.4; +} +.menu-swatch.active > .label > span { + border-radius: 2px; +} +.menu-swatch .ui-checkmark, +.menu-swatch .ui-mixedmark { + position: absolute; + margin: 0; + padding: 0; + color: white; +} +.menu-swatch.dark-contrast .ui-checkmark, +.menu-swatch.dark-contrast .ui-mixedmark { + color: #000; +} +.ML__insert-template { + font-size: 1em; +} +.ML__insert-label { + opacity: 0.5; + margin-left: 2ex; +} +`;var nh=`.ML__container { + min-height: auto !important; + --_hue: var(--hue, 212); + --_placeholder-color: var(--placeholder-color, hsl(var(--_hue), 40%, 49%)); + --_placeholder-opacity: var(--placeholder-opacity, 0.4); + --_text-font-family: var(--text-font-family, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif); +} +.ML__sr-only { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + overflow: hidden; + clip: rect(0, 0, 0, 0); + clip-path: inset(50%); + white-space: nowrap; + border: 0; +} +.ML__is-inline { + display: inline-block; +} +.ML__base { + visibility: inherit; + display: inline-block; + position: relative; + cursor: text; + padding: 0; + margin: 0; + box-sizing: content-box; + border: 0; + outline: 0; + vertical-align: baseline; + font-weight: inherit; + font-family: inherit; + font-style: inherit; + text-decoration: none; + width: min-content; +} +.ML__strut, +.ML__strut--bottom { + display: inline-block; + min-height: 0.5em; +} +.ML__small-delim { + font-family: KaTeX_Main; +} +/* Text mode */ +.ML__text { + font-family: var(--_text-font-family); + white-space: pre; +} +/* Use cmr for 'math upright' */ +.ML__cmr { + font-family: KaTeX_Main; + font-style: normal; +} +.ML__mathit { + font-family: KaTeX_Math; + /* The KaTeX_Math font is italic by default, so the font-style below is only + useful when a fallback font is used + */ + font-style: italic; +} +.ML__mathbf { + font-family: KaTeX_Main; + font-weight: bold; +} +/* Lowercase greek symbols should stick to math font when \\mathbf is applied + to match TeX idiosyncratic behavior */ +.lcGreek.ML__mathbf { + font-family: KaTeX_Math; +} +.ML__mathbfit { + font-family: KaTeX_Math; + font-weight: bold; + font-style: italic; +} +.ML__ams { + font-family: KaTeX_AMS; +} +/* Blackboard */ +.ML__bb { + font-family: KaTeX_AMS; +} +.ML__cal { + font-family: KaTeX_Caligraphic; +} +.ML__frak { + font-family: KaTeX_Fraktur; +} +.ML__tt { + font-family: KaTeX_Typewriter; +} +.ML__script { + font-family: KaTeX_Script; +} +.ML__sans { + font-family: KaTeX_SansSerif; +} +.ML__series_ul { + font-weight: 100; +} +.ML__series_el { + font-weight: 100; +} +.ML__series_l { + font-weight: 200; +} +.ML__series_sl { + font-weight: 300; +} +.ML__series_sb { + font-weight: 500; +} +.ML__bold { + font-weight: 700; +} +.ML__series_eb { + font-weight: 800; +} +.ML__series_ub { + font-weight: 900; +} +.ML__series_uc { + font-stretch: ultra-condensed; +} +.ML__series_ec { + font-stretch: extra-condensed; +} +.ML__series_c { + font-stretch: condensed; +} +.ML__series_sc { + font-stretch: semi-condensed; +} +.ML__series_sx { + font-stretch: semi-expanded; +} +.ML__series_x { + font-stretch: expanded; +} +.ML__series_ex { + font-stretch: extra-expanded; +} +.ML__series_ux { + font-stretch: ultra-expanded; +} +.ML__it { + font-style: italic; +} +.ML__shape_ol { + -webkit-text-stroke: 1px black; + text-stroke: 1px black; + color: transparent; +} +.ML__shape_sc { + font-variant: small-caps; +} +.ML__shape_sl { + font-style: oblique; +} +/* First level emphasis */ +.ML__emph { + color: #bc2612; +} +/* Second level emphasis */ +.ML__emph .ML__emph { + color: #0c7f99; +} +.ML__highlight { + color: #007cb2; + background: #edd1b0; +} +.ML__center { + text-align: center; +} +.ML__left { + text-align: left; +} +.ML__right { + text-align: right; +} +.ML__label_padding { + padding: 0 0.5em; +} +.ML__frac-line { + width: 100%; + min-height: 1px; +} +.ML__frac-line:after { + content: ''; + display: block; + /* A custom bar thickness, for example from \`\\genfrac\`, sets the + \`--frac-line-thickness\` variable on the element. The bar then fills + the element, so \`--frac-line-margin\` is set to 0. */ + margin-top: var(--frac-line-margin, max(-1px, -0.04em)); + min-height: var(--frac-line-thickness, max(1px, 0.04em)); + /* Ensure the line is visible when printing even if "turn off background images" is on*/ + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + /* There's a bug since Chrome 62 where + sub-pixel border lines don't draw at some zoom + levels (110%, 90%). + Setting the min-height used to work around it, but that workaround + broke in Chrome 84 or so. + Setting the background (and the min-height) seems to work for now. + */ + background: currentColor; + box-sizing: content-box; + /* Vuetify sets the box-sizing to inherit + causes the fraction line to not draw at all sizes (see #26) */ + /* On some versions of Firefox on Windows, the line fails to + draw at some zoom levels, but setting the transform triggers + the hardware accelerated path, which works */ + transform: translate(0, 0); + forced-color-adjust: preserve-parent-color; +} +@media (forced-colors: active) { + .ML__frac-line { + min-height: 0px; + } +} +.ML__sqrt { + display: inline-block; +} +.ML__sqrt-sign { + display: inline-block; + position: relative; +} +.ML__sqrt-line { + display: inline-block; + height: max(1px, 0.04em); + width: 100%; +} +.ML__sqrt-line:before { + content: ''; + display: block; + margin-top: min(-1px, -0.04em); + min-height: max(1px, 0.04em); + /* Ensure the line is visible when printing even if "turn off background images" is on*/ + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + background: currentColor; + /* On some versions of Firefox on Windows, the line fails to + draw at some zoom levels, but setting the transform triggers + the hardware accelerated path, which works */ + transform: translate(0, 0); + forced-color-adjust: preserve-parent-color; +} +@media (forced-colors: active) { + .ML__sqrt-line:after { + background: white !important; + } +} +.ML__sqrt-line:after { + border-bottom-width: 1px; + content: ' '; + display: block; + margin-top: -0.1em; +} +.ML__sqrt-index { + margin-left: 0.27777778em; + margin-right: -0.55555556em; +} +.ML__delim-size1 { + font-family: KaTeX_Size1; +} +.ML__delim-size2 { + font-family: KaTeX_Size2; +} +.ML__delim-size3 { + font-family: KaTeX_Size3; +} +.ML__delim-size4 { + font-family: KaTeX_Size4; +} +.ML__delim-mult .delim-size1 > span { + font-family: KaTeX_Size1; +} +.ML__delim-mult .delim-size4 > span { + font-family: KaTeX_Size4; +} +.ML__accent-body { + font-family: KaTeX_Main; +} +.ML__accent-combining-char { + position: relative; + left: 0.24em; +} +/** The markup for a LaTeX formula, either in an editable mathfield or + in a static display. +*/ +.ML__latex { + display: inline-block; + direction: ltr; + text-align: left; + text-indent: 0; + text-rendering: auto; + font-family: inherit; + font-style: normal; + font-size-adjust: none; + font-stretch: normal; + font-variant-caps: normal; + letter-spacing: normal; + line-height: 1.2; + word-wrap: normal; + word-spacing: normal; + white-space: nowrap; + text-shadow: none; + -webkit-user-select: none; + user-select: none; + width: min-content; + forced-color-adjust: preserve-parent-color; +} +.ML__latex .style-wrap { + position: relative; +} +.ML__latex .ML__mfrac { + display: inline-block; +} +.ML__latex .ML__left-right { + display: inline-block; +} +.ML__latex .ML__vlist-t { + display: inline-table; + table-layout: fixed; + border-collapse: collapse; +} +.ML__latex .ML__vlist-r { + display: table-row; +} +.ML__latex .ML__vlist { + display: table-cell; + vertical-align: bottom; + position: relative; +} +.ML__latex .ML__vlist > span { + display: block; + height: 0; + position: relative; +} +.ML__latex .ML__vlist > span > span { + display: inline-block; +} +.ML__latex .ML__vlist > span > .ML__pstrut { + overflow: hidden; + width: 0; +} +.ML__latex .ML__vlist-t2 { + margin-right: -2px; +} +.ML__latex .ML__vlist-s { + display: table-cell; + vertical-align: bottom; + font-size: 1px; + width: 2px; + min-width: 2px; +} +.ML__latex .ML__msubsup { + text-align: left; +} +.ML__latex .ML__negativethinspace { + display: inline-block; + margin-left: -0.16667em; + height: 0.71em; +} +.ML__latex .ML__thinspace { + display: inline-block; + width: 0.16667em; + height: 0.71em; +} +.ML__latex .ML__mediumspace { + display: inline-block; + width: 0.22222em; + height: 0.71em; +} +.ML__latex .ML__thickspace { + display: inline-block; + width: 0.27778em; + height: 0.71em; +} +.ML__latex .ML__enspace { + display: inline-block; + width: 0.5em; + height: 0.71em; +} +.ML__latex .ML__quad { + display: inline-block; + width: 1em; + height: 0.71em; +} +.ML__latex .ML__qquad { + display: inline-block; + width: 2em; + height: 0.71em; +} +.ML__latex .ML__llap, +.ML__latex .ML__rlap { + width: 0; + position: relative; + display: inline-block; +} +.ML__latex .ML__llap > .ML__inner, +.ML__latex .ML__rlap > .ML__inner { + position: absolute; +} +.ML__latex .ML__llap > .ML__fix, +.ML__latex .ML__rlap > .ML__fix { + display: inline-block; +} +.ML__latex .ML__llap > .ML__inner { + right: 0; +} +.ML__latex .ML__rlap > .ML__inner { + left: 0; +} +.ML__latex .ML__rule { + display: inline-block; + border: solid 0; + position: relative; + box-sizing: border-box; +} +.ML__latex .overline .overline-line, +.ML__latex .underline .underline-line { + width: 100%; +} +.ML__latex .overline .overline-line:before, +.ML__latex .underline .underline-line:before { + content: ''; + border-bottom-style: solid; + border-bottom-width: max(1px, 0.04em); + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + display: block; +} +.ML__latex .overline .overline-line:after, +.ML__latex .underline .underline-line:after { + border-bottom-style: solid; + border-bottom-width: max(1px, 0.04em); + -webkit-print-color-adjust: exact; + print-color-adjust: exact; + content: ''; + display: block; + margin-top: -1px; +} +.ML__latex .ML__stretchy { + display: block; + position: absolute; + width: 100%; + left: 0; + overflow: hidden; +} +.ML__latex .ML__stretchy:before, +.ML__latex .ML__stretchy:after { + content: ''; +} +.ML__latex .ML__stretchy svg { + display: block; + position: absolute; + width: 100%; + height: inherit; + fill: currentColor; + stroke: currentColor; + fill-rule: nonzero; + fill-opacity: 1; + stroke-width: 1; + stroke-linecap: butt; + stroke-linejoin: miter; + stroke-miterlimit: 4; + stroke-dasharray: none; + stroke-dashoffset: 0; + stroke-opacity: 1; +} +.ML__latex .slice-1-of-2 { + display: inline-flex; + position: absolute; + left: 0; + width: 50.2%; + overflow: hidden; +} +.ML__latex .slice-2-of-2 { + display: inline-flex; + position: absolute; + right: 0; + width: 50.2%; + overflow: hidden; +} +.ML__latex .slice-1-of-3 { + display: inline-flex; + position: absolute; + left: 0; + width: 25.1%; + overflow: hidden; +} +.ML__latex .slice-2-of-3 { + display: inline-flex; + position: absolute; + left: 25%; + width: 50%; + overflow: hidden; +} +.ML__latex .slice-3-of-3 { + display: inline-flex; + position: absolute; + right: 0; + width: 25.1%; + overflow: hidden; +} +.ML__latex .slice-1-of-1 { + display: inline-flex; + position: absolute; + width: 100%; + left: 0; + overflow: hidden; +} +.ML__latex .ML__nulldelimiter { + display: inline-block; +} +.ML__latex .ML__op-group { + display: inline-block; +} +.ML__latex .ML__op-symbol { + position: relative; +} +.ML__latex .ML__op-symbol.ML__small-op { + font-family: KaTeX_Size1; +} +.ML__latex .ML__op-symbol.ML__large-op { + font-family: KaTeX_Size2; +} +.ML__latex:has(.ML__center_environment), +.ML__latex:has(.ML__multiline_environment), +.ML__latex:has(.ML__align_environment), +.ML__latex:has(.ML__eqnarray_environment), +.ML__latex:has(.ML__gather_environment) { + width: 100%; +} +.ML__latex .ML__multiline_environment { + display: inline-flex; + width: 100%; +} +.ML__latex .ML__center_environment { + display: inline-flex; + width: 100%; + justify-content: center; +} +.ML__latex .ML__align_environment, +.ML__latex .ML__eqnarray_environment, +.ML__latex .ML__gather_environment { + display: inline-block; +} +.ML__latex .ML__mtable .ML__vertical-separator { + display: inline-block; + min-width: 1px; + box-sizing: border-box; +} +.ML__latex .ML__mtable .ML__arraycolsep { + display: inline-block; +} +.ML__latex .ML__mtable .col-align-m > .ML__vlist-t { + text-align: center; +} +.ML__latex .ML__mtable .col-align-c > .ML__vlist-t { + text-align: center; +} +.ML__latex .ML__mtable .col-align-l > .ML__vlist-t { + text-align: left; +} +.ML__latex .ML__mtable .col-align-r > .ML__vlist-t { + text-align: right; +} +[data-href] { + cursor: pointer; +} +.ML__error { + display: inline-block; + background-image: radial-gradient(ellipse at center, hsl(341, 100%, 40%), rgba(0, 0, 0, 0) 70%); + background-color: hsla(341, 100%, 40%, 0.1); + background-repeat: repeat-x; + background-size: 3px 3px; + padding-bottom: 3px; + background-position: 0 100%; +} +.ML__error > .ML__error { + background: transparent; + padding: 0; +} +.ML__placeholder { + color: var(--_placeholder-color); + opacity: var(--_placeholder-opacity); + padding-left: 0.4ex; + padding-right: 0.4ex; + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; +} +.ML__notation { + position: absolute; + box-sizing: border-box; + line-height: 0; +} +/* This class is used to implement the \`\\mathtip\` and \`\\texttip\` commands + For UI elements, see \`[data-ML__tooltip]\` +*/ +.ML__tooltip-container { + position: relative; + transform: scale(0); +} +.ML__tooltip-container .ML__tooltip-content { + position: fixed; + display: inline-table; + visibility: hidden; + z-index: 2; + width: max-content; + max-width: 400px; + padding: 12px 12px; + border: var(--_tooltip-border); + border-radius: var(--_tooltip-border-radius); + background: var(--_tooltip-background-color); + --_selection-color: var(--_tooltip-color); + color: var(--_tooltip-color); + box-shadow: var(--_tooltip-box-shadow); + opacity: 0; + transition: opacity 0.15s cubic-bezier(0.4, 0, 1, 1); +} +.ML__tooltip-container .ML__tooltip-content .ML__text { + white-space: normal; +} +.ML__tooltip-container .ML__tooltip-content .ML__base { + display: contents; +} +.ML__tooltip-container:hover .ML__tooltip-content { + visibility: visible; + opacity: 1; + font-size: 0.75em; + transform: scale(1) translate(0, 3em); +} +.ML__bg { + background-color: transparent !important; +} +.ML__bg::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: var(--bg-color); + z-index: -1; + box-sizing: border-box; +} +`;var oh=`#mathlive-environment-popover.is-visible { + visibility: visible; +} +#mathlive-environment-popover { + --_environment-panel-height: var(--environment-panel-height, 70px); + --_accent-color: var(--accent-color, #aaa); + --_background: var(--environment-panel-background, #fff); + --_button-background: var(--environment-panel-button-background, white); + --_button-background-hover: var(--environment-panel-button-background-hover, #f5f5f7); + --_button-background-active: var(--environment-panel-button-background-active, #f5f5f7); + --_button-text: var(--environment-panel-button-text, #e3e4e8); + position: absolute; + width: calc(var(--_environment-panel-height) * 2); + height: var(--_environment-panel-height); + border-radius: 4px; + border: 1.5px solid var(--_accent-color); + background-color: var(--_background); + box-shadow: 0 0 30px 0 var(--environment-shadow, rgba(0, 0, 0, 0.4)); + pointer-events: all; + visibility: hidden; +} +#mathlive-environment-popover .MLEP__array-buttons { + height: calc(var(--_environment-panel-height) * 5/4); + width: calc(var(--_environment-panel-height) * 5/4); + margin-left: calc(0px - var(--_environment-panel-height) * 0.16); + margin-top: calc(0px - var(--_environment-panel-height) * 0.19); +} +#mathlive-environment-popover .MLEP__array-buttons .font { + fill: white; +} +#mathlive-environment-popover .MLEP__array-buttons circle { + fill: #7f7f7f; + transition: fill 300ms; +} +#mathlive-environment-popover .MLEP__array-buttons .MLEP__array-insert-background { + fill-opacity: 1; + fill: var(--_background); + stroke: var(--_accent-color); + stroke-width: 3px; +} +#mathlive-environment-popover .MLEP__array-buttons line { + stroke: var(--_accent-color); + stroke-opacity: 0; + stroke-width: 40; + pointer-events: none; + transition: stroke-opacity 300ms; + stroke-linecap: round; +} +#mathlive-environment-popover .MLEP__array-buttons g[data-command]:hover circle { + fill: var(--_accent-color); +} +#mathlive-environment-popover .MLEP__array-buttons g[data-command]:hover line { + stroke-opacity: 1; +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls { + height: 100%; + width: 50%; +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options { + width: var(--_environment-panel-height); + height: var(--_environment-panel-height); + display: flex; + flex-wrap: wrap; + flex-direction: row; + justify-content: space-around; +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg { + pointer-events: all; + margin-top: 2px; + width: calc(var(--_environment-panel-height) / 3 * 28 / 24); + height: calc(var(--_environment-panel-height) / 3 - 2px); + border-radius: calc(var(--_environment-panel-height) / 25); + background-color: var(--_button-background); +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg:hover { + background-color: var(--_button-background-hover); +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg path, +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg line { + stroke: var(--_button-text); + stroke-width: 2; + stroke-linecap: round; +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg rect, +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg path { + fill-opacity: 0; +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg.active { + pointer-events: none; + background-color: var(--_button-background-active); +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg.active path, +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg.active line { + stroke: var(--_accent-color); +} +#mathlive-environment-popover .MLEP__environment-delimiter-controls .MLEP__array-delimiter-options svg.active circle { + fill: var(--_accent-color); +} +`;var ah=`/* The element that display info while in latex mode */ +#mathlive-suggestion-popover { + --_suggestion-zindex: var(--suggestion-zindex, 100); + background-color: rgba(97, 97, 97); + color: #fff; + text-align: center; + border-radius: 8px; + position: fixed; + z-index: var(--_suggestion-zindex); + display: none; + flex-direction: column; + justify-content: center; + box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22); +} +#mathlive-suggestion-popover.top-tip::after { + content: ''; + position: absolute; + top: -15px; + left: calc(50% - 15px); + width: 0; + height: 0; + border-left: 15px solid transparent; + border-right: 15px solid transparent; + border-bottom: 15px solid rgba(97, 97, 97); + font-size: 1rem; +} +#mathlive-suggestion-popover.bottom-tip::after { + content: ''; + position: absolute; + bottom: -15px; + left: calc(50% - 15px); + width: 0; + height: 0; + border-left: 15px solid transparent; + border-right: 15px solid transparent; + border-top: 15px solid rgba(97, 97, 97); + font-size: 1rem; +} +#mathlive-suggestion-popover.is-animated { + transition: all 0.2s cubic-bezier(0.64, 0.09, 0.08, 1); + animation: ML__fade-in cubic-bezier(0, 0, 0.2, 1) 0.15s; +} +#mathlive-suggestion-popover.is-visible { + display: flex; +} +@keyframes ML__fade-in { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +/* The wrapper class for the entire content of the popover panel */ +#mathlive-suggestion-popover ul { + display: flex; + flex-flow: column; + list-style: none; + margin: 0; + padding: 0; + align-items: flex-start; + max-height: 400px; + overflow-y: auto; +} +#mathlive-suggestion-popover li { + display: flex; + flex-direction: row; + justify-content: space-between; + margin: 8px; + padding: 8px; + width: calc(100% - 16px - 16px); + column-gap: 1em; + border-radius: 8px; + cursor: pointer; + /* Since the content can be clicked on, provide feedback on hover */ +} +#mathlive-suggestion-popover li a { + color: #5ea6fd; + padding-top: 0.3em; + margin-top: 0.4em; + display: block; +} +#mathlive-suggestion-popover li a:hover { + color: #5ea6fd; + text-decoration: underline; +} +#mathlive-suggestion-popover li:hover, +#mathlive-suggestion-popover li.is-pressed, +#mathlive-suggestion-popover li.is-active { + background: rgba(255, 255, 255, 0.1); +} +/* The command inside a popover (inside a #mathlive-suggestion-popover) */ +.ML__popover__command { + font-size: 1.6rem; + font-family: KaTeX_Main; +} +.ML__popover__current { + background: #5ea6fd; + color: #fff; +} +.ML__popover__latex { + font-family: 'IBM Plex Mono', 'Source Code Pro', Consolas, 'Roboto Mono', Menlo, 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace; + align-self: center; +} +/* The keyboard shortcuts for a symbol as displayed in the popover */ +.ML__popover__keybinding { + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-size: 0.8em; + opacity: 0.7; +} +/* Style for the character that joins the modifiers of a keyboard shortcut +(usually a "+" sign)*/ +.ML__shortcut-join { + opacity: 0.5; +} +`;var sh=`/* The element that displays the keys as the user type them */ +#mathlive-keystroke-caption-panel { + visibility: hidden; + /*min-width: 160px;*/ + /*background-color: rgba(97, 97, 200, .95);*/ + background: var(--secondary, hsl(var(--_hue), 19%, 26%)); + border-color: var(--secondary-border, hsl(0, 0%, 91%)); + box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23); + text-align: center; + border-radius: 6px; + padding: 16px; + position: absolute; + z-index: 1; + display: flex; + flex-direction: row-reverse; + justify-content: center; + --keystroke: white; + --on-keystroke: #555; + --keystroke-border: #f7f7f7; +} +@media (prefers-color-scheme: dark) { + body:not([theme='light']) #mathlive-keystroke-caption-panel { + --keystroke: hsl(var(--_hue), 50%, 30%); + --on-keystroke: hsl(0, 0%, 98%); + --keystroke-border: hsl(var(--_hue), 50%, 25%); + } +} +body[theme='dark'] #mathlive-keystroke-caption-panel { + --keystroke: hsl(var(--_hue), 50%, 30%); + --on-keystroke: hsl(0, 0%, 98%); + --keystroke-border: hsl(var(--_hue), 50%, 25%); +} +#mathlive-keystroke-caption-panel > span { + min-width: 14px; + /*height: 8px;*/ + margin: 0 8px 0 0; + padding: 4px; + background-color: var(--keystroke); + color: var(--on-keystroke); + fill: currentColor; + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-size: 1em; + border-radius: 6px; + border: 2px solid var(--keystroke-border); + /*box-shadow: 0 7px 14px rgba(0,0,0,0.25), 0 5px 5px rgba(0,0,0,0.22);*/ +} +`;var lh=`.ML__keyboard { + --_keyboard-height: 0; + --_keyboard-zindex: var(--keyboard-zindex, 105); + --_accent-color: var(--keyboard-accent-color, #0c75d8); + --_background: var(--keyboard-background, #cacfd7); + --_border: var(--keyboard-border, #ddd); + --_padding-horizontal: var(--keyboard-padding-horizontal, 0px); + --_padding-top: var(--keyboard-padding-top, 5px); + --_padding-bottom: var(--keyboard-padding-bottom, 0px); + --_row-padding-left: var(--keyboard-row-padding-left, 0px); + --_row-padding-right: var(--keyboard-row-padding-right, 0px); + --_toolbar-text: var(--keyboard-toolbar-text, #2c2e2f); + --_toolbar-text-active: var(--keyboard-toolbar-text-active, var(--_accent-color)); + --_toolbar-background: var(--keyboard-toolbar-background, transparent); + --_toolbar-background-hover: var(--keyboard-toolbar-background-hover, #eee); + --_toolbar-background-selected: var(--keyboard-toolbar-background-selected, transparent); + --_toolbar-font-size: var(--keyboard-toolbar-font-size, '135%'); + --_horizontal-rule: var(--keyboard-horizontal-rule, 1px solid #fff); + --_keycap-background: var(--keycap-background, #f0f0f0); + --_keycap-background-hover: var(--keycap-background-hover, #f5f5f7); + --_keycap-background-active: var(--keycap-background-active, var(--_accent-color)); + --_keycap-background-pressed: var(--keycap-background-pressed, var(--_accent-color)); + --_keycap-border: var(--keycap-border, #e5e6e9); + --_keycap-border-bottom: var(--keycap-border-bottom, #8d8f92); + --_keycap-text: var(--keycap-text, #000); + --_keycap-text-active: var(--keycap-text-active, #fff); + --_keycap-text-hover: var(--keycap-text-hover, var(--_keycap-text)); + --_keycap-text-pressed: var(--keycap-text-pressed, #fff); + --_keycap-shift-text: var(--keycap-shift-text, var(--_accent-color)); + --_keycap-primary-background: var(--keycap-primary-background, var(--_accent-color)); + --_keycap-primary-text: var(--keycap-primary-text, #ddd); + --_keycap-primary-background-hover: var(--keycap-primary-background-hover, #0d80f2); + --_keycap-secondary-background: var(--keycap-secondary-background, #a0a9b8); + --_keycap-secondary-background-hover: var(--keycap-secondary-background-hover, #7d8795); + --_keycap-secondary-text: var(--keycap-secondary-text, #060707); + --_keycap-secondary-border: var(--keycap-secondary-border, #c5c9d0); + --_keycap-secondary-border-bottom: var(--keycap-secondary-border-bottom, #989da6); + --_keycap-height: var(--keycap-height, 60px); + /* Keycap width (incl. margin) */ + --_keycap-max-width: var(--keycap-max-width, 100px); + --_keycap-gap: var(--keycap-gap, 8px); + --_keycap-font-size: var(--keycap-font-size, clamp(16px, 4cqw, 24px)); + --_keycap-small-font-size: var(--keycap-small-font-size, calc(var(--keycap-font-size) * 0.8)); + --_keycap-extra-small-font-size: var(--keycap-extra-small-font-size, calc(var(--keycap-font-size) / 1.42)); + --_variant-panel-background: var(--variant-panel-background, #f0f0f0); + --_variant-keycap-text: var(--variant-keycap-text, var(--_keycap-text)); + --_variant-keycap-text-active: var(--variant-keycap-text-active, var(--_keycap-text-active)); + --_variant-keycap-background-active: var(--variant-keycap-background-active, var(--_accent-color)); + --_variant-keycap-length: var(--variant-keycap-length, 70px); + --_variant-keycap-font-size: var(--variant-keycap-font-size, 30px); + --_variant-keycap-aside-font-size: var(--variant-keycap-aside-font-size, 12px); + --_keycap-shift-font-size: var(--keycap-shift-font-size, 16px); + --_keycap-shift-color: var(--keycap-shift-color, var(--_accent-color)); + --_box-placeholder-color: var(--box-placeholder-color, var(--_accent-color)); + --_box-placeholder-pressed-color: var(--box-placeholder-pressed-color, var(--keycap-text-pressed)); + --_keycap-glyph-size: var(--keycap-glyph-size, 20px); + --_keycap-glyph-size-lg: var(--keycap-glyph-size-lg, 24px); + --_keycap-glyph-size-xl: var(--keycap-glyph-size-xl, 50px); +} +.is-math-mode .MLK__rows .if-text-mode, +.is-text-mode .MLK__rows .if-math-mode { + display: none; +} +.if-can-undo, +.if-can-redo, +.if-can-copy, +.if-can-cut, +.if-can-paste { + opacity: 0.4; + pointer-events: none; +} +.can-undo .if-can-undo, +.can-redo .if-can-redo, +.can-copy .if-can-copy, +.can-cut .if-can-cut, +.can-paste .if-can-paste { + opacity: 1; + pointer-events: all; +} +body > .ML__keyboard { + position: fixed; + --_padding-bottom: calc(var(--keyboard-padding-bottom, 0px) + env(safe-area-inset-bottom, 0)); +} +body > .ML__keyboard.is-visible > .MLK__backdrop { + box-shadow: 0 -5px 6px rgba(0, 0, 0, 0.08); + border-top: 1px solid var(--_border); +} +body > .ML__keyboard.backdrop-is-transparent.is-visible > .MLK__backdrop { + box-shadow: none; + border: none; +} +body > .ML__keyboard.is-visible.animate > .MLK__backdrop { + transition: 0.28s cubic-bezier(0, 0, 0.2, 1); + transition-property: transform, opacity; + transition-timing-function: cubic-bezier(0.4, 0, 1, 1); +} +.ML__keyboard { + position: relative; + overflow: hidden; + top: 0; + left: 0; + height: 100%; + width: 100%; + z-index: var(--_keyboard-zindex); + box-sizing: border-box; + outline: none; + border: none; + margin: 0; + padding: 0; + line-height: 1; + overflow-wrap: unset; + text-align: left; + vertical-align: baseline; + cursor: auto; + white-space: pre; + box-shadow: none; + opacity: 1; + transform: none; + pointer-events: none; +} +.ML__keyboard :where(div) { + box-sizing: border-box; + outline: none; + border: none; + margin: 0; + padding: 0; + line-height: 1; + overflow-wrap: unset; + text-align: left; + vertical-align: baseline; + cursor: auto; + white-space: pre; + box-shadow: none; + transform: none; +} +.MLK__backdrop { + position: absolute; + bottom: calc(-1 * var(--_keyboard-height)); + width: 100%; + height: var(--_keyboard-height); + box-sizing: border-box; + padding-top: var(--_padding-top); + padding-bottom: var(--_padding-bottom); + padding-left: var(--_padding-horizontal); + padding-right: var(--_padding-horizontal); + opacity: 0; + visibility: hidden; + transform: translate(0, 0); + background: var(--_background); +} +.backdrop-is-transparent .MLK__backdrop { + background: transparent; +} +/* If a custom layout has a custom container/backdrop + (backdrop-is-transparent), make sure to let pointer event go through. */ +.backdrop-is-transparent .MLK__plate { + background: transparent; + pointer-events: none; +} +/* If a custom layout has a custom container/backdrop, make sure to + allow pointer events on it. */ +.backdrop-is-transparent .MLK__layer > div > div { + pointer-events: all; +} +.ML__keyboard.is-visible > .MLK__backdrop { + transform: translate(0, calc(-1 * var(--_keyboard-height))); + opacity: 1; + visibility: visible; +} +.caps-lock-indicator { + display: none; + width: 8px; + height: 8px; + background: #0cbc0c; + box-shadow: inset 0 0 4px 0 #13ca13, 0 0 4px 0 #a9ef48; + border-radius: 8px; + right: 8px; + top: 8px; + position: absolute; +} +.ML__keyboard.is-caps-lock .caps-lock-indicator { + display: block; +} +.ML__keyboard.is-caps-lock .shift { + background: var(--_keycap-background-active); + color: var(--_keycap-text-active); +} +.MLK__plate { + position: absolute; + top: var(--_padding-top); + left: var(--_padding-horizontal); + width: calc(100% - 2 * var(--_padding-horizontal)); + margin: 0; + padding: 0; + box-sizing: border-box; + container-type: inline-size; + touch-action: none; + -webkit-user-select: none; + user-select: none; + pointer-events: all; + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-size: 16px; + /* Size of toolbar labels */ + font-weight: 400; + text-shadow: none; +} +.ML__box-placeholder { + color: var(--_box-placeholder-color); +} +.MLK__tex { + font-family: KaTeX_Main, KaTeX_Math, 'Cambria Math', 'Asana Math', OpenSymbol, Symbola, STIX, Times, serif !important; +} +.MLK__tex-math { + font-family: KaTeX_Math, KaTeX_Main, 'Cambria Math', 'Asana Math', OpenSymbol, Symbola, STIX, Times, serif !important; + font-style: italic; +} +.MLK__layer { + display: none; + outline: none; +} +.MLK__layer.is-visible { + display: flex; + flex-flow: column; +} +/* Keyboard layouts are made or rows of keys... */ +.MLK__rows { + --_keycap-width: var(--keycap-width, min(var(--_keycap-max-width), 10cqw)); + display: flex; + flex-flow: column; + align-items: center; + border-collapse: separate; + clear: both; + border: 0; + margin: 0; + margin-bottom: var(--_keycap-gap); + gap: var(--_keycap-gap); + /* If the styling include, e.g., some shadows, they will be + cut off by the overflow. In that case, set the padding to + compensate. */ + padding-left: var(--_row-padding-left); + padding-right: var(--_row-padding-right); + overflow: visible; + touch-action: none; +} +.MLK__rows > .MLK__row { + display: flex; + flex-flow: row; + justify-content: center; + width: 100%; + gap: var(--_keycap-gap); + margin: 0; + padding: 0; + /* For the alignment of the text on some modifiers (e.g. shift) */ + /* Extra spacing between two adjacent keys */ +} +.MLK__rows > .MLK__row .tex { + font-family: KaTeX_Math, KaTeX_Main, 'Cambria Math', 'Asana Math', OpenSymbol, Symbola, STIX, Times, serif !important; +} +.MLK__rows > .MLK__row .tex-math { + font-family: KaTeX_Math, 'Cambria Math', 'Asana Math', OpenSymbol, Symbola, STIX, Times, serif !important; +} +.MLK__rows > .MLK__row .big-op { + font-size: calc(1.25 * var(--_keycap-font-size)); +} +.MLK__rows > .MLK__row .small { + font-size: var(--_keycap-small-font-size); +} +.MLK__rows > .MLK__row .bottom { + justify-content: flex-end; +} +.MLK__rows > .MLK__row .left { + align-items: flex-start; + padding-left: 12px; +} +.MLK__rows > .MLK__row .right { + align-items: flex-end; + padding-right: 12px; +} +.MLK__rows > .MLK__row .w0 { + width: 0; +} +.MLK__rows > .MLK__row .w5 { + width: calc(0.5 * var(--_keycap-width) - var(--_keycap-gap)); +} +.MLK__rows > .MLK__row .w15 { + width: calc(1.5 * var(--_keycap-width) - var(--_keycap-gap)); +} +.MLK__rows > .MLK__row .w20 { + width: calc(2 * var(--_keycap-width) - var(--_keycap-gap)); +} +.MLK__rows > .MLK__row .w40 { + width: calc(4 * var(--_keycap-width) - var(--_keycap-gap)); +} +.MLK__rows > .MLK__row .w50 { + width: calc(5 * var(--_keycap-width) - var(--_keycap-gap)); +} +.MLK__rows > .MLK__row .MLK__keycap.w50 { + font-size: 80%; + padding-top: 10px; + font-weight: 100; +} +.MLK__rows > .MLK__row .separator { + background: transparent; + border: none; + pointer-events: none; +} +.MLK__rows > .MLK__row .horizontal-rule { + height: 6px; + margin-top: 3px; + margin-bottom: 0; + width: 100%; + border-radius: 0; + border-top: var(--_horizontal-rule); +} +.MLK__rows > .MLK__row .ghost { + background: var(--_toolbar-background); + border: none; + color: var(--_toolbar-text); +} +.MLK__rows > .MLK__row .ghost:hover { + background: var(--_toolbar-background-hover); +} +.MLK__rows > .MLK__row .bigfnbutton { + font-size: var(--_keycap-extra-small-font-size); +} +.MLK__rows > .MLK__row .shift, +.MLK__rows > .MLK__row .action { + color: var(--_keycap-secondary-text); + background: var(--_keycap-secondary-background); + border-color: var(--_keycap-secondary-border); + border-bottom-color: var(--_keycap-secondary-border-bottom); + line-height: 0.8; + font-size: min(1rem, var(--_keycap-small-font-size)); + font-weight: 600; + padding: 8px 12px 8px 12px; +} +.MLK__rows > .MLK__row .shift:hover, +.MLK__rows > .MLK__row .action:hover { + background: var(--_keycap-secondary-background-hover); +} +.MLK__rows > .MLK__row .action.primary { + background: var(--_keycap-primary-background); + color: var(--_keycap-primary-text); +} +.MLK__rows > .MLK__row .action.primary:hover { + background: var(--_keycap-primary-background-hover); + color: var(--_keycap-primary-text); +} +.MLK__rows > .MLK__row .shift.selected, +.MLK__rows > .MLK__row .action.selected { + color: var(--_toolbar-text-active); +} +.MLK__rows > .MLK__row .shift.selected.is-pressed, +.MLK__rows > .MLK__row .action.selected.is-pressed, +.MLK__rows > .MLK__row .shift.selected.is-active, +.MLK__rows > .MLK__row .action.selected.is-active { + color: white; +} +.MLK__rows > .MLK__row .warning { + background: #cd0030; + color: white; +} +.MLK__rows > .MLK__row .warning svg.svg-glyph { + width: var(--_keycap-glyph-size-lg); + height: var(--_keycap-glyph-size-lg); + min-height: var(--_keycap-glyph-size-lg); +} +/** A regular keycap + * Use the :where() pseudo-class to give it a very low specifity, + * so that it can be overriden by custom style. + */ +:where(.MLK__rows > .MLK__row div) { + display: flex; + flex-flow: column; + align-items: center; + justify-content: space-evenly; + width: calc(var(--_keycap-width) - var(--_keycap-gap)); + height: var(--_keycap-height); + box-sizing: border-box; + padding: 0; + vertical-align: top; + text-align: center; + float: left; + color: var(--_keycap-text); + fill: currentColor; + font-size: var(--_keycap-font-size); + background: var(--_keycap-background); + border: 1px solid var(--_keycap-border); + border-bottom-color: var(--_keycap-border-bottom); + border-radius: 6px; + cursor: pointer; + touch-action: none; + /* Keys with a variants panel */ + position: relative; + overflow: hidden; + -webkit-user-select: none; + user-select: none; + -webkit-tap-highlight-color: transparent; +} +:where(.MLK__rows > .MLK__row div):hover { + overflow: visible; + background: var(--_keycap-background-hover); + color: var(--_keycap-text-hover); +} +:where(.MLK__rows > .MLK__row div) .ML__latex { + pointer-events: none; + touch-action: none; +} +:where(.MLK__rows > .MLK__row div) svg.svg-glyph { + margin: 8px 0; + width: var(--_keycap-glyph-size); + height: var(--_keycap-glyph-size); + min-height: var(--_keycap-glyph-size); +} +:where(.MLK__rows > .MLK__row div) svg.svg-glyph-lg { + margin: 8px 0; + width: var(--_keycap-glyph-size-lg); + height: var(--_keycap-glyph-size-lg); + min-height: var(--_keycap-glyph-size-lg); +} +:where(.MLK__rows > .MLK__row div).MLK__tex-math { + font-size: 25px; +} +:where(.MLK__rows > .MLK__row div).is-pressed { + background: var(--_keycap-background-pressed); + color: var(--_keycap-text-pressed); + --_box-placeholder-color: var(--_box-placeholder-pressed-color); +} +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-active, +:where(.MLK__rows > .MLK__row div).action.is-active, +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-pressed, +:where(.MLK__rows > .MLK__row div).action.is-pressed { + z-index: calc(var(--_keyboard-zindex) - 5); +} +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-active aside, +:where(.MLK__rows > .MLK__row div).action.is-active aside, +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-pressed aside, +:where(.MLK__rows > .MLK__row div).action.is-pressed aside { + display: none; +} +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-active .MLK__shift, +:where(.MLK__rows > .MLK__row div).action.is-active .MLK__shift, +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-pressed .MLK__shift, +:where(.MLK__rows > .MLK__row div).action.is-pressed .MLK__shift { + display: none; +} +:where(.MLK__rows > .MLK__row div).shift.is-pressed, +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-pressed, +:where(.MLK__rows > .MLK__row div).action.is-pressed { + background: var(--_keycap-background-pressed); + color: var(--_keycap-text-pressed); +} +:where(.MLK__rows > .MLK__row div).shift.is-active, +:where(.MLK__rows > .MLK__row div).MLK__keycap.is-active, +:where(.MLK__rows > .MLK__row div).action.is-active { + background: var(--_keycap-background-active); + color: var(--_keycap-text-active); + --_box-placeholder-color: var(--_box-placeholder-pressed-color); +} +:where(.MLK__rows > .MLK__row div) small { + color: var(--_keycap-secondary-text); +} +:where(.MLK__rows > .MLK__row div) aside { + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-size: 10px; + line-height: 10px; + color: var(--_keycap-secondary-text); +} +/* Add an attribute 'data-tooltip' to display a tooltip on hover. +Note there are a different set of tooltip rules for the keyboard toggle +(it's in a different CSS tree) */ +.ML__keyboard [data-tooltip] { + position: relative; +} +.ML__keyboard [data-tooltip]::after { + position: absolute; + display: inline-table; + content: attr(data-tooltip); + top: inherit; + bottom: 100%; + width: max-content; + max-width: 200px; + padding: 8px 8px; + background: #616161; + color: #fff; + text-align: center; + z-index: 2; + box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 1px 5px 0 rgba(0, 0, 0, 0.12), 0 3px 1px -2px rgba(0, 0, 0, 0.2); + border-radius: 2px; + font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; + font-weight: 400; + font-size: 12px; + transition: all 0.15s cubic-bezier(0.4, 0, 1, 1) 1s; + opacity: 0; + transform: scale(0.5); +} +.ML__keyboard [data-tooltip]:hover { + position: relative; +} +.ML__keyboard [data-tooltip]:hover::after { + opacity: 1; + transform: scale(1); +} +.MLK__toolbar { + align-self: center; + display: flex; + flex-flow: row; + justify-content: space-between; + width: 100%; + max-width: 996px; + min-height: 32px; + /* Icons for undo/redo, etc. */ +} +.MLK__toolbar svg { + height: 20px; + width: 20px; +} +.MLK__toolbar > .left { + position: relative; + display: flex; + justify-content: flex-start; + flex-flow: row; +} +.MLK__toolbar > .right { + display: flex; + justify-content: flex-end; + flex-flow: row; +} +.MLK__toolbar > div > div { + /* "button" in the toolbar */ + display: flex; + align-items: center; + justify-content: center; + color: var(--_toolbar-text); + fill: currentColor; + background: var(--_toolbar-background); + font-size: var(--_toolbar-font-size); + padding: 4px 15px; + cursor: pointer; + width: max-content; + min-width: 42px; + min-height: 34px; + border: none; + padding-left: 10px; + padding-right: 10px; + padding-bottom: 8px; + padding-top: 8px; + margin-top: 0; + margin-bottom: 4px; + margin-left: 4px; + margin-right: 4px; + border-radius: 8px; + box-shadow: none; + border-bottom: 2px solid transparent; +} +.MLK__toolbar > div > div:not(.disabled):not(.selected):hover { + background: var(--_toolbar-background-hover); +} +.MLK__toolbar > div > div.disabled svg, +.MLK__toolbar > div > div.disabled:hover svg, +.MLK__toolbar > div > div.disabled.is-pressed svg { + color: var(--_toolbar-text); + opacity: 0.2; +} +.MLK__toolbar > div > div:hover, +.MLK__toolbar > div > div:active, +.MLK__toolbar > div > div.is-pressed, +.MLK__toolbar > div > div.is-active { + color: var(--_toolbar-text-active); +} +.MLK__toolbar > div > div.selected { + color: var(--_toolbar-text-active); + background: var(--_toolbar-background-selected); + border-radius: 0; + border-bottom-color: var(--_toolbar-text-active); + padding-bottom: 4px; + margin-bottom: 8px; +} +/* This is the element that displays variants on press+hold */ +.MLK__variant-panel { + visibility: hidden; + position: fixed; + display: flex; + flex-flow: row wrap-reverse; + justify-content: center; + align-content: center; + margin: 0; + padding: 0; + bottom: auto; + top: 0; + box-sizing: content-box; + transform: none; + z-index: calc(var(--_keyboard-zindex) + 1); + touch-action: none; + max-width: 350px; + background: var(--_variant-panel-background); + text-align: center; + border-radius: 6px; + padding: 6px; + box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22); + transition: none; +} +.MLK__variant-panel.is-visible { + visibility: visible; +} +.MLK__variant-panel.compact { + --_variant-keycap-length: var(--variant-keycap-length, 50px); + --_variant-keycap-font-size: var(--variant-keycap-font-size, 24px); + --_variant-keycap-aside-font-size: var(--variant-keycap-aside-font-size, 10px); +} +.MLK__variant-panel .item { + display: flex; + flex-flow: column; + align-items: center; + justify-content: center; + font-size: var(--_variant-keycap-font-size); + height: var(--_variant-keycap-length); + width: var(--_variant-keycap-length); + margin: 0; + box-sizing: border-box; + border-radius: 5px; + border: 1px solid transparent; + background: transparent; + pointer-events: all; + cursor: pointer; + color: var(--_variant-keycap-text); + fill: currentColor; +} +@media (max-height: 412px) { + .MLK__variant-panel .item { + --_variant-keycap-font-size: var(--variant-keycap-font-size, 24px); + --_variant-keycap-length: var(--variant-keycap-length, 50px); + } +} +.MLK__variant-panel .item .ML__latex { + pointer-events: none; +} +.MLK__variant-panel .item:hover { + color: var(--_keycap-text-hover); +} +.MLK__variant-panel .item.is-active { + background: var(--_variant-keycap-background-active); + color: var(--_variant-keycap-text-active); + --_box-placeholder-color: var(--_box-placeholder-pressed-color); +} +.MLK__variant-panel .item.is-pressed { + background: var(--_variant-keycap-background-pressed); + color: var(--_variant-keycap-text-pressed); + --_box-placeholder-color: var(--_box-placeholder-pressed-color); +} +.MLK__variant-panel .item.small { + font-size: var(--_keycap-small-font-size); +} +.MLK__variant-panel .item.swatch-button { + box-sizing: border-box; + background: #fbfbfb; +} +.MLK__variant-panel .item.swatch-button > span { + display: inline-block; + margin: 6px; + width: calc(100% - 12px); + height: calc(100% - 12px); + border-radius: 50%; +} +.MLK__variant-panel .item.swatch-button:hover { + background: #f0f0f0; +} +.MLK__variant-panel .item.swatch-button:hover > span { + border-radius: 2px; +} +.MLK__variant-panel .item.box > div, +.MLK__variant-panel .item.box > span { + border: 1px dashed rgba(0, 0, 0, 0.24); +} +.MLK__variant-panel .item .warning { + min-height: 60px; + min-width: 60px; + background: #cd0030; + color: white; + padding: 5px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 5px; +} +.MLK__variant-panel .item .warning.is-pressed, +.MLK__variant-panel .item .warning.is-active { + background: red; +} +.MLK__variant-panel .item .warning svg.svg-glyph { + width: var(--_keycap-glyph-size-xl); + height: var(--_keycap-glyph-size-xl); +} +.MLK__variant-panel .item aside { + font-size: var(--_variant-keycap-aside-font-size); + line-height: 12px; + opacity: 0.78; + padding-top: 2px; + width: 100%; + text-align: center; + text-wrap: wrap; +} +.MLK__keycap { + position: relative; +} +.MLK__shift { + display: block; + position: absolute; + right: 4px; + top: 4px; + font-size: var(--_keycap-shift-font-size); + color: var(--_keycap-shift-color); +} +.hide-shift .MLK__shift { + display: none; +} +@media (max-width: 414px) { + .MLK__variant-panel { + max-width: 350px; + --_variant-keycap-font-size: var(--variant-keycap-font-size, 24px); + --_variant-keycap-length: var(--variant-keycap-length, 50px); + } +} +/* @xs breakpoint: iPhone 5 */ +@container (max-width: 414px) { + .MLK__rows { + --_keycap-gap: max(var(--_keycap-gap, 2px), 2px); + --_keycap-height: var(--keycap-height, 42px); + --_keycap-width: var(--keycap-width, min(min(var(--_keycap-max-width)), 10cqw), 62px)); + } + .MLK__toolbar > div > div { + font-size: 100%; + margin-left: 2px; + margin-right: 2px; + } + .MLK__rows .shift, + .MLK__rows .action { + font-size: 65%; + } + .MLK__rows .warning svg.svg-glyph { + width: 14px; + height: 14px; + min-height: 14px; + } +} +@container (max-width: 744px) { + .MLK__rows { + --_keycap-gap: max(var(--keycap-gap, 2px), 2px); + --_keycap-height: var(--keycap-height, 52px); + --_keycap-width: var(--keycap-width, min(min(var(--_keycap-max-width), 10cqw), 62px)); + } + .MLK__toolbar > div > div { + padding-left: 0; + padding-right: 0; + } + .MLK__tooltip::after { + padding: 8px 16px; + font-size: 16px; + } + .MLK__rows > .MLK__row > div.fnbutton { + font-size: 16px; + } + .MLK__rows > .MLK__row > div.bigfnbutton { + font-size: calc(var(--_keycap-extra-small-font-size) / 1.55); + } + .MLK__rows > .MLK__row > div.small { + font-size: 13px; + } + .MLK__rows > .MLK__row > div > aside { + display: none; + } + .MLK__shift { + display: none; + } +} +/* Medium breakpoint: larger phones */ +@container (max-width: 768px) { + .MLK__rows { + --_keycap-height: var(--keycap-height, 42px); + } + .MLK__rows > .MLK__row > div > small { + font-size: 14px; + } +} +@media (max-height: 768px) { + .MLK__rows { + --_keycap-height: var(--keycap-height, 42px); + } + .MLK__rows > .MLK__row > div > small { + font-size: 14px; + } +} +@container (max-width: 1444px) { + .MLK__rows .if-wide { + display: none; + } +} +@media (prefers-color-scheme: dark) { + .ML__keyboard { + --_accent-color: var(--keyboard-accent-color, #0b5c9c); + --_background: var(--keyboard-background, #151515); + --_border: var(--keyboard-border, transparent); + --_toolbar-text: var(--keyboard-toolbar-text, #e3e4e8); + --_toolbar-background-hover: var(--keyboard-toolbar-background-hover, #303030); + --keyboard-toolbar-background-hover: #303030; + --_horizontal-rule: var(--keyboard-horizontal-rule, 1px solid #303030); + --_keycap-background: var(--keycap-background, #1f2022); + --_keycap-background-hover: var(--keycap-background-hover, #2f3032); + --_keycap-border: var(--_keycap-border, transparent); + --_keycap-border-bottom: var(--_keycap-border-bottom, transparent); + --_keycap-text: var(--keycap-text, #e3e4e8); + --_keycap-secondary-background: var(--keycap-secondary-background, #3d4144); + --_keycap-secondary-background-hover: var(--keycap-secondary-background-hover, #4d5154); + --_keycap-secondary-text: var(--keycap-secondary-text, #e7ebee); + --keycap-secondary-border: transparent; + --keycap-secondary-border-bottom: transparent; + --_keycap-secondary-border: var(--keycap-secondary-border, transparent); + --_keycap-secondary-border-bottom: var(--keycap-secondary-border-bottom, transparent); + --_variant-panel-background: var(--variant-panel-background, #303030); + --_variant-keycap-text-active: var(--variant-keycap-text-active, #fff); + } +} +/* Same as the media query, but with a class */ +[theme='dark'] .ML__keyboard { + --_accent-color: var(--keyboard-accent-color, #0b5c9c); + --_background: var(--keyboard-background, #151515); + --_border: var(--keyboard-border, transparent); + --_toolbar-text: var(--keyboard-toolbar-text, #e3e4e8); + --_toolbar-background-hover: var(--keyboard-toolbar-background-hover, #303030); + --keyboard-toolbar-background-hover: #303030; + --_horizontal-rule: var(--keyboard-horizontal-rule, 1px solid #303030); + --_keycap-background: var(--keycap-background, #1f2022); + --_keycap-background-hover: var(--keycap-background-hover, #2f3032); + --_keycap-border: var(--_keycap-border, transparent); + --_keycap-border-bottom: var(--_keycap-border-bottom, transparent); + --_keycap-text: var(--keycap-text, #e3e4e8); + --_keycap-secondary-background: var(--keycap-secondary-background, #3d4144); + --_keycap-secondary-background-hover: var(--keycap-secondary-background-hover, #4d5154); + --_keycap-secondary-text: var(--keycap-secondary-text, #e7ebee); + --keycap-secondary-border: transparent; + --keycap-secondary-border-bottom: transparent; + --_keycap-secondary-border: var(--keycap-secondary-border, transparent); + --_keycap-secondary-border-bottom: var(--keycap-secondary-border-bottom, transparent); + --_variant-panel-background: var(--variant-panel-background, #303030); + --_variant-keycap-text-active: var(--variant-keycap-text-active, #fff); +} +[theme='light'] .ML__keyboard { + --_accent-color: var(--keyboard-accent-color, #0c75d8); + --_background: var(--keyboard-background, #cacfd7); + --_border: var(--keyboard-border, #ddd); + --_toolbar-text: var(--keyboard-toolbar-text, #2c2e2f); + --_toolbar-background: var(--keyboard-toolbar-background, transparent); + --_toolbar-background-hover: var(--keyboard-toolbar-background-hover, #eee); + --_toolbar-background-selected: var(--keyboard-toolbar-background-selected, transparent); + --_horizontal-rule: var(--keyboard-horizontal-rule, 1px solid #fff); + --_keycap-background: var(--keycap-background, white); + --_keycap-background-hover: var(--keycap-background-hover, #f5f5f7); + --_keycap-background-active: var(--keycap-background-active, var(--_accent-color)); + --_keycap-background-pressed: var(--keycap-background-pressed, var(--_accent-color)); + --_keycap-border: var(--_keycap-border, #e5e6e9); + --_keycap-border-bottom: var(--_keycap-border-bottom, #8d8f92); + --_keycap-text: var(--keycap-text, #000); + --_keycap-text-active: var(--keycap-text-active, #fff); + --_keycap-text-hover: var(--keycap-text-hover, var(--_keycap-text)); + --_keycap-text-pressed: var(--keycap-text-pressed, #fff); + --_keycap-shift-text: var(--keycap-shift-text, var(--_accent-color)); + --_keycap-secondary-background: var(--keycap-secondary-background, #a0a9b8); + --_keycap-secondary-background-hover: var(--keycap-secondary-background-hover, #7d8795); + --_keycap-secondary-text: var(--keycap-secondary-text, #060707); + --_keycap-secondary-border: var(--keycap-secondary-border, #c5c9d0); + --_keycap-secondary-border-bottom: var(--keycap-secondary-border-bottom, #989da6); + --_variant-panel-background: var(--variant-panel-background, #f0f0f0); + --_variant-keycap-text: var(--variant-keycap-textvar, var(--_keycap-text)); + --_variant-keycap-text-active: var(--variant-keycap-text-active, var(--_keycap-text-active)); + --_variant-keycap-background-active: var(--variant-keycap-background-active, var(--_accent-color)); +} +`;var ch=`:host { + --primary-color: #5898ff; + --primary-color-dimmed: #c0c0f0; + --primary-color-dark: var(--blue-500); + --primary-color-light: var(--blue-100); + --primary-color-reverse: #ffffff; + --secondary-color: #ff8a65; + --secondary-color-dimmed: #f0d5c5; + --secondary-color-dark: var(--orange-500); + --secondary-color-light: var(--orange-100); + --secondary-color-reverse: #ffffff; + --link-color: #5898ff; + --link-color-dimmed: #c5c5c5; + --link-color-dark: #121212; + --link-color-light: #e2e2e2; + --link-color-reverse: #ffffff; + --semantic-blue: var(--blue-700); + --semantic-red: var(--red-400); + --semantic-orange: var(--orange-400); + --semantic-green: var(--green-700); + --neutral-100: #f5f5f5; + --neutral-200: #eeeeee; + --neutral-300: #e0e0e0; + --neutral-400: #bdbdbd; + --neutral-500: #9e9e9e; + --neutral-600: #757575; + --neutral-700: #616161; + --neutral-800: #424242; + --neutral-900: #212121; + --red-25: #fff8f7; + --red-50: #fff1ef; + --red-100: #ffeae6; + --red-200: #ffcac1; + --red-300: #ffa495; + --red-400: #ff7865; + --red-500: #f21c0d; + --red-600: #e50018; + --red-700: #d30024; + --red-800: #bd002c; + --red-900: #a1002f; + --orange-25: #fffbf8; + --orange-50: #fff7f1; + --orange-100: #fff3ea; + --orange-200: #ffe1c9; + --orange-300: #ffcca2; + --orange-400: #ffb677; + --orange-500: #fe9310; + --orange-600: #f58700; + --orange-700: #ea7c00; + --orange-800: #dc6d00; + --orange-900: #ca5b00; + --brown-25: #fff8ef; + --brown-50: #fff1df; + --brown-100: #ffe9ce; + --brown-200: #ebcca6; + --brown-300: #cdaf8a; + --brown-400: #af936f; + --brown-500: #856a47; + --brown-600: #7f5e34; + --brown-700: #78511f; + --brown-800: #6e4200; + --brown-900: #593200; + --yellow-25: #fffdf9; + --yellow-50: #fffcf2; + --yellow-100: #fffaec; + --yellow-200: #fff2ce; + --yellow-300: #ffe8ab; + --yellow-400: #ffdf85; + --yellow-500: #ffcf33; + --yellow-600: #f1c000; + --yellow-700: #dfb200; + --yellow-800: #c9a000; + --yellow-900: #ad8a00; + --lime-25: #f4ffee; + --lime-50: #e9ffdd; + --lime-100: #ddffca; + --lime-200: #a8fb6f; + --lime-300: #94e659; + --lime-400: #80d142; + --lime-500: #63b215; + --lime-600: #45a000; + --lime-700: #268e00; + --lime-800: #007417; + --lime-900: #005321; + --green-25: #f5fff5; + --green-50: #ebffea; + --green-100: #e0ffdf; + --green-200: #a7ffa7; + --green-300: #5afa65; + --green-400: #45e953; + --green-500: #17cf36; + --green-600: #00b944; + --green-700: #00a34a; + --green-800: #008749; + --green-900: #00653e; + --teal-25: #f3ffff; + --teal-50: #e6fffe; + --teal-100: #d9fffe; + --teal-200: #8dfffe; + --teal-300: #57f4f4; + --teal-400: #43e5e5; + --teal-500: #17cfcf; + --teal-600: #00c2c0; + --teal-700: #00b5b1; + --teal-800: #00a49e; + --teal-900: #009087; + --cyan-25: #f7fcff; + --cyan-50: #eff8ff; + --cyan-100: #e7f5ff; + --cyan-200: #c2e6ff; + --cyan-300: #95d5ff; + --cyan-400: #61c4ff; + --cyan-500: #13a7ec; + --cyan-600: #069eda; + --cyan-700: #0095c9; + --cyan-800: #0088b2; + --cyan-900: #0a7897; + --blue-25: #f7faff; + --blue-50: #eef5ff; + --blue-100: #e5f1ff; + --blue-200: #bfdbff; + --blue-300: #92c2ff; + --blue-400: #63a8ff; + --blue-500: #0d80f2; + --blue-600: #0077db; + --blue-700: #006dc4; + --blue-800: #0060a7; + --blue-900: #005086; + --indigo-25: #f8f7ff; + --indigo-50: #f1efff; + --indigo-100: #eae7ff; + --indigo-200: #ccc3ff; + --indigo-300: #ac99ff; + --indigo-400: #916aff; + --indigo-500: #63c; + --indigo-600: #5a21b2; + --indigo-700: #4e0b99; + --indigo-800: #3b0071; + --indigo-900: #220040; + --purple-25: #fbf7ff; + --purple-50: #f8f0ff; + --purple-100: #f4e8ff; + --purple-200: #e4c4ff; + --purple-300: #d49aff; + --purple-400: #c36aff; + --purple-500: #a219e6; + --purple-600: #9000c4; + --purple-700: #7c009f; + --purple-800: #600073; + --purple-900: #3d0043; + --magenta-25: #fff8fb; + --magenta-50: #fff2f6; + --magenta-100: #ffebf2; + --magenta-200: #ffcddf; + --magenta-300: #ffa8cb; + --magenta-400: #ff7fb7; + --magenta-500: #eb4799; + --magenta-600: #da3689; + --magenta-700: #c82179; + --magenta-800: #b00065; + --magenta-900: #8a004c; +} +@media (prefers-color-scheme: dark) { + :host { + --semantic-blue: var(--blue-700); + --semantic-red: var(--red-400); + --semantic-orange: var(--orange-400); + --semantic-green: var(--green-700); + --semantic-bg-blue: var(--blue-25); + --semantic-bg-red: var(--red-25); + --semantic-bg-orange: var(--orange-25); + --semantic-bg-green: var(--green-25); + --neutral-100: #121212; + --neutral-200: #424242; + --neutral-300: #616161; + --neutral-400: #757575; + --neutral-500: #9e9e9e; + --neutral-600: #bdbdbd; + --neutral-700: #e0e0e0; + --neutral-800: #eeeeee; + --neutral-900: #f5f5f5; + } +} +:host([theme='dark']) { + --semantic-blue: var(--blue-700); + --semantic-red: var(--red-400); + --semantic-orange: var(--orange-400); + --semantic-green: var(--green-700); + --semantic-bg-blue: var(--blue-25); + --semantic-bg-red: var(--red-25); + --semantic-bg-orange: var(--orange-25); + --semantic-bg-green: var(--green-25); + --neutral-100: #121212; + --neutral-200: #424242; + --neutral-300: #616161; + --neutral-400: #757575; + --neutral-500: #9e9e9e; + --neutral-600: #bdbdbd; + --neutral-700: #e0e0e0; + --neutral-800: #eeeeee; + --neutral-900: #f5f5f5; +} +/* @media (prefers-color-scheme: dark) { + :host { + --label-color: #fff; + --active-label-color: #000; + --menu-bg: #525252; + --active-bg: #5898ff; + --active-bg-dimmed: #5c5c5c; + } +} */ +:host { + --ui-font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; + --ui-font-size: 14px; + --ui-line-height: 1.5; + --ui-letter-spacing: 0.007em; + --mono-font-family: 'Berkeley Mono', 'JetBrains Mono', 'IBM Plex Mono', 'Source Code Pro', Menlo, Monaco, 'Courier New', monospace; + --ui-layer-1: var(--neutral-100); + --ui-layer-2: var(--neutral-200); + --ui-layer-3: var(--neutral-300); + --ui-layer-4: var(--neutral-400); + --ui-layer-5: var(--neutral-500); + --ui-layer-6: var(--neutral-600); + --ui-border-color: var(--primary-color); + --ui-border-radius: 4px; + --ui-text: var(--neutral-900); + --ui-text-secondary: var(--neutral-700); + --ui-text-placeholder: var(--neutral-500); + --ui-text-muted: var(--neutral-300); + /** A field is a UI element in which a user can type data, for + * example an input or textarea element. + */ + --ui-field-bg: var(--neutral-100); + --ui-field-bg-hover: var(--neutral-100); + --ui-field-bg-disabled: var(--neutral-300); + --ui-field-bg-invalid: var(--red-100); + --ui-field-bg-focus: var(--neutral-100); + --ui-field-border: 0.5px solid var(--border-color); + --ui-field-border-hover: 0.5px solid var(--border-color); + --ui-field-border-disabled: 0.5px solid var(--border-color); + --ui-field-border-invalid: 0.5px solid var(--border-color); + --ui-field-border-focus: 0.5px solid var(--border-color); + --ui-menu-bg: var(--neutral-100); + --ui-menu-text: var(--neutral-900); + --ui-menu-bg-hover: var(--neutral-200); + --ui-menu-text-hover: var(--neutral-900); + /** The \`active\` state is used for the state of menu items + * when they are selected. + */ + --ui-menu-bg-active: var(--primary-color); + --ui-menu-text-active: var(--primary-color-reverse); + /** The \`active-muted\` set is used for the state of + * submenus when they are open. + */ + --ui-menu-bg-active-muted: var(--neutral-300); + --ui-menu-text-active-muted: var(--neutral-900); + /* --ui-menu-shadow: 0 1px 2px 0 rgba(60, 64, 67, 0.302), +0 2px 6px 2px rgba(60, 64, 67, 0.149); */ + --ui-menu-shadow: 0 0 2px rgba(0, 0, 0, 0.5), 0 0 20px rgba(0, 0, 0, 0.2); + --ui-menu-divider: 0.5px solid #c7c7c7; + /* var(--neutral-300); */ + --ui-menu-z-index: 10000; + --page-bg: var(--neutral-100); + --content-bg: var(--neutral-200); +} +@media (prefers-color-scheme: dark) { + :host { + --ui-menu-bg: var(--neutral-200); + } +} +:host([theme='dark']) { + --ui-menu-bg: var(--neutral-200); +} +/* PingFang SC is a macOS font. Microsoft Yahei is a Windows font. + Noto is a Linux/Android font. +*/ +:lang(zh-cn), +:lang(zh-sg), +:lang(zh-my), +:lang(zh) { + --ui-font-family: -apple-system, system-ui, 'PingFang SC', 'Hiragino Sans GB', 'Noto Sans CJK SC', 'Noto Sans SC', 'Noto Sans', 'Microsoft Yahei UI', 'Microsoft YaHei New', 'Microsoft Yahei', '\u5FAE\u8F6F\u96C5\u9ED1', SimSun, '\u5B8B\u4F53', STXihei, '\u534E\u6587\u7EC6\u9ED1', sans-serif; +} +:lang(zh-tw), +:lang(zh-hk), +:lang(zh-mo) { + --ui-font-family: -apple-system, system-ui, 'Noto Sans', 'Microsoft JhengHei UI', 'Microsoft JhengHei', '\u5FAE\u8EDF\u6B63\u9ED1\u9AD4', '\u65B0\u7D30\u660E\u9AD4', 'PMingLiU', '\u7D30\u660E\u9AD4', 'MingLiU', sans-serif; +} +:lang(ja), +:lang(ja-jp), +:lang(ja-jp-mac) { + --ui-font-family: -apple-system, system-ui, 'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Noto Sans CJK JP', 'Noto Sans JP', 'Noto Sans', '\u6E38\u30B4\u30B7\u30C3\u30AF', '\u6E38\u30B4\u30B7\u30C3\u30AF\u4F53', YuGothic, 'Yu Gothic', '\u30E1\u30A4\u30EA\u30AA', Meiryo, '\uFF2D\uFF33 \uFF30\u30B4\u30B7\u30C3\u30AF', 'MS PGothic', sans-serif; +} +:lang(ko), +:lang(ko-kr), +:lang(ko-kr-std) { + --ui-font-family: -apple-system, system-ui, 'Noto Sans CJK KR', 'Noto Sans KR', 'Noto Sans', 'Malgun Gothic', '\uB9D1\uC740 \uACE0\uB515', 'Apple SD Gothic Neo', '\uC560\uD50C SD \uC0B0\uB3CC\uACE0\uB515 Neo', 'Apple SD \uC0B0\uB3CC\uACE0\uB515 Neo', '\uB3CB\uC6C0', Dotum, sans-serif; +} +:lang(ko-kr-apple) { + --ui-font-family: -apple-system, system-ui, 'Noto Sans CJK KR', 'Noto Sans KR', 'Noto Sans', 'Apple SD Gothic Neo', '\uC560\uD50C SD \uC0B0\uB3CC\uACE0\uB515 Neo', 'Apple SD \uC0B0\uB3CC\uACE0\uB515 Neo', '\uB3CB\uC6C0', Dotum, sans-serif; +} +:lang(zh-cn), +:lang(zh-sg), +:lang(zh-my), +:lang(zh), +:lang(zh-tw), +:lang(zh-hk), +:lang(zh-mo), +:lang(ja), +:lang(ja-jp), +:lang(ja-jp-mac), +:lang(ko), +:lang(ko-kr), +:lang(ko-kr-std), +:lang(ko-kr-apple) { + --ui-font-size: 1rem; + --ui-line-height: 1.7; + --ui-letter-spacing: 0; +} +:dir(rtl) { + --ui-line-height: auto; + --ui-letter-spacing: 0; +} +`;var uh=`.ui-menu *, +.ui-menu ::before, +.ui-menu ::after { + box-sizing: border-box; +} +.ui-menu { + display: none; + color-scheme: light dark; + -webkit-user-select: none; + /* Important: Safari iOS doesn't respect user-select */ + user-select: none; + cursor: default; + -webkit-touch-callout: none; + -webkit-tap-highlight-color: rgba(0 0 0 0); + --active-label-color: #fff; + /* ui-menu-text-active */ + --label-color: #121212; + /* ui-menu-text */ + --menu-bg: #e2e2e2; + /* ui-menu-background */ + --active-bg: #5898ff; + /* ui-menu-background-active */ + --active-bg-dimmed: #c5c5c5; + /* ui-menu-background-active-muted */ +} +/** Use the :where pseudo selector to make the specificity of the + * selector 0, so that it can be overridden by the user. + */ +:where(.ui-menu-container) { + position: absolute; + overflow: visible; + width: auto; + height: auto; + z-index: 10000; + border-radius: 8px; + background: var(--ui-menu-bg); + box-shadow: var(--ui-menu-shadow); + list-style: none; + padding: 6px 0 6px 0; + margin: 0; + user-select: none; + cursor: default; + color: var(--ui-menu-text); + font-weight: normal; + font-style: normal; + text-shadow: none; + text-transform: none; + letter-spacing: 0; + outline: none; + opacity: 1; + /* The [popover] elements have a 1px solid black border. Ugh. */ + border: none; + width: fit-content; + height: fit-content; +} +:where(.ui-menu-container > li) { + display: flex; + flex-flow: row; + align-items: center; + padding: 1px 7px 1px 7px; + margin-top: 0; + margin-left: 6px; + margin-right: 6px; + border-radius: 4px; + white-space: nowrap; + position: relative; + outline: none; + fill: currentColor; + user-select: none; + cursor: default; + text-align: left; + color: inherit; + font-family: var(--ui-font-family); + font-size: var(--ui-font-size); + line-height: var(--ui-line-height); + letter-spacing: var(--ui-letter-spacing); +} +:where(.ui-menu-container > li > .label) { + display: flex; + align-items: center; + justify-content: space-between; + appearance: none; + background: none; + outline: none; + width: 100%; + margin: 0; + padding: 1px 2px 1px 1px; + overflow: visible; + border: 1px solid transparent; + white-space: nowrap; + text-align: start; + align-content: center; +} +:where(.ui-menu-container > li:has(.heading)) { + margin-top: 0.5em; +} +:where(.ui-menu-container > li > .label.heading) { + font-weight: bold; + opacity: 0.4; +} +:where(.ui-menu-container > li.indent > .label) { + margin-inline-start: 12px; +} +:where(.ui-menu-container > li > .label.indent) { + margin-inline-start: 12px; +} +:where(.ui-menu-container > li[role='divider']) { + border-bottom: 1px solid var(--ui-menu-divider); + border-radius: 0; + padding: 0; + margin-left: 15px; + margin-right: 15px; + padding-top: 5px; + margin-bottom: 5px; + width: calc(100% - 30px); + /** 100% - (margin-left + margin-right) */ +} +:where(.ui-menu-container > li[aria-disabled='true']) { + opacity: 0.5; +} +:where(.ui-menu-container > li.active) { + background: var(--ui-menu-bg-active); + background: -apple-system-control-accent; + color: var(--ui-menu-text-active); +} +:where(.ui-menu-container > li.active.is-submenu-open) { + background: var(--ui-menu-bg-active-muted); + color: inherit; +} +:where(.ui-menu-container > li[aria-haspopup='true'] > .label) { + padding-inline-end: 0; +} +:where(.ui-menu-container > li[aria-haspopup='true'].active::after) { + color: var(--ui-menu-text-active); +} +/** Keyboard shortcut */ +:where(.ui-menu-container > li > kbd) { + font-family: var(--ui-font-family); + margin-inline-start: 12px; + opacity: 0.4; +} +:where(.ui-menu-container > li.active > kbd) { + opacity: 0.85; +} +.ui-trailing-chevron { + display: flex; + margin-inline-start: 24px; + width: 10px; + height: 10px; + margin-bottom: 4px; +} +.ui-trailing-chevron:dir(rtl) { + transform: scaleX(-1); +} +.ui-checkmark { + display: flex; + margin-inline-end: -11px; + margin-inline-start: -4px; + margin-top: 2px; + width: 16px; + height: 16px; +} +.ui-mixedmark { + display: flex; + margin-inline-end: -11px; + margin-inline-start: -4px; + margin-top: 2px; + width: 16px; + height: 16px; +} +`;var zr;function Ft(t){let e="";switch(t){case"mathfield-element":e=` + :host { display: inline-block; background-color: field; color: fieldtext; border-width: 1px; border-style: solid; border-color: #acacac; border-radius: 2px;} + :host([hidden]) { display: none; } + :host([disabled]), :host([disabled]:focus), :host([disabled]:focus-within) { outline: none; opacity: .5; } + :host(:focus), :host(:focus-within) { + outline: Highlight auto 1px; /* For Firefox */ + outline: -webkit-focus-ring-color auto 1px; + } + :host([readonly]:focus), :host([readonly]:focus-within), + :host([read-only]:focus), :host([read-only]:focus-within) { + outline: none; + }`;break;case"core":e=nh;break;case"mathfield":e=ih;break;case"environment-popover":e=oh;break;case"suggestion-popover":e=ah;break;case"keystroke-caption":e=sh;break;case"virtual-keyboard":e=lh;break;case"ui":e=ch;break;case"menu":e=uh;break;default:}return e}function sr(t){return zr||(zr={}),zr[t]||(zr[t]=new CSSStyleSheet,zr[t].replaceSync(Ft(t))),zr[t]}var Nt;function Ge(t){var e;try{if(!("adoptedStyleSheets"in document)){if(window.document.getElementById(`mathlive-style-${t}`))return;let r=window.document.createElement("style");r.id=`mathlive-style-${t}`,r.append(window.document.createTextNode(Ft(t))),window.document.head.appendChild(r);return}if(Nt||(Nt={}),((e=Nt[t])!=null?e:0)!==0)Nt[t]+=1;else{let r=sr(t);document.adoptedStyleSheets=[...document.adoptedStyleSheets,r],Nt[t]=1}}catch(r){console.error("Error injecting stylesheet",t,r)}}function ot(t){if("adoptedStyleSheets"in document&&Nt!=null&&Nt[t]&&(Nt[t]-=1,Nt[t]<=0)){let e=zr[t];document.adoptedStyleSheets=document.adoptedStyleSheets.filter(r=>r!==e)}}var Nr=class t extends x{constructor(e){var r;super(g(h({},e),{type:"accent",body:(r=e.body)!=null?r:void 0})),e.accentChar?this.accent=e.accentChar:this.svgAccent=e==null?void 0:e.svgAccent,this.skipBoundary=!0,this.captureSelection=!0}static fromJson(e){return new t(e)}toJson(){return g(h({},super.toJson()),{accentChar:this.accent,svgAccent:this.svgAccent})}render(e){var c;let r=new P({parent:e,mathstyle:"cramp"},this.style),i=(c=x.createBox(r,this.body))!=null?c:new w("\u25A1",{style:this.style}),n=0;!this.hasEmptyBranch("body")&&this.body.length===2&&this.body[1].isCharacterBox()&&(n=i.skew);let o=Math.min(i.height,Xe),a;if(this.svgAccent)a=Zi(this.svgAccent),o=r.metrics.bigOpSpacing1-o;else if(this.accent){let u=new w(this.accent,{fontFamily:"Main-Regular"});u.italic=0;let d=this.accent===8407||this.accent===8411||this.accent===8412?" ML__accent-combining-char":"";a=new w(u,{classes:"ML__accent-body"+d})}let s=(i.width-a.width)/2+i.left+2*n;a=new te({shift:0,children:[{box:new w(i)},-o,{box:a,marginLeft:s,classes:["ML__center"]}]});let l=new w(a,{type:"ord"});return this.caret&&(l.caret=this.caret),this.bind(r,l.wrap(r)),this.attachSupsub(r,{base:l})}};var nn={"(":")","{":"}","[":"]","|":"|","\\lbrace":"\\rbrace","\\lparen":"\\rparen","\\{":"\\}","\\langle":"\\rangle","\\lfloor":"\\rfloor","\\lceil":"\\rceil","\\vert":"\\vert","\\lvert":"\\rvert","\\Vert":"\\Vert","\\lVert":"\\rVert","\\lbrack":"\\rbrack","\\ulcorner":"\\urcorner","\\llcorner":"\\lrcorner","\\lgroup":"\\rgroup","\\lmoustache":"\\rmoustache"},on=Object.fromEntries(Object.entries(nn).map(([t,e])=>[e,t]));function ts(t){var e;return(e={"[":91,"]":93,"(":40,")":41,"\\mid":8739,"|":8739,"\u2223":8739,"\u2225":8741,"\\|":8739,"\\{":123,"\\}":125,"\\lbrace":123,"\\rbrace":125,"\\lparen":40,"\\rparen":41,"\\lbrack":91,"\\rbrack":93,"\\vert":8739,"\\lvert":8739,"\\mvert":8739,"\\rvert":8739,"\\Vert":8741,"\\lVert":8741,"\\mVert":8741,"\\rVert":8741,"\\parallel":8741,"\\shortparallel":8741,"\\langle":10216,"\\rangle":10217,"\\lfloor":8970,"\\rfloor":8971,"\\lceil":8968,"\\rceil":8969,"\\ulcorner":9484,"\\urcorner":9488,"\\llcorner":9492,"\\lrcorner":9496,"\\lgroup":10222,"\\rgroup":10223,"\\lmoustache":9136,"\\rmoustache":9137,"\\surd":8730}[t])!=null?e:t.codePointAt(0)}function ag(t,e,r,i){var a;let o=new w(ts(t),{fontFamily:"Main-Regular",isSelected:i.isSelected,classes:"ML__small-delim "+((a=i.classes)!=null?a:"")}).wrap(e);return r&&o.setTop((1-e.scalingFactor)*Ie),o}function dh(t,e,r,i,n){var s,l;let o=new P({parent:i,mathstyle:"textstyle"},n==null?void 0:n.style),a=new w(ts(t),{fontFamily:`Size${e}-Regular`,isSelected:n.isSelected,classes:((s=n.classes)!=null?s:"")+` ML__delim-size${e}`,type:(l=n.type)!=null?l:"ignore"}).wrap(o);return r&&a.setTop((1-o.scalingFactor)*Ie),a}function mh(t,e,r,i,n){var j;let o,a,s,l;o=s=l=ts(t),a=null;let c="Size1-Regular";t==="\\vert"||t==="\\lvert"||t==="\\rvert"||t==="\\mvert"||t==="\\mid"?s=o=l=8739:t==="\\Vert"||t==="\\lVert"||t==="\\rVert"||t==="\\mVert"||t==="\\|"?s=o=l=8741:t==="\\uparrow"?s=l=9168:t==="\\Uparrow"?s=l=8214:t==="\\downarrow"?o=s=9168:t==="\\Downarrow"?o=s=8214:t==="\\updownarrow"?(o=8593,s=9168,l=8595):t==="\\Updownarrow"?(o=8657,s=8214,l=8659):t==="["||t==="\\lbrack"?(o=9121,s=9122,l=9123,c="Size4-Regular"):t==="]"||t==="\\rbrack"?(o=9124,s=9125,l=9126,c="Size4-Regular"):t==="\\lfloor"||t==="\u230A"?(s=o=9122,l=9123,c="Size4-Regular"):t==="\\lceil"||t==="\u2308"?(o=9121,s=l=9122,c="Size4-Regular"):t==="\\rfloor"||t==="\u230B"?(s=o=9125,l=9126,c="Size4-Regular"):t==="\\rceil"||t==="\u2309"?(o=9124,s=l=9125,c="Size4-Regular"):t==="("||t==="\\lparen"?(o=9115,s=9116,l=9117,c="Size4-Regular"):t===")"||t==="\\rparen"?(o=9118,s=9119,l=9120,c="Size4-Regular"):t==="\\{"||t==="\\lbrace"?(o=9127,a=9128,l=9129,s=9130,c="Size4-Regular"):t==="\\}"||t==="\\rbrace"?(o=9131,a=9132,l=9133,s=9130,c="Size4-Regular"):t==="\\lgroup"||t==="\u27EE"?(o=9127,l=9129,s=9130,c="Size4-Regular"):t==="\\rgroup"||t==="\u27EF"?(o=9131,l=9133,s=9130,c="Size4-Regular"):t==="\\lmoustache"||t==="\u23B0"?(o=9127,l=9133,s=9130,c="Size4-Regular"):t==="\\rmoustache"||t==="\u23B1"?(o=9131,l=9129,s=9130,c="Size4-Regular"):t==="\\surd"?(o=57345,l=9143,s=57344,c="Size4-Regular"):t==="\\ulcorner"?(o=9484,s=l=32):t==="\\urcorner"?(o=9488,s=l=32):t==="\\llcorner"?(l=9492,s=o=32):t==="\\lrcorner"&&(o=9496,s=o=32);let u=Tr(o,c),d=u.height+u.depth,m=Tr(s,c),p=m.height+m.depth,f=Tr(l,c),y=f.height+f.depth,v=0,b=1;if(a!==null){let D=Tr(a,c);v=D.height+D.depth,b=2}let k=d+y+v,S=Math.max(0,Math.ceil((e-k)/(b*p))),A=k+S*b*p,E=Ie;r&&(E=E*i.scalingFactor);let C=A/2-E,_=.008,O=[];O.push({box:new w(l,{fontFamily:c})}),O.push(-_);let I=new w(s,{fontFamily:c});if(a===null)for(let D=0;D","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"]),lg=[0,1.2,1.8,2.4,3];function fh(t,e,r,i){return t===void 0||t==="."?lr(r,i.classes):(t==="<"||t==="\\lt"||t==="\u27E8"?t="\\langle":(t===">"||t==="\\gt"||t==="\u27E9")&&(t="\\rangle"),hh.has(t)||ph.has(t)?dh(t,e,!1,r,i):sg.has(t)?mh(t,lg[e],!1,r,i):(""+t,null))}var cg=[{type:"small",mathstyle:"scriptscriptstyle"},{type:"small",mathstyle:"scriptstyle"},{type:"small",mathstyle:"textstyle"},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],ug=[{type:"small",mathstyle:"scriptscriptstyle"},{type:"small",mathstyle:"scriptscriptstyle"},{type:"small",mathstyle:"textstyle"},{type:"stack"}],dg=[{type:"small",mathstyle:"scriptscriptstyle"},{type:"small",mathstyle:"scriptstyle"},{type:"small",mathstyle:"textstyle"},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}];function mg(t){return t.type==="small"?"Main-Regular":t.type==="large"?"Size"+t.size+"-Regular":(t.type,"Size4-Regular")}function hg(t,e,r,i){let n={"-4":0,"-3":1,0:2}[i.mathstyle.sizeDelta];for(let o=n;oe)return r[o]}return r[r.length-1]}function an(t,e,r,i,n,o){if(!e||e.length===0||e===".")return lr(n);e==="<"||e==="\\lt"?e="\\langle":(e===">"||e==="\\gt")&&(e="\\rangle");let a;ph.has(e)?a=cg:hh.has(e)?a=dg:a=ug;let s=hg(ts(e),r,a,n),l=new P({parent:n,mathstyle:s.mathstyle},o==null?void 0:o.style);return s.type==="small"?ag(e,l,i,g(h({},o),{type:t})):s.type==="large"?dh(e,s.size,i,l,g(h({},o),{type:t})):(s.type,mh(e,r,i,l,g(h({},o),{type:t})))}function hi(t,e,r,i,n,o){if(e===".")return lr(n,o==null?void 0:o.classes);let a=Ie*n.scalingFactor,s=901,l=5/Rt,c=Math.max(r-a,i+a),u=Math.max(c/500*s,2*c-l);return an(t,e,u,!0,n,o)}function lr(t,e){let r=new w(null,{classes:" ML__nulldelimiter "+(e!=null?e:""),type:"ignore"});return r.width=t.getRegisterAsEm("nulldelimiterspace"),r.wrap(new P({parent:t,mathstyle:"textstyle"}))}var Me=class t extends x{constructor(e){var r;super({type:"placeholder",command:"\\placeholder",mode:(r=e==null?void 0:e.mode)!=null?r:"math",style:e==null?void 0:e.style}),this.captureSelection=!0}static fromJson(e){return new t(e)}toJson(){return super.toJson()}render(e){let r;return this.value=e.placeholderSymbol,typeof e.renderPlaceholder=="function"?r=e.renderPlaceholder(e):r=this.createBox(e),this.caret&&(r.classes+=" ML__placeholder-selected"),r}_serialize(e){return e.skipPlaceholders?"":"\\placeholder{}"}};var gh=["matrix","matrix*","pmatrix","pmatrix*","bmatrix","bmatrix*","Bmatrix","Bmatrix*","vmatrix","vmatrix*","Vmatrix","Vmatrix*"],fc=["cases","dcases","rcases"],bh=["align","align*","aligned","gather","gather*","gathered","split"],pg=["array","subequations","eqnarray"];function yh(t){return bh.includes(t)||fc.includes(t)||fc.includes(t)||gh.includes(t)||pg.includes(t)}function rs(t){return gh.includes(t)}function xh(t){return fc.includes(t)}function vh(t){return bh.includes(t)}function fg(t,e,r){let i=0;for(let c of r.columns)"align"in c&&(i+=1);i=Math.max(i,r.minColumns);let n=0,o=[];for(let c of e){n=Math.max(n,Math.min(c.length,i));let u=0;for(;u0&&o[o.length-1].length===1&&xg(o[o.length-1][0])&&o.pop();let a=[];for(let c of o){if(c.length!==n)for(let u=c.length;u0&&t.every(e=>e.type==="first")}function bg(t,e,r){let i=new w(null,{classes:"ML__empty-line-anchor"}),n=t[0];n&&(n.id||(n.id=e.makeID()),i.atomID=n.id),i.setStyle("display","inline-block"),i.setStyle("width",0),i.setStyle("position","relative"),i.setStyle("height",Math.max(0,r.height+r.depth),"em"),i.setStyle("vertical-align",-r.depth,"em"),i.height=r.height,i.depth=r.depth;let o=t.find(a=>a.caret);return o!=null&&o.caret&&(i.caret=o.caret),t.some(a=>a.isSelected)&&i.selected(!0),i}function yg(t,e){return t.length===0?[new x({type:"first",mode:e})]:t[0].type!=="first"?[new x({type:"first",mode:e}),...t]:(t.slice(1).some(r=>r.type==="first"),t)}function xg(t){return t.length===1&&t[0].type==="first"}var z=class t extends x{get isMultiline(){let e=this.environmentName;return["lines","multline","multline*","align","split","gather","gathered"].includes(e)}constructor(e,r,i,n={}){var o,a,s,l;if(super({type:"array",isRoot:n.isRoot}),this.environmentName=e,n.columns)n.columns.length===0?this.colFormat=[{align:"l"}]:this.colFormat=[...n.columns];else if(n.minColumns){let c=[];for(let u=0;ur.map(i=>i.map(n=>n.toJson()))),rowGaps:this.rowGaps,columns:this.colFormat,colSeparationType:this.colSeparationType,minColumns:this.minColumns,minRows:this.minRows,maxRows:this.maxRows});return this.arraystretch!==void 0&&(e.arraystretch=this.arraystretch),this.arraycolsep!==void 0&&(e.arraycolsep=this.arraycolsep),this.leftDelim&&(e.leftDelim=this.leftDelim),this.rightDelim&&(e.rightDelim=this.rightDelim),this.isRoot&&(e.isRoot=!0),e.minColumns=this.minColumns,e.minRows=this.minRows,e.maxRows=this.maxRows,this.mathstyleName&&(e.mathstyleName=this.mathstyleName),this.classes.length>0&&(e.classes=this.classes),e}branch(e){var r;if(Ze(e))return(r=this._rows[e[0]][e[1]])!=null?r:void 0}createBranch(e){var r;return Ze(e)?(this.isDirty=!0,(r=this.branch(e))!=null?r:[]):[]}get rowCount(){return this._rows.length}get colCount(){return this._rows[0].length}get maxColumns(){return this.colFormat.filter(e=>!!e.align).length}removeBranch(e){if(Rr(e))return super.removeBranch(e);let[r,...i]=this.branch(e);return r.type,this._rows[e[0]][e[1]]=void 0,i.forEach(n=>{n.parent=void 0,n.parentBranch=void 0}),this.isDirty=!0,i}get hasChildren(){return this.children.length>0}get children(){let e=[];for(let r of this._rows)for(let i of r)if(i)for(let n of i)e.push(...n.children),e.push(n);return[...e,...super.children]}render(e){var K,N,j,D,W,ie;let r=new P({parent:e,mathstyle:this.mathstyleName},this.style),i=r.getRegisterAsEm("arrayrulewidth"),n=r.getRegisterAsEm("arraycolsep"),o=r.getRegisterAsEm("doublerulesep"),a=(N=(K=this.arraystretch)!=null?K:r.getRegisterAsNumber("arraystretch"))!=null?N:1,s=typeof this.arraycolsep=="number"?this.arraycolsep:n;this.colSeparationType==="small"&&(s=.2778*(new P({parent:e,mathstyle:"scriptstyle"}).scalingFactor/e.scalingFactor));let l=a*P0,c=.7*l,u=.3*l,d=0,m=[],p=0,f=this._rows.length;for(let X=0;X0&&(we+=u,Ct=Math.max(Ct,we),we=0),X0&&v.push(new te({individualShift:ye}))}let b=[],k=!1,S=!1,A=0,E=!this.leftDelim,{colFormat:C}=this;for(let X of C){if("align"in X&&A>=v.length)break;if("align"in X)k?b.push(ns(2*s)):(S||E)&&b.push(ns(s)),b.push(new w(v[A],{classes:"col-align-"+X.align})),A++,k=!0,S=!1,E=!1;else if("gap"in X){if(typeof X.gap=="number")b.push(ns(X.gap));else{let ye=vg(e,m,y,X.gap);ye&&b.push(ye)}k=!1,S=!1,E=!1}else if("separator"in X){let ye=new w(null,{classes:"ML__vertical-separator"});ye.height=d,ye.setStyle("height",d,"em"),ye.setStyle("border-right",`${i}em ${X.separator} currentColor`),ye.setStyle("vertical-align",-(d-y),"em");let xe=0;S?xe=o-i:k&&(xe=s-i),ye.left=xe,b.push(ye),k=!1,S=!0,E=!1}}k&&!this.rightDelim&&b.push(ns(s));let _=new w(b,{classes:["ML__mtable",...this.classes].join(" ")});if(this.environmentName==="array"&&!this.isMultiline&&(_.height=m[0].height,_.depth=d-m[0].height),(!this.leftDelim||this.leftDelim===".")&&(!this.rightDelim||this.rightDelim==="."))return this.caret&&(_.caret=this.caret),this.bind(e,_);let O=_.height,I=_.depth,V=this.bind(e,new w([this.bind(e,hi("open",(W=this.leftDelim)!=null?W:".",O,I,r,{isSelected:this.isSelected})),_,this.bind(e,hi("close",(ie=this.rightDelim)!=null?ie:".",O,I,r,{isSelected:this.isSelected}))],{type:"ord"}));return V?(V.setStyle("display","inline-block"),this.caret&&(V.caret=this.caret),this.bind(e,this.attachSupsub(e,{base:V}))):null}_serialize(e){var i;let r=[];if(this.environmentName==="lines"&&this._rows.length>1?r.push("\\displaylines{"):this.environmentName!=="lines"&&r.push(`\\begin{${this.environmentName}}`),this.environmentName==="array"){if(r.push("{"),this.colFormat!==void 0)for(let n of this.colFormat)"align"in n&&typeof n.align=="string"?r.push(n.align):"separator"in n&&n.separator==="solid"?r.push("|"):"separator"in n&&n.separator==="dashed"&&r.push(":");r.push("}")}for(let n=0;n0&&r.push(" & "),r.push(x.serialize(this._rows[n][o],e));if(n1?r.push("}"):this.environmentName!=="lines"&&r.push(`\\end{${this.environmentName}}`),R(r)}forEachCell(e){for(let r=0;ro.type!=="first")];this._rows[e][r]=n,pi(this),this.isDirty=!0}addRowBefore(e){this.type==="array"&&Array.isArray(this._rows),this._rows.splice(e,0,Array.from({length:this.colCount},()=>is(this,!this.isMultiline))),pi(this),this.isDirty=!0}addRowAfter(e){this.type==="array"&&Array.isArray(this._rows),this._rows.splice(e+1,0,Array.from({length:this.colCount},()=>is(this,!this.isMultiline))),pi(this),this.isDirty=!0}removeRow(e){this.type==="array"&&Array.isArray(this._rows)&&this.rowCount>e;let r=this._rows.splice(e,1);for(let i of r)for(let n of i)if(n)for(let o of n)o.parent=void 0,o.parentBranch=void 0;pi(this),this.isDirty=!0}addColumnBefore(e){this.type==="array"&&Array.isArray(this._rows);for(let r of this._rows)r.splice(e,0,is(this));pi(this),this.isDirty=!0}addColumnAfter(e){this.type==="array"&&Array.isArray(this._rows);for(let r of this._rows)r.splice(e+1,0,is(this));pi(this),this.isDirty=!0}addColumn(){this.addColumnAfter(this.colCount-1)}removeColumn(e){this.type==="array"&&Array.isArray(this._rows)&&this.colCount>e;for(let r of this._rows){let i=r.splice(e,1);for(let n of i)if(n)for(let o of n)o.parent=void 0,o.parentBranch=void 0}pi(this),this.isDirty=!0}get cells(){let e=[];for(let r of this._rows)for(let i of r)i&&e.push(i.filter(n=>n.type!=="first"));return e}get rows(){return this._rows}};function is(t,e=!1){let r=new x({type:"first",mode:t.mode});r.parent=t;let i=[r];if(e){let n=new Me;n.parent=t,i.push(n)}return i}function pi(t){for(let e=0;e0?i:0),l.depth=r.depth+o+(i<0?-i:0),l.setStyle("padding-left",o,"em"),l.setStyle("padding-right",o,"em"),l.setStyle("height",Math.floor(100*(r.height+r.depth+2*o+Math.abs(i)))/100,"em"),l.setStyle("margin-top",-o,"em"),l.setStyle("top",Math.floor(100*(r.depth-r.height+2*o-i))/100,"em"),l.setStyle("vertical-align",Math.floor(100*(r.depth+2*o))/100,"em"),this.caret&&(l.caret=this.caret),this.attachSupsub(e,{base:l})}_serialize(e){return e.skipStyles?R([this.bodyToLatex(e),this.supsubToLatex(e)]):super._serialize(e)}};var sn=class t extends x{constructor(e,r){var i;super({type:"composition",mode:(i=r==null?void 0:r.mode)!=null?i:"math",value:e})}static fromJson(e){return new t(e.value,e)}toJson(){return super.toJson()}render(e){let r=new w(this.value,{classes:"ML__composition",type:"composition"});return this.bind(e,r),this.caret&&(r.caret=this.caret),r}_serialize(e){return""}};var bt=class t extends x{constructor(e){super({type:"error",value:e,command:e,mode:"math"}),this.verbatimLatex=e}static fromJson(e){return new t(e.command)}toJson(){return super.toJson()}render(e){let r=this.createBox(e,{classes:"ML__error"});return this.caret&&(r.caret=this.caret),r}};var ln=class t extends x{constructor(e,r){super({type:"group",mode:r}),this.body=e,this.boxType=e.length>1?"ord":"ignore",this.skipBoundary=!0,this.displayContainsHighlight=!1,(e==null?void 0:e.length)===1&&e[0].command===","&&(this.captureSelection=!0)}static fromJson(e){return new t(e.body,e.mode)}render(e){let r=x.createBox(e,this.body,{type:this.boxType});return r?(this.caret&&(r.caret=this.caret),this.bind(e,r)):null}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);return r!=null&&r.serialize?r.serialize(this,e):`{${this.bodyToLatex(e)}}`}};var J=class t extends x{constructor(e,r,i){super({type:"leftright",style:i.style,displayContainsHighlight:!0}),this.variant=e,this.body=r,this.leftDelim=i.leftDelim,this.rightDelim=i.rightDelim}static fromJson(e){var r;return new t((r=e.variant)!=null?r:"",e.body,e)}toJson(){let e=super.toJson();return this.variant&&(e.variant=this.variant),this.leftDelim&&(e.leftDelim=this.leftDelim),this.rightDelim&&(e.rightDelim=this.rightDelim),e}_serialize(e){var i,n;let r=this.matchingRightDelim();return this.variant==="left...right"?R(["\\left",(i=this.leftDelim)!=null?i:".",this.bodyToLatex(e),"\\right",r]):this.variant==="mleft...mright"?R(["\\mleft",(n=this.leftDelim)!=null?n:".",this.bodyToLatex(e),"\\mright",r]):R([!this.leftDelim||this.leftDelim==="."?"":this.leftDelim,this.bodyToLatex(e),r])}matchingRightDelim(){var r,i;if(this.rightDelim&&this.rightDelim!=="?")return this.rightDelim;let e=(r=this.leftDelim)!=null?r:".";return(i=nn[e])!=null?i:e}render(e){var d,m;let r=new P({parent:e},this.style);this.body;let i=new P({parent:e,mathstyle:"textstyle"},this.style),n=(d=x.createBox(r,this.body,{type:"inner"}))!=null?d:new w(null,{type:"inner"}),o=n.height/i.scalingFactor,a=n.depth/i.scalingFactor,s=[];if(this.leftDelim&&s.push(this.bind(i,hi("open",this.leftDelim,o,a,i,{isSelected:this.isSelected,classes:"ML__open"+(this.containsCaret?" ML__contains-caret":""),mode:this.mode,style:this.style}))),n&&(_h(n.children,this,r,o,a),s.push(n)),this.rightDelim){let p=this.containsCaret?" ML__contains-caret":"",f=this.rightDelim;f==="?"&&(r.smartFence?(f=this.matchingRightDelim(),p+=" ML__smart-fence__close"):f="."),s.push(this.bind(i,hi("close",f,o,a,i,{isSelected:this.isSelected,classes:p+" ML__close",mode:this.mode,style:this.style})))}let l=this.variant==="mleft...mright",c=this.leftSibling;c&&(!l&&c.isFunction&&(l=!0),!l&&c.type==="subsup"&&((m=c.leftSibling)!=null&&m.isFunction)&&(l=!0));let u=new w(s,{type:l?"close":"inner",classes:"ML__left-right"});return u.setStyle("margin-top",`${-n.depth}em`),u.setStyle("height",`${n.height+n.depth}em`),this.caret&&(u.caret=this.caret),this.bind(r,u.wrap(r))}};function _h(t,e,r,i,n){if(t)for(let o=0;or.type!=="first").map(r=>r.toJson())),this.correctness&&(e.correctness=this.correctness),e.locked=this.locked,e}render(e){var C,_,O,I,V;let r=new P({parent:e}),i=r.getRegisterAsEm("fboxsep"),n=i,o=i,a=x.createBox(e,this.body);if(!a)return null;let l=!this.body||this.body.length===0||this.body.every(K=>K.type==="first")?new Me({mode:this.mode,style:this.style}).render(new P({parent:e,isPhantom:!0})):null,c=(C=l==null?void 0:l.height)!=null?C:r.metrics.xHeight,u=(_=l==null?void 0:l.depth)!=null?_:c/2,d=Math.max((O=a.height)!=null?O:0,c),m=Math.max((I=a.depth)!=null?I:0,u);a.setStyle("vertical-align",`calc(-${d}em + 2px)`),this.correctness==="correct"?a.setStyle("color","var(--correct-color, var(--ML__correct-color))"):this.correctness==="incorrect"&&a.setStyle("color","var(--incorrect-color, var(--ML__incorrect-color))");let f=d+m+2*o-2*n,y=new w(a,{type:"ord"});y.setStyle("display","inline-block"),y.height=d,y.depth=m,y.setStyle("height",d+m,"em"),y.setStyle("vertical-align",-o,"em"),((V=a.width)!=null?V:0)'),k&&(b.svgOverlay=k);let S=new w([b,y],{classes:"ML__prompt-atom"});y.setStyle("line-height",1),S.setStyle("position","relative"),S.setStyle("display","inline-block"),S.setStyle("line-height",0),S.height=d+o+.2,S.depth=m+o,S.left=n,S.right=n,S.setStyle("height",d+2*o,"em"),S.setStyle("top",m-d-o/2,"em"),S.setStyle("vertical-align",y.depth,"em"),S.setStyle("margin-left",.5,"em"),S.setStyle("margin-right",.5,"em"),this.caret&&(S.caret=this.caret);let A=this.attachSupsub(e,{base:S}),E=this.bind(r,A);return E&&this.id&&(b.atomID=this.id,y.atomID=this.id,S.atomID=this.id),E}_serialize(e){var n;let r=(n=this.bodyToLatex(e))!=null?n:"";if(e.skipPlaceholders)return r;let i="\\placeholder";return this.placeholderId&&(i+=`[${this.placeholderId}]`),this.correctness==="correct"?i+="[correct]":this.correctness==="incorrect"&&(i+="[incorrect]"),this.locked&&(i+="[locked]"),U(i,r)}};var cr=class t extends x{constructor(e){super({type:"subsup",style:e==null?void 0:e.style}),this.subsupPlacement="auto"}get children(){if(!this._children){let e=[],r=this.branch("subscript");if(r)for(let n of r)e.push(...n.children),e.push(n);let i=this.branch("superscript");if(i)for(let n of i)e.push(...n.children),e.push(n);this._children=e}return this._children}static fromJson(e){let r=new t(e);for(let i of Ir)e[i]&&r.setChildren(e[i],i);return r}render(e){var a;let r=new P({parent:e,isPhantom:!0}),i=this.leftSibling,n=(a=i.render(r))!=null?a:new w(null),o=new w(null);return o.height=n.height,o.depth=n.depth,this.attachSupsub(e,{base:o,isCharacterBox:i.isCharacterBox(),type:"ignore"})}_serialize(e){return this.supsubToLatex(e)}};function dn(t){return t?!/^(<$$>|<$>||<{>|<}>|#[0-9\?]|\\.+)$/.test(t):!1}var as=class{constructor(e,r,i){this.errors=[];this.index=0;this.endCount=0;var n,o,a,s;i!=null||(i={}),this.tokens=e,this.context=r instanceof P&&!(i!=null&&i.parseMode)&&!i.mathstyle?r:new P({from:r,mathstyle:i.mathstyle},i.style),this.args=(n=i.args)!=null?n:void 0,this.smartFence=this.context.smartFence,this.parsingContext={parent:void 0,mathlist:[],style:(o=i.style)!=null?o:{},parseMode:(a=i.parseMode)!=null?a:"math",mathstyle:(s=i.mathstyle)!=null?s:"displaystyle",tabular:!1}}beginContext(e){var n,o,a,s,l,c;if(e!=null&&e.root){this.parsingContext={parent:this.parsingContext.parent,mathlist:[],style:{},parseMode:(n=e==null?void 0:e.mode)!=null?n:"math",mathstyle:(o=e==null?void 0:e.mathstyle)!=null?o:"displaystyle",tabular:(a=e==null?void 0:e.tabular)!=null?a:!1};return}let r=this.parsingContext,i={parent:r,mathlist:[],style:h({},r.style),parseMode:(s=e==null?void 0:e.mode)!=null?s:r.parseMode,mathstyle:(l=e==null?void 0:e.mathstyle)!=null?l:r.mathstyle,tabular:(c=e==null?void 0:e.tabular)!=null?c:!1};this.parsingContext=i}endContext(){this.parsingContext=this.parsingContext.parent}onError(e){this.errors.push(h({before:Dr(this.tokens.slice(this.index,this.index+10)),after:Dr(this.tokens.slice(Math.max(0,this.index-10),this.index))},e))}get mathlist(){return this.parsingContext.mathlist}set mathlist(e){this.parsingContext.mathlist=e}get parseMode(){return this.parsingContext.parseMode}set parseMode(e){this.parsingContext.parseMode=e}get tabularMode(){return this.parsingContext.tabular}get style(){let e=this.parsingContext;for(;e;){if(e.style)return h({},e.style);e=e.parent}return{}}set style(e){this.parsingContext.style=e}end(){return this.endCount++,this.index>=this.tokens.length||this.endCount>1e3}next(){this.index+=1}get(){return this.endCount=0,this.index0&&(e=this.mathlist[this.mathlist.length-1],e.type==="subsup"||e.subsupPlacement!==void 0)||(e=new cr({style:this.style}),this.mathlist.push(e)),e}hasPattern(e){return e.test(this.tokens[this.index])}hasInfixCommand(){var r;let{index:e}=this;if(e"););}skipUntilToken(e){let r=this.tokens[this.index];for(;r&&r!==e;)r=this.tokens[++this.index];r===e&&this.index++}skipFiller(){for(;this.match("\\relax")||this.match(""););}matchKeyword(e){let r=this.index,i=this.end(),n="";for(;!i;){let a=this.get();dn(a)?(n+=a,i=this.end()||n.length>=e.length):i=!0}let o=e.toUpperCase()===n.toUpperCase();return o||(this.index=r),o}scanString(){let e="";for(;!this.end();){let r=this.peek();if(r==="]")return e;if(r==="")e+=" ";else if(r.startsWith("\\"))this.onError({code:"unexpected-command-in-string"}),e+=r.substring(1);else if(dn(r))e+=r;else return e;this.next()}return e}scanBalancedString(){let e="",r=this.end(),i=1;for(;!r;){let n=this.get();n===""?e+=" ":n==="<{>"?(e+="{",i+=1):n==="<}>"?(i-=1,i>0?e+="}":this.index-=1):n==="<$>"?e+="$":n==="<$$>"?e+="$$":e+=n,r=i===0||this.end()}return e}scanLiteralGroup(){var i;if(!this.match("<{>"))return"";let e="",r=1;for(;r>0&&!this.end();){let n=this.get();n==="<}>"?(r-=1,r>0&&(e+="}")):n==="<{>"?(r+=1,e+="{"):(/\\[a-zA-Z]+$/.test(e)&&/^[a-zA-Z]/.test(n)&&(e+=" "),e+=(i={"":" ","<$$>":"$$","<$>":"$"}[n])!=null?i:n)}return e}scanNumber(e=!0){var l,c;let r=!1,i=this.peek();for(;i===""||i==="+"||i==="-";)this.get(),i==="-"&&(r=!r),i=this.peek();e=!!e;let n=10,o=/\d/;if(this.match("'"))n=8,o=/[0-7]/,e=!0;else if(this.match('"'))n=16,o=/[\dA-F]/,e=!0;else if(this.match("x"))n=16,o=/[\dA-Fa-f]/,e=!0;else if(this.match("`"))return i=this.get(),i?i.length===2&&i.startsWith("\\")?{number:(r?-1:1)*((l=i.codePointAt(1))!=null?l:0),base:"alpha"}:{number:(r?-1:1)*((c=i.codePointAt(0))!=null?c:0),base:"alpha"}:null;let a="";for(;this.hasPattern(o);)a+=this.get();if(!e&&(this.match(".")||this.match(",")))for(a+=".";this.hasPattern(o);)a+=this.get();let s=e?Number.parseInt(a,n):Number.parseFloat(a);return Number.isNaN(s)?null:{number:r?-s:s,base:n===16?"hexadecimal":n===8?"octal":"decimal"}}scanRegister(){var o;let e=this.index,r=this.scanNumber(!1);if(this.skipWhitespace(),this.match("\\relax"))return r;let i=!1;if(r===null)for(;;){let a=this.peek();if(a==="-")i=!i;else if(a!=="+")break;this.next(),this.skipWhitespace()}if(this.match("\\global")){this.skipWhitespace();let a=this.get();return a.startsWith("\\")?r?{register:a,global:!0,factor:(i?-1:1)*r.number}:i?{register:a,global:!0,factor:-1}:{register:a,global:!0}:(this.index=e,null)}let n=this.get();return n!=null&&n.startsWith("\\")?(n=n.substring(1),this.context.registers[n]?!i||r!==null?{register:n,factor:(i?-1:1)*((o=r==null?void 0:r.number)!=null?o:1)}:{register:n}:(this.index=e,null)):(this.index=e,null)}scanValue(){let e=this.scanRegister();if(e)return e;let r=this.index,i=this.scanGlueOrDimen();if(i&&("unit"in i||"glue"in i&&"unit"in i.glue))return i;this.index=r;let n=this.scanNumber();if(n)return n;if(this.end()||!dn(this.peek()))return null;let o=this.scanString();return o.length>0?{string:o}:null}scanDimen(){let e=this.scanNumber(!1);if(e===null)return null;let r=e.number;this.skipWhitespace(),this.matchKeyword("true"),this.skipWhitespace();let i;return this.matchKeyword("pt")?i="pt":this.matchKeyword("mm")?i="mm":this.matchKeyword("cm")?i="cm":this.matchKeyword("ex")?i="ex":this.matchKeyword("px")?i="px":this.matchKeyword("em")?i="em":this.matchKeyword("bp")?i="bp":this.matchKeyword("dd")?i="dd":this.matchKeyword("pc")?i="pc":this.matchKeyword("in")?i="in":this.matchKeyword("mu")&&(i="mu"),i?{dimension:r,unit:i}:{dimension:r}}scanGlueOrDimen(){let e=this.scanDimen();if(e===null)return null;if(this.skipWhitespace(),this.match("\\relax"))return e;let r={glue:e};if(this.matchKeyword("plus")){let i=this.scanDimen();if(i)r.grow=i;else return r}if(this.skipWhitespace(),this.match("\\relax"))return r;if(this.skipWhitespace(),this.matchKeyword("minus")){let i=this.scanDimen();if(i)r.shrink=i;else return r}return!r.grow&&!r.shrink?e:r}scanColspec(){this.skipWhitespace();let e=[];for(;!this.end()&&!(this.peek()==="<}>"||this.peek()==="]");){let r=this.get();r==="c"||r==="r"||r==="l"?e.push({align:r}):r==="|"?e.push({separator:"solid"}):r===":"?e.push({separator:"dashed"}):r==="@"&&(this.match("<{>")&&(this.beginContext({mode:"math"}),e.push({gap:this.scan(i=>i==="<}>")}),this.endContext()),this.match("<}>")||this.onError({code:"unbalanced-braces"}))}return e}scanModeSet(){let e;if(this.match("\\(")&&(e="textstyle"),!e&&this.match("\\[")&&(e="displaystyle"),!e)return null;this.beginContext({mode:"math",mathstyle:e});let r=this.scan(i=>i===(e==="displaystyle"?"\\]":"\\)"));return this.match(e==="displaystyle"?"\\]":"\\)")||this.onError({code:"unbalanced-mode-shift"}),this.endContext(),r}scanModeShift(){let e="";if(this.match("<$>")&&(e="<$>"),!e&&this.match("<$$>")&&(e="<$$>"),!e)return null;this.beginContext({mode:"math",mathstyle:e==="<$>"?"textstyle":"displaystyle"});let r=this.scan(i=>i===e);return this.match(e)||this.onError({code:"unbalanced-mode-shift"}),this.endContext(),r}scanEnvironment(){if(!this.match("\\begin"))return null;let e=this.scanArgument("string");if(!e)return null;let r=Vu(e);if(!r)return this.onError({code:"unknown-environment",arg:e}),null;let i=[];if(r.params)for(let l of r.params)if(l.isOptional)i.push(this.scanOptionalArgument(l.type));else{let c=this.scanArgument(l.type);c||this.onError({code:"missing-argument",arg:e}),i.push(c)}this.beginContext({tabular:r.tabular,root:r.rootOnly});let n=[],o=[],a=[],s=!1;do if(this.end()&&(this.onError({code:"unbalanced-environment",arg:e}),s=!0),!s&&this.match("\\end")&&(this.scanArgument("string")!==e&&this.onError({code:"unbalanced-environment",arg:e}),s=!0),!s)if(this.matchColumnSeparator())a.push(this.mathlist),this.mathlist=[];else if(this.matchRowSeparator()){a.push(this.mathlist),this.mathlist=[];let l=null;this.skipWhitespace(),this.match("[")&&(l=this.scanDimen(),this.skipWhitespace(),this.match("]")),o.push(l!=null?l:{dimension:0}),n.push(a),a=[]}else this.mathlist.push(...this.scan(l=>["<}>","&","\\end","\\cr","\\\\","\\tabularnewline"].includes(l)));while(!s);return a.push(this.mathlist),a.length>0&&n.push(a),this.endContext(),r.rootOnly&&(this.index=this.tokens.length),r.createAtom(e,n,o,i,this.context.maxMatrixCols)}scanExpression(){let e=this.mathlist;if(this.mathlist=[],this.parseExpression()){let r=this.mathlist;return this.mathlist=e,r}return this.mathlist=e,null}scan(e){this.beginContext(),e||(e=s=>s==="<}>");let r="",i=null,n=[],o=null;for(;!this.end()&&!e(this.peek());)this.hasInfixCommand()&&!r?(r=this.get(),i=ne(r,"math"),i&&(n=this.scanArguments(i)[1]),o=this.mathlist,this.mathlist=[]):this.parseExpression();let a;return r?(n.unshift(this.mathlist),o&&n.unshift(o),a=[i.createAtom({command:r,args:n,style:this.style,mode:this.parseMode})]):a=this.mathlist,this.endContext(),a}scanGroup(){let e=this.index;if(!this.match("<{>"))return null;let r=this.scan(n=>n==="<}>");if(this.match("<}>")||this.onError({code:"unbalanced-braces"}),r.length===1&&r[0].type==="placeholder")return r[0];let i=new ln(r,this.parseMode);return i.verbatimLatex=Dr(this.tokens.slice(e,this.index)),i}scanSmartFence(){if(this.skipWhitespace(),!this.match("("))return null;this.beginContext();let e=1;for(;!this.end()&&e!==0;)this.match("(")&&(e+=1),this.match(")")&&(e-=1),e!==0&&this.parseExpression();let r=new J("",this.mathlist,{leftDelim:"(",rightDelim:e===0?")":"?"});return this.endContext(),r}scanDelim(){this.skipWhitespace();let e=this.peek();if(!e)return this.onError({code:"unexpected-end-of-string"}),null;if(!dn(e)&&!e.startsWith("\\"))return null;this.next();let r=ne(e,"math");return r?r.definitionType==="function"&&r.ifMode&&!r.ifMode.includes(this.parseMode)?(this.onError({code:"unexpected-delimiter",arg:e}),null):r.definitionType==="symbol"&&(r.type==="mopen"||r.type==="mclose")||/^(\.|\?|\||<|>|\\vert|\\Vert|\\\||\\surd|\\uparrow|\\downarrow|\\Uparrow|\\Downarrow|\\updownarrow|\\Updownarrow|\\mid|\\mvert|\\mVert)$/.test(e)?e:(this.onError({code:"unexpected-delimiter",arg:e}),null):(this.onError({code:"unknown-command",arg:e}),null)}scanLeftRight(){var o;if(this.match("\\right"))return this.onError({code:"unbalanced-braces"}),new bt("\\right");if(this.match("\\mright"))return this.onError({code:"unbalanced-braces"}),new bt("\\mright");let e="\\right";if(!this.match("\\left")){if(!this.match("\\mleft"))return null;e="\\mright"}let r=this.scanDelim();if(!r)return this.onError({code:"unexpected-delimiter"}),new bt(e==="\\right"?"\\left":"\\mleft");for(this.beginContext();!this.end()&&!this.match(e);)this.parseExpression();let i=this.mathlist;this.endContext();let n=(o=this.scanDelim())!=null?o:".";return new J(e==="\\right"?"left...right":"mleft...mright",i,{leftDelim:r,rightDelim:n,style:this.style})}parseSupSub(){if(this.parseMode!=="math")return!1;let e=this.peek();if(e!=="^"&&e!=="_"&&e!=="'")return!1;let r=this.lastSubsupAtom();for(;e==="^"||e==="_"||e==="'";)this.match("'")?this.match("'")?r.addChild(new x({type:"mord",command:"\\doubleprime",mode:"math",value:"\u2032\u2032"}),"superscript"):r.addChild(new x({type:"mord",command:"\\prime",mode:"math",value:"\u2032"}),"superscript"):(this.match("^")||this.match("_"))&&r.addChildren(T(this.scanArgument("expression")),e==="_"?"subscript":"superscript"),e=this.peek();return!0}parseLimits(){if(this.parseMode!=="math")return!1;let e=this.match("\\limits"),r=!e&&this.match("\\nolimits"),i=!r&&!e&&this.match("\\displaylimits");if(!e&&!r&&!i)return!1;let n=this.mathlist.length>0?this.mathlist[this.mathlist.length-1]:null;return n===null?!1:(n.explicitSubsupPlacement=!0,e&&(n.subsupPlacement="over-under"),r&&(n.subsupPlacement="adjacent"),i&&(n.subsupPlacement="auto"),!0)}scanArguments(e){if(!(e!=null&&e.params))return[void 0,[]];let r,i=[],n=e.infix?2:0;for(;n["<}>","&","\\end","\\cr","\\\\","\\tabularnewline","\\right"].includes(a))):o.isOptional?i.push(this.scanOptionalArgument(o.type)):o.type.endsWith("*")?r=o.type.slice(0,-1):i.push(this.scanArgument(o.type)),n+=1}return[r,i]}scanSymbolOrLiteral(){let e=this.peek();if(!e)return null;this.next();let r;if(dn(e)){let i=_e.createAtom(this.parseMode,e,h({},this.style));return i?[i]:null}if(r=this.scanMacro(e),r)return[r];if(e.startsWith("\\")){let i=ne(e,this.parseMode);if(!i)return this.onError({code:"unknown-command",arg:e}),[new bt(e)];if(i.definitionType==="symbol"){let n=h({},this.style);i.variant&&(n.variant=i.variant),r=new x({type:i.type,command:e,style:n,value:String.fromCodePoint(i.codepoint),mode:this.parseMode,verbatimLatex:e})}else{if(i.applyMode||i.applyStyle||i.infix)return this.onError({code:"invalid-command",arg:e}),[new bt(e)];i.createAtom&&(r=i.createAtom({command:e,args:[],style:this.style,mode:this.parseMode}))}}return r?[r]:null}scanArgument(e){var n,o;this.skipFiller();let r=this.parseMode;if(e==="auto"&&(e=r),!this.match("<{>")){if(e==="string")return this.scanString();if(e==="value")return this.scanValue();if(e==="delim")return(n=this.scanDelim())!=null?n:".";if(e==="expression")return this.scanExpression();if(e==="math"){e!==r&&this.beginContext({mode:"math"});let a=this.scanSymbolOrLiteral();return e!==r&&this.endContext(),a}if(e==="text"){e!==r&&this.beginContext({mode:"text"});let a=this.scanSymbolOrLiteral();return e!==r&&this.endContext(),a}return e==="balanced-string"?null:e==="rest"?this.scan(a=>["<}>","&","\\end","\\cr","\\\\","\\tabularnewline","\\right"].includes(a)):null}if(e==="text"){this.beginContext({mode:"text"});do this.mathlist.push(...this.scan());while(!this.match("<}>")&&!this.end());let a=this.mathlist;return this.endContext(),{group:a}}if(e==="math"){this.beginContext({mode:"math"});do this.mathlist.push(...this.scan());while(!this.match("<}>")&&!this.end());let a=this.mathlist;return this.endContext(),{group:a}}if(e==="rest"){let a=this.scan();return this.match("<}>")||this.onError({code:"unbalanced-braces"}),{group:a}}let i=null;if(e==="expression"){this.beginContext({mode:"math"});do this.mathlist.push(...this.scan());while(!this.match("<}>")&&!this.end());let a=this.mathlist;return this.endContext(),{group:a}}return e==="string"?i=this.scanString():e==="balanced-string"?i=this.scanBalancedString():e==="colspec"?i=this.scanColspec():e==="value"?i=this.scanValue():e==="delim"&&(i=this.peek()==="<}>"?".":(o=this.scanDelim())!=null?o:"."),this.skipUntilToken("<}>"),i}scanOptionalArgument(e){if(e=e==="auto"?this.parseMode:e,this.skipFiller(),!this.match("["))return null;let r=null;for(;!this.end()&&!this.match("]");)if(e==="string")r=this.scanString();else if(e==="value")r=this.scanValue();else if(e==="colspec")r=this.scanColspec();else if(e==="bbox"){let i={},n=this.scanString().toLowerCase().trim().split(/,(?![^(]*\)(?:(?:[^(]*\)){2})*[^"]*$)/);for(let o of n){let a=o.match(/^\s*([\d.]+)\s*([a-z]{2})/);if(a)i.padding={dimension:Number.parseFloat(a[1]),unit:a[2]};else{let s=o.match(/^\s*border\s*:\s*(.*)/);s?i.border=s[1]:i.backgroundcolor={string:o}}}r=i}else e==="math"&&(this.beginContext({mode:"math"}),r=this.mathlist.concat(this.scan(i=>i==="]")),this.endContext());return r}scanSymbolOrCommand(e){var o,a,s;if(e==="\\placeholder"){let l=this.scanOptionalArgument("string"),c=this.scanOptionalArgument("math"),u=x.serialize(c,{defaultMode:"math"}),d=[],m;!m&&u==="correct"?m="correct":!m&&u==="incorrect"?m="incorrect":u!==""&&(d=c);let p=this.scanOptionalArgument("string")==="locked",f=this.scanArgument("auto"),y;return f&&Array.isArray(f)&&f.length>0?y=f:f&&typeof f=="object"&&"group"in f?y=f.group:y=d,l?[new un(l,m,p,y!=null?y:d,{mode:this.parseMode,style:this.style})]:[new Me({mode:this.parseMode,style:this.style})]}if(e==="\\renewcommand"||e==="\\newcommand"||e==="\\providecommand"||e==="\\def"){let l=this.index,c=this.scanLiteralGroup()||this.next();if(!c)return null;if(this.context.registers[c.substring(1)]){let u=this.scanArgument("string");u!==null&&(this.context.registers[c.substring(1)]=u);let d=R([e,Dr(this.tokens.slice(l,this.index))]);return[new x({type:"text",value:"",verbatimLatex:d})]}}let r=this.scanMacro(e);if(r)return[r];let i=ne(e,this.parseMode);if(!i)return this.parseMode==="text"?(/[a-zA-Z]/.test((o=this.peek())!=null?o:"")&&(e+=" "),[...e].map(l=>new x({type:"text",value:l,mode:"text",style:this.style}))):(this.onError({code:"unknown-command",arg:e}),[new bt(e)]);let n=this.index;if(i.definitionType==="symbol"){let l=h({},this.style);i.variant&&(l.variant=i.variant),r=new x({type:i.type,command:e,style:l,value:String.fromCodePoint(i.codepoint),mode:this.parseMode})}else{if(i.ifMode&&!i.ifMode.includes(this.parseMode))return[];let l=this.parseMode;i.applyMode&&(this.parseMode=i.applyMode);let c,u=[];if(i.parse?u=i.parse(this):[c,u]=this.scanArguments(i),this.parseMode=l,i.applyMode&&!i.applyStyle&&!i.createAtom)return T(u[0]);if(i.infix)return this.onError({code:"too-many-infix-commands",arg:e}),null;if(typeof i.createAtom=="function")r=i.createAtom({command:e,args:u,style:this.style,mode:this.parseMode}),c&&(r.body=T(this.scanArgument(c)));else if(typeof i.applyStyle=="function"){let d=i.applyStyle(this.style,e,u,this.context),m=this.parseMode;if(i.applyMode&&(this.parseMode=i.applyMode),c){let p=this.style;this.style=d;let f=this.scanArgument(c);return this.style=p,this.parseMode=m,T(f)}this.style=d}else r=new x({type:"mord",command:(a=i.command)!=null?a:e,style:h({},this.style),value:e,mode:(s=i.applyMode)!=null?s:this.parseMode})}if(!r)return null;if(r instanceof x&&r.verbatimLatex===void 0&&!/^\\(llap|rlap|class|cssId|htmlData)$/.test(e)){let l=R([e,Dr(this.tokens.slice(n,this.index))]);l&&(r.verbatimLatex=l)}if(r.verbatimLatex===null&&(r.verbatimLatex=void 0),r.isFunction&&this.smartFence){let l=this.scanSmartFence();if(l)return[r,l]}return[r]}scanSymbolCommandOrLiteral(){this.expandUnicode();let e=this.get();if(!e)return null;if(dn(e)){let r=_e.createAtom(this.parseMode,e,h({},this.style));if(!r)return null;if(r.isFunction&&this.smartFence){let i=this.scanSmartFence();if(i)return[r,i]}return[r]}return e.startsWith("\\")?this.scanSymbolOrCommand(e):e===""?this.parseMode==="text"?[new We(" "," ",this.style)]:null:(e==="<}>"?this.onError({latex:"",code:"unbalanced-braces"}):this.onError({latex:"",code:"unexpected-token",arg:e}),null)}scanMacro(e){var a;let r=this.context.getMacro(e);if(!r)return null;let i=this.index,n=r.args,o={"?":(a=this.args)==null?void 0:a.call(this,"?")};for(let s=1;s<=n;s++){let l=this.scanLiteralGroup();if(!l){let c=this.index;this.scanExpression(),l=Dr(this.tokens.slice(c,this.index))}o[s]=l}return new cn(e,{expand:r.expand,captureSelection:r.captureSelection,args:i===this.index?null:Dr(this.tokens.slice(i,this.index)),style:this.parsingContext.style,body:be(r.def,{context:this.context,parseMode:this.parseMode,args:s=>o[s],mathstyle:this.parsingContext.mathstyle,style:this.parsingContext.style})})}parseExpression(){var r,i,n,o;let e=(o=(n=(i=(r=this.scanEnvironment())!=null?r:this.scanModeShift())!=null?i:this.scanModeSet())!=null?n:this.scanGroup())!=null?o:this.scanLeftRight();if(e===null){if(this.parseSupSub()||this.parseLimits())return!0;e=this.scanSymbolCommandOrLiteral()}return e?(ee(e)?this.mathlist.push(...e):this.mathlist.push(e),!0):!1}};function be(t,e){var o,a,s,l;let r=(o=e==null?void 0:e.args)!=null?o:void 0,i=new as(Ji(t,r),e==null?void 0:e.context,{args:r,mathstyle:(a=e==null?void 0:e.mathstyle)!=null?a:"displaystyle",parseMode:(s=e==null?void 0:e.parseMode)!=null?s:"math",style:(l=e==null?void 0:e.style)!=null?l:{}}),n=[];for(;!i.end();)n.push(...i.scan(()=>!1));return n}function ss(t,e){var i;let r=new as(Ji(t,null),e==null?void 0:e.context,{mathstyle:"displaystyle",parseMode:(i=e==null?void 0:e.parseMode)!=null?i:"math"});for(;!r.end();)r.scan();return r.errors}var to=class t extends x{constructor(e,r){super({type:"chem"},{command:e,mode:"math"});let i=me.go(L.go(r,e==="\\pu"?"pu":"ce"),!1);this.body=be(i),this._verbatimLatex=e+"{"+r+"}",this.arg=r,this.captureSelection=!0}static fromJson(e){return new t(e.command,e.arg)}set verbatimLatex(e){}get verbatimLatex(){return this._verbatimLatex}toJson(){return g(h({},super.toJson()),{arg:this.arg})}render(e){let r=x.createBox(e,this.body,{type:"inner"});return this.caret&&(r.caret=this.caret),this.bind(e,r)}_serialize(e){return this.verbatimLatex,this.verbatimLatex}};M(["ce","pu"],"{chemformula:balanced-string}",{createAtom:t=>{var e;return new to(t.command,(e=t.args[0])!=null?e:"")}});var L={go:function(t,e){if(!t)return[];e===void 0&&(e="ce");var r="0",i={};i.parenthesisLevel=0,t=t.replace(/\n/g," "),t=t.replace(/[\u2212\u2013\u2014\u2010]/g,"-"),t=t.replace(/[\u2026]/g,"...");for(var n,o=10,a=[];;){n!==t?(o=10,n=t):o--;var s=L.stateMachines[e],l=s.transitions[r]||s.transitions["*"];e:for(var c=0;c0){if(d.revisit||(t=u.remainder),!d.toContinue)break e}else return a}}if(o<=0)throw["MhchemBugU","mhchem bug U. Please report."]}},concatArray:function(t,e){if(e)if(Object.prototype.toString.call(e)==="[object Array]")for(var r=0;r":/^[=<>]/,"#":/^[#\u2261]/,"+":/^\+/,"-$":/^-(?=[\s_},;\]/]|$|\([a-z]+\))/,"-9":/^-(?=[0-9])/,"- orbital overlap":/^-(?=(?:[spd]|sp)(?:$|[\s,;\)\]\}]))/,"-":/^-/,"pm-operator":/^(?:\\pm|\$\\pm\$|\+-|\+\/-)/,operator:/^(?:\+|(?:[\-=<>]|<<|>>|\\approx|\$\\approx\$)(?=\s|$|-?[0-9]))/,arrowUpDown:/^(?:v|\(v\)|\^|\(\^\))(?=$|[\s,;\)\]\}])/,"\\bond{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\bond{","","","}")},"->":/^(?:<->|<-->|->|<-|<=>>|<<=>|<=>|[\u2192\u27F6\u21CC])/,CMT:/^[CMT](?=\[)/,"[(...)]":function(t){return L.patterns.findObserveGroups(t,"[","","","]")},"1st-level escape":/^(&|\\\\|\\hline)\s*/,"\\,":/^(?:\\[,\ ;:])/,"\\x{}{}":function(t){return L.patterns.findObserveGroups(t,"",/^\\[a-zA-Z]+\{/,"}","","","{","}","",!0)},"\\x{}":function(t){return L.patterns.findObserveGroups(t,"",/^\\[a-zA-Z]+\{/,"}","")},"\\ca":/^\\ca(?:\s+|(?![a-zA-Z]))/,"\\x":/^(?:\\[a-zA-Z]+\s*|\\[_&{}%])/,orbital:/^(?:[0-9]{1,2}[spdfgh]|[0-9]{0,2}sp)(?=$|[^a-zA-Z])/,others:/^[\/~|]/,"\\frac{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\frac{","","","}","{","","","}")},"\\overset{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\overset{","","","}","{","","","}")},"\\underset{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\underset{","","","}","{","","","}")},"\\underbrace{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\underbrace{","","","}_","{","","","}")},"\\color{(...)}0":function(t){return L.patterns.findObserveGroups(t,"\\color{","","","}")},"\\color{(...)}{(...)}1":function(t){return L.patterns.findObserveGroups(t,"\\color{","","","}","{","","","}")},"\\color(...){(...)}2":function(t){return L.patterns.findObserveGroups(t,"\\color","\\","",/^(?=\{)/,"{","","","}")},"\\ce{(...)}":function(t){return L.patterns.findObserveGroups(t,"\\ce{","","","}")},oxidation$:/^(?:[+-][IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,"d-oxidation$":/^(?:[+-]?\s?[IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,"roman numeral":/^[IVX]+/,"1/2$":/^[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+(?:\$[a-z]\$|[a-z])?$/,amount:function(t){var e;if(e=t.match(/^(?:(?:(?:\([+\-]?[0-9]+\/[0-9]+\)|[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+|[+\-]?[0-9]+[.,][0-9]+|[+\-]?\.[0-9]+|[+\-]?[0-9]+)(?:[a-z](?=\s*[A-Z]))?)|[+\-]?[a-z](?=\s*[A-Z])|\+(?!\s))/),e)return{match_:e[0],remainder:t.substr(e[0].length)};var r=L.patterns.findObserveGroups(t,"","$","$","");return r&&(e=r.match_.match(/^\$(?:\(?[+\-]?(?:[0-9]*[a-z]?[+\-])?[0-9]*[a-z](?:[+\-][0-9]*[a-z]?)?\)?|\+|-)\$$/),e)?{match_:e[0],remainder:t.substr(e[0].length)}:null},amount2:function(t){return this.amount(t)},"(KV letters),":/^(?:[A-Z][a-z]{0,2}|i)(?=,)/,formula$:function(t){if(t.match(/^\([a-z]+\)$/))return null;var e=t.match(/^(?:[a-z]|(?:[0-9\ \+\-\,\.\(\)]+[a-z])+[0-9\ \+\-\,\.\(\)]*|(?:[a-z][0-9\ \+\-\,\.\(\)]+)+[a-z]?)$/);return e?{match_:e[0],remainder:t.substr(e[0].length)}:null},uprightEntities:/^(?:pH|pOH|pC|pK|iPr|iBu)(?=$|[^a-zA-Z])/,"/":/^\s*(\/)\s*/,"//":/^\s*(\/\/)\s*/,"*":/^\s*[*.]\s*/},findObserveGroups:function(t,e,r,i,n,o,a,s,l,c){var u=function(b,k){if(typeof k=="string")return b.indexOf(k)!==0?null:k;var S=b.match(k);return S?S[0]:null},d=function(b,k,S){for(var A=0;k0,null},m=u(t,e);if(m===null||(t=t.substr(m.length),m=u(t,r),m===null))return null;var p=d(t,m.length,i||n);if(p===null)return null;var f=t.substring(0,i?p.endMatchEnd:p.endMatchBegin);if(o||a){var y=this.findObserveGroups(t.substr(p.endMatchEnd),o,a,s,l);if(y===null)return null;var v=[f,y.match_];return{match_:c?v.join(""):v,remainder:y.remainder}}else return{match_:f,remainder:t.substr(p.endMatchEnd)}},match_:function(t,e){var r=L.patterns.patterns[t];if(r===void 0)throw["MhchemBugP","mhchem bug P. Please report. ("+t+")"];if(typeof r=="function")return L.patterns.patterns[t](e);var i=e.match(r);if(i){var n;return i[2]?n=[i[1],i[2]]:i[1]?n=i[1]:n=i[0],{match_:n,remainder:e.substr(i[0].length)}}return null}},actions:{"a=":function(t,e){t.a=(t.a||"")+e},"b=":function(t,e){t.b=(t.b||"")+e},"p=":function(t,e){t.p=(t.p||"")+e},"o=":function(t,e){t.o=(t.o||"")+e},"q=":function(t,e){t.q=(t.q||"")+e},"d=":function(t,e){t.d=(t.d||"")+e},"rm=":function(t,e){t.rm=(t.rm||"")+e},"text=":function(t,e){t.text_=(t.text_||"")+e},insert:function(t,e,r){return{type_:r}},"insert+p1":function(t,e,r){return{type_:r,p1:e}},"insert+p1+p2":function(t,e,r){return{type_:r,p1:e[0],p2:e[1]}},copy:function(t,e){return e},rm:function(t,e){return{type_:"rm",p1:e||""}},text:function(t,e){return L.go(e,"text")},"{text}":function(t,e){var r=["{"];return L.concatArray(r,L.go(e,"text")),r.push("}"),r},"tex-math":function(t,e){return L.go(e,"tex-math")},"tex-math tight":function(t,e){return L.go(e,"tex-math tight")},bond:function(t,e,r){return{type_:"bond",kind_:r||e}},"color0-output":function(t,e){return{type_:"color0",color:e[0]}},ce:function(t,e){return L.go(e)},"1/2":function(t,e){var r=[];e.match(/^[+\-]/)&&(r.push(e.substr(0,1)),e=e.substr(1));var i=e.match(/^([0-9]+|\$[a-z]\$|[a-z])\/([0-9]+)(\$[a-z]\$|[a-z])?$/);return i[1]=i[1].replace(/\$/g,""),r.push({type_:"frac",p1:i[1],p2:i[2]}),i[3]&&(i[3]=i[3].replace(/\$/g,""),r.push({type_:"tex-math",p1:i[3]})),r},"9,9":function(t,e){return L.go(e,"9,9")}},createTransitions:function(t){var e,r,i,n,o={};for(e in t)for(r in t[e])for(i=r.split("|"),t[e][r].stateArray=i,n=0;n":{"0|1|2|3":{action_:"r=",nextState:"r"},"a|as":{action_:["output","r="],nextState:"r"},"*":{action_:["output","r="],nextState:"r"}},"+":{o:{action_:"d= kv",nextState:"d"},"d|D":{action_:"d=",nextState:"d"},q:{action_:"d=",nextState:"qd"},"qd|qD":{action_:"d=",nextState:"qd"},dq:{action_:["output","d="],nextState:"d"},3:{action_:["sb=false","output","operator"],nextState:"0"}},amount:{"0|2":{action_:"a=",nextState:"a"}},"pm-operator":{"0|1|2|a|as":{action_:["sb=false","output",{type_:"operator",option:"\\pm"}],nextState:"0"}},operator:{"0|1|2|a|as":{action_:["sb=false","output","operator"],nextState:"0"}},"-$":{"o|q":{action_:["charge or bond","output"],nextState:"qd"},d:{action_:"d=",nextState:"d"},D:{action_:["output",{type_:"bond",option:"-"}],nextState:"3"},q:{action_:"d=",nextState:"qd"},qd:{action_:"d=",nextState:"qd"},"qD|dq":{action_:["output",{type_:"bond",option:"-"}],nextState:"3"}},"-9":{"3|o":{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"3"}},"- orbital overlap":{o:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"},d:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"}},"-":{"0|1|2":{action_:[{type_:"output",option:1},"beginsWithBond=true",{type_:"bond",option:"-"}],nextState:"3"},3:{action_:{type_:"bond",option:"-"}},a:{action_:["output",{type_:"insert",option:"hyphen"}],nextState:"2"},as:{action_:[{type_:"output",option:2},{type_:"bond",option:"-"}],nextState:"3"},b:{action_:"b="},o:{action_:{type_:"- after o/d",option:!1},nextState:"2"},q:{action_:{type_:"- after o/d",option:!1},nextState:"2"},"d|qd|dq":{action_:{type_:"- after o/d",option:!0},nextState:"2"},"D|qD|p":{action_:["output",{type_:"bond",option:"-"}],nextState:"3"}},amount2:{"1|3":{action_:"a=",nextState:"a"}},letters:{"0|1|2|3|a|as|b|p|bp|o":{action_:"o=",nextState:"o"},"q|dq":{action_:["output","o="],nextState:"o"},"d|D|qd|qD":{action_:"o after d",nextState:"o"}},digits:{o:{action_:"q=",nextState:"q"},"d|D":{action_:"q=",nextState:"dq"},q:{action_:["output","o="],nextState:"o"},a:{action_:"o=",nextState:"o"}},"space A":{"b|p|bp":{}},space:{a:{nextState:"as"},0:{action_:"sb=false"},"1|2":{action_:"sb=true"},"r|rt|rd|rdt|rdq":{action_:"output",nextState:"0"},"*":{action_:["output","sb=true"],nextState:"1"}},"1st-level escape":{"1|2":{action_:["output",{type_:"insert+p1",option:"1st-level escape"}]},"*":{action_:["output",{type_:"insert+p1",option:"1st-level escape"}],nextState:"0"}},"[(...)]":{"r|rt":{action_:"rd=",nextState:"rd"},"rd|rdt":{action_:"rq=",nextState:"rdq"}},"...":{"o|d|D|dq|qd|qD":{action_:["output",{type_:"bond",option:"..."}],nextState:"3"},"*":{action_:[{type_:"output",option:1},{type_:"insert",option:"ellipsis"}],nextState:"1"}},". |* ":{"*":{action_:["output",{type_:"insert",option:"addition compound"}],nextState:"1"}},"state of aggregation $":{"*":{action_:["output","state of aggregation"],nextState:"1"}},"{[(":{"a|as|o":{action_:["o=","output","parenthesisLevel++"],nextState:"2"},"0|1|2|3":{action_:["o=","output","parenthesisLevel++"],nextState:"2"},"*":{action_:["output","o=","output","parenthesisLevel++"],nextState:"2"}},")]}":{"0|1|2|3|b|p|bp|o":{action_:["o=","parenthesisLevel--"],nextState:"o"},"a|as|d|D|q|qd|qD|dq":{action_:["output","o=","parenthesisLevel--"],nextState:"o"}},", ":{"*":{action_:["output","comma"],nextState:"0"}},"^_":{"*":{}},"^{(...)}|^($...$)":{"0|1|2|as":{action_:"b=",nextState:"b"},p:{action_:"b=",nextState:"bp"},"3|o":{action_:"d= kv",nextState:"D"},q:{action_:"d=",nextState:"qD"},"d|D|qd|qD|dq":{action_:["output","d="],nextState:"D"}},"^a|^\\x{}{}|^\\x{}|^\\x|'":{"0|1|2|as":{action_:"b=",nextState:"b"},p:{action_:"b=",nextState:"bp"},"3|o":{action_:"d= kv",nextState:"d"},q:{action_:"d=",nextState:"qd"},"d|qd|D|qD":{action_:"d="},dq:{action_:["output","d="],nextState:"d"}},"_{(state of aggregation)}$":{"d|D|q|qd|qD|dq":{action_:["output","q="],nextState:"q"}},"_{(...)}|_($...$)|_9|_\\x{}{}|_\\x{}|_\\x":{"0|1|2|as":{action_:"p=",nextState:"p"},b:{action_:"p=",nextState:"bp"},"3|o":{action_:"q=",nextState:"q"},"d|D":{action_:"q=",nextState:"dq"},"q|qd|qD|dq":{action_:["output","q="],nextState:"q"}},"=<>":{"0|1|2|3|a|as|o|q|d|D|qd|qD|dq":{action_:[{type_:"output",option:2},"bond"],nextState:"3"}},"#":{"0|1|2|3|a|as|o":{action_:[{type_:"output",option:2},{type_:"bond",option:"#"}],nextState:"3"}},"{}":{"*":{action_:{type_:"output",option:1},nextState:"1"}},"{...}":{"0|1|2|3|a|as|b|p|bp":{action_:"o=",nextState:"o"},"o|d|D|q|qd|qD|dq":{action_:["output","o="],nextState:"o"}},"$...$":{a:{action_:"a="},"0|1|2|3|as|b|p|bp|o":{action_:"o=",nextState:"o"},"as|o":{action_:"o="},"q|d|D|qd|qD|dq":{action_:["output","o="],nextState:"o"}},"\\bond{(...)}":{"*":{action_:[{type_:"output",option:2},"bond"],nextState:"3"}},"\\frac{(...)}":{"*":{action_:[{type_:"output",option:1},"frac-output"],nextState:"3"}},"\\overset{(...)}":{"*":{action_:[{type_:"output",option:2},"overset-output"],nextState:"3"}},"\\underset{(...)}":{"*":{action_:[{type_:"output",option:2},"underset-output"],nextState:"3"}},"\\underbrace{(...)}":{"*":{action_:[{type_:"output",option:2},"underbrace-output"],nextState:"3"}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:[{type_:"output",option:2},"color-output"],nextState:"3"}},"\\color{(...)}0":{"*":{action_:[{type_:"output",option:2},"color0-output"]}},"\\ce{(...)}":{"*":{action_:[{type_:"output",option:2},"ce"],nextState:"3"}},"\\,":{"*":{action_:[{type_:"output",option:1},"copy"],nextState:"1"}},"\\x{}{}|\\x{}|\\x":{"0|1|2|3|a|as|b|p|bp|o|c0":{action_:["o=","output"],nextState:"3"},"*":{action_:["output","o=","output"],nextState:"3"}},others:{"*":{action_:[{type_:"output",option:1},"copy"],nextState:"3"}},else2:{a:{action_:"a to o",nextState:"o",revisit:!0},as:{action_:["output","sb=true"],nextState:"1",revisit:!0},"r|rt|rd|rdt|rdq":{action_:["output"],nextState:"0",revisit:!0},"*":{action_:["output","copy"],nextState:"3"}}}),actions:{"o after d":function(t,e){var r;if((t.d||"").match(/^[0-9]+$/)){var i=t.d;t.d=void 0,r=this.output(t),t.b=i}else r=this.output(t);return L.actions["o="](t,e),r},"d= kv":function(t,e){t.d=e,t.dType="kv"},"charge or bond":function(t,e){if(t.beginsWithBond){var r=[];return L.concatArray(r,this.output(t)),L.concatArray(r,L.actions.bond(t,e,"-")),r}else t.d=e},"- after o/d":function(t,e,r){var i=L.patterns.match_("orbital",t.o||""),n=L.patterns.match_("one lowercase greek letter $",t.o||""),o=L.patterns.match_("one lowercase latin letter $",t.o||""),a=L.patterns.match_("$one lowercase latin letter$ $",t.o||""),s=e==="-"&&(i&&i.remainder===""||n||o||a);s&&!t.a&&!t.b&&!t.p&&!t.d&&!t.q&&!i&&o&&(t.o="$"+t.o+"$");var l=[];return s?(L.concatArray(l,this.output(t)),l.push({type_:"hyphen"})):(i=L.patterns.match_("digits",t.d||""),r&&i&&i.remainder===""?(L.concatArray(l,L.actions["d="](t,e)),L.concatArray(l,this.output(t))):(L.concatArray(l,this.output(t)),L.concatArray(l,L.actions.bond(t,e,"-")))),l},"a to o":function(t){t.o=t.a,t.a=void 0},"sb=true":function(t){t.sb=!0},"sb=false":function(t){t.sb=!1},"beginsWithBond=true":function(t){t.beginsWithBond=!0},"beginsWithBond=false":function(t){t.beginsWithBond=!1},"parenthesisLevel++":function(t){t.parenthesisLevel++},"parenthesisLevel--":function(t){t.parenthesisLevel--},"state of aggregation":function(t,e){return{type_:"state of aggregation",p1:L.go(e,"o")}},comma:function(t,e){var r=e.replace(/\s*$/,""),i=r!==e;return i&&t.parenthesisLevel===0?{type_:"comma enumeration L",p1:r}:{type_:"comma enumeration M",p1:r}},output:function(t,e,r){var i;if(!t.r)i=[],!t.a&&!t.b&&!t.p&&!t.o&&!t.q&&!t.d&&!r||(t.sb&&i.push({type_:"entitySkip"}),!t.o&&!t.q&&!t.d&&!t.b&&!t.p&&r!==2?(t.o=t.a,t.a=void 0):!t.o&&!t.q&&!t.d&&(t.b||t.p)?(t.o=t.a,t.d=t.b,t.q=t.p,t.a=t.b=t.p=void 0):t.o&&t.dType==="kv"&&L.patterns.match_("d-oxidation$",t.d||"")?t.dType="oxidation":t.o&&t.dType==="kv"&&!t.q&&(t.dType=void 0),i.push({type_:"chemfive",a:L.go(t.a,"a"),b:L.go(t.b,"bd"),p:L.go(t.p,"pq"),o:L.go(t.o,"o"),q:L.go(t.q,"pq"),d:L.go(t.d,t.dType==="oxidation"?"oxidation":"bd"),dType:t.dType}));else{var n;t.rdt==="M"?n=L.go(t.rd,"tex-math"):t.rdt==="T"?n=[{type_:"text",p1:t.rd||""}]:n=L.go(t.rd);var o;t.rqt==="M"?o=L.go(t.rq,"tex-math"):t.rqt==="T"?o=[{type_:"text",p1:t.rq||""}]:o=L.go(t.rq),i={type_:"arrow",r:t.r,rd:n,rq:o}}for(var a in t)a!=="parenthesisLevel"&&a!=="beginsWithBond"&&delete t[a];return i},"oxidation-output":function(t,e){var r=["{"];return L.concatArray(r,L.go(e,"oxidation")),r.push("}"),r},"frac-output":function(t,e){return{type_:"frac-ce",p1:L.go(e[0]),p2:L.go(e[1])}},"overset-output":function(t,e){return{type_:"overset",p1:L.go(e[0]),p2:L.go(e[1])}},"underset-output":function(t,e){return{type_:"underset",p1:L.go(e[0]),p2:L.go(e[1])}},"underbrace-output":function(t,e){return{type_:"underbrace",p1:L.go(e[0]),p2:L.go(e[1])}},"color-output":function(t,e){return{type_:"color",color1:e[0],color2:L.go(e[1])}},"r=":function(t,e){t.r=e},"rdt=":function(t,e){t.rdt=e},"rd=":function(t,e){t.rd=e},"rqt=":function(t,e){t.rqt=e},"rq=":function(t,e){t.rq=e},operator:function(t,e,r){return{type_:"operator",kind_:r||e}}}},a:{transitions:L.createTransitions({empty:{"*":{}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"1",revisit:!0}},"$(...)$":{"*":{action_:"tex-math tight",nextState:"1"}},",":{"*":{action_:{type_:"insert",option:"commaDecimal"}}},else2:{"*":{action_:"copy"}}}),actions:{}},o:{transitions:L.createTransitions({empty:{"*":{}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"1",revisit:!0}},letters:{"*":{action_:"rm"}},"\\ca":{"*":{action_:{type_:"insert",option:"circa"}}},"\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"{text}"}},else2:{"*":{action_:"copy"}}}),actions:{}},text:{transitions:L.createTransitions({empty:{"*":{action_:"output"}},"{...}":{"*":{action_:"text="}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"\\greek":{"*":{action_:["output","rm"]}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:["output","copy"]}},else:{"*":{action_:"text="}}}),actions:{output:function(t){if(t.text_){var e={type_:"text",p1:t.text_};for(var r in t)delete t[r];return e}}}},pq:{transitions:L.createTransitions({empty:{"*":{}},"state of aggregation $":{"*":{action_:"state of aggregation"}},i$:{0:{nextState:"!f",revisit:!0}},"(KV letters),":{0:{action_:"rm",nextState:"0"}},formula$:{0:{nextState:"f",revisit:!0}},"1/2$":{0:{action_:"1/2"}},else:{0:{nextState:"!f",revisit:!0}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"text"}},"a-z":{f:{action_:"tex-math"}},letters:{"*":{action_:"rm"}},"-9.,9":{"*":{action_:"9,9"}},",":{"*":{action_:{type_:"insert+p1",option:"comma enumeration S"}}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:"color-output"}},"\\color{(...)}0":{"*":{action_:"color0-output"}},"\\ce{(...)}":{"*":{action_:"ce"}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},else2:{"*":{action_:"copy"}}}),actions:{"state of aggregation":function(t,e){return{type_:"state of aggregation subscript",p1:L.go(e,"o")}},"color-output":function(t,e){return{type_:"color",color1:e[0],color2:L.go(e[1],"pq")}}}},bd:{transitions:L.createTransitions({empty:{"*":{}},x$:{0:{nextState:"!f",revisit:!0}},formula$:{0:{nextState:"f",revisit:!0}},else:{0:{nextState:"!f",revisit:!0}},"-9.,9 no missing 0":{"*":{action_:"9,9"}},".":{"*":{action_:{type_:"insert",option:"electron dot"}}},"a-z":{f:{action_:"tex-math"}},x:{"*":{action_:{type_:"insert",option:"KV x"}}},letters:{"*":{action_:"rm"}},"'":{"*":{action_:{type_:"insert",option:"prime"}}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},"{(...)}":{"*":{action_:"text"}},"\\color{(...)}{(...)}1|\\color(...){(...)}2":{"*":{action_:"color-output"}},"\\color{(...)}0":{"*":{action_:"color0-output"}},"\\ce{(...)}":{"*":{action_:"ce"}},"\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"copy"}},else2:{"*":{action_:"copy"}}}),actions:{"color-output":function(t,e){return{type_:"color",color1:e[0],color2:L.go(e[1],"bd")}}}},oxidation:{transitions:L.createTransitions({empty:{"*":{}},"roman numeral":{"*":{action_:"roman-numeral"}},"${(...)}$|$(...)$":{"*":{action_:"tex-math"}},else:{"*":{action_:"copy"}}}),actions:{"roman-numeral":function(t,e){return{type_:"roman numeral",p1:e||""}}}},"tex-math":{transitions:L.createTransitions({empty:{"*":{action_:"output"}},"\\ce{(...)}":{"*":{action_:["output","ce"]}},"{...}|\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"o="}},else:{"*":{action_:"o="}}}),actions:{output:function(t){if(t.o){var e={type_:"tex-math",p1:t.o};for(var r in t)delete t[r];return e}}}},"tex-math tight":{transitions:L.createTransitions({empty:{"*":{action_:"output"}},"\\ce{(...)}":{"*":{action_:["output","ce"]}},"{...}|\\,|\\x{}{}|\\x{}|\\x":{"*":{action_:"o="}},"-|+":{"*":{action_:"tight operator"}},else:{"*":{action_:"o="}}}),actions:{"tight operator":function(t,e){t.o=(t.o||"")+"{"+e+"}"},output:function(t){if(t.o){var e={type_:"tex-math",p1:t.o};for(var r in t)delete t[r];return e}}}},"9,9":{transitions:L.createTransitions({empty:{"*":{}},",":{"*":{action_:"comma"}},else:{"*":{action_:"copy"}}}),actions:{comma:function(){return{type_:"commaDecimal"}}}},pu:{transitions:L.createTransitions({empty:{"*":{action_:"output"}},space$:{"*":{action_:["output","space"]}},"{[(|)]}":{"0|a":{action_:"copy"}},"(-)(9)^(-9)":{0:{action_:"number^",nextState:"a"}},"(-)(9.,9)(e)(99)":{0:{action_:"enumber",nextState:"a"}},space:{"0|a":{}},"pm-operator":{"0|a":{action_:{type_:"operator",option:"\\pm"},nextState:"0"}},operator:{"0|a":{action_:"copy",nextState:"0"}},"//":{d:{action_:"o=",nextState:"/"}},"/":{d:{action_:"o=",nextState:"/"}},"{...}|else":{"0|d":{action_:"d=",nextState:"d"},a:{action_:["space","d="],nextState:"d"},"/|q":{action_:"q=",nextState:"q"}}}),actions:{enumber:function(t,e){var r=[];return e[0]==="+-"||e[0]==="+/-"?r.push("\\pm "):e[0]&&r.push(e[0]),e[1]&&(L.concatArray(r,L.go(e[1],"pu-9,9")),e[2]&&(e[2].match(/[,.]/)?L.concatArray(r,L.go(e[2],"pu-9,9")):r.push(e[2])),(e[3]||e[4])&&(e[3]==="e"||e[4]==="*"?r.push({type_:"cdot"}):r.push({type_:"times"}))),e[5]&&r.push("10^{"+e[5]+"}"),r},"number^":function(t,e){var r=[];return e[0]==="+-"||e[0]==="+/-"?r.push("\\pm "):e[0]&&r.push(e[0]),L.concatArray(r,L.go(e[1],"pu-9,9")),r.push("^{"+e[2]+"}"),r},operator:function(t,e,r){return{type_:"operator",kind_:r||e}},space:function(){return{type_:"pu-space-1"}},output:function(t){var e,r=L.patterns.match_("{(...)}",t.d||"");r&&r.remainder===""&&(t.d=r.match_);var i=L.patterns.match_("{(...)}",t.q||"");if(i&&i.remainder===""&&(t.q=i.match_),t.d&&(t.d=t.d.replace(/\u00B0C|\^oC|\^{o}C/g,"{}^{\\circ}C"),t.d=t.d.replace(/\u00B0F|\^oF|\^{o}F/g,"{}^{\\circ}F")),t.q){t.q=t.q.replace(/\u00B0C|\^oC|\^{o}C/g,"{}^{\\circ}C"),t.q=t.q.replace(/\u00B0F|\^oF|\^{o}F/g,"{}^{\\circ}F");var n={d:L.go(t.d,"pu"),q:L.go(t.q,"pu")};t.o==="//"?e={type_:"pu-frac",p1:n.d,p2:n.q}:(e=n.d,n.d.length>1||n.q.length>1?e.push({type_:" / "}):e.push({type_:"/"}),L.concatArray(e,n.q))}else e=L.go(t.d,"pu-2");for(var o in t)delete t[o];return e}}},"pu-2":{transitions:L.createTransitions({empty:{"*":{action_:"output"}},"*":{"*":{action_:["output","cdot"],nextState:"0"}},"\\x":{"*":{action_:"rm="}},space:{"*":{action_:["output","space"],nextState:"0"}},"^{(...)}|^(-1)":{1:{action_:"^(-1)"}},"-9.,9":{0:{action_:"rm=",nextState:"0"},1:{action_:"^(-1)",nextState:"0"}},"{...}|else":{"*":{action_:"rm=",nextState:"1"}}}),actions:{cdot:function(){return{type_:"tight cdot"}},"^(-1)":function(t,e){t.rm+="^{"+e+"}"},space:function(){return{type_:"pu-space-2"}},output:function(t){var e=[];if(t.rm){var r=L.patterns.match_("{(...)}",t.rm||"");r&&r.remainder===""?e=L.go(r.match_,"pu"):e={type_:"rm",p1:t.rm}}for(var i in t)delete t[i];return e}}},"pu-9,9":{transitions:L.createTransitions({empty:{0:{action_:"output-0"},o:{action_:"output-o"}},",":{0:{action_:["output-0","comma"],nextState:"o"}},".":{0:{action_:["output-0","copy"],nextState:"o"}},else:{"*":{action_:"text="}}}),actions:{comma:function(){return{type_:"commaDecimal"}},"output-0":function(t){var e=[];if(t.text_=t.text_||"",t.text_.length>4){var r=t.text_.length%3;r===0&&(r=3);for(var i=t.text_.length-3;i>0;i-=3)e.push(t.text_.substr(i,3)),e.push({type_:"1000 separator"});e.push(t.text_.substr(0,r)),e.reverse()}else e.push(t.text_);for(var n in t)delete t[n];return e},"output-o":function(t){var e=[];if(t.text_=t.text_||"",t.text_.length>4){for(var r=t.text_.length-3,i=0;i"||t.r==="<=>>"||t.r==="<<=>"||t.r==="<-->"?(a="\\long"+a,o.rd&&(a="\\overset{"+o.rd+"}{"+a+"}"),o.rq&&(t.r==="<-->"?a="\\underset{\\lower2mu{"+o.rq+"}}{"+a+"}":a="\\underset{\\lower6mu{"+o.rq+"}}{"+a+"}"),a=" {}\\mathrel{"+a+"}{} "):(o.rq&&(a+="[{"+o.rq+"}]"),a+="{"+o.rd+"}",a=" {}\\mathrel{\\x"+a+"}{} "):a=" {}\\mathrel{\\long"+a+"}{} ",e=a;break;case"operator":e=me._getOperator(t.kind_);break;case"1st-level escape":e=t.p1+" ";break;case"space":e=" ";break;case"entitySkip":e="~";break;case"pu-space-1":e="~";break;case"pu-space-2":e="\\mkern3mu ";break;case"1000 separator":e="\\mkern2mu ";break;case"commaDecimal":e="{,}";break;case"comma enumeration L":e="{"+t.p1+"}\\mkern6mu ";break;case"comma enumeration M":e="{"+t.p1+"}\\mkern3mu ";break;case"comma enumeration S":e="{"+t.p1+"}\\mkern1mu ";break;case"hyphen":e="\\text{-}";break;case"addition compound":e="\\,{\\cdot}\\,";break;case"electron dot":e="\\mkern1mu \\bullet\\mkern1mu ";break;case"KV x":e="{\\times}";break;case"prime":e="\\prime ";break;case"cdot":e="\\cdot ";break;case"tight cdot":e="\\mkern1mu{\\cdot}\\mkern1mu ";break;case"times":e="\\times ";break;case"circa":e="{\\sim}";break;case"^":e="uparrow";break;case"v":e="downarrow";break;case"ellipsis":e="\\ldots ";break;case"/":e="/";break;case" / ":e="\\,/\\,";break;default:throw["MhchemBugT","mhchem bug T. Please report."]}return e},_getArrow:function(t){switch(t){case"->":return"rightarrow";case"\u2192":return"rightarrow";case"\u27F6":return"rightarrow";case"<-":return"leftarrow";case"<->":return"leftrightarrow";case"<-->":return"leftrightarrows";case"<=>":return"rightleftharpoons";case"\u21CC":return"rightleftharpoons";case"<=>>":return"Rightleftharpoons";case"<<=>":return"Leftrightharpoons";default:throw["MhchemBugT","mhchem bug T. Please report."]}},_getBond:function(t){switch(t){case"-":return"{-}";case"1":return"{-}";case"=":return"{=}";case"2":return"{=}";case"#":return"{\\equiv}";case"3":return"{\\equiv}";case"~":return"{\\tripledash}";case"~-":return"{\\rlap{\\lower.1em{-}}\\raise.1em{\\tripledash}}";case"~=":return"{\\rlap{\\lower.2em{-}}\\rlap{\\raise.2em{\\tripledash}}-}";case"~--":return"{\\rlap{\\lower.2em{-}}\\rlap{\\raise.2em{\\tripledash}}-}";case"-~-":return"{\\rlap{\\lower.2em{-}}\\rlap{\\raise.2em{-}}\\tripledash}";case"...":return"{{\\cdot}{\\cdot}{\\cdot}}";case"....":return"{{\\cdot}{\\cdot}{\\cdot}{\\cdot}}";case"->":return"{\\rightarrow}";case"<-":return"{\\leftarrow}";case"<":return"{<}";case">":return"{>}";default:throw["MhchemBugT","mhchem bug T. Please report."]}},_getOperator:function(t){switch(t){case"+":return" {}+{} ";case"-":return" {}-{} ";case"=":return" {}={} ";case"<":return" {}<{} ";case">":return" {}>{} ";case"<<":return" {}\\ll{} ";case">>":return" {}\\gg{} ";case"\\pm":return" {}\\pm{} ";case"\\approx":return" {}\\approx{} ";case"$\\approx$":return" {}\\approx{} ";case"v":return" \\downarrow{} ";case"(v)":return" \\downarrow{} ";case"^":return" \\uparrow{} ";case"(^)":return" \\uparrow{} ";default:throw["MhchemBugT","mhchem bug T. Please report."]}}};var mn=class t extends x{constructor(e){super(g(h({},e),{type:"delim"})),this.value=e.delim,this.size=e.size}static fromJson(e){return new t(e)}toJson(){return g(h({},super.toJson()),{delim:this.value,size:this.size})}render(e){return new w(this.value,{type:"middle"})}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);return r!=null&&r.serialize?r.serialize(this,e):U(this.command,this.value)}},hn=class t extends x{constructor(e){super(g(h({},e),{type:"sizeddelim",value:e.delim})),this.delimType=e.delimType,this.size=e.size}static fromJson(e){return new t(e)}toJson(){return g(h({},super.toJson()),{delim:this.value,size:this.size,delimType:this.delimType})}render(e){let r=fh(this.value,this.size,e,{classes:{open:"ML__open",close:"ML__close"}[this.delimType],type:this.delimType,isSelected:this.isSelected});return r?(r=this.bind(e,r),this.caret&&(r.caret=this.caret),r):null}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);return r!=null&&r.serialize?r.serialize(this,e):U(this.command,this.value)}};function ro(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}var ur=class t extends x{constructor(e,r,i,n){var o,a,s,l,c,u;super({type:"enclose",command:e,style:n.style}),this.body=r,i.updiagonalarrow&&(i.updiagonalstrike=!1),i.box&&(i.left=!1,i.right=!1,i.bottom=!1,i.top=!1),this.notation=i,this.shadow=(o=n.shadow)!=null?o:"none",this.strokeWidth=(a=W0(n.strokeWidth))!=null?a:"0.06em",this.strokeStyle=/^(solid|dashed|dotted|double|none)$/.test((s=n.strokeStyle)!=null?s:"")?n.strokeStyle:"solid",this.svgStrokeStyle=n.svgStrokeStyle,this.strokeColor=(l=Yi(n.strokeColor))!=null?l:"currentColor",this.backgroundcolor=(c=Yi(n.backgroundcolor))!=null?c:"transparent",this.borderStyle=(u=Ga(n.borderStyle))!=null?u:`${this.strokeWidth} ${this.strokeStyle} ${this.strokeColor}`,this.padding=n.padding,this.captureSelection=!1}static fromJson(e){return new t(e.command,e.body,e.notation,e)}toJson(){return g(h({},super.toJson()),{notation:this.notation,shadow:this.shadow,strokeWidth:this.strokeWidth,strokeStyle:this.strokeStyle,svgStrokeStyle:this.svgStrokeStyle,strokeColor:this.strokeColor,borderStyle:this.borderStyle,padding:this.padding})}_serialize(e){var n;if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);if(r!=null&&r.serialize)return r.serialize(this,e);let i=(n=this.command)!=null?n:"";if(this.command==="\\enclose"){i+="{"+Object.keys(this.notation).join(" ")+"}";let o="",a="";this.backgroundcolor&&this.backgroundcolor!=="transparent"&&(o+=a+'mathbackground="'+this.backgroundcolor+'"',a=","),this.shadow&&this.shadow!=="auto"&&(o+=a+'shadow="'+this.shadow+'"',a=","),this.strokeWidth||this.strokeStyle!=="solid"?(o+=a+this.borderStyle,a=","):this.strokeColor&&this.strokeColor!=="currentColor"&&(o+=a+'mathcolor="'+this.strokeColor+'"',a=","),o&&(i+=`[${o}]`)}return U(i,this.bodyToLatex(e))}render(e){var p,f,y,v;let r=new P({parent:e},this.style),i=x.createBox(r,this.body);if(!i)return null;let n=_g(this.borderStyle),o=r.toEm(!this.padding||this.padding==="auto"?{register:"fboxsep"}:{string:this.padding});i.setStyle("position","relative"),i.setStyle("display","inline-block"),i.setStyle("height",i.height+i.depth,"em"),i.setStyle("width",i.width,"em");let a=new w(null,{classes:"ML__notation"}),s=i.height+i.depth+2*o,l=i.width+2*o,c="",u=Math.min(o*.2,.05);if(this.notation.horizontalstrike){let b=2*o+i.height-Xe/2;c+=this.line((o+u).toString(),b.toString(),(o+i.width-u).toString(),b.toString())}if(this.notation.verticalstrike){let b=o+i.width/2;c+=this.line(b.toString(),(o+u).toString(),b.toString(),(s-o-u).toString())}if(this.notation.updiagonalstrike&&(c+=this.line((o+u).toString(),(s-o-u).toString(),(o+i.width-u).toString(),(o+u).toString())),this.notation.downdiagonalstrike&&(c+=this.line((o+u).toString(),(o+u).toString(),(o+i.width-u).toString(),(s-o-u).toString())),this.notation.updiagonalarrow){c+=this.line(o.toString(),(2*o+i.depth+i.height).toString(),(o+i.width).toString(),o.toString());let S=.03*Math.sqrt(l*l+s*s)*1,A=i.width*S,E=(i.depth+i.height)*S,C=o+i.width,_=o;_+E-.4*A<0&&(_=.4*A-E),c+='
    `}};function ls(t){return typeof t=="number"?`${Math.floor(100*t)/100}%`:t}function _g(t){if(!t)return"1px";let e=t.match(/([0-9][a-zA-Z\%]+)/);return e===null?"1px":e[1]}function Mg(t){return(Math.floor(100*t.metrics.sqrtRuleThickness/t.scalingFactor)/100/10).toString()+"em"}function Mh(t){let e=t.isDisplayStyle?Xe:t.metrics.defaultRuleThickness;return t.metrics.defaultRuleThickness+t.scalingFactor*e/4}var pn={fractionNavigationOrder:"numerator-denominator"};var st=class t extends x{constructor(e,r,i){var n,o,a;super(g(h({},i),{type:"genfrac",displayContainsHighlight:!0})),this.above=e,this.below=r,this.hasBarLine=(n=i==null?void 0:i.hasBarLine)!=null?n:!0,this.continuousFraction=(o=i==null?void 0:i.continuousFraction)!=null?o:!1,this.align=(a=i==null?void 0:i.align)!=null?a:"center",this.numerPrefix=i==null?void 0:i.numerPrefix,this.denomPrefix=i==null?void 0:i.denomPrefix,this.mathstyleName=i==null?void 0:i.mathstyleName,this.leftDelim=i==null?void 0:i.leftDelim,this.rightDelim=i==null?void 0:i.rightDelim,this.barThickness=i==null?void 0:i.barThickness}static fromJson(e){return new t(e.above,e.below,e)}toJson(){let e={};return this.continuousFraction&&(e.continuousFraction=!0),this.align!=="center"&&(e.align=this.align),this.numerPrefix&&(e.numerPrefix=this.numerPrefix),this.denomPrefix&&(e.denomPrefix=this.denomPrefix),this.leftDelim&&(e.leftDelim=this.leftDelim),this.rightDelim&&(e.rightDelim=this.rightDelim),this.hasBarLine||(e.hasBarLine=!1),this.barThickness&&(e.barThickness=this.barThickness),this.mathstyleName&&(e.mathstyleName=this.mathstyleName),h(h({},super.toJson()),e)}get children(){if(this._children)return this._children;let e=[];if(pn.fractionNavigationOrder==="denominator-numerator"){for(let r of this.below)e.push(...r.children),e.push(r);for(let r of this.above)e.push(...r.children),e.push(r)}else{for(let r of this.above)e.push(...r.children),e.push(r);for(let r of this.below)e.push(...r.children),e.push(r)}return this._children=e,e}render(e){var E,C;let r=new P({parent:e,mathstyle:this.mathstyleName},this.style),i=r.metrics,n=new P({parent:r,mathstyle:this.continuousFraction?"":"numerator"},this.style),o=this.numerPrefix?new w([new w(this.numerPrefix),x.createBox(n,this.above)],{isTight:n.isTight,type:"ignore"}):(E=x.createBox(n,this.above,{type:"ignore"}))!=null?E:new w(null,{type:"ignore"}),a=new P({parent:r,mathstyle:this.continuousFraction?"":"denominator"},this.style),s=this.denomPrefix?new w([new w(this.denomPrefix),x.createBox(a,this.below,{type:"ignore"})]):(C=x.createBox(a,this.below,{type:"ignore"}))!=null?C:new w(null,{type:"ignore"}),l=0;this.hasBarLine&&(l=this.barThickness?r.toEm(this.barThickness):i.defaultRuleThickness);let c,u=0,d;r.isDisplayStyle?(c=n.metrics.num1,u=l>0?3*l:7*l,d=a.metrics.denom1):(l>0?(c=n.metrics.num2,u=l):(c=n.metrics.num3,u=3*i.defaultRuleThickness),d=a.metrics.denom2);let m=[];this.isSelected&&m.push("ML__selected");let p=o.depth,f=s.height,y;if(l<=0){let _=c-p-(f-d);_new he(r)),this.skipBoundary=!0}static fromJson(e){return new t}toJson(){return super.toJson()}render(e){let r=x.createBox(e,this.body);return r?(this.caret&&(r.caret=this.caret),this.bind(e,r)):null}_serialize(e){var r,i;return(i=(r=this.body)==null?void 0:r.map(n=>n.value).join(""))!=null?i:""}};var fi=class t extends x{constructor(e,r){super(g(h({},r),{type:"extensible-symbol",isFunction:r==null?void 0:r.isFunction})),this.value=e,this.variant=r==null?void 0:r.variant,this.subsupPlacement=r==null?void 0:r.limits}static fromJson(e){return new t(e.symbol,e)}toJson(){let e=super.toJson();return this.variant&&(e.variant=this.variant),this.subsupPlacement&&(e.limits=this.subsupPlacement),this.value&&(e.symbol=this.value),e}render(e){var s;let r=e.isDisplayStyle&&this.value!=="\\smallint",i=new w(this.value,{fontFamily:r?"Size2-Regular":"Size1-Regular",classes:"ML__op-symbol "+(r?"ML__large-op":"ML__small-op"),type:"op",maxFontSize:e.scalingFactor,isSelected:this.isSelected});if(!i)return null;i.right=i.italic;let n=(i.height-i.depth)/2-Ie*e.scalingFactor,o=i.italic;i.setTop(n);let a=i;if(this.superscript||this.subscript){let l=(s=this.subsupPlacement)!=null?s:"auto";l==="auto"&&e.isDisplayStyle&&(l="over-under"),a=l==="over-under"?this.attachLimits(e,{base:i,baseShift:n,slant:o}):this.attachSupsub(e,{base:i})}return new w(this.bind(e,a),{type:"op",caret:this.caret,isSelected:this.isSelected,classes:"ML__op-group"}).wrap(e)}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);if(r!=null&&r.serialize)return r.serialize(this,e);let i=[];return i.push(this.command),this.explicitSubsupPlacement&&(this.subsupPlacement==="over-under"&&i.push("\\limits"),this.subsupPlacement==="adjacent"&&i.push("\\nolimits"),this.subsupPlacement==="auto"&&i.push("\\displaylimits")),i.push(this.supsubToLatex(e)),R(i)}};var yt=class t extends x{constructor(e){let r=e.body;super(g(h({},e),{type:"overlap",body:typeof r=="string"?[new x({value:r})]:r,style:e==null?void 0:e.style})),this.skipBoundary=!0,this.align=e==null?void 0:e.align,this.boxType=e==null?void 0:e.boxType}static fromJson(e){return new t(e)}toJson(){let e={};return this.align&&(e.align=this.align),this.boxType&&(e.boxType=this.boxType),h(h({},super.toJson()),e)}render(e){let r=x.createBox(e,this.body,{classes:"ML__inner"});return r?(this.caret&&(r.caret=this.caret),this.bind(e,new w([r,new w(null,{classes:"ML__fix"})],{classes:this.align==="right"?"ML__rlap":"ML__llap",type:this.boxType}))):null}};var Ae=class t extends x{constructor(e){var r,i,n,o;super({type:"overunder",command:e.command,style:e.style,mode:e.mode,body:e.body,skipBoundary:(r=e.skipBoundary)!=null?r:!0}),this.subsupPlacement=e.supsubPlacement,this.svgAbove=e.svgAbove,this.svgBelow=e.svgBelow,this.svgBody=e.svgBody,this.above=e.above,this.below=e.below,this.boxType=(i=e.boxType)!=null?i:"ord",this.paddedBody=(n=e.paddedBody)!=null?n:!1,this.paddedLabels=(o=e.paddedLabels)!=null?o:!1}static fromJson(e){return new t(e)}toJson(){let e=super.toJson();return this.skipBoundary||(e.skipBoundary=!1),this.subsupPlacement&&(e.subsupPlacement=this.subsupPlacement),this.svgAbove&&(e.svgAbove=this.svgAbove),this.svgBelow&&(e.svgBelow=this.svgBelow),this.svgBody&&(e.svgBody=this.svgBody),this.boxType!=="ord"&&(e.boxType=this.boxType),this.paddedBody&&(e.paddedBody=!0),this.paddedLabels&&(e.paddedLabels=!0),e}render(e){let r=this.svgBody?Zi(this.svgBody):x.createBox(e,this.body,{type:"ignore"}),i=new P({parent:e,mathstyle:"scriptstyle"},this.style),n=null;this.svgAbove?n=Zi(this.svgAbove):this.above&&(n=x.createBox(i,this.above,{type:"ignore"}));let o=null;this.svgBelow?o=Zi(this.svgBelow):this.below&&(o=x.createBox(i,this.below,{type:"ignore"})),this.paddedBody&&(r=new w([lr(e,"ML__open"),r,lr(e,"ML__close")],{type:"ignore"}));let a=wg(e,{base:r,above:n,below:o,type:this.boxType==="bin"||this.boxType==="rel"?this.boxType:"ord",paddedAboveBelow:this.paddedLabels});return a?(this.subsupPlacement==="over-under"?a=this.attachLimits(e,{base:a,type:a.type}):a=this.attachSupsub(e,{base:a}),this.caret&&(a.caret=this.caret),this.bind(e,a)):null}};function wg(t,e){if(!e.base)return null;if(!e.above&&!e.below){let s=new w(e.base,{type:e.type});return s.setStyle("position","relative"),s}let r=0;e.above&&(r=t.metrics.bigOpSpacing5);let i=null,n=e.base,o=0,a=["ML__center"];if(e.paddedAboveBelow&&a.push("ML__label_padding"),e.below&&e.above){let s=t.metrics.bigOpSpacing5+e.below.height+e.below.depth+n.depth+o;i=new te({bottom:s,children:[t.metrics.bigOpSpacing5,{box:e.below,classes:a},{box:n,classes:["ML__center"]},r,{box:e.above,classes:a},t.metrics.bigOpSpacing5]})}else e.below?i=new te({top:n.height-o,children:[t.metrics.bigOpSpacing5,{box:e.below,classes:a},{box:n,classes:["ML__center"]}]}):e.above&&(i=new te({bottom:n.depth+o,children:[{box:n,classes:["ML__center"]},r,{box:e.above,classes:a},t.metrics.bigOpSpacing5]}));return new w(i,{type:e.type})}var Vt=class t extends x{constructor(e){var r,i,n,o;super(g(h({},e),{type:"phantom"})),this.captureSelection=!0,this.isInvisible=(r=e.isInvisible)!=null?r:!1,this.smashDepth=(i=e.smashDepth)!=null?i:!1,this.smashHeight=(n=e.smashHeight)!=null?n:!1,this.smashWidth=(o=e.smashWidth)!=null?o:!1}static fromJson(e){return new t(e)}toJson(){let e={};return this.isInvisible&&(e.isInvisible=!0),this.smashDepth&&(e.smashDepth=!0),this.smashHeight&&(e.smashHeight=!0),this.smashWidth&&(e.smashWidth=!0),h(h({},super.toJson()),e)}render(e){let r=new P({parent:e,isPhantom:!0});if(!this.smashDepth&&!this.smashHeight&&!this.smashWidth)return this.isInvisible,x.createBox(r,this.body,{classes:"ML__inner"});let i=x.createBox(this.isInvisible?r:e,this.body);if(!i)return null;if(this.smashWidth){let n=new w(null,{classes:"ML__fix"});return new w([i,n],{classes:"ML__rlap"}).wrap(e)}if(!this.smashHeight&&!this.smashDepth)return i;if(this.smashHeight&&(i.height=0),this.smashDepth&&(i.depth=0),i.children)for(let n of i.children)this.smashHeight&&(n.height=0),this.smashDepth&&(n.depth=0);return new te({firstBaseline:[{box:i}]},{type:i.type}).wrap(e)}};var qt=class t extends x{constructor(e){var r;super(h({type:"spacing"},e)),this.width=e==null?void 0:e.width,this._braced=(r=e==null?void 0:e.braced)!=null?r:!1}static fromJson(e){return new t(e)}toJson(){let e=super.toJson();return this.width!==void 0&&(e.width=this.width),this._braced&&(e.braced=!0),e}render(e){var i;if(this.command==="space")return new w(this.mode==="math"?null:" ");let r;if(this.width!==void 0)r=new w(null,{classes:"ML__mspace"}),r.left=e.toEm(this.width);else{let n=(i={"\\qquad":"ML__qquad","\\quad":"ML__quad","\\enspace":"ML__enspace","\\;":"ML__thickspace","\\:":"ML__mediumspace","\\>":"ML__mediumspace","\\,":"ML__thinspace","\\!":"ML__negativethinspace"}[this.command])!=null?i:"ML__mediumspace";r=new w(null,{classes:n})}return r=this.bind(e,r),this.caret&&(r.caret=this.caret),r}_serialize(e){var n;if(!e.expandMacro&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);if(r!=null&&r.serialize)return r.serialize(this,e);let i=(n=this.command)!=null?n:"";return this.width===void 0?i:this._braced&&!("register"in this.width)?`${i}{${ge(this.width)}}`:`${i}${ge(this.width)}`}};var fn=class t extends x{constructor(e){var r;super(g(h({},e),{type:"surd",mode:(r=e.mode)!=null?r:"math",style:e.style,displayContainsHighlight:!0,body:e.body})),this.above=e.index}static fromJson(e){return new t(g(h({},e),{index:e.above}))}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);if(r!=null&&r.serialize)return r.serialize(this,e);let i=this.command,n=this.bodyToLatex(e);return this.above&&!this.hasEmptyBranch("above")?U(`${i}[${this.aboveToLatex(e)}]`,n):/^[0-9]$/.test(n)?`${i}${n}`:U(i,n)}get children(){if(this._children)return this._children;let e=[];if(this.above)for(let r of this.above)e.push(...r.children),e.push(r);if(this.body)for(let r of this.body)e.push(...r.children),e.push(r);return this._children=e,e}render(e){var k;let r=new P({parent:e,mathstyle:"cramp"},this.style),i=(k=x.createBox(r,this.body,{type:"inner"}))!=null?k:new w(null),n=r.scalingFactor,o=r.metrics.defaultRuleThickness/n,a=e.isDisplayStyle?Xe:o,s=new w(null,{classes:"ML__sqrt-line",style:this.style});s.height=o,s.softWidth=i.width;let l=n*(o+a/4),u=Math.max(n*2*a,i.height+i.depth)+l+o,d=new P({parent:e},this.style),m=this.bind(d,new w(an("inner","\\surd",u,!1,d,{isSelected:this.isSelected}),{isSelected:this.isSelected,classes:"ML__sqrt-sign",style:this.style}));if(!m)return null;let p=m.height+m.depth-o;p>i.height+i.depth+l&&(l=(l+p-(i.height+i.depth))/2),m.setTop(m.height-i.height-l);let f=this.bind(e,new te({firstBaseline:[{box:new w(i)},l-2*o,{box:s},o]})),y=x.createBox(new P({parent:e,mathstyle:"scriptscriptstyle"}),this.above,{type:"ignore"});if(!y){let S=new w([m,f],{classes:this.containsCaret?"ML__contains-caret":"",type:"inner"});return S.setStyle("display","inline-block"),S.setStyle("height",S.height+S.depth,"em"),this.caret&&(S.caret=this.caret),this.bind(e,S)}let v=new te({shift:-.6*(Math.max(m.height,f.height)-Math.max(m.depth,f.depth)),children:[{box:y}]}),b=new w([new w(v,{classes:"ML__sqrt-index",type:"ignore"}),m,f],{type:"inner",classes:this.containsCaret?"ML__contains-caret":""});return b.height=m.height,b.depth=m.depth,this.caret&&(b.caret=this.caret),this.bind(e,b)}};var gc=class extends w{constructor(e){super(null,{type:"skip"}),this._width=e}toMarkup(){return``}};function io(t,e){if(!t.parent)return;let r=t.parent.children,i=r.indexOf(t),n=i-1;for(;n>=0&&r[n].type==="ignore";)n-=1;if(n<0&&t.parent.parent&&t.parent.type==="lift"){io(t.parent,e);return}i>0&&r[i-1].type==="skip"?r[i-1].width+=e:r.splice(i,0,new gc(e))}var Sg={ord:{op:3,bin:4,rel:5,inner:3},op:{ord:3,op:3,rel:5,inner:3},bin:{ord:4,op:4,open:4,inner:4},rel:{ord:5,op:5,open:5,inner:5},close:{op:3,bin:4,rel:5,inner:3},punct:{ord:3,op:3,rel:3,open:3,punct:3,inner:3},inner:{ord:3,op:3,bin:4,rel:5,open:3,punct:3,inner:3}},kg={ord:{op:3},op:{ord:3,op:3},close:{op:3},inner:{op:3}};function Lg(t){no(t,(e,r)=>{r.type==="bin"&&(!e||/^(middle|bin|op|rel|open|punct)$/.test(e.type))&&(r.type="ord"),(e==null?void 0:e.type)==="bin"&&/^(rel|close|punct)$/.test(r.type)&&(e.type="ord"),r.type!=="ignore"&&(e=r)})}function Ht(t,e){if(!t.children)return t;let r=t.children;Lg(r);let i=e.getRegisterAsEm("thinmuskip"),n=e.getRegisterAsEm("medmuskip"),o=e.getRegisterAsEm("thickmuskip");return no(r,(a,s)=>{var d,m,p;if(!a)return;let l=a.type,c=s.isTight?(d=kg[l])!=null?d:null:(m=Sg[l])!=null?m:null,u=(p=c==null?void 0:c[s.type])!=null?p:null;u===3&&io(s,i),u===4&&io(s,n),u===5&&io(s,o)}),t}function no(t,e,r=void 0){if(!t)return r;t=[...t];for(let i of t)i.type==="lift"?r=no(i.children,e,r):i.type==="ignore"?no(i.children,e):(e(r,i),no(i.children,e),r=i);return r}var gi=class t extends x{constructor(e){super({type:"tooltip",command:e.command,mode:e.mode,style:e.style,body:e.body,displayContainsHighlight:!0}),this.tooltip=new x({type:"root",mode:e.content,body:e.tooltip,style:{}}),this.skipBoundary=!0,this.captureSelection=!1}static fromJson(e){return new t(g(h({},e),{tooltip:xt(e.tooltip)}))}toJson(){var r;let e=(r=this.tooltip.body)==null?void 0:r.filter(i=>i.type!=="first").map(i=>i.toJson());return g(h({},super.toJson()),{tooltip:e})}render(e){let r=x.createBox(e,this.body);if(!r)return null;let i=new P({parent:e,mathstyle:"displaystyle"},{fontSize:ji}),n=Or(Ht(new w(this.tooltip.render(i),{classes:"ML__tooltip-content"}),i)),o=new w([n,r],{classes:"ML__tooltip-container"});return this.caret&&(o.caret=this.caret),this.bind(e,o)}};var vt=class t extends x{constructor(e,r){super(g(h({},r),{type:"operator",isFunction:r==null?void 0:r.isFunction})),this.value=e,this.variant=r==null?void 0:r.variant,this.variantStyle=r==null?void 0:r.variantStyle,this.subsupPlacement=r==null?void 0:r.limits}static fromJson(e){return new t(e.symbol,e)}toJson(){let e=super.toJson();return this.variant&&(e.variant=this.variant),this.variantStyle&&(e.variantStyle=this.variantStyle),this.subsupPlacement&&(e.limits=this.subsupPlacement),this.value&&(e.symbol=this.value),e}render(e){var n;let r=new w(this.value,{type:"op",mode:"math",maxFontSize:e.scalingFactor,style:{variant:this.variant,variantStyle:this.variantStyle},isSelected:this.isSelected,letterShapeStyle:e.letterShapeStyle}),i=r;if(this.superscript||this.subscript){let o=(n=this.subsupPlacement)!=null?n:"auto";i=o==="over-under"||o==="auto"&&e.isDisplayStyle?this.attachLimits(e,{base:r}):this.attachSupsub(e,{base:r})}return new w(this.bind(e,i),{type:"op",caret:this.caret,isSelected:this.isSelected,classes:"ML__op-group"}).wrap(e)}_serialize(e){if(!(e.expandMacro||e.skipStyles||e.skipPlaceholders)&&typeof this.verbatimLatex=="string")return this.verbatimLatex;let r=ne(this.command,this.mode);if(r!=null&&r.serialize)return r.serialize(this,e);let i=[this.command];return this.explicitSubsupPlacement&&(this.subsupPlacement==="over-under"&&i.push("\\limits"),this.subsupPlacement==="adjacent"&&i.push("\\nolimits"),this.subsupPlacement==="auto"&&i.push("\\displaylimits")),i.push(this.supsubToLatex(e)),R(i)}};function xt(t){if(ee(t))return t.map(i=>xt(i));if(typeof t=="string")return x.fromJson(t);t=h({},t);for(let i of Ir)t[i]&&(t[i]=xt(t[i]));t.args&&(t.args=Ag(t.args)),t.array&&(t.array=xt(t.array));let e=t.type,r;e==="accent"&&(r=Nr.fromJson(t)),e==="array"&&(r=z.fromJson(t)),e==="box"&&(r=at.fromJson(t)),e==="chem"&&(r=to.fromJson(t)),e==="composition"&&(r=sn.fromJson(t)),e==="delim"&&(r=mn.fromJson(t)),e==="enclose"&&(r=ur.fromJson(t)),e==="error"&&(r=bt.fromJson(t)),e==="extensible-symbol"&&(r=fi.fromJson(t)),e==="genfrac"&&(r=st.fromJson(t)),e==="group"&&(r=ln.fromJson(t)),e==="latex"&&(r=he.fromJson(t)),e==="latexgroup"&&(r=$t.fromJson(t)),e==="leftright"&&(r=J.fromJson(t)),e==="macro"&&(r=cn.fromJson(t)),e==="macro-argument"&&(r=os.fromJson(t)),e==="operator"&&(r=vt.fromJson(t)),e==="overlap"&&(r=yt.fromJson(t)),e==="overunder"&&(r=Ae.fromJson(t)),e==="placeholder"&&(r=Me.fromJson(t)),e==="prompt"&&(r=un.fromJson(t)),e==="phantom"&&(r=Vt.fromJson(t)),e==="sizeddelim"&&(r=hn.fromJson(t)),e==="spacing"&&(r=qt.fromJson(t)),e==="subsup"&&(r=cr.fromJson(t)),e==="surd"&&(r=fn.fromJson(t)),e==="text"&&(r=We.fromJson(t)),e==="tooltip"&&(r=gi.fromJson(t)),r||(!e||["first","mbin","mrel","mclose","minner","mop","mopen","mord","mpunct","root","space"].includes(e),`${e}`,r=x.fromJson(t));for(let i of Ir)t[i]&&r.setChildren(t[i],i);return t.verbatimLatex!==void 0&&(r.verbatimLatex=t.verbatimLatex),t.subsupPlacement&&(r.subsupPlacement=t.subsupPlacement),t.explicitSubsupPlacement&&(r.explicitSubsupPlacement=!0),t.isFunction&&(r.isFunction=!0),t.skipBoundary&&(r.skipBoundary=!0),t.captureSelection&&(r.captureSelection=!0),r}function Ag(t){if(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>e===""?null:typeof e=="object"&&"group"in e?{group:e.group.map(r=>xt(r))}:typeof e=="object"&&"atoms"in e?e.atoms.map(r=>xt(r)):e)}}function oo(t,e){!t||!e||(ee(t)?t.forEach(r=>oo(r,e)):typeof t=="object"&&t.applyStyle(e,{unstyledOnly:!0}))}function ao(t,e,r,i){function n(a,s){for(let l of o)if(l.style[a]!==s)return!1;return!0}if(e=t.normalizeRange(e),e[0]===e[1])return!1;let o=t.getAtoms(e,{includeChildren:!0});i.operation==="toggle"&&(r.color&&n("color",r.color)&&(r.color="none",delete r.verbatimColor),r.backgroundColor&&n("backgroundColor",r.backgroundColor)&&(r.backgroundColor="none",delete r.verbatimBackgroundColor),r.fontFamily&&n("fontFamily",r.fontFamily)&&(r.fontFamily="none"),r.fontSeries&&n("fontSeries",r.fontSeries)&&(r.fontSeries="auto"),r.fontShape&&n("fontShape",r.fontShape)&&(r.fontShape="auto"),r.fontSize&&n("fontSize",r.fontSize)&&(r.fontSize=ji),r.variant&&n("variant",r.variant)&&(r.variant="normal"),r.variantStyle&&n("variantStyle",r.variantStyle)&&(r.variantStyle=""));for(let a of o)a.applyStyle(r);return!0}function wh(t){return{up:"italic",bold:"bolditalic",italic:"italic",bolditalic:"bolditalic","":"italic"}[t!=null?t:""]}function so(t){return{up:"up",bold:"bold",italic:void 0,bolditalic:"bold","":void 0}[t!=null?t:""]}var Sh={acute:714,grave:715,dot:729,ddot:168,dddot:8411,ddddot:8412,mathring:730,tilde:126,bar:713,breve:728,check:711,hat:94,vec:8407};M(Object.keys(Sh),"{body:auto}",{createAtom:t=>new Nr(g(h({},t),{body:T(t.args[0]),accentChar:Sh[t.command.slice(1)]}))});M(["widehat","widecheck","widetilde"],"{body:auto}",{createAtom:t=>{let e=bl(T(t.args[0]));return new Nr(g(h({},t),{body:T(t.args[0]),svgAccent:t.command.slice(1)+(e.length>5?"4":["1","1","2","2","3","3"][e.length])}))}});M(["overarc","overparen","wideparen"],"{body:auto}",{createAtom:t=>new Nr(g(h({},t),{body:T(t.args[0]),svgAccent:"overarc"}))});M(["underarc","underparen"],"{body:auto}",{createAtom:t=>new Ae(g(h({},t),{body:T(t.args[0]),svgBelow:"underarc"}))});M("utilde","{body:auto}",{createAtom:t=>{let e=T(t.args[0]),r=bl(e),i="widetilde"+(r.length>5?"4":["1","1","2","2","3","3"][r.length]);return new Ae(g(h({},t),{body:e,svgBelow:i,boxType:ci(e)}))}});M("^","{:string}",{createAtom:t=>{var e;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:t.args[0]&&(e={a:"\xE2",e:"\xEA",i:"\xEE",o:"\xF4",u:"\xFB",A:"\xC2",E:"\xCA",I:"\xCE",O:"\xD4",U:"\xDB"}[t.args[0]])!=null?e:"^"}))}});M("`","{:string}",{createAtom:t=>{var e;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:t.args[0]&&(e={a:"\xE0",e:"\xE8",i:"\xEC",o:"\xF2",u:"\xF9",A:"\xC0",E:"\xC8",I:"\xCC",O:"\xD2",U:"\xD9"}[t.args[0]])!=null?e:"`"}))}});M("'","{:string}",{createAtom:t=>{var e;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:t.args[0]&&(e={a:"\xE1",e:"\xE9",i:"\xED",o:"\xF3",u:"\xFA",A:"\xC1",E:"\xC9",I:"\xCD",O:"\xD3",U:"\xDA"}[t.args[0]])!=null?e:"'"}))}});M('"',"{:string}",{createAtom:t=>{var e,r;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:(e=t.args)!=null&&e[0]?(r={a:"\xE4",e:"\xEB",i:"\xEF",o:"\xF6",u:"\xFC",A:"\xC4",E:"\xCB",I:"\xCB",O:"\xD6",U:"\xDC"}[t.args[0]])!=null?r:'"'+t.args[0]:'"'}))}});M(".","{:string}",{createAtom:t=>{var e,r;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:(e=t.args)!=null&&e[0]?(r={a:"\u0227",e:"\u0117",i:"\u0307i",o:"\u022F",u:"\u0307u",A:"\u0226",E:"\u0116",I:"\u0130",O:"\u022E",U:"\u0307U"}[t.args[0]])!=null?r:"."+t.args[0]:"."}))}});M("=","{:string}",{createAtom:t=>{var e,r;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:(e=t.args)!=null&&e[0]?(r={a:"\u0101",e:"\u0113",i:"\u012B",o:"\u014D",u:"\u016B",A:"\u0100",E:"\u0112",I:"\u012A",O:"\u014C",U:"\u016A"}[t.args[0]])!=null?r:"="+t.args[0]:"="}))}});M("~","{:string}",{createAtom:t=>{var e;return new x(g(h({type:"mord"},t),{isFunction:!1,limits:"adjacent",value:t.args[0]&&(e={n:"\xF1",N:"\xD1",a:"\xE3",o:"\xF5",A:"\xC3",O:"\xD5"}[t.args[0]])!=null?e:"\xB4"}))}});M("c","{:string}",{createAtom:t=>{var e;return new x(g(h({},t),{type:"mord",isFunction:!1,limits:"adjacent",value:t.args[0]&&(e={c:"\xE7",C:"\xC7"}[t.args[0]])!=null?e:""}))}});var Cg=new Set(["downdiagonalstrike","updiagonalstrike","verticalstrike","horizontalstrike","updiagonalarrow","right","bottom","left","top","circle","roundedbox","madruwb","actuarial","box","phasorangle","longdiv"]);function Eg(t,e){let r=[],i=0,n=!1,o="";for(let a of t)a==='"'?n=!n:!n&&a==="("?i+=1:!n&&a===")"&&(i=Math.max(0,i-1)),a===e&&i===0&&!n?(o.length>0&&r.push(o),o=""):o+=a;return o.length>0&&r.push(o),r}M("enclose","{notation:string}[style:string]{body:auto}",{createAtom:t=>{var n,o;let e=t.args,r={strokeColor:"currentColor",strokeWidth:"",strokeStyle:"solid",backgroundcolor:"transparent",padding:"auto",shadow:"none",svgStrokeStyle:void 0,borderStyle:void 0,style:(n=t.style)!=null?n:{}};if(e[1]){let a=Eg(e[1],",");for(let s of a){let l=s.match(/^\s*([a-z]*)\s*=\s*"(.*)"\s*$/);if(l)l[1]==="mathbackground"?r.backgroundcolor=l[2]:l[1]==="mathcolor"?r.strokeColor=l[2]:l[1]==="padding"?r.padding=l[2]:l[1]==="shadow"&&(r.shadow=l[2]);else{let c=s.match(/\s*(\S+)\s+(\S+)\s+(.*)/);c&&(r.strokeWidth=c[1],r.strokeStyle=c[2],r.strokeColor=c[3])}}r.strokeStyle==="dashed"?r.svgStrokeStyle="5,5":r.strokeStyle==="dotted"&&(r.svgStrokeStyle="1,5")}r.borderStyle=`${r.strokeWidth} ${r.strokeStyle} ${r.strokeColor}`;let i={};return((o=e[0])!=null?o:"").split(/[, ]/).filter(a=>a.length>0).forEach(a=>{let s=a.toLowerCase();Cg.has(s)&&(i[s]=!0)}),new ur(t.command,T(e[2]),i,r)}});M("cancel","{body:auto}",{createAtom:t=>{var e;return new ur(t.command,T(t.args[0]),{updiagonalstrike:!0},{strokeColor:"currentColor",strokeWidth:"",strokeStyle:"solid",borderStyle:"1px solid currentColor",backgroundcolor:"transparent",padding:"auto",shadow:"none",style:(e=t.style)!=null?e:{}})}});M("bcancel","{body:auto}",{createAtom:t=>{var e;return new ur(t.command,T(t.args[0]),{downdiagonalstrike:!0},{strokeColor:"currentColor",strokeWidth:"",strokeStyle:"solid",borderStyle:"1px solid currentColor",backgroundcolor:"transparent",padding:"auto",shadow:"none",style:(e=t.style)!=null?e:{}})}});M("xcancel","{body:auto}",{createAtom:t=>{var e;return new ur(t.command,T(t.args[0]),{updiagonalstrike:!0,downdiagonalstrike:!0},{strokeColor:"currentColor",strokeWidth:"",strokeStyle:"solid",borderStyle:"1px solid currentColor",backgroundcolor:"transparent",padding:"auto",shadow:"none",style:(e=t.style)!=null?e:{}})}});Qo(["math","displaymath"],ze);Qo("center",ze);Tt(["multline","multline*"],"",ze);M("displaylines","",{parse:t=>{if(t.skipWhitespace(),!t.match("<{>"))return[];let e=[],r=[];t.mathlist.length>0&&e.push([t.mathlist]),t.beginContext({tabular:!0,root:!0});do{if(t.end()||t.match("<}>"))break;t.matchColumnSeparator()||t.matchRowSeparator()?(e.push([r]),r=[]):r.push(...t.scan(n=>["<}>","&","\\cr","\\\\","\\tabularnewline"].includes(n)))}while(!0);t.endContext(),e.push([r]);let i=t.scan();return i.length>0&&e.push([i]),e},createAtom:t=>new z("lines",t.args,[],{leftDelim:".",rightDelim:".",columns:[{align:"l"}],classes:["ML__multiline_environment"],isRoot:!0,minColumns:1,maxColumns:1,minRows:1})});Tt("split","",ze);Tt(["gather","gather*","gathered"],"",ze);Tt(["equation","equation*","subequations"],"",ze);Qo(["align","align*","eqnarray"],ze,{tabular:!0});Tt(["aligned"],"",ze);Tt("array","{columns:colspec}",(t,e,r,i)=>new z(t,e,r,{columns:i[0],mathstyleName:"textstyle"}));Tt(["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],"[columns:colspec]",ze);Tt(["smallmatrix","smallmatrix*"],"[columns:colspec]",ze);Tt(["cases","dcases","rcases"],"",ze);function ze(t,e=[[[]]],r=[],i=[],n){switch(t){case"math":return new z(t,e,r,{mathstyleName:"textstyle",isRoot:!0,minColumns:1,maxColumns:1,minRows:1,maxRows:1});case"displaymath":return new z(t,e,r,{mathstyleName:"textstyle",isRoot:!0,minColumns:1,maxColumns:1,minRows:1,maxRows:1});case"center":return new z(t,e,r,{columns:[{align:"c"}],classes:["ML__center_environment"],isRoot:!0,minColumns:1,maxColumns:1,minRows:1,maxRows:1});case"multline":case"multline*":return new z(t,e,r,{columns:[{align:"m"}],leftDelim:".",rightDelim:".",isRoot:!0,minColumns:1,maxColumns:1,minRows:1});case"split":return new z(t,e,r,{columns:[{align:"r"},{align:"l"}],minColumns:2,minRows:1,isRoot:!1});case"gather":case"gather*":return new z(t,e,r,{columns:[{gap:.25},{align:"c"},{gap:0}],minColumns:1,maxColumns:1,minRows:1,isRoot:!0,classes:["ML__gather_environment"]});case"gathered":return new z(t,e,r,{columns:[{gap:.25},{align:"c"},{gap:0}],minColumns:1,maxColumns:1,minRows:1});case"equation":case"equation*":case"subequations":return new z(t,e,r,{columns:[{align:"c"}],isRoot:!0,minColumns:1,maxColumns:1,minRows:1});case"aligned":{let o=0;for(let l of e)o=Math.max(o,l.length);let a=[{gap:0},{align:"r"},{gap:.25},{align:"l"}],s=2;for(;s0&&e.push({gap:1}),e.push({align:"l"});return e}M(["overrightarrow","overleftarrow","Overrightarrow","overleftharpoon","overrightharpoon","overleftrightarrow","overlinesegment","overgroup"],"{:auto}",{createAtom:t=>{var e;return new Ae(g(h({},t),{body:T((e=t.args)==null?void 0:e[0]),skipBoundary:!1,supsubPlacement:"over-under",paddedBody:!0,boxType:"rel",svgAbove:t.command.slice(1)}))}});M("overbrace","{:auto}",{createAtom:t=>new Ae(g(h({},t),{body:T(t.args[0]),skipBoundary:!1,supsubPlacement:"over-under",paddedBody:!0,boxType:"ord",svgAbove:t.command.slice(1)}))});M(["underrightarrow","underleftarrow","underleftrightarrow","underlinesegment","undergroup"],"{:auto}",{createAtom:t=>new Ae(g(h({},t),{body:T(t.args[0]),skipBoundary:!1,supsubPlacement:"over-under",paddedBody:!0,boxType:"rel",svgBelow:t.command.slice(1)}))});M(["underbrace"],"{:auto}",{createAtom:t=>new Ae(g(h({},t),{body:T(t.args[0]),skipBoundary:!1,supsubPlacement:"over-under",paddedBody:!0,boxType:"ord",svgBelow:t.command.slice(1)}))});M(["xrightarrow","longrightarrow","xleftarrow","longleftarrow","xRightarrow","xLeftarrow","xleftharpoonup","xleftharpoondown","xrightharpoonup","xrightharpoondown","xlongequal","xtwoheadleftarrow","xtwoheadrightarrow","xleftrightarrow","longleftrightarrow","xLeftrightarrow","xrightleftharpoons","longrightleftharpoons","xleftrightharpoons","xhookleftarrow","xhookrightarrow","xmapsto","xtofrom","xleftrightarrows","longleftrightarrows","xRightleftharpoons","longRightleftharpoons","xLeftrightharpoons","longLeftrightharpoons"],"[:auto]{:auto}",{createAtom:t=>{var e,r,i,n,o;return new Ae(g(h({},t),{svgBody:t.command.slice(1),above:((r=T((e=t.args)==null?void 0:e[1]))==null?void 0:r.length)===0?void 0:T((i=t.args)==null?void 0:i[1]),below:(o=T((n=t.args)==null?void 0:n[0]))!=null?o:null,skipBoundary:!1,supsubPlacement:"over-under",paddedBody:!0,paddedLabels:!0,boxType:"rel"}))},serialize:(t,e)=>t.command+(t.hasEmptyBranch("below")?"":`[${t.belowToLatex(e)}]`)+`{${t.aboveToLatex(e)}}${t.supsubToLatex(e)}`});M(["arccos","arcsin","arctan","arctg","arcctg","arg","ch","cos","cosh","cot","cotg","coth","ctg","cth","csc","cosec","deg","dim","exp","gcd","hom","inf","ker","lb","lg","ln","log","Pr","sec","sh","sin","sinh","sup","tan","tanh","tg","th","arcsec","arccsc","arsinh","arcosh","artanh","arcsech","arccsch"],"",{isFunction:!0,ifMode:"math",createAtom:t=>new vt(t.command.slice(1),g(h({},t),{limits:"adjacent",isFunction:!0,variant:"main",variantStyle:"up"}))});M(["liminf","limsup"],"",{ifMode:"math",createAtom:t=>new vt({"\\liminf":"lim inf","\\limsup":"lim sup"}[t.command],g(h({},t),{limits:"over-under",variant:"main"}))});M(["lim","mod"],"",{ifMode:"math",createAtom:t=>new vt(t.command.slice(1),g(h({},t),{limits:"over-under",variant:"main"}))});M(["det","max","min"],"",{ifMode:"math",isFunction:!0,createAtom:t=>new vt(t.command.slice(1),g(h({},t),{limits:"over-under",isFunction:!0,variant:"main"}))});M("ang","{:math}",{ifMode:"math",createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),serialize:(t,e)=>`\\ang{${t.bodyToLatex(e)}}`,render:(t,e)=>{let r=t.createBox(e),i=r.caret;r.caret=void 0;let n=new w("\xB0",{style:g(h({},t.style),{variant:"normal",variantStyle:"up"})});return new w([r,n],{type:"inner",isSelected:t.isSelected,caret:i})}});M("sqrt","[index:auto]{radicand:expression}",{ifMode:"math",createAtom:t=>new fn(g(h({},t),{body:T(t.args[1]),index:t.args[0]?T(t.args[0]):void 0}))});M(["frac","dfrac","tfrac","binom","dbinom","tbinom"],"{:expression}{:expression}",{ifMode:"math",createAtom:t=>{let e=h({},t),r=t.command,i=t.args;switch(r){case"\\dfrac":case"\\frac":case"\\tfrac":e.hasBarLine=!0;break;case"\\atopfrac":e.hasBarLine=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":e.hasBarLine=!1,e.leftDelim="(",e.rightDelim=")";break;case"\\cfrac":e.hasBarLine=!0,e.continuousFraction=!0;break;default:}switch(r){case"\\dfrac":case"\\dbinom":e.mathstyleName="displaystyle";break;case"\\tfrac":case"\\tbinom":e.mathstyleName="textstyle";break;default:}return new st(i[0]?T(i[0]):[new Me],i[1]?T(i[1]):[new Me],e)},serialize:(t,e)=>{let r=t.aboveToLatex(e),i=t.belowToLatex(e);return/^[0-9]$/.test(r)&&/^[0-9]$/.test(i)?`${t.command}${r}${i}`:U(t.command,r,i)}});M(["cfrac"],"[:string]{:expression}{:expression}",{ifMode:"math",createAtom:t=>{let e=h({},t),r=t.args;return e.hasBarLine=!0,e.continuousFraction=!0,r[0]==="r"&&(e.align="right"),r[0]==="l"&&(e.align="left"),new st(r[1]?T(r[1]):[new Me],r[2]?T(r[2]):[new Me],e)},serialize:(t,e)=>{let r=t.aboveToLatex(e),i=t.belowToLatex(e);return U(t.command,r,i)}});var Lh=["displaystyle","textstyle","scriptstyle","scriptscriptstyle"];M("genfrac","{left-delim:delim}{right-delim:delim}{thickness:value}{mathstyle:string}{numerator:expression}{denominator:expression}",{ifMode:"math",createAtom:t=>{let[e,r,i,n,o,a]=t.args,s=h({},t);e&&e!=="."&&(s.leftDelim=e),r&&r!=="."&&(s.rightDelim=r),i?(s.barThickness=i,s.hasBarLine=!Tg(i)):s.hasBarLine=!0;let l=n==null?void 0:n.trim();return l&&/^[0-3]$/.test(l)&&(s.mathstyleName=Lh[Number(l)]),new st(o?T(o):[new Me],a?T(a):[new Me],s)},serialize:(t,e)=>{var i,n,o;let r=t.mathstyleName?Lh.indexOf(t.mathstyleName):-1;return U(t.command,(i=t.leftDelim)!=null?i:"",(n=t.rightDelim)!=null?n:"",(o=ge(t.barThickness))!=null?o:"",r>=0?r.toString():"",t.aboveToLatex(e),t.belowToLatex(e))}});function Tg(t){return"dimension"in t?t.dimension===0:"glue"in t?t.glue.dimension===0:"number"in t?t.number===0:"string"in t?parseFloat(t.string)===0:!1}M(["brace","brack"],"",{infix:!0,createAtom:t=>new st(T(t.args[0]),T(t.args[1]),g(h({},t),{hasBarLine:!1,leftDelim:t.command==="\\brace"?"\\lbrace":"\\lbrack",rightDelim:t.command==="\\brace"?"\\rbrace":"\\rbrack"})),serialize:(t,e)=>R([t.aboveToLatex(e),t.command,t.belowToLatex(e)])});M(["over","atop","choose"],"",{infix:!0,createAtom:t=>{let e,r,i=t.args;return t.command==="\\choose"&&(e="(",r=")"),new st(T(i[0]),T(i[1]),g(h({},t),{hasBarLine:t.command==="\\over",leftDelim:e,rightDelim:r}))},serialize:(t,e)=>R([t.aboveToLatex(e),t.command,t.belowToLatex(e)])});M(["overwithdelims","atopwithdelims"],"{numer:auto}{denom:auto}{left-delim:delim}{right-delim:delim}",{infix:!0,createAtom:t=>{var r,i;let e=t.args;return new st(T(e[0]),T(e[1]),g(h({},t),{leftDelim:(r=e[2])!=null?r:".",rightDelim:(i=e[3])!=null?i:".",hasBarLine:!1}))},serialize:(t,e)=>`${t.aboveToLatex(e)} ${t.command}${t.leftDelim}${t.rightDelim}${t.belowToLatex(e)}`});M("pdiff","{numerator}{denominator}",{ifMode:"math",createAtom:t=>new st(T(t.args[0]),T(t.args[1]),g(h({},t),{hasBarLine:!0,numerPrefix:"\u2202",denomPrefix:"\u2202"})),serialize:(t,e)=>R([t.aboveToLatex(e),t.command,t.belowToLatex(e)])});M(["sum","prod","bigcup","bigcap","coprod","bigvee","bigwedge","biguplus","bigotimes","bigoplus","bigodot","bigsqcup","intop"],"",{ifMode:"math",createAtom:t=>new fi({coprod:"\u2210",bigvee:"\u22C1",bigwedge:"\u22C0",biguplus:"\u2A04",bigcap:"\u22C2",bigcup:"\u22C3",intop:"\u222B",prod:"\u220F",sum:"\u2211",bigotimes:"\u2A02",bigoplus:"\u2A01",bigodot:"\u2A00",bigsqcup:"\u2A06",smallint:"\u222B"}[t.command.slice(1)],g(h({},t),{limits:"auto",variant:"main"}))});M("smallint","",{ifMode:"math",createAtom:t=>new vt("\u222B",g(h({},t),{limits:"adjacent",variant:"main"}))});var Ah={int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",oiint:"\u222F",oiiint:"\u2230",intclockwise:"\u2231",varointclockwise:"\u2232",ointctrclockwise:"\u2233",intctrclockwise:"\u2A11",sqcup:"\u2294",sqcap:"\u2293",uplus:"\u228E",wr:"\u2240",amalg:"\u2A3F",Cap:"\u22D2",Cup:"\u22D3",doublecap:"\u22D2",doublecup:"\u22D3"};M(Object.keys(Ah),"",{ifMode:"math",createAtom:t=>{let e=t.command,r=Ah[e.slice(1)];return new fi(r,g(h({},t),{limits:"adjacent",variant:{"\u22D2":"ams","\u22D3":"ams"}[r]}))}});M(["Re","Im"],"",{ifMode:"math",createAtom:t=>new vt({"\\Re":"\u211C","\\Im":"\u2111"}[t.command],g(h({},t),{limits:"adjacent",isFunction:!0,variant:"fraktur"}))});M("middle","{:delim}",{ifMode:"math",createAtom:t=>{var e;return new mn(g(h({},t),{delim:(e=t.args[0])!=null?e:"|",size:1}))}});M("the","{:value}",{createAtom:t=>new x(g(h({},t),{captureSelection:!0,verbatimLatex:null})),render:(t,e)=>{var o;let r=new P({parent:e},t.style),i="";t.isSelected&&(i+=" ML__selected");let n=r.evaluate(t.args[0]);return new w(((o=ge(n))!=null?o:"").split("").map(a=>new w(a,{type:"ord",classes:i,mode:t.mode,isSelected:t.isSelected,style:h({variant:"main"},t.style)})),{type:"lift",style:t.style,caret:t.caret,isSelected:t.isSelected,classes:i}).wrap(r)},serialize:t=>{var e;return`\\the${(e=ge(t.args[0]))!=null?e:"\\relax"}`}});M("mathtip","{:auto}{:math}",{createAtom:t=>new gi(g(h({},t),{body:T(t.args[0]),tooltip:T(t.args[1]),content:"math"})),serialize:(t,e)=>e.skipStyles?t.bodyToLatex(e):`\\mathtip{${t.bodyToLatex(e)}}{${x.serialize([t.tooltip],g(h({},e),{defaultMode:"math"}))}}`});M("texttip","{:auto}{:text}",{createAtom:t=>new gi(g(h({},t),{body:T(t.args[0]),tooltip:T(t.args[1]),content:"text"})),serialize:(t,e)=>e.skipStyles?t.bodyToLatex(e):`\\texttip{${t.bodyToLatex(e)}}{${x.serialize([t.tooltip],g(h({},e),{defaultMode:"text"}))}}`});M("error","{:math}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),serialize:(t,e)=>`\\error{${t.bodyToLatex(e)}}`,render:(t,e)=>t.createBox(e,{classes:"ML__error"})});M("ensuremath","{:math}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),serialize:(t,e)=>`${t.command}{${t.bodyToLatex(g(h({},e),{defaultMode:"math"}))}}`});M("color","{:value}",{applyStyle:(t,e,r,i)=>{var n,o;return g(h({},t),{verbatimColor:(n=ge(r[0]))!=null?n:void 0,color:i.toColor((o=r[0])!=null?o:{string:"red"})})}});M("textcolor","{:value}{content:auto*}",{applyStyle:(t,e,r,i)=>{var n,o;return g(h({},t),{verbatimColor:(n=ge(r[0]))!=null?n:void 0,color:i.toColor((o=r[0])!=null?o:{string:"red"})})}});M("boxed","{content:math}",{createAtom:t=>new at(g(h({},t),{body:T(t.args[0]),framecolor:{string:"black"}}))});M("colorbox","{:value}{:text*}",{applyStyle:(t,e,r,i)=>{var n,o;return g(h({},t),{verbatimBackgroundColor:(n=ge(r[0]))!=null?n:void 0,backgroundColor:i.toBackgroundColor((o=r[0])!=null?o:{string:"yellow"})})}});M("fcolorbox","{frame-color:value}{background-color:value}{content:text}",{applyMode:"text",createAtom:t=>{var e,r;return new at(g(h({},t),{body:T(t.args[2]),framecolor:(e=t.args[0])!=null?e:{string:"blue"},backgroundcolor:(r=t.args[1])!=null?r:{string:"yellow"}}))},serialize:(t,e)=>{var r,i;return e.skipStyles?t.bodyToLatex(g(h({},e),{defaultMode:"text"})):U(t.command,(r=ge(t.framecolor))!=null?r:"",(i=ge(t.backgroundcolor))!=null?i:"",t.bodyToLatex(g(h({},e),{defaultMode:"text"})))}});M("bbox","[:bbox]{body:auto}",{createAtom:t=>{var i;let e=t.args[0],r=T(t.args[1]);return e?new at(g(h({},t),{body:r,padding:e.padding,border:e.border,backgroundcolor:(i=e.backgroundcolor)!=null?i:void 0})):new at(g(h({},t),{body:r}))},serialize:(t,e)=>{var i,n;if(e.skipStyles)return t.bodyToLatex(e);let r=t.command;if(Number.isFinite(t.padding)||t.border!==void 0||t.backgroundcolor!==void 0){let o=[];t.padding&&o.push((i=ge(t.padding))!=null?i:""),t.border&&o.push(`border: ${t.border}`),t.backgroundcolor&&o.push((n=ge(t.backgroundcolor))!=null?n:""),r+=`[${o.join(",")}]`}return U(r,t.bodyToLatex(e))}});M(["displaystyle","textstyle","scriptstyle","scriptscriptstyle"],"{:rest}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),render:(t,e)=>{let r=new P({parent:e,mathstyle:t.command.slice(1)},t.style),i=x.createBox(r,t.body,{type:"lift"});return t.caret&&(i.caret=t.caret),t.bind(e,i)},serialize:(t,e)=>e.skipStyles?t.bodyToLatex(e):`{${R([t.command,t.bodyToLatex(e)])}}`});M(["tiny","scriptsize","footnotesize","small","normalsize","large","Large","LARGE","huge","Huge"],"",{applyStyle:(t,e)=>g(h({},t),{fontSize:{"\\tiny":1,"\\scriptsize":2,"\\footnotesize":3,"\\small":4,"\\normalsize":5,"\\large":6,"\\Large":7,"\\LARGE":8,"\\huge":9,"\\Huge":10}[e]})});M("fontseries","{:string}",{ifMode:"text",applyStyle:(t,e,r)=>{var i;return g(h({},t),{fontSeries:(i=r[0])!=null?i:"auto"})}});M("fontshape","{:string}",{ifMode:"text",applyStyle:(t,e,r)=>{var i;return g(h({},t),{fontShape:(i=r[0])!=null?i:"auto"})}});M("fontfamily","{:string}",{ifMode:"text",applyStyle:(t,e,r)=>{var i;return g(h({},t),{fontFamily:(i=r[0])!=null?i:"roman"})}});M("selectfont","",{ifMode:"text",applyStyle:t=>t});M("bf","{:rest*}",{applyStyle:t=>g(h({},t),{fontSeries:"b",fontShape:"n",fontFamily:"roman"})});M(["boldsymbol","bm","bold"],"{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variantStyle:"bold"})});M("bfseries","{:rest*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontSeries:"b"})});M("mdseries","{:rest*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontSeries:"m"})});M("upshape","{:rest*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"n"})});M("slshape","{:rest*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"sl"})});M("scshape","{:rest*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"sc"})});M("textbf","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontSeries:"b"})});M("textmd","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontSeries:"m"})});M("textup","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"n"})});M("textnormal","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"n",fontSeries:"m"})});M("textsl","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"sl"})});M("textit","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"it"})});M("textsc","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontShape:"sc"})});M("textrm","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontFamily:"roman"})});M("textsf","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontFamily:"sans-serif"})});M("texttt","{:text*}",{applyMode:"text",applyStyle:t=>g(h({},t),{fontFamily:"monospace"})});M("mathbf","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"normal",variantStyle:"bold"})});M("mathit","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"main",variantStyle:"italic"})});M("mathnormal","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"normal",variantStyle:"italic"})});M("mathbfit","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"main",variantStyle:"bolditalic"})});M("mathrm","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"normal",variantStyle:"up"})});M("mathsf","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"sans-serif",variantStyle:"up"})});M("mathtt","{:math*}",{applyMode:"math",applyStyle:t=>g(h({},t),{variant:"monospace",variantStyle:"up"})});M("it","{:rest*}",{applyStyle:t=>g(h({},t),{fontSeries:"m",fontShape:"it",fontFamily:"roman",variantStyle:"italic"})});M("rmfamily","{:rest*}",{applyStyle:t=>g(h({},t),{fontFamily:"roman"})});M("sffamily","{:rest*}",{applyStyle:t=>g(h({},t),{fontFamily:"sans-serif"})});M("ttfamily","{:rest*}",{applyStyle:t=>g(h({},t),{fontFamily:"monospace"})});M(["Bbb","mathbb"],"{:math*}",{applyStyle:t=>g(h({},t),{variant:"double-struck",variantStyle:so(t.variantStyle)})});M(["frak","mathfrak"],"{:math*}",{applyStyle:t=>g(h({},t),{variant:"fraktur",variantStyle:so(t.variantStyle)})});M("mathcal","{:math*}",{applyStyle:t=>g(h({},t),{variant:"calligraphic",variantStyle:so(t.variantStyle)})});M("mathscr","{:math*}",{applyStyle:t=>g(h({},t),{variant:"script",variantStyle:so(t.variantStyle)})});M("mbox","{:text}",{ifMode:"math",createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[0]),mode:"math"})),serialize:(t,e)=>U("\\mbox",t.bodyToLatex(g(h({},e),{defaultMode:"text"})))});M("text","{:text}",{ifMode:"math",applyMode:"text"});M(["class","htmlClass"],"{name:string}{content:auto*}",{createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[1])})),serialize:(t,e)=>!t.args[0]||e.skipStyles?t.bodyToLatex(e):`${t.command}{${t.args[0]}}{${t.bodyToLatex(e)}}`,render:(t,e)=>{var r;return t.createBox(e,{classes:(r=t.args[0])!=null?r:"",boxType:"lift"})}});M(["cssId","htmlId"],"{id:string}{content:auto*}",{createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[1])})),serialize:(t,e)=>{var r;return!((r=t.args)!=null&&r[0])||e.skipStyles?t.bodyToLatex(e):`${t.command}{${t.args[0]}}{${t.bodyToLatex(e)}}`},render:(t,e)=>{var i;let r=t.createBox(e);return r.cssId=(i=t.args[0])!=null?i:"",r}});M("htmlData","{data:string}{content:auto*}",{createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[1])})),serialize:(t,e)=>{var r;return!((r=t.args)!=null&&r[0])||e.skipStyles?t.bodyToLatex(e):`\\htmlData{${t.args[0]}}{${t.bodyToLatex(e)}}`},render:(t,e)=>{var i;let r=t.createBox(e);return r.htmlData=(i=t.args[0])!=null?i:"",r}});M(["style","htmlStyle"],"{data:string}{content:auto*}",{createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[1])})),serialize:(t,e)=>{var r;return!((r=t.args)!=null&&r[0])||e.skipStyles?t.bodyToLatex(e):`${t.command}{${t.args[0]}}{${t.bodyToLatex(e)}}`},render:(t,e)=>{var i;let r=t.createBox(e);return r.htmlStyle=(i=t.args[0])!=null?i:"",r}});M("href","{url:string}{content:auto*}",{createAtom:t=>new x(g(h({},t),{type:"mord",body:T(t.args[1])})),render:(t,e)=>{var n;let r=t.createBox(e),i=(n=t.args[0])!=null?n:"";return i&&(r.htmlData=`href=${i}`),r}});M("em","{:rest}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),serialize:(t,e)=>e.skipStyles?t.bodyToLatex(e):`{\\em ${t.bodyToLatex(e)}}`,render:(t,e)=>t.createBox(e,{classes:"ML__emph",boxType:"lift"})});M("emph","{:auto}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[1])})),serialize:(t,e)=>e.skipStyles?t.bodyToLatex(e):`\\emph{${t.bodyToLatex(e)}}`,render:(t,e)=>t.createBox(e,{classes:"ML__emph",boxType:"lift"})});var Ch={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}};M(["bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr","bigm","Bigm","biggm","Biggm","big","Big","bigg","Bigg"],"{:delim}",{createAtom:t=>{var e;return new hn(g(h({},t),{delim:(e=t.args[0])!=null?e:".",size:Ch[t.command].size,delimType:Ch[t.command].mclass}))},serialize:(t,e)=>R([t.command,/^[a-zA-Z]/.test(t.value)?`{${t.value}}`:t.value])});M(["hspace","hspace*"],"{width:value}",{createAtom:t=>{var e;return new qt(g(h({},t),{width:(e=t.args[0])!=null?e:{dimension:0}}))}});M(["mkern","kern","mskip","hskip","mspace"],"{width:value}",{createAtom:t=>{var e;return new qt(g(h({},t),{width:(e=t.args[0])!=null?e:{dimension:0}}))}});M("mathchoice","{:math}{:math}{:math}{:math}",{createAtom:t=>new x(t),render:(t,e)=>{let r=0,i=e.mathstyle.id;(i===Yn||i===Kr)&&(r=1),(i===ui||i===He)&&(r=2),(i===Pr||i===Ee)&&(r=3);let n=T(t.args[r]);return x.createBox(e,n)},serialize:(t,e)=>`\\mathchoice{${x.serialize(t.args[0],e)}}{${x.serialize(t.args[1],e)}}{${x.serialize(t.args[2],e)}}{${x.serialize(t.args[3],e)}}`});M("mathop","{:auto}",{createAtom:t=>new x(g(h({},t),{type:"mop",body:T(t.args[0]),limits:"over-under",isFunction:!0,captureSelection:!0})),render:(t,e)=>{var i;let r=x.createBox(e,t.body);if(t.superscript||t.subscript){let n=(i=t.subsupPlacement)!=null?i:"auto";r=n==="over-under"||n==="auto"&&e.isDisplayStyle?t.attachLimits(e,{base:r}):t.attachSupsub(e,{base:r})}return t.caret&&(r.caret=t.caret),new w(t.bind(e,r),{type:"op",isSelected:t.isSelected,classes:"ML__op-group"})},serialize:(t,e)=>{let r=[U(t.command,t.bodyToLatex(e))];return t.explicitSubsupPlacement&&(t.subsupPlacement==="over-under"&&r.push("\\limits"),t.subsupPlacement==="adjacent"&&r.push("\\nolimits"),t.subsupPlacement==="auto"&&r.push("\\displaylimits")),r.push(t.supsubToLatex(e)),R(r)}});M(["mathbin","mathrel","mathopen","mathclose","mathpunct","mathord","mathinner"],"{:auto}",{createAtom:t=>new x(g(h({},t),{type:{"\\mathbin":"mbin","\\mathrel":"mrel","\\mathopen":"mopen","\\mathclose":"mclose","\\mathpunct":"mpunct","\\mathord":"mord","\\mathinner":"minner"}[t.command],body:T(t.args[0])}))});M(["operatorname","operatorname*"],"{operator:math}",{createAtom:t=>{let e=T(t.args[0]).map(r=>{var i;return r.type!=="first"&&(r.type="mord",r.value=(i={"\u2217":"*","\u2212":"-"}[r.value])!=null?i:r.value,r.isFunction=!1,!r.style.variant&&!r.style.variantStyle&&(r.style.variant="main",r.style.variantStyle="up")),r});return new x(g(h({},t),{type:"mop",body:e,isFunction:!0,limits:t.command==="\\operatorname"?"adjacent":"over-under"}))},render:(t,e)=>{var i;let r=x.createBox(e,t.body);if(t.superscript||t.subscript){let n=(i=t.subsupPlacement)!=null?i:"auto";r=n==="over-under"||n==="auto"&&e.isDisplayStyle?t.attachLimits(e,{base:r}):t.attachSupsub(e,{base:r})}return t.caret&&(r.caret=t.caret),new w(t.bind(e,r),{type:"op",isSelected:t.isSelected,classes:"ML__op-group"})},serialize:(t,e)=>{let r=[U(t.command,t.bodyToLatex(e))];return t.explicitSubsupPlacement&&(t.subsupPlacement==="over-under"&&r.push("\\limits"),t.subsupPlacement==="adjacent"&&r.push("\\nolimits"),t.subsupPlacement==="auto"&&r.push("\\displaylimits")),r.push(t.supsubToLatex(e)),R(r)}});M(["char","unicode"],"{charcode:value}",{createAtom:t=>new x(g(h({},t),{type:t.mode==="text"?"text":"mord"})),serialize:t=>{var e;return`${t.command}${ge((e=t.args[0])!=null?e:{number:10067,base:"hexadecimal"})}`},render:(t,e)=>{let r=e.evaluate(t.args[0]);return(!r||!("number"in r))&&(r={number:10067,base:"hexadecimal"}),t.value=String.fromCodePoint(r.number),t.createBox(e)}});M("rule","[raise:value]{width:value}{thickness:value}",{createAtom:t=>new x(t),render:(t,e)=>{var s,l,c;let r=new P({parent:e,mathstyle:"textstyle"},t.style),i=r.toEm((s=t.args[0])!=null?s:{dimension:0}),n=r.toEm((l=t.args[1])!=null?l:{dimension:10}),o=r.toEm((c=t.args[2])!=null?c:{dimension:10}),a=new w(null,{classes:"ML__rule",type:"ord"});return a.width=n,a.height=o+i,a.depth=-i,a.setStyle("border-right-width",n,"em"),a.setStyle("border-top-width",o,"em"),a.setStyle("border-color",t.style.color),a.setStyle("vertical-align",i,"em"),t.isSelected&&a.setStyle("opacity","50%"),t.bind(r,a),t.caret&&(a.caret=t.caret),a.wrap(e)},serialize:t=>`\\rule${t.args[0]?`[${ge(t.args[0])}]`:""}{${ge(t.args[1])}}{${ge(t.args[2])}}`});M(["overline","underline"],"{:auto}",{createAtom:t=>new x(g(h({},t),{body:T(t.args[0])})),render:(t,e)=>{let r=t.command.substring(1),i=new P({parent:e,mathstyle:"cramp"},t.style),n=x.createBox(i,t.body);if(!n)return null;let o=i.metrics.defaultRuleThickness/i.scalingFactor,a=new w(null,{classes:r+"-line"});a.height=o,a.maxFontSize=o*1.125*i.scalingFactor;let s;return r==="overline"?s=new te({shift:0,children:[{box:n},3*o,{box:a},o]}):s=new te({top:n.height,children:[o,{box:a},3*o,{box:n}]}),t.caret&&(s.caret=t.caret),new w(s,{classes:r,type:"ignore"})}});M("overset","{:auto}{base:auto}",{createAtom:t=>{let e=T(t.args[1]);return new Ae(g(h({},t),{above:T(t.args[0]),body:e,skipBoundary:!1,boxType:ci(e)}))},serialize:(t,e)=>U(t.command,t.aboveToLatex(e),t.bodyToLatex(e))});M("underset","{:auto}{base:auto}",{createAtom:t=>{let e=T(t.args[1]);return new Ae(g(h({},t),{below:T(t.args[0]),body:e,skipBoundary:!1,boxType:ci(e)}))},serialize:(t,e)=>U(t.command,t.belowToLatex(e),t.bodyToLatex(e))});M("overunderset","{above:auto}{below:auto}{base:auto}",{createAtom:t=>{let e=T(t.args[2]);return new Ae(g(h({},t),{above:T(t.args[0]),below:T(t.args[1]),body:e,skipBoundary:!1,boxType:ci(e)}))},serialize:(t,e)=>U(t.command,t.belowToLatex(e),t.bodyToLatex(e))});M(["stackrel","stackbin"],"[below:auto]{above:auto}{base:auto}",{createAtom:t=>new Ae(g(h({},t),{body:T(t.args[2]),above:T(t.args[1]),below:T(t.args[0]),skipBoundary:!1,boxType:t.command==="\\stackrel"?"rel":"bin"})),serialize:(t,e)=>U(t.command,t.aboveToLatex(e),t.bodyToLatex(e))});M("smash","[:string]{:auto}",{createAtom:t=>{var e,r,i,n;return new Vt(g(h({},t),{body:T(t.args[1]),smashHeight:(r=(e=t.args[0])==null?void 0:e.includes("t"))!=null?r:!0,smashDepth:(n=(i=t.args[0])==null?void 0:i.includes("b"))!=null?n:!0}))}});M("vphantom","{:auto}",{createAtom:t=>new Vt(g(h({},t),{body:T(t.args[0]),isInvisible:!0,smashWidth:!0}))});M("hphantom","{:auto}",{createAtom:t=>new Vt(g(h({},t),{body:T(t.args[0]),isInvisible:!0,smashHeight:!0,smashDepth:!0}))});M("phantom","{:auto}",{createAtom:t=>new Vt(g(h({},t),{body:T(t.args[0]),isInvisible:!0}))});M("mathstrut","",{createAtom:t=>new Vt(g(h({},t),{body:[new x({value:"("})],isInvisible:!0}))});M("not","{:math}",{createAtom:t=>{let e=T(t.args[0]);return e.length===0?new x(g(h({},t),{type:"mrel",value:"\uE020"})):new x(g(h({},t),{body:[new yt(g(h({},t),{body:"\uE020",align:"right"})),...e],captureSelection:!0}))},serialize:(t,e)=>{let r=t.args[0],i=r&&typeof r=="object"&&"group"in r;return t.value!=="\uE020"?i?`\\not{${x.serialize(r.group,e)}}`:`\\not${x.serialize(r,e)}`:i?"\\not{}":"\\not"},render:(t,e)=>{if(t.value)return t.createBox(e);let i=t.args[0]&&typeof t.args[0]=="object"&&"group"in t.args[0]?"ord":ci(T(t.args[0])),n=x.createBox(e,t.body,{type:i});return t.caret&&(n.caret=t.caret),t.bind(e,n)}});M(["ne","neq"],"",{createAtom:t=>new x(g(h({},t),{type:"mrel",body:[new yt(g(h({},t),{body:"\uE020",align:"right",boxType:"rel"})),new x(g(h({},t),{value:"="}))],captureSelection:!0})),serialize:t=>t.command});M("rlap","{:auto}",{createAtom:t=>new yt(g(h({},t),{body:T(t.args[0]),align:"right"}))});M("llap","{:auto}",{createAtom:t=>new yt(g(h({},t),{body:T(t.args[0]),align:"left"}))});M("mathrlap","{:math}",{createAtom:t=>new yt(g(h({},t),{body:T(t.args[0]),align:"right"}))});M("mathllap","{:math}",{createAtom:t=>new yt(g(h({},t),{body:T(t.args[0]),align:"left"}))});M("raisebox","{:value}{:text}",{createAtom:t=>{var e;return new at(g(h({},t),{body:T(t.args[1]),padding:{dimension:0},offset:(e=t.args[0])!=null?e:{dimension:0}}))},serialize:(t,e)=>{var r;return U("\\raisebox",(r=ge(t.offset))!=null?r:"0pt",t.bodyToLatex(e))}});M("raise","{:value}{:auto}",{createAtom:t=>{var e;return new at(g(h({},t),{body:T(t.args[1]),padding:{dimension:0},offset:(e=t.args[0])!=null?e:{dimension:0}}))},serialize:(t,e)=>{var r;return U("\\raise",(r=ge(t.offset))!=null?r:"0pt",t.bodyToLatex(e))}});M("lower","{:value}{:auto}",{createAtom:t=>{var e;return new at(g(h({},t),{body:T(t.args[1]),padding:{dimension:0},offset:(e=gt(t.args[0],-1))!=null?e:{dimension:0}}))},serialize:(t,e)=>{var r,i;return U("\\lower",(i=ge(gt((r=t.offset)!=null?r:{dimension:0},-1)))!=null?i:"0pt",t.bodyToLatex(e))}});Se("0123456789/@.?!");gl(65,90);gl(97,122);Se([["\\forall",8704],["\\exists",8707],["\\nexists",8708,"mord","ams"],["\\mid",8739,"mrel"],["\\top",8868],["\\bot",8869]]);Se([["\\#",35],["\\&",38],["\\parallelogram",9649],["\\spadesuit",9824],["\\heartsuit",9825],["\\diamondsuit",9826],["\\clubsuit",9827],["\\flat",9837],["\\natural",9838],["\\sharp",9839]]);Se([["\\backslash",92],["\\nabla",8711],["\\partial",8706],["\\ell",8467],["\\hbar",8463],["\\pounds",163],["\\euro",8364]]);Se([["\\rightarrow",8594],["\\to",8594],["\\leftarrow",8592],["\\gets",8592],["\\Rightarrow",8658],["\\Leftarrow",8656],["\\longrightarrow",10230],["\\longleftarrow",10229],["\\Longrightarrow",10233],["\\implies",10233],["\\Longleftarrow",10232],["\\impliedby",10232],["\\longleftrightarrow",10231],["\\biconditional",10231],["\\Longleftrightarrow",10234],["\\mapsto",8614],["\\longmapsto",10236],["\\uparrow",8593],["\\downarrow",8595],["\\Uparrow",8657],["\\Downarrow",8659],["\\updownarrow",8597],["\\Updownarrow",8661],["\\hookrightarrow",8618],["\\hookleftarrow",8617],["\\rightharpoonup",8640],["\\leftharpoonup",8636],["\\rightharpoondown",8641],["\\leftharpoondown",8637],["\\searrow",8600],["\\nearrow",8599],["\\swarrow",8601],["\\nwarrow",8598],["\\originalof",8886],["\\laplace",8886],["\\imageof",8887],["\\Laplace",8887]],"mrel");Se([["\\mapsfrom",8612,"mrel"],["\\Mapsfrom",10502,"mrel"],["\\MapsTo",10503,"mrel"],["\\Yup",8516,"mord"],["\\lightning",8623,"mrel"],["\\leftarrowtriangle",8701,"mrel"],["\\rightarrowtriangle",8702,"mrel"],["\\leftrightarrowtriangle",8703,"mrel"],["\\boxdot",8865,"mbin"],["\\bigtriangleup",9651,"mbin"],["\\bigtriangledown",9661,"mbin"],["\\boxbar",9707,"mbin"],["\\Lbag",10181,"mopen"],["\\Rbag",10182,"mclose"],["\\llbracket",10214,"mopen"],["\\rrbracket",10215,"mclose"],["\\longmapsfrom",10235,"mrel"],["\\Longmapsfrom",10237,"mrel"],["\\Longmapsto",10238,"mrel"],["\\boxslash",10692,"mbin"],["\\boxbslash",10693,"mbin"],["\\boxast",10694,"mbin"],["\\boxcircle",10695,"mbin"],["\\boxbox",10696,"mbin"],["\\fatsemi",10783,"mop"],["\\leftslice",10918,"mrel"],["\\rightslice",10919,"mrel"],["\\interleave",10996,"mbin"],["\\biginterleave",11004,"mop"],["\\sslash",11005,"mbin"],["\\talloblong",11006,"mbin"]]);Se([["\\lbrace",123,"mopen"],["\\rbrace",125,"mclose"],["\\lparen",40,"mopen"],["\\rparen",41,"mclose"],["\\langle",10216,"mopen"],["\\rangle",10217,"mclose"],["\\lfloor",8970,"mopen"],["\\rfloor",8971,"mclose"],["\\lceil",8968,"mopen"],["\\rceil",8969,"mclose"],["\\vert",8739],["\\lvert",8739,"mopen"],["\\rvert",8739,"mclose"],["\\|",8741],["\\Vert",8741],["\\mVert",8741],["\\lVert",8741,"mopen"],["\\rVert",8741,"mclose"],["\\lbrack",91,"mopen"],["\\rbrack",93,"mclose"],["\\{",123,"mopen"],["\\}",125,"mclose"],["(",40,"mopen"],[")",41,"mclose"],["[",91,"mopen"],["]",93,"mclose"],["\\ulcorner",9484,"mopen","ams"],["\\urcorner",9488,"mclose","ams"],["\\llcorner",9492,"mopen","ams"],["\\lrcorner",9496,"mclose","ams"],["\\lgroup",10222,"mopen"],["\\rgroup",10223,"mclose"],["\\lmoustache",9136,"mopen"],["\\rmoustache",9137,"mclose"]]);Se([["\\dashrightarrow",8674],["\\dashleftarrow",8672],["\\Rrightarrow",8667],["\\Lleftarrow",8666],["\\leftrightarrows",8646],["\\rightleftarrows",8644],["\\curvearrowright",8631],["\\curvearrowleft",8630],["\\rightrightarrows",8649],["\\leftleftarrows",8647],["\\upuparrows",8648],["\\downdownarrows",8650],["\\vartriangle",9651],["\\triangleq",8796],["\\vartriangleleft",8882],["\\trianglelefteq",8884],["\\ntriangleleft",8938],["\\ntrianglelefteq",8940],["\\vartriangleright",8883],["\\trianglerighteq",8885],["\\ntriangleright",8939],["\\ntrianglerighteq",8941],["\\blacktriangleleft",9664],["\\blacktriangleright",9654],["\\leftarrowtail",8610],["\\rightarrowtail",8611],["\\looparrowright",8620],["\\looparrowleft",8619],["\\twoheadleftarrow",8606],["\\twoheadrightarrow",8608],["\\twoheadrightarrowtail",10518],["\\rightleftharpoons",8652],["\\leftrightharpoons",8651],["\\Rsh",8625],["\\Lsh",8624],["\\circlearrowright",8635],["\\circlearrowleft",8634],["\\restriction",8638],["\\upharpoonright",8638],["\\upharpoonleft",8639],["\\downharpoonright",8642],["\\downharpoonleft",8643],["\\rightsquigarrow",8669],["\\leadsto",8669],["\\leftrightsquigarrow",8621],["\\multimap",8888],["\\nleftarrow",8602],["\\nrightarrow",8603],["\\nRightarrow",8655],["\\nLeftarrow",8653],["\\nleftrightarrow",8622],["\\nLeftrightarrow",8654],["\\nvrightarrow",8696],["\\nvtwoheadrightarrow",10496],["\\nvrightarrowtail",10516],["\\nvtwoheadrightarrowtail",10519],["\\shortparallel",8741],["\\nless",8814],["\\nleqslant",57360],["\\lneq",10887],["\\lneqq",8808],["\\nleqq",57361],["\\lvertneqq",57356],["\\lnsim",8934],["\\lnapprox",10889],["\\nprec",8832],["\\npreceq",8928],["\\precnsim",8936],["\\precnapprox",10937],["\\nsim",8769],["\\nshortmid",57350],["\\nmid",8740],["\\nvdash",8876],["\\nvDash",8877],["\\ngtr",8815],["\\ngeqslant",57359],["\\ngeqq",57358],["\\gneq",10888],["\\gneqq",8809],["\\gvertneqq",57357],["\\gnsim",8935],["\\gnapprox",10890],["\\nsucc",8833],["\\nsucceq",8929],["\\succnsim",8937],["\\succnapprox",10938],["\\ncong",8774],["\\nshortparallel",57351],["\\nparallel",8742],["\\nVDash",8879],["\\nsupseteqq",57368],["\\supsetneq",8843],["\\varsupsetneq",57371],["\\supsetneqq",10956],["\\varsupsetneqq",57369],["\\nVdash",8878],["\\precneqq",10933],["\\succneqq",10934],["\\nsubseteqq",57366],["\\leqslant",10877],["\\geqslant",10878],["\\gtrsim",8819],["\\approxeq",8778],["\\thickapprox",8776],["\\lessapprox",10885],["\\gtrapprox",10886],["\\precapprox",10935],["\\succapprox",10936],["\\thicksim",8764],["\\succsim",8831],["\\precsim",8830],["\\backsim",8765],["\\eqsim",8770],["\\backsimeq",8909],["\\lesssim",8818],["\\nleq",8816],["\\ngeq",8817],["\\smallsmile",8995],["\\smallfrown",8994],["\\leqq",8806],["\\eqslantless",10901],["\\lll",8920],["\\lessgtr",8822],["\\lesseqgtr",8922],["\\lesseqqgtr",10891],["\\risingdotseq",8787],["\\fallingdotseq",8786],["\\subseteqq",10949],["\\Subset",8912],["\\sqsubset",8847],["\\preccurlyeq",8828],["\\curlyeqprec",8926],["\\vDash",8872],["\\Vvdash",8874],["\\bumpeq",8783],["\\Bumpeq",8782],["\\geqq",8807],["\\eqslantgtr",10902],["\\ggg",8921],["\\gtrless",8823],["\\gtreqless",8923],["\\gtreqqless",10892],["\\supseteqq",10950],["\\Supset",8913],["\\sqsupset",8848],["\\succcurlyeq",8829],["\\curlyeqsucc",8927],["\\Vdash",8873],["\\shortmid",8739],["\\between",8812],["\\pitchfork",8916],["\\varpropto",8733],["\\backepsilon",8717],["\\llless",8920],["\\gggtr",8921],["\\doteqdot",8785],["\\Doteq",8785],["\\eqcirc",8790],["\\circeq",8791],["\\therefore",8756],["\\because",8757]],"mrel","ams");Se([["+",43],["-",8722],["\u2212",8722],["\\pm",177],["\\mp",8723],["*",8727],["\\times",215],["\\div",247],["\\divides",8739],["\\cdot",8901],["\\cap",8745],["\\cup",8746],["\\setminus",8726],["\\land",8743],["\\wedge",8743],["\\lor",8744],["\\vee",8744],["\\circ",8728],["\\bigcirc",9711],["\\bullet",8729],["\\oplus",8853],["\\ominus",8854],["\\otimes",8855],["\\odot",8857],["\\oslash",8856],["\\bigtriangleup",9651],["\\bigtriangledown",9661],["\\triangleleft",9667],["\\triangleright",9657],["\\And",38],["\\dagger",8224],["\\dag",8224],["\\ddag",8225],["\\ddagger",8225],["\\ast",8727],["\\star",8902],["\\bigstar",9733],["\\diamond",8900]],"mbin");Se([["\\lhd",8882],["\\rhd",8883],["\\lessdot",8918],["\\gtrdot",8919],["\\ltimes",8905],["\\rtimes",8906],["\\leftthreetimes",8907],["\\rightthreetimes",8908],["\\intercal",8890],["\\dotplus",8724],["\\doublebarwedge",10846],["\\divideontimes",8903],["\\centerdot",8901],["\\smallsetminus",8726],["\\barwedge",8892],["\\veebar",8891],["\\nor",8891],["\\curlywedge",8911],["\\curlyvee",8910],["\\boxminus",8863],["\\boxplus",8862],["\\boxtimes",8864],["\\boxdot",8865],["\\circleddash",8861],["\\circledast",8859],["\\circledcirc",8858],["\\unlhd",8884],["\\unrhd",8885]],"mbin","ams");Se([["\\surd",8730],["\\S",167],["\\infty",8734],["\\prime",8242],["\\doubleprime",8243],["\\angle",8736],["`",8216],["\\$",36],["\\%",37],["\\_",95],["\\alpha",945],["\\beta",946],["\\gamma",947],["\\delta",948],["\\epsilon",1013],["\\varepsilon",949],["\\zeta",950],["\\eta",951],["\\theta",952],["\\vartheta",977],["\\iota",953],["\\kappa",954],["\\varkappa",1008,"mord","ams"],["\\lambda",955],["\\mu",956],["\\nu",957],["\\xi",958],["\\omicron",111],["\\pi",960],["\\varpi",982],["\\rho",961],["\\varrho",1009],["\\sigma",963],["\\varsigma",962],["\\tau",964],["\\phi",981],["\\varphi",966],["\\upsilon",965],["\\chi",967],["\\psi",968],["\\omega",969],["\\Gamma",915],["\\Delta",916],["\\Theta",920],["\\Lambda",923],["\\Xi",926],["\\Pi",928],["\\Sigma",931],["\\Upsilon",933],["\\Phi",934],["\\Psi",936],["\\Omega",937],["\\digamma",989,"mord","ams"],["\\varkappa",1008,"mord","ams"],["\\coppa",985,"mord","ams"],["\\koppa",985,"mord","ams"],["\\Coppa",984,"mord","ams"],["\\Koppa",984,"mord","ams"],["\\sampi",993,"mord","ams"],["\\Sampi",992,"mord","ams"],["\\emptyset",8709]]);Se([["=",61],["<",60],["\\lt",60],[">",62],["\\gt",62],["\\le",8804],["\\leq",8804],["\\ge",8805],["\\geq",8805],["\\ll",8810],["\\gg",8811],["\\coloneq",8788],["\\coloneqq",8788],["\\colonequals",8788],["\\measeq",8797],["\\eqdef",8798],["\\questeq",8799],[":",58],["\\cong",8773],["\\equiv",8801],["\\prec",8826],["\\preceq",10927],["\\succ",8827],["\\succeq",10928],["\\perp",10178],["\\propto",8733],["\\Colon",8759],["\\smile",8995],["\\frown",8994],["\\sim",8764],["\\doteq",8784],["\\bowtie",8904],["\\Join",8904],["\\asymp",8781],["\\sqsubseteq",8849],["\\sqsupseteq",8850],["\\approx",8776],["\\~",126],["\\leftrightarrow",8596],["\\Leftrightarrow",8660],["\\models",8872],["\\vdash",8866],["\\dashv",8867],["\\roundimplies",10608],["\\in",8712],["\\notin",8713],["\\ni",8715],["\\owns",8715],["\\subset",8834],["\\supset",8835],["\\subseteq",8838],["\\supseteq",8839],["\\differencedelta",8710],["\\mvert",8739],["\\parallel",8741],["\\simeq",8771]],"mrel");Se([["\\lnot",172],["\\neg",172],["\\triangle",9651],["\\subsetneq",8842],["\\varsubsetneq",57370],["\\subsetneqq",10955],["\\varsubsetneqq",57367],["\\nsubset",8836],["\\nsupset",8837],["\\nsubseteq",8840],["\\nsupseteq",8841]],"mrel","ams");Se([["\\wp",8472],["\\aleph",8501]]);Se([["\\blacktriangle",9650],["\\hslash",8463],["\\Finv",8498],["\\Game",8513],["\\eth",240],["\\mho",8487],["\\Bbbk",107],["\\yen",165],["\\square",9633],["\\Box",9633],["\\blacksquare",9632],["\\circledS",9416],["\\circledR",174],["\\triangledown",9661],["\\blacktriangledown",9660],["\\checkmark",10003],["\\diagup",9585],["\\measuredangle",8737],["\\sphericalangle",8738],["\\backprime",8245],["\\backdoubleprime",8246],["\\Diamond",9674],["\\lozenge",9674],["\\blacklozenge",10731],["\\varnothing",8709],["\\complement",8705],["\\maltese",10016],["\\beth",8502],["\\daleth",8504],["\\gimel",8503]],"mord","ams");Se([["\\ ",160],["~",160]],"space");M(["!",",",":",";",">","enskip","enspace","quad","qquad"],"",{createAtom:t=>new qt(t)});M("space","",{createAtom:t=>new qt(t)});Se([["\\colon",58],["\\cdotp",8901],["\\vdots",8942,"mord"],["\\ldotp",46],[",",44],[";",59]],"mpunct");Se([["\\cdots",8943],["\\ddots",8945],["\\ldots",8230],["\\mathellipsis",8230]],"minner");Se([["\\/",47],["|",8739,"mord"],["\\imath",305],["\\jmath",567],["\\degree",176],["'",8242],['"',8221]]);var us={main:["Main-Regular","ML__cmr"],"main-italic":["Main-Italic","ML__cmr ML__it"],"main-bold":["Main-Bold","ML__cmr ML__bold"],"main-bolditalic":["Main-BoldItalic","ML__cmr ML__bold ML__it"],normal:["Main-Regular","ML__cmr"],"normal-bold":["Main-Bold","ML__mathbf"],"normal-italic":["Math-Italic","ML__mathit"],"normal-bolditalic":["Math-BoldItalic","ML__mathbfit"],roman:["Main-Regular","ML__cmr"],"roman-bold":["Main-Bold","ML__mathbf"],"roman-italic":["Math-Italic","ML__mathit"],"roman-bolditalic":["Math-BoldItalic","ML__mathbfit"],ams:["AMS-Regular","ML__ams"],"ams-bold":["AMS-Regular","ML__ams ML__bold"],"ams-italic":["AMS-Regular","ML__ams ML__it"],"ams-bolditalic":["AMS-Regular","ML__ams ML__bold ML__it"],"sans-serif":["SansSerif-Regular","ML__sans"],"sans-serif-bold":["SansSerif-Regular","ML__sans ML__bold"],"sans-serif-italic":["SansSerif-Regular","ML__sans ML__it"],"sans-serif-bolditalic":["SansSerif-Regular","ML__sans ML__bold ML__it"],calligraphic:["Caligraphic-Regular","ML__cal"],"calligraphic-bold":["Caligraphic-Regular","ML__cal ML__bold"],"calligraphic-italic":["Caligraphic-Regular","ML__cal ML__it"],"calligraphic-bolditalic":["Caligraphic-Regular","ML__cal ML__bold ML__it"],script:["Script-Regular","ML__script"],"script-bold":["Script-Regular","ML__script ML__bold"],"script-italic":["Script-Regular","ML__script ML__it"],"script-bolditalic":["Script-Regular","ML__script ML__bold ML__it"],fraktur:["Fraktur-Regular","ML__frak"],"fraktur-bold":["Fraktur-Regular","ML__frak ML__bold"],"fraktur-italic":["Fraktur-Regular","ML__frak ML__it"],"fraktur-bolditalic":["Fraktur-Regular","ML__frak ML__bold ML__it"],monospace:["Typewriter-Regular","ML__tt"],"monospace-bold":["Typewriter-Regular","ML__tt ML__bold"],"monospace-italic":["Typewriter-Regular","ML__tt ML__it"],"monospace-bolditalic":["Typewriter-Regular","ML__tt ML__bold ML__it"],"double-struck":["AMS-Regular","ML__bb"],"double-struck-bold":["AMS-Regular","ML__bb ML__bold"],"double-struck-italic":["AMS-Regular","ML__bb ML_italic"],"double-struck-bolditalic":["AMS-Regular","ML__bb ML_bolditalic"]},ms={"double-struck":/^[A-Z ]$/,script:/^[A-Z ]$/,calligraphic:/^[\dA-Z ]$/,fraktur:/^[\dA-Za-z ]$|^[!"#$%&'()*+,\-./:;=?[]^’‘]$/,monospace:/^[\dA-Za-z ]$|^[!"&'()*+,\-./:;=?@[\]^_~\u0131\u0237\u0393\u0394\u0398\u039B\u039E\u03A0\u03A3\u03A5\u03A8\u03A9]$/,"sans-serif":/^[\dA-Za-z ]$|^[!"&'()*+,\-./:;=?@[\]^_~\u0131\u0237\u0393\u0394\u0398\u039B\u039E\u03A0\u03A3\u03A5\u03A8\u03A9]$/},Eh=/^[\u03B1-\u03C9]|\u03D1|\u03D5|\u03D6|\u03F1|\u03F5]$/,Dg=/^[\u0393|\u0394\u0398\u039B\u039E\u03A0\u03A3\u03A5\u03A6\u03A8\u03A9]$/,Og=[/^[a-z]$/,/^[A-Z]$/,Eh,Dg],Bg={iso:["it","it","it","it"],tex:["it","it","it","up"],french:["it","up","up","up"],upright:["up","up","up","up"]},bc=class extends _e{constructor(){super("math")}createAtom(e,r,i){var a,s,l,c,u,d;if(r===null)return new x({type:"mord",mode:"math",command:e,value:e,style:i});let n;try{n=(l=(s=globalThis.MathfieldElement)==null?void 0:s.isFunction((a=r.command)!=null?a:e))!=null?l:!1}catch(m){n=!1}if(r.definitionType==="symbol"){let m=new x({type:(c=r.type)!=null?c:"mord",mode:"math",command:(u=r.command)!=null?u:e,value:String.fromCodePoint(r.codepoint),isFunction:n,style:i});return e.startsWith("\\")&&(m.verbatimLatex=e),m}let o=new x({type:"mord",mode:"math",command:(d=r.command)!=null?d:e,value:e,isFunction:n,style:i});return e.startsWith("\\")&&(o.verbatimLatex=e),o}serialize(e,r){let i=Kg(e,g(h({},r),{defaultMode:"math"}));return i.length===0||r.defaultMode!=="text"?i:["$ ",...i," $"]}getFont(e,r){var l,c,u;if(r.variant,r.fontFamily){let d=r.fontFamily;r.fontSeries==="b"&&r.fontShape==="it"?d+="-bolditalic":r.fontSeries==="b"?d+="-bold":r.fontShape==="it"&&(d+="-italic");let m=(l=us[d])!=null?l:us[r.fontFamily];if(!m)return console.error(`Unknown font family variant: ${d}`),null;let[p,f]=m;return f&&(e.classes+=" "+f),p}let{variant:i}=r,{variantStyle:n}=r;if(i==="normal"&&!n&&/[\u00A3\u0131\u0237]/.test(e.value)&&(i="main",n="italic"),i==="normal"&&!n&&e.value.length===1){let d=!1;Og.forEach((m,p)=>{var f;m.test(e.value)&&Bg[(f=r.letterShapeStyle)!=null?f:"tex"][p]==="it"&&(d=!0)}),d&&(n=wh(n))}n==="up"&&(n=void 0);let o=n?i+"-"+n:i;us[o];let[a,s]=us[o];if(ms[i]&&!ms[i].test(e.value)){let d=Bn(e.value,i,n);return d||(d=(c=Bn(e.value,i))!=null?c:e.value,e.classes+=(u={bold:" ML__bold",italic:" ML__it","bold-italic":" ML__bold ML__it"}[n!=null?n:""])!=null?u:""),e.value=d,null}return Eh.test(e.value)&&(e.classes+=" lcGreek"),s&&(e.classes+=" "+s),a}};function Kg(t,e){return pt(t,"bold").map(r=>{if(Ha(r[0])!=="bold")return R(ds(r,e));if(Ha(r[0].parent)==="bold")return R(ds(r,e));let n=R(r.map(o=>{var a;return(a=o.value)!=null?a:""}));return/^[a-zA-Z0-9]+$/.test(n)?U("\\mathbf",R(ds(r,e))):U("\\bm",R(ds(r,e)))})}function ds(t,e){let{parent:r}=t[0],i=Wa(r);return pt(t,"variant").map(n=>{let o=Wa(n[0]),a="";o&&o!==i&&(a={calligraphic:"\\mathcal","calligraphic-uo":"\\mathcal",fraktur:"\\mathfrak","fraktur-uo":"\\mathfrak","double-struck":"\\mathbb","double-struck-uo":"\\mathbb",script:"\\mathscr","script-uo":"\\mathscr",monospace:"\\mathtt","monospace-uo":"\\mathtt","sans-serif":"\\mathsf","sans-serif-uo":"\\mathsf",normal:"","normal-up":"\\mathrm","normal-italic":"\\mathnormal","normal-bold":"","normal-bolditalic":"\\mathbfit",ams:"","ams-up":"\\mathrm","ams-italic":"\\mathit","ams-bold":"","ams-bolditalic":"\\mathbfit",main:"","main-up":"\\mathrm","main-italic":"\\mathit","main-bold":"","main-bolditalic":"\\mathbfit"}[o]);let s="",l=n[n.length-1],c=a&&n.length>0&&(l.branch("subscript")!==void 0||l.branch("superscript")!==void 0);c&&(s=l.supsubToLatex(e));let u=R(n.map((d,m)=>{if(c&&m===n.length-1){let p=ne(d.command,d.mode);return p!=null&&p.serialize?p.serialize(d,e):d.body&&d.command?U(d.command,d.bodyToLatex(e)):d.body?d.bodyToLatex(e):!d.value||d.value==="\u200B"?"":d.command||d.value}return d._serialize(e)}));return a?U(a,u)+s:u})}new bc;function Pg(t,e){return t.map(r=>r._serialize(e))}function Rg(t,e){return pt(t,"fontShape").map(r=>{let i=Pg(r,e),{fontShape:n}=r[0].style,o="";return n==="it"&&(o="\\textit"),n==="sl"&&(o="\\textsl"),n==="sc"&&(o="\\textsc"),n==="n"&&(o="\\textup"),!o&&n?`{${U("\\fontshape",n)}${R(i)}}`:o?U(o,R(i)):R(i)})}function Ig(t,e){return pt(t,"fontSeries").map(r=>{let i=Rg(r,e),{fontSeries:n}=r[0].style,o="";return n==="b"&&(o="\\textbf"),n==="l"&&(o="\\textlf"),n==="m"&&(o="\\textmd"),n&&!o?`{${U("\\fontseries",n)}${R(i)}}`:o?U(o,R(i)):R(i)})}function zg(t,e){return pt(t,"fontSize").map(r=>{var o,a;let i=Ig(r,e),n=(a=["","\\tiny","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"][(o=r[0].style.fontSize)!=null?o:""])!=null?a:"";return n?`${n} ${R(i)}`:R(i)})}function Ng(t,e,r){return pt(t,"fontFamily").map(i=>{var s;r=r&&!i.every(l=>l.style.fontFamily||l.style.fontShape||l.style.fontSeries||l.style.fontSize);let n=zg(i,e),{fontFamily:o}=i[0].style,a=(s={roman:"textrm",monospace:"texttt","sans-serif":"textsf"}[o!=null?o:""])!=null?s:"";return a?`\\${a}{${R(n)}}`:o?`{\\fontfamily{${i[0].style.fontFamily}} ${R(n)}}`:r?`\\text{${R(n)}}`:R(n)})}var Th={roman:"","sans-serif":"ML__sans",monospace:"ML__tt"},yc=class extends _e{constructor(){super("text")}createAtom(e,r,i){return r&&r.definitionType==="symbol"?new We(e,String.fromCodePoint(r.codepoint),i!=null?i:{}):null}serialize(e,r){return Ng(e,g(h({},r),{defaultMode:"text"}),r.defaultMode!=="text")}getFont(e,r){var n,o,a,s,l;let{fontFamily:i}=r;if(Th[i])e.classes+=" "+Th[i];else if(i){let c=G0(i);c&&e.setStyle("font-family",c)}if(r.fontShape&&(e.classes+=" ",e.classes+=(n={it:"ML__it",sl:"ML__shape_sl",sc:"ML__shape_sc",ol:"ML__shape_ol"}[r.fontShape])!=null?n:""),r.fontSeries){let c=r.fontSeries.match(/(.?[lbm])?(.?[cx])?/);c&&(e.classes+=" ",e.classes+=(a={ul:"ML__series_ul",el:"ML__series_el",l:"ML__series_l",sl:"ML__series_sl",m:"",sb:"ML__series_sb",b:"ML__bold",eb:"ML__series_eb",ub:"ML__series_ub"}[(o=c[1])!=null?o:""])!=null?a:"",e.classes+=" ",e.classes+=(l={uc:"ML__series_uc",ec:"ML__series_ec",c:"ML__series_c",sc:"ML__series_sc",n:"",sx:"ML__series_sx",x:"ML__series_x",ex:"ML__series_ex",ux:"ML__series_ux"}[(s=c[2])!=null?s:""])!=null?l:"")}return"Main-Regular"}};new yc;var xc=class extends _e{constructor(){super("latex")}createAtom(e){return new he(e)}serialize(e,r){return e.filter(i=>i instanceof he&&!i.isSuggestion).map(i=>i.value)}getFont(){return null}};new xc;function gn(t){var n;let e=/macos|ios/.test(Et()),r=t.split("+"),i="";for(let o of r)i&&(i+=e?"\u2009":'+'),o.startsWith("[Key")?i+=o.slice(4,5):o.startsWith("Key")?i+=o.slice(3,4):o.startsWith("[Digit")?i+=o.slice(6,7):o.startsWith("Digit")?i+=o.slice(5,6):i+=(n={cmd:"\u2318",meta:e?"\u2318":"Ctrl",shift:e?"\u21E7":"Shift",alt:e?"\u2325":"Alt",ctrl:e?"\u2303":"Ctrl","\n":e?"\u23CE":"Return","[return]":e?"\u23CE":"Return","[enter]":e?"\u2324":"Enter","[tab]":e?"\u21E5":"Tab","[escape]":"Esc","[backspace]":e?"\u232B":"Backspace","[delete]":e?"\u2326":"Del","[pageup]":e?"\u21DE":"Page Up","[pagedown]":e?"\u21DF":"Page Down","[home]":e?"\u2912":"Home","[end]":e?"\u2913":"End","[space]":"Space","[equal]":"=","[minus]":"-","[comma]":",","[slash]":"/","[backslash]":"\\","[bracketleft]":"[","[bracketright]":"]",semicolon:";",period:".",comma:",",minus:"-",equal:"=",quote:"'",backslash:"\\",intlbackslash:"\\",backquote:"`",slash:"/",numpadmultiply:"* 🔢",numpaddivide:"/ 🔢",numpadsubtract:"- 🔢",numpadadd:"+ 🔢",numpaddecimal:". 🔢",numpadcomma:", 🔢",help:"help",left:"\u21E0",up:"\u21E1",right:"\u21E2",down:"\u21E3","[arrowleft]":"\u21E0","[arrowup]":"\u21E1","[arrowright]":"\u21E2","[arrowdown]":"\u21E3"}[o.toLowerCase()])!=null?n:o.toUpperCase();return i}function bn(t){if(t instanceof MouseEvent||t instanceof PointerEvent)return{x:t.clientX,y:t.clientY};if(typeof TouchEvent!="undefined"&&t instanceof TouchEvent){let e=[...t.touches].reduce((i,n)=>({x:i.x+n.clientX,y:i.y+n.clientY}),{x:0,y:0}),r=t.touches.length;return{x:e.x/r,y:e.y/r}}}function Wt(t){let e={alt:!1,control:!1,shift:!1,meta:!1};return(t instanceof MouseEvent||t instanceof PointerEvent||typeof TouchEvent!="undefined"&&t instanceof TouchEvent||t instanceof KeyboardEvent)&&(t.altKey&&(e.alt=!0),t.ctrlKey&&(e.control=!0),t.metaKey&&(e.meta=!0),t.shiftKey&&(e.shift=!0)),e}function Dh(t,e){return!t&&e||t&&!e?!1:!t||!e?!0:t.alt===e.alt&&t.control===e.control&&t.shift===e.shift&&t.meta===e.meta}var Fg=new Set(["Backquote","Digit0","Digit1","Digit2","Digit3","Digit4","Digit5","Digit6","Digit7","Digit8","Digit9","Minus","Equal","IntlYen","KeyQ","KeyW","KeyE","KeyR","KeyT","KeyY","KeyU","KeyI","KeyO","KeyP","BracketLeft","BracketRight","Backslash","KeyA","KeyS","KeyD","KeyF","KeyG","KeyH","KeyJ","KeyK","KeyL","Semicolon","Quote","IntlBackslash","KeyZ","KeyX","KeyC","KeyV","KeyB","KeyN","KeyM","Comma","Period","Slash","IntlRo","Space","Numpad0","Numpad1","Numpad2","Numpad3","Numpad4","Numpad5","Numpad6","Numpad7","Numpad8","Numpad9","NumpadAdd","NumpadComma","NumpadDecimal","NumpadDivide","NumpadEqual","NumpadHash","NumpadMultiply","NumpadParenLeft","NumpadParenRight","NumpadStar","NumpadSubstract"]);function dr(t){return t.ctrlKey||t.metaKey||["Dead","Process"].includes(t.key)?!1:t.code===""?!0:Fg.has(t.code)}function Ut(){var e;let t=document.activeElement;for(;(e=t==null?void 0:t.shadowRoot)!=null&&e.activeElement;)t=t.shadowRoot.activeElement;return t}var Te=class t{static get scrim(){return t._scrim||(t._scrim=new t),t._scrim}static open(e){t.scrim.open(e)}static close(){t.scrim.close()}static get state(){return t.scrim.state}static get element(){return t.scrim.element}constructor(e){var r,i;this.lightDismiss=(r=e==null?void 0:e.lightDismiss)!=null?r:!0,this.translucent=(i=e==null?void 0:e.translucent)!=null?i:!1,this.state="closed"}get element(){if(this._element)return this._element;let e=document.createElement("div");return e.setAttribute("role","presentation"),e.style.position="fixed",e.style.contain="content",e.style.top="0",e.style.left="0",e.style.right="0",e.style.bottom="0",e.style.zIndex="var(--scrim-zindex, 10099)",e.style.outline="none",this.translucent?(e.style.background="rgba(255, 255, 255, .2)",e.style.backdropFilter="contrast(40%)"):e.style.background="transparent",this._element=e,e}open(e){var a;if(this.state!=="closed")return;this.state="opening",this.onDismiss=e==null?void 0:e.onDismiss,this.savedActiveElement=Ut();let{element:r}=this;((a=e==null?void 0:e.root)!=null?a:document.body).appendChild(r),r.addEventListener("click",this),document.addEventListener("touchmove",this,!1),document.addEventListener("scroll",this,!1);let i=window.innerWidth-document.documentElement.clientWidth;this.savedMarginRight=document.body.style.marginRight,this.savedOverflow=document.body.style.overflow,document.body.style.overflow="hidden";let n=Number.parseFloat(getComputedStyle(document.body).marginRight);document.body.style.marginRight=`${n+i}px`;let o=document.querySelector(".MLK__plate");if(o instanceof HTMLElement){this.savedMlkPaddingRight=o.style.paddingRight;let s=Number.parseFloat(getComputedStyle(o).paddingRight);o.style.paddingRight=`${s+i}px`}e!=null&&e.child&&r.append(e.child),this.state="open"}close(){var i,n,o,a,s;if(this.state!=="open"){this.element.parentElement;return}this.state="closing",typeof this.onDismiss=="function"&&this.onDismiss(),this.onDismiss=void 0;let{element:e}=this;e.removeEventListener("click",this),document.removeEventListener("touchmove",this,!1),document.removeEventListener("scroll",this,!1),e.remove(),document.body.style.overflow=(i=this.savedOverflow)!=null?i:"",document.body.style.marginRight=(n=this.savedMarginRight)!=null?n:"";let r=document.querySelector(".MLK__plate");r instanceof HTMLElement&&(r.style.paddingRight=(o=this.savedMlkPaddingRight)!=null?o:""),Ut()!==this.savedActiveElement&&((s=(a=this.savedActiveElement)==null?void 0:a.focus)==null||s.call(a)),e.innerHTML="",this.state="closed"}handleEvent(e){this.lightDismiss&&(e.target===this._element&&e.type==="click"?(this.close(),e.preventDefault(),e.stopPropagation()):e.target===document&&(e.type==="touchmove"||e.type==="scroll")&&(this.close(),e.preventDefault(),e.stopPropagation()))}};function Oh(t,e,r){let i=null,n=null,o=!1,a=!1,s=!1,l=new AbortController,c=l.signal;return t.addEventListener("keydown",u=>{if(o||u.key==="Process"||u.code==="CapsLock"||/(Control|Meta|Alt|Shift)(Left|Right)/.test(u.code)){i=null;return}i=u,n=null,r.onKeystroke(u)?t.textContent="":i=null},{capture:!0,signal:c}),t.addEventListener("keypress",u=>{o||(i&&n&&r.onKeystroke(i),n=u)},{capture:!0,signal:c}),t.addEventListener("compositionstart",u=>{t.textContent="",o=!0,r.onCompositionStart(u.data)},{capture:!0,signal:c}),t.addEventListener("compositionupdate",u=>{o&&r.onCompositionUpdate(u.data)},{capture:!0,signal:c}),t.addEventListener("compositionend",u=>{t.textContent="",o&&(o=!1,r.onCompositionEnd(u.data))},{capture:!0,signal:c}),t.addEventListener("beforeinput",u=>u.stopImmediatePropagation(),{signal:c}),t.addEventListener("input",u=>{var d;if(!o&&(t.textContent="",u.inputType!=="insertCompositionText")){if(u.inputType==="insertFromPaste"){u.preventDefault(),u.stopPropagation();return}r.onInput((d=u.data)!=null?d:""),u.preventDefault(),u.stopPropagation()}},{signal:c}),t.addEventListener("paste",u=>{t.focus({preventScroll:!0}),t.textContent="",r.onPaste(u)||u.preventDefault(),u.stopImmediatePropagation()},{signal:c}),t.addEventListener("cut",u=>r.onCut(u),{capture:!0,signal:c}),t.addEventListener("copy",u=>r.onCopy(u),{capture:!0,signal:c}),t.addEventListener("blur",u=>{var f,y;if(((y=(f=u.relatedTarget)==null?void 0:f._mathfield)==null?void 0:y.element)===e){t.focus({preventScroll:!0}),u.preventDefault(),u.stopPropagation();return}let d=!1,m=u.relatedTarget;for(;m;){if(m.classList.contains("ML__keyboard")){d=!0;break}m=m.parentElement}if(d){t.focus({preventScroll:!0}),u.preventDefault(),u.stopPropagation();return}let p=Te.state;if(p==="open"||p==="opening"){u.preventDefault(),u.stopPropagation();return}if(u.relatedTarget===u.target.getRootNode().host){u.preventDefault(),u.stopPropagation();return}s||a||(s=!0,i=null,n=null,r.onBlur(),s=!1)},{capture:!0,signal:c}),t.addEventListener("focus",u=>{s||a||(a=!0,r.onFocus(),a=!1)},{capture:!0,signal:c}),{dispose:()=>l.abort(),cancelComposition:()=>{o&&(typeof t.blur=="function"&&t.blur(),requestAnimationFrame(()=>t.focus({preventScroll:!0})))},blur:()=>{typeof t.blur=="function"&&(s=!0,t.blur(),s=!1)},focus:()=>{!a&&typeof t.focus=="function"&&(a=!0,t.focus({preventScroll:!0}),a=!1)},hasFocus:()=>Ut()===t,setAriaLabel:u=>t.setAttribute("aria-label",u),setAriaReadOnly:u=>{u?t.setAttribute("aria-readonly","true"):t.removeAttribute("aria-readonly")},setValue:u=>{var d;t.textContent!==u&&(t.textContent=u,t.style.left="-1000px",(d=window.getSelection())==null||d.selectAllChildren(t))},moveTo:(u,d)=>{t.style.top=`${d}px`,t.style.left=`${u}px`}}}function Fr(t){var r;if(!t||!dr(t))return"";let e;return t.key==="Unidentified"&&t.target&&(e=t.target.value),e=(r=e!=null?e:t.key)!=null?r:t.code,/^(Dead|Return|Enter|Tab|Escape|Delete|PageUp|PageDown|Home|End|Help|ArrowLeft|ArrowRight|ArrowUp|ArrowDown)$/.test(e)&&(e=""),e}function hs(t){t=Cu(t);let e=[];return t.ctrlKey&&e.push("ctrl"),t.metaKey&&e.push("meta"),t.altKey&&e.push("alt"),t.shiftKey&&e.push("shift"),e.length===0?`[${t.code}]`:(e.push(`[${t.code}]`),e.join("+"))}function $g(t){if(Le()){let e=Et(),r=t.startsWith("!"),i=t.endsWith(e);if(r&&!i||!r&&i)return!0}return t==="!other"?!1:t==="other"}function Kh(t,e,r){if(t.length===0)return"";let i=Zr(ll(hs(r))),n=Zr({key:r.key,shift:r.shiftKey,alt:r.altKey,ctrl:r.ctrlKey,meta:r.metaKey||r.ctrlKey&&/macos|ios/.test(Et()),cmd:!1,win:!1});for(let o=t.length-1;o>=0;o--)if((t[o].key===i||t[o].key===n)&&(!t[o].ifMode||t[o].ifMode===e))return t[o].command;return""}function Bh(t){let e=t;return ee(e)&&(e=e.length>0?e[0]+"("+e.slice(1).join("")+")":""),e}function Ph(t,e){let r=[];if(typeof e=="string"){let o=eh[e];ee(o)?r=o.slice():o&&r.push(o)}let i=Bh(e),n=new RegExp("^"+i.replace("\\","\\\\").replace("|","\\|").replace("*","\\*").replace("$","\\$").replace("^","\\^")+"([^*a-zA-Z]|$)");for(let o of t)n.test(Bh(o.command))&&r.push(o.key);return r.map(gn)}function Vg(t,e){if(t.ifPlatform&&!/^!?(macos|windows|android|ios|chromeos|other)$/.test(t.ifPlatform))throw new Error(`Unexpected platform "${t.ifPlatform}" for keybinding ${t.key}`);if(t.ifLayout!==void 0&&(e.score===0||!t.ifLayout.includes(e.id)))return;let r=ll(t.key),i=t.ifPlatform;if(r.cmd){if(i&&i!=="macos"&&i!=="ios")throw new Error('Unexpected "cmd" modifier with platform "'+i+`" +"cmd" modifier can only be used with macOS or iOS platform.`);i||(i=Et()==="ios"?"ios":"macos"),r.win=!1,r.cmd=!1,r.meta=!0}if(r.win){if(i&&i!=="windows")throw new Error('Unexpected "win" modifier with platform "'+i+`" +"win" modifier can only be used with Windows platform.`);i="windows",r.win=!1,r.cmd=!1,r.meta=!0}if(i&&!$g(i))return;if(/^\[.+\]$/.test(r.key))return g(h({},t),{key:Zr(r)});let n=Au(r.key,e);if(!n)return g(h({},t),{key:Zr(r)});if(n.shift&&r.shift||n.alt&&r.alt)throw new Error(`The keybinding ${t.key} (${vc(t.command)}) is conflicting with the key combination ${Zr(n)} using the ${e.displayName} keyboard layout`);return n.shift=n.shift||r.shift,n.alt=n.alt||r.alt,n.meta=r.meta,n.ctrl=r.ctrl,g(h({},t),{key:Zr(n)})}function vc(t){if(Array.isArray(t)){let e=[...t];return e.shift()+"("+e.map(r=>typeof r=="string"?`"${r}"`:r.toString()).join(", ")+")"}return t}function Rh(t,e){let r=[],i=[];for(let n of t)try{let o=Vg(n,e);if(!o)continue;let a=i.find(s=>s.key===o.key&&s.ifMode===o.ifMode);if(a)throw new Error(`Ambiguous key binding ${n.key} (${vc(n.command)}) matches ${a.key} (${vc(a.command)}) with the ${e.displayName} keyboard layout`);i.push(o)}catch(o){o instanceof Error&&r.push(o.message)}return[i,r]}var _c=class extends H{constructor(){super("latex")}createAtom(e){return new he(e)}onPaste(e,r){if(!r)return!1;let i=typeof r=="string"?r:r.getData("application/x-latex")||r.getData("text/plain");return i&&e.model.contentWillChange({inputType:"insertFromPaste",data:i})?(e.stopCoalescingUndo(),e.stopRecording(),this.insert(e.model,i)&&(e.startRecording(),e.snapshot("paste"),e.model.contentDidChange({inputType:"insertFromPaste"}),Y(e)),e.startRecording(),!0):!1}insert(e,r,i){if(!e.contentWillChange({data:r,inputType:"insertText"}))return!1;i||(i={}),i.insertionMode||(i.insertionMode="replaceSelection"),i.selectionMode||(i.selectionMode="placeholder");let{silenceNotifications:n}=e;i.silenceNotifications&&(e.silenceNotifications=!0);let o=e.silenceNotifications;e.silenceNotifications=!0,i.insertionMode==="replaceSelection"&&!e.selectionIsCollapsed?e.deleteAtoms(de(e.selection)):i.insertionMode==="replaceAll"?(e.root.setChildren([],"body"),e.position=0):i.insertionMode==="insertBefore"?e.collapseSelection("backward"):i.insertionMode==="insertAfter"&&e.collapseSelection("forward");let a=[];for(let c of r)$u.test(c)&&a.push(new he(c));let s=e.at(e.position);if(s instanceof $t&&(s=s.lastChild),!(s.parent instanceof $t)){let c=new $t;s.parent.addChildAfter(c,s),s=c.firstChild}let l=s.parent.addChildrenAfter(a,s);return e.silenceNotifications=o,i.selectionMode==="before"||(i.selectionMode==="item"?e.setSelection(e.anchor,e.offsetOf(l)):l&&(e.position=e.offsetOf(l))),e.contentDidChange({data:r,inputType:"insertText"}),e.silenceNotifications=n,!0}};function lo(t){return t.atoms.find(e=>e.type==="latexgroup")}function yi(t){var r,i;let e=lo(t);return(i=(r=e==null?void 0:e.body)==null?void 0:r.filter(n=>n.type==="latex"))!=null?i:[]}function ps(t,e){var s;let r=0,i=!1,n=Number.isFinite(e==null?void 0:e.before)?(s=e==null?void 0:e.before)!=null?s:0:t.lastOffset;for(;r<=n&&!i;){let l=t.at(r);i=l instanceof he&&l.isSuggestion,i||r++}if(!i)return[void 0,void 0];let o=r,a=!1;for(;o<=n&&!a;){let l=t.at(o);a=!(l instanceof he&&l.isSuggestion),a||o++}return[r-1,o-1]}new _c;function qg(t,e){t.flushInlineShortcutBuffer(),t.stopCoalescingUndo();let r=fs(t,e),{model:i}=t;return i.selectionIsCollapsed?(t.defaultStyle.fontSeries&&r.fontSeries===t.defaultStyle.fontSeries&&(r.fontSeries="auto"),r.fontShape&&r.fontShape===t.defaultStyle.fontShape&&(r.fontShape="auto"),r.color&&r.color===t.defaultStyle.color&&(r.color="none"),r.backgroundColor&&r.backgroundColor===t.defaultStyle.backgroundColor&&(r.backgroundColor="none"),r.fontSize&&r.fontSize===t.defaultStyle.fontSize&&(r.fontSize="auto"),t.defaultStyle=h(h({},t.defaultStyle),r)):t.model.deferNotifications({content:!0,type:"insertText"},()=>{i.selection.ranges.forEach(n=>ao(i,n,r,{operation:"toggle"})),t.snapshot("style-change")}),!0}fe({applyStyle:qg},{target:"mathfield",canUndo:!0,changeContent:!0});function fs(t,e){var n,o,a,s,l,c,u,d,m,p;let r={};if(typeof e.color=="string"){let f=(o=t.colorMap((n=e.color)!=null?n:e.verbatimColor))!=null?o:"none";f!==e.color&&(r.verbatimColor=(a=e.verbatimColor)!=null?a:e.color),r.color=f}if(typeof e.backgroundColor=="string"){let f=(l=t.backgroundColorMap((s=e.backgroundColor)!=null?s:e.verbatimBackgroundColor))!=null?l:"none";f!==e.backgroundColor&&(r.verbatimBackgroundColor=(c=e.verbatimBackgroundColor)!=null?c:e.backgroundColor),r.backgroundColor=f}typeof e.fontFamily=="string"&&(r.fontFamily=e.fontFamily),typeof e.series=="string"&&(r.fontSeries=e.series),typeof e.fontSeries=="string"&&(r.fontSeries=e.fontSeries.toLowerCase()),r.fontSeries&&(r.fontSeries=(u={bold:"b",medium:"m",normal:"m"}[r.fontSeries])!=null?u:r.fontSeries),typeof e.shape=="string"&&(r.fontShape=e.shape),typeof e.fontShape=="string"&&(r.fontShape=e.fontShape.toLowerCase()),r.fontShape&&(r.fontShape=(d={italic:"it",up:"n",upright:"n",normal:"n"}[r.fontShape])!=null?d:r.fontShape),e.variant&&(r.variant=e.variant.toLowerCase()),e.variantStyle!==void 0&&(r.variantStyle=typeof e.variantStyle=="string"&&e.variantStyle!==""?e.variantStyle.toLowerCase():e.variantStyle);let i=(m=e.size)!=null?m:e.fontSize;return typeof i=="number"?r.fontSize=Math.max(1,Math.min(10,i)):typeof i=="string"&&(r.fontSize=(p={size1:1,size2:2,size3:3,size4:4,size5:5,size6:6,size7:7,size8:8,size9:9,size10:10}[i.toLowerCase()])!=null?p:{tiny:1,scriptsize:2,footnotesize:3,small:4,normal:5,normalsize:5,large:6,Large:7,LARGE:8,huge:9,Huge:10}[i]),r}function co(t,e,r){var o,a;let i=t.model;if(i.mode==="latex")return{};let n=t.styleBias;if(n==="none")return t.defaultStyle;if(i.mode==="text")return(a=(o=i.at(n==="right"?r.after:r.before))==null?void 0:o.style)!=null?a:t.defaultStyle;if(i.mode==="math"){let s=i.at(n==="right"?r.after:r.before);return h(s?g(h({},s.style),{variant:"normal"}):{variant:"normal"},t.defaultStyle)}return{}}function Gt(t){let e=t.options.onInsertStyle;if(e===null)return{};e===void 0&&(e=co);let r=t.model,i=t.styleBias,n=r.at(r.position),o=Ih(r,n,i),a=Ih(r,n.rightSibling,i);return e(t,r.position,{before:o,after:a})}function Ih(t,e,r){var i;return!e||e.type==="first"&&r!=="right"?-1:e.type!=="group"?t.offsetOf(e):!e.body||e.body.length<2?-1:((i=e.body)==null?void 0:i.length)===1||r!=="right"?t.offsetOf(e.body[0]):t.offsetOf(e.body[e.body.length-1])}function xi(t){let e=yi(t.model).filter(r=>r.isSuggestion);if(e.length!==0){t.model.position=t.model.offsetOf(e[0].leftSibling);for(let r of e)r.parent.removeChild(r)}}function Vr(t,e){var c;let{model:r}=t;xi(t);for(let u of yi(r))u.isError=!1;if(!r.selectionIsCollapsed||t.options.popoverPolicy==="off"){$r(t);return}let i=[],n=r.at(r.position);for(;n&&n instanceof he&&/^[a-zA-Z\*]$/.test(n.value);)n=n.leftSibling;if(n&&n instanceof he&&n.value==="\\")for(i.push(n),n=n.rightSibling;n&&n instanceof he&&/^[a-zA-Z\*]$/.test(n.value);)i.push(n),n=n.rightSibling;let o=i.map(u=>u.value).join(""),a=qu(t,o);if(a.length===0){if(/^\\[a-zA-Z\*]+$/.test(o))for(let u of i)u.isError=!0;$r(t);return}let s=(c=e==null?void 0:e.atIndex)!=null?c:0;t.suggestionIndex=s<0?a.length-1:s%a.length;let l=a[t.suggestionIndex];if(l!==o){let u=i[i.length-1];u.parent.addChildrenAfter([...l.slice(o.length-l.length)].map(d=>new he(d,{isSuggestion:!0})),u),_t(t,{interactive:!0})}zh(t,a)}function gs(t){let[e,r]=ps(t,{before:t.position});if(e===void 0||r===void 0)return!1;let i=!1;return t.getAtoms([e,r]).forEach(n=>{n.isSuggestion&&(n.isSuggestion=!1,i=!0)}),i}function Qe(t,e="accept",r){var l,c;$r(t);let i=lo(t.model);if(!i)return!1;if(e==="accept-suggestion"||e==="accept-all"){let u=yi(t.model).filter(d=>d.isSuggestion);if(u.length!==0){for(let d of u)d.isSuggestion=!1;t.model.position=t.model.offsetOf(u[u.length-1])}if(e==="accept-suggestion")return u.length!==0}let o=yi(t.model).filter(u=>!u.isSuggestion).map(u=>u.value).join(""),a=i.leftSibling;if(i.parent.removeChild(i),t.model.position=t.model.offsetOf(a),t.switchMode((l=r==null?void 0:r.mode)!=null?l:"math"),e==="reject")return!0;let s=h({},Gt(t));return!/^[a-zA-Z0-9]$/.test(o)&&t.styleBias!=="none"&&(s.variant="normal",s.variantStyle=void 0),H.insert(t.model,o,{selectionMode:(c=r==null?void 0:r.selectItem)!=null&&c?"item":"placeholder",format:"latex",mode:"math",style:s}),t.snapshot(),t.model.announce("replacement"),t.switchMode("math"),!0}function vi(t){var r;let e=document.getElementById(t);return e?e.dataset.refcount=Number(Number.parseInt((r=e.dataset.refcount)!=null?r:"0")+1).toString():(e=document.createElement("div"),e.setAttribute("aria-hidden","true"),e.dataset.refcount="1",e.id=t,document.body.append(e)),e}function qr(t){var i;let e=document.getElementById(t);if(!e)return;let r=Number.parseInt((i=e.getAttribute("data-refcount"))!=null?i:"0");r<=1?e.remove():e.dataset.refcount=Number(r-1).toString()}function Nh(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}function Hg(t,e){let r=new P({from:t.context}),i=new x({mode:"math",type:"root",body:be(e,{context:r})}),n=Or(Ht(new w(i.render(r),{classes:"ML__base"}),r));return Br(n,{classes:"ML__latex"}).toMarkup()}function zh(t,e){var n;if(e.length===0){$r(t);return}let r="";for(let[o,a]of e.entries()){let s=a,l=Hg(t,a),c=Ph(t.keybindings,s).join("
    ");r+=`
  • ${Nh(s)}${l}`,c&&(r+=`${c}`),r+="
  • "}let i=Wg(t,`
      ${r}
    `);Mc()&&((n=i.querySelector(".ML__popover__current"))==null||n.scrollIntoView({block:"nearest",inline:"nearest"})),setTimeout(()=>{var o;i&&!Mc()&&(i.classList.add("is-visible"),yn(t),(o=i.querySelector(".ML__popover__current"))==null||o.scrollIntoView({block:"nearest",inline:"nearest"}))},32)}function Mc(){let t=document.getElementById("mathlive-suggestion-popover");return t?t.classList.contains("is-visible"):!1}function yn(t,e){var d,m,p;if(!t.element||t.element.mathfield!==t||!Mc())return;if(((d=t.model.at(t.model.position))==null?void 0:d.type)!=="latex"){$r(t);return}if(e!=null&&e.deferred){setTimeout(()=>yn(t),32);return}let r=tn(t.field);if(!r)return;let i=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight,n=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,o=window.innerWidth-document.documentElement.clientWidth,a=window.innerHeight-document.documentElement.clientHeight,s=(p=(m=window.mathVirtualKeyboard)==null?void 0:m.boundingRect.height)!=null?p:0,l=document.getElementById("mathlive-suggestion-popover");r.x+l.offsetWidth/2>n-o?l.style.left=`${n-l.offsetWidth-o}px`:r.x-l.offsetWidth/2<0?l.style.left="0":l.style.left=`${r.x-l.offsetWidth/2}px`;let c=r.y-r.height;i-a-s-r.yi.preventDefault()),r.addEventListener("click",i=>{let n=i.target;for(;n&&!n.dataset.command;)n=n.parentElement;n&&(Qe(t,"reject"),H.insert(t.model,n.dataset.command,{selectionMode:"placeholder",format:"latex",mode:"math"}),t.dirty=!0,t.focus())}),r.innerHTML=globalThis.MathfieldElement.createHTML(e),r}function Fh(){document.getElementById("mathlive-suggestion-popover")&&(qr("mathlive-suggestion-popover"),ot("suggestion-popover"),ot("core"))}function Ug(){let t=String(new Error().stack).replace(/^Error.*\n/,"").split(` +`);if(t.length===0)return console.error(`Can't use relative paths to specify assets location because the sourcefile location could not be determined (unexpected stack trace format "${new Error().stack}").`),"";let e=t[1],r=e.match(/http.*\.ts[\?:]/);return r&&(e=t[2]),r=e.match(/(https?:.*):[0-9]+:[0-9]+/),r||(r=e.match(/at (.*(\.ts))[\?:]/),r||(r=e.match(/at (.*(\.mjs|\.js))[\?:]/))),r?r[1]:(console.error(t),console.error(`Can't use relative paths to specify assets location because the source file location could not be determined (unexpected location "${e}").`),"")}var mr=null,$h,Vh,wc=((Vh=($h=globalThis==null?void 0:globalThis.document)==null?void 0:$h.currentScript)==null?void 0:Vh.src)||Ug();async function bs(t){if(/^(?:[a-z+]+:)?\/\//i.test(t)){try{return new URL(t).href}catch(e){}if(t.startsWith("//"))try{return new URL(`${window.location.protocol}${t}`).href}catch(e){}return t}if(mr===null)try{let e=await fetch(wc,{method:"HEAD"});e.status===200&&(mr=e.url,mr=mr.replace(/\/\+esm$/,"/"),mr.includes("jsdelivr.net/")&&(mr+="/"))}catch(e){console.error(`Invalid URL "${t}" (relative to "${wc}")`)}return new URL(t,mr!=null?mr:wc).href}function Gg(t,e,r={}){return new FontFace(t,`url(${e}.woff2) format('woff2')`,r)}var Ne="not-loaded";async function qh(){return Ne="not-loaded",hr()}async function hr(){var e;if(Ne!=="not-loaded")return;if(Ne="loading",(e=getComputedStyle(document.documentElement).getPropertyValue("--ML__static-fonts"))!=null?e:!1){Ne="ready";return}if(document.body.classList.remove("ML__fonts-did-not-load"),"fonts"in document){let r=["KaTeX_Main","KaTeX_Math","KaTeX_AMS","KaTeX_Caligraphic","KaTeX_Fraktur","KaTeX_SansSerif","KaTeX_Script","KaTeX_Typewriter","KaTeX_Size1","KaTeX_Size2","KaTeX_Size3","KaTeX_Size4"],i=Array.from(document.fonts).map(a=>a.family);if(r.every(a=>i.includes(a))){Ne="ready";return}if(!globalThis.MathfieldElement.fontsDirectory){Ne="not-loaded";return}let n=await bs(globalThis.MathfieldElement.fontsDirectory);if(!n){document.body.classList.add("ML__fonts-did-not-load"),Ne="error";return}n.endsWith("/")&&(n=n.slice(0,-1));let o=[["KaTeX_Main-Regular"],["KaTeX_Main-BoldItalic",{style:"italic",weight:"bold"}],["KaTeX_Main-Bold",{weight:"bold"}],["KaTeX_Main-Italic",{style:"italic"}],["KaTeX_Math-Italic",{style:"italic"}],["KaTeX_Math-BoldItalic",{style:"italic",weight:"bold"}],["KaTeX_AMS-Regular"],["KaTeX_Caligraphic-Regular"],["KaTeX_Caligraphic-Bold",{weight:"bold"}],["KaTeX_Fraktur-Regular"],["KaTeX_Fraktur-Bold",{weight:"bold"}],["KaTeX_SansSerif-Regular"],["KaTeX_SansSerif-Bold",{weight:"bold"}],["KaTeX_SansSerif-Italic",{style:"italic"}],["KaTeX_Script-Regular"],["KaTeX_Typewriter-Regular"],["KaTeX_Size1-Regular"],["KaTeX_Size2-Regular"],["KaTeX_Size3-Regular"],["KaTeX_Size4-Regular"]].map(a=>Gg(a[0].replace(/-[a-zA-Z]+$/,""),`${n}/${a[0]}`,a[1]));try{(await Promise.all(o.map(s=>{try{return s.load()}catch(l){}}))).forEach(s=>document.fonts.add(s)),Ne="ready";return}catch(a){console.error(`MathLive 0.111.1: The math fonts could not be loaded from "${n}"`,{cause:a}),document.body.classList.add("ML__fonts-did-not-load")}Ne="error"}}function Hh(t,e=0){let r=3735928559^e,i=1103547991^e;for(let n=0;n>>16,2246822507),r^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(r^r>>>13,3266489909),4294967296*(2097151&i)+(r>>>0)}function Y(t,e){!t||t.dirty||!t.field||(t.resizeObserver.unobserve(t.field),t.dirty=!0,requestAnimationFrame(()=>{Ye(t)&&t.dirty&&(t.atomBoundsCache=new Map,_t(t,e),t.resizeObserver.observe(t.field),t.resizeObserverStarted=!0)}))}function jg(t,e){var o;e=e!=null?e:{};let r=new P({from:g(h({},t.context),{atomIdsSettings:{seed:e.forHighlighting?Hh(x.serialize([t.model.root],{expandMacro:!1,defaultMode:t.options.defaultMode})):"random",groupNumbers:(o=e.forHighlighting)!=null?o:!1},letterShapeStyle:t.options.letterShapeStyle}),mathstyle:t.options.defaultMode==="inline-math"?"textstyle":"displaystyle"}),i=t.model.root.render(r);return Br(Ht(i,r),{classes:t.hasEditablePrompts?"ML__latex ML__prompting":"ML__latex",attributes:{translate:"no","aria-hidden":"true"}})}function Sc(t,e){try{let{model:r}=t;r.root.caret=void 0,r.root.isSelected=!1,r.root.containsCaret=!0;for(let n of r.atoms)n.caret=void 0,n.isSelected=!1,n.containsCaret=!1;if(r.selectionIsCollapsed){let n=r.at(r.position);n.caret=t.model.mode;let o=n.parent;for(;o;)o.containsCaret=!0,o=o.parent}else{let n=r.getAtoms(r.selection,{includeChildren:!0,includeFirstAtoms:!0});for(let o of n)o.isSelected=!0}return jg(t,e).toMarkup()}catch(r){return console.error(r),''}}function _t(t,e){if(!Ye(t))return;e!=null||(e={});let r=t.element.querySelector("[part=virtual-keyboard-toggle]");r&&(r.style.display=t.hasEditableContent?"":"none");let i=t.field;if(!i)return;let n=t.isSelectionEditable&&t.hasFocus(),o=i.classList.contains("ML__focused");o&&!n?i.classList.remove("ML__focused"):!o&&n&&i.classList.add("ML__focused");let a=Sc(t,e),s=t.element.querySelector("[part=menu-toggle]");if(s){let l=!1;(t.disabled||t.readOnly&&!t.hasEditableContent||t.userSelect==="none")&&(l=!0),!l&&t.element.offsetWidth<50&&(l=!0),s.style.display=l?"none":""}if(t.model.atoms.length<=1){let l=t.options.contentPlaceholder;l&&(a+=`${pe(l)}`)}i.innerHTML=globalThis.MathfieldElement.createHTML(a),uo(t,e.interactive),t.updateToggleLayout(),t.dirty=!1}function uo(t,e){var l;let r=t.field;if(!r)return;for(let c of r.querySelectorAll(".ML__selection, .ML__contains-highlight"))c.remove();if(!(e!=null&&e)&&Ne!=="error"&&Ne!=="ready"){setTimeout(()=>{Ne==="ready"?uo(t):setTimeout(()=>uo(t),128)},32);return}let i=t.model;(l=t.atomBoundsCache)==null||l.clear();let n,o=()=>{if(n!==void 0)return n;let c=r.offsetWidth,u=r.getBoundingClientRect().width;return n=Math.floor(u)/c,isNaN(n)&&(n=1),n};if(i.selectionIsCollapsed){yn(t,{deferred:!0});let c=i.at(i.position);for(;c&&c.type!=="prompt"&&!(c.containsCaret&&c.displayContainsHighlight);)c=c.parent;if(c!=null&&c.containsCaret&&c.displayContainsHighlight){let u=o(),d=hc(t,ar(t,c),u);if(d){d.left/=u,d.right/=u,d.top/=u,d.bottom/=u;let m=document.createElement("div");m.classList.add("ML__contains-highlight"),m.style.position="absolute",m.style.left=`${d.left+1}px`,m.style.top=`${Math.ceil(d.top)}px`,m.style.width=`${Math.ceil(d.right-d.left)}px`,m.style.height=`${Math.ceil(d.bottom-d.top)}px`,r.insertBefore(m,r.childNodes[0])}}return}let a=o(),s=Jg(Qa(t,{excludeAtomsWithBackground:!0}));for(let c of s){c.left/=a,c.right/=a,c.top/=a,c.bottom/=a;let u=document.createElement("div");u.classList.add("ML__selection"),u.style.position="absolute",u.style.left=`${c.left}px`,u.style.top=`${c.top}px`,u.style.width=`${Math.ceil(c.right-c.left)}px`,u.style.height=`${Math.max(1,Math.ceil(c.bottom-c.top-1))}px`,r.insertBefore(u,r.childNodes[0])}}function Jg(t){let e=[];for(let r of t){let i=!1;for(let n of e)if(r.left===n.left&&r.right===n.right&&r.top===n.top&&r.bottom===n.bottom){i=!0;break}i||e.push(r)}t=e,e=[];for(let r of t){let i=0;for(let n of t)if(r.left>=n.left&&r.right<=n.right&&r.top>=n.top&&r.bottom<=n.bottom&&(i+=1,i>1))break;i===1&&e.push(r)}return e}function kc(t){if(!t)return;let e=t.model,r=e.selection,i=x.serialize([e.root],{expandMacro:!1,defaultMode:t.options.defaultMode});H.insert(e,i,{insertionMode:"replaceAll",selectionMode:"after",format:"latex",silenceNotifications:!0,mode:"math"});let n=e.silenceNotifications;e.silenceNotifications=!0,e.selection=r,e.silenceNotifications=n,Y(t)}function Lc(){for(let t of document.querySelectorAll(".ML__mathfield"))"_mathfield"in t&&kc(t._mathfield)}var mo=3,Mt;function fe(t,e){e=h({target:"mathfield",canUndo:!1,audioFeedback:void 0,changeContent:!1,changeSelection:!1},e!=null?e:{}),Mt||(Mt={});for(let r of Object.keys(t))Mt[r],Mt[r]=g(h({},e),{fn:t[r]})}function Ac(t){let e;if(Array.isArray(t)){if(t[0]==="performWithFeedback")return Ac(t[1]);e=t[0]}else e=t;return Mt[e]}function pr(t){var e;return(e=Ac(t))==null?void 0:e.target}function Wh(t,e){var l,c;if(e=_i(e),!e)return!1;let r,i=[],n=!1,o=!1;ee(e)?(r=e[0],i=e.slice(1)):r=e;let a=Mt[r],s=a==null?void 0:a.target;if(s==="model"){if(!t.isSelectionEditable&&(a!=null&&a.changeContent))return t.model.announce("plonk"),!1;/^(delete|add)/.test(r)&&(r!=="deleteBackward"&&t.flushInlineShortcutBuffer(),t.snapshot(r)),/^complete/.test(r)||xi(t),Mt[r].fn(t.model,...i),Vr(t),o=!0,n=!0}else if(s==="virtual-keyboard")o=(c=(l=window.mathVirtualKeyboard)==null?void 0:l.executeCommand(e))!=null?c:!1,n=!0;else if(Mt[r]){if(!t.isSelectionEditable&&(a!=null&&a.changeContent))return t.model.announce("plonk"),!1;/^(undo|redo)/.test(r)&&t.flushInlineShortcutBuffer(),o=Mt[r].fn(t,...i),n=!0}else throw new Error(`Unknown command "${r}"`);return s!=="virtual-keyboard"&&(!t.model.selectionIsCollapsed||a!=null&&a.changeSelection&&r!=="deleteBackward")&&(t.flushInlineShortcutBuffer(),a!=null&&a.changeContent||t.stopCoalescingUndo(),t.defaultStyle={}),o&&(a!=null&&a.changeSelection&&n?(t.dirty=!0,t.scrollIntoView()):Y(t)),n}function Xg(t,e){var n;if(!t)return!1;t.focus(),xn.keypressVibration&&Di()&&navigator.vibrate(mo);let r=Ac(e);globalThis.MathfieldElement.playSound((n=r==null?void 0:r.audioFeedback)!=null?n:"keypress");let i=t.executeCommand(e);return t.scrollIntoView(),i}fe({performWithFeedback:(t,e)=>Xg(t,e)});function Zg(t){return Vr(t,{atIndex:t.suggestionIndex+1}),!1}function Yg(t){return Vr(t,{atIndex:t.suggestionIndex-1}),!1}fe({complete:Qe},{target:"mathfield",audioFeedback:"return",canUndo:!0,changeContent:!0,changeSelection:!0});fe({dispatchEvent:(t,e,r)=>{var i,n;return(n=(i=t.host)==null?void 0:i.dispatchEvent(new CustomEvent(e,{detail:r})))!=null?n:!1}},{target:"mathfield"});fe({nextSuggestion:Zg,previousSuggestion:Yg},{target:"mathfield",audioFeedback:"keypress",changeSelection:!0});function _i(t){if(!t)return;if(ee(t)&&t.length>0){let i=t[0];return i=i.replace(/-\w/g,n=>n[1].toUpperCase()),i==="performWithFeedback"&&t.length===2?[i,_i(t[1])]:[i,...t.slice(1)]}if(typeof t!="string")return;let e=t.trim().match(/^([a-zA-Z0-9-]+)\((.*)\)$/);if(e){let i=e[1].replace(/-\w/g,o=>o[1].toUpperCase()),n=e[2].split(",").map(o=>o.trim());return[i,...n.map(o=>{if(/"[^"]*"/.test(o)||/'[^']*'/.test(o))return o.slice(1,-1);if(/^true$/.test(o))return!0;if(/^false$/.test(o))return!1;if(/^[-]?\d+$/.test(o))return parseInt(o,10);if(/^\{.*\}$/.test(o))try{return JSON.parse(o)}catch(a){return console.error("Invalid argument:",o),o}return _i(o)})]}return t.replace(/-\w/g,i=>i[1].toUpperCase())}var po="mathlive#virtual-keyboard-message";function fo(t){var r;return t.type!=="message"?!1:((r=t.data)==null?void 0:r.type)===po}var ho=class t{constructor(){this.targetOrigin=window.origin;this.originValidator="none";this.targetWindow=window.top;this._boundingRect=new DOMRect(0,0,0,0);this._isShifted=!1;window.addEventListener("message",this),this.sendMessage("proxy-created"),this.listeners={}}static get singleton(){return this._singleton||(this._singleton=new t),this._singleton}getKeycap(e){}setKeycap(e,r){this.sendMessage("update-setting",{setKeycap:{keycap:e,value:r}})}set alphabeticLayout(e){this.sendMessage("update-setting",{alphabeticLayout:e})}set layouts(e){this.sendMessage("update-setting",{layouts:e})}get normalizedLayouts(){return[]}set editToolbar(e){this.sendMessage("update-setting",{editToolbar:e})}set container(e){throw new Error("Container inside an iframe cannot be changed")}show(e){this.dispatchEvent(new CustomEvent("before-virtual-keyboard-toggle",{detail:{visible:!0},bubbles:!0,cancelable:!0,composed:!0}))&&(this.sendMessage("show",e),this.dispatchEvent(new Event("virtual-keyboard-toggle")))}hide(e){this.dispatchEvent(new CustomEvent("before-virtual-keyboard-toggle",{detail:{visible:!1},bubbles:!0,cancelable:!0,composed:!0}))&&(this.sendMessage("hide",e),this.dispatchEvent(new Event("virtual-keyboard-toggle")))}get isShifted(){return this._isShifted}get visible(){return this._boundingRect.height>0}set visible(e){e?this.show():this.hide()}get boundingRect(){return this._boundingRect}executeCommand(e){return this.sendMessage("execute-command",{command:e}),!0}updateToolbar(e){this.sendMessage("update-toolbar",e)}update(e){this.sendMessage("update-setting",e)}connect(){this.sendMessage("connect")}disconnect(){this.sendMessage("disconnect")}addEventListener(e,r,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].has(r)||this.listeners[e].add(r)}dispatchEvent(e){return!this.listeners[e.type]||this.listeners[e.type].size===0?!0:(this.listeners[e.type].forEach(r=>{typeof r=="function"?r(e):r==null||r.handleEvent(e)}),!e.defaultPrevented)}removeEventListener(e,r,i){this.listeners[e]&&this.listeners[e].delete(r)}handleEvent(e){if(fo(e)){if(!rn(e.origin,this.originValidator))throw new DOMException(`Message from unknown origin (${e.origin}) cannot be handled`,"SecurityError");this.handleMessage(e.data)}}handleMessage(e){let{action:r}=e;if(r==="execute-command"){let{command:i}=e;pr(i)==="virtual-keyboard"&&this.executeCommand(i);return}if(r==="synchronize-proxy"){this._boundingRect=e.boundingRect,this._isShifted=e.isShifted;return}if(r==="geometry-changed"){this._boundingRect=e.boundingRect,this.dispatchEvent(new Event("geometrychange"));return}}sendMessage(e,r={}){if(!this.targetWindow)throw new DOMException("A frame does not have access to the top window and can't communicate with the keyboard.","SecurityError");this.targetWindow.postMessage(h({type:po,action:e},r),this.targetOrigin)}};var Cc={numeric:{label:"123",labelClass:"MLK__tex-math",tooltip:"keyboard.tooltip.numeric",rows:[[{latex:"x",shift:"y",variants:["y","z","t","r","x^2","x^n","x^{#?}","x_n","x_i","x_{#?}",{latex:"f(#?)",class:"small"},{latex:"g(#?)",class:"small"}]},{latex:"n",shift:"a",variants:["i","j","p","k","a","u"]},"[separator-5]","[7]","[8]","[9]","[/]","[separator-5]",{latex:"\\exponentialE",shift:"\\ln",variants:["\\exp","\\times 10^{#?}","\\ln","\\log_{10}","\\log","\\lg","\\operatorname{lb}"]},{latex:"\\imaginaryI",variants:["\\Re","\\Im","\\imaginaryJ","\\Vert #0 \\Vert"]},{latex:"\\pi",shift:"\\sin",variants:["\\prod",{latex:"\\theta",aside:"theta"},{latex:"\\rho",aside:"rho"},{latex:"\\tau",aside:"tau"},"\\sin","\\cos","\\tan"]}],[{label:"<",latex:"<",class:"hide-shift",shift:{latex:"\\le",label:"\u2264"}},{label:">",latex:">",class:"hide-shift",shift:{latex:"\\ge",label:"\u2265"}},"[separator-5]","[4]","[5]","[6]","[*]","[separator-5]",{class:"hide-shift",latex:"#@^2}",shift:"#@^{\\prime}}"},{latex:"#@^{#0}}",class:"hide-shift",shift:"#@_{#?}"},{class:"hide-shift",latex:"\\sqrt{#0}",shift:{latex:"\\sqrt[#0]{#?}}"}}],["[(]","[)]","[separator-5]","[1]","[2]","[3]","[-]","[separator-5]",{latex:"\\int^{\\infty}_{0}\\!#?\\,\\mathrm{d}x",class:"small hide-shift",shift:"\\int",variants:[{latex:"\\int_{#?}^{#?}",class:"small"},{latex:"\\int",class:"small"},{latex:"\\iint",class:"small"},{latex:"\\iiint",class:"small"},{latex:"\\oint",class:"small"},"\\mathrm{d}x",{latex:"\\dfrac{\\mathrm{d}}{\\mathrm{d} x}",class:"small"},{latex:"\\frac{\\partial}{\\partial x}",class:"small"},"\\partial"]},{class:"hide-shift",latex:"\\forall",shift:"\\exists"},{label:"[backspace]",width:1}],[{label:"[shift]",width:2},"[separator-5]","[0]","[.]","[=]","[+]","[separator-5]","[left]","[right]",{label:"[action]",width:1}]]},greek:{label:"αβγ",labelClass:"MLK__tex-math",tooltip:"keyboard.tooltip.greek",rows:[[{label:"φ",class:"MLK__tex hide-shift",insert:"\\varphi",aside:"phi var.",shift:"\\Phi"},{label:"ς",class:"MLK__tex hide-shift",insert:"\\varsigma",aside:"sigma var.",shift:"\\Sigma"},{label:"ϵ",class:"MLK__tex hide-shift",insert:"\\epsilon",aside:"epsilon",shift:'\\char"0190'},{label:"ρ",class:"MLK__tex hide-shift",insert:"\\rho",aside:"rho",shift:'\\char"3A1'},{label:"τ",class:"MLK__tex hide-shift",insert:"\\tau",aside:"tau",shift:'\\char"3A4'},{label:"υ",class:"MLK__tex hide-shift",insert:"\\upsilon",aside:"upsilon",shift:"\\Upsilon"},{label:"θ",class:"MLK__tex hide-shift",insert:"\\theta",aside:"theta",shift:"\\Theta"},{label:"ι",class:"MLK__tex hide-shift",insert:"\\iota",aside:"iota",shift:'\\char"399'},{label:"ο",class:"MLK__tex hide-shift",insert:"\\omicron",aside:"omicron",shift:'\\char"39F'},{label:"π",class:"MLK__tex hide-shift",insert:"\\pi",aside:"pi",shift:"\\Pi"}],["[separator-5]",{label:"α",class:"MLK__tex hide-shift",insert:"\\alpha",aside:"alpha",shift:'\\char"391'},{label:"σ",class:"MLK__tex hide-shift",insert:"\\sigma",aside:"sigma",shift:"\\Sigma"},{label:"δ",class:"MLK__tex hide-shift",insert:"\\delta",aside:"delta",shift:"\\Delta"},{latex:"\\phi",class:"MLK__tex hide-shift",insert:"\\phi",aside:"phi",shift:"\\Phi"},{label:"γ",class:"MLK__tex hide-shift",insert:"\\gamma",aside:"gamma",shift:"\\Gamma"},{label:"η",class:"MLK__tex hide-shift",insert:"\\eta",aside:"eta",shift:'\\char"397'},{label:"ξ",class:"MLK__tex hide-shift",insert:"\\xi",aside:"xi",shift:"\\Xi"},{label:"κ",class:"MLK__tex hide-shift",insert:"\\kappa",aside:"kappa",shift:"\\Kappa"},{label:"λ",class:"MLK__tex hide-shift",insert:"\\lambda",aside:"lambda",shift:"\\Lambda"},"[separator-5]"],["[shift]",{label:"ζ",class:"MLK__tex hide-shift",insert:"\\zeta",aside:"zeta",shift:'\\char"396'},{label:"χ",class:"MLK__tex hide-shift",insert:"\\chi",aside:"chi",shift:'\\char"3A7'},{label:"ψ",class:"MLK__tex hide-shift",insert:"\\psi",aside:"psi",shift:"\\Psi"},{label:"ω",class:"MLK__tex hide-shift",insert:"\\omega",aside:"omega",shift:"\\Omega"},{label:"β",class:"MLK__tex hide-shift",insert:"\\beta",aside:"beta",shift:'\\char"392'},{label:"ν",class:"MLK__tex hide-shift",insert:"\\nu",aside:"nu",shift:'\\char"39D'},{label:"μ",class:"MLK__tex hide-shift",insert:"\\mu",aside:"mu",shift:'\\char"39C'},"[backspace]"],["[separator]",{label:"ε",class:"MLK__tex",insert:"\\varepsilon",aside:"epsilon var."},{label:"ϑ",class:"MLK__tex",insert:"\\vartheta",aside:"theta var."},{label:"ϰ",class:"MLK__tex",insert:"\\varkappa",aside:"kappa var."},{label:"ϖ",class:"MLK__tex",insert:"\\varpi",aside:"pi var."},{label:"ϱ",class:"MLK__tex",insert:"\\varrho",aside:"rho var."},"[left]","[right]","[action]"]]},symbols:{label:"∞\u2260\u2208",labelClass:"MLK__tex",tooltip:"keyboard.tooltip.symbols",rows:[[{latex:"\\sin",shift:"\\sin^{-1}",variants:[{class:"small",latex:"\\sinh"},{class:"small",latex:"\\sin^{-1}"},{class:"small",latex:"\\operatorname{arsinh}"}]},"\\ln",{latex:"\\mathrm{abs}",insert:"\\mathrm{abs}\\left(#0\\right)"},{latex:"\\rightarrow",shift:"\\Rightarrow",variants:[{latex:"\\implies",aside:"implies"},{latex:"\\to",aside:"to"},"\\dashv",{latex:"\\roundimplies",aside:"round implies"}]},{latex:"\\exists",variants:["\\nexists"],shift:"\\nexists"},{latex:"\\in",shift:"\\notin",variants:["\\notin","\\owns"]},"\\cup",{latex:"\\overrightarrow{#@}",shift:"\\overleftarrow{#@}",variants:["\\overleftarrow{#@}","\\bar{#@}","\\vec{#@}","\\hat{#@}","\\check{#@}","\\dot{#@}","\\ddot{#@}","\\mathring{#@}","\\breve{#@}","\\acute{#@}","\\tilde{#@}","\\grave{#@}"]},{class:"small hide-shift",latex:"\\lim_{#?}",shift:"\\lim_{x\\to\\infty}",variants:[{class:"small",latex:"\\liminf_{#?}"},{class:"small",latex:"\\limsup_{#?}"}]},"\\exponentialE"],[{latex:"\\cos",shift:"\\cos^{-1}",variants:[{class:"small",latex:"\\cosh"},{class:"small",latex:"\\cos^{-1}"},{class:"small",latex:"\\operatorname{arcosh}"}]},{latex:"\\log",shift:"\\log_{10}",variants:["\\log_{#0}","\\log_{10}"]},"\\left\\vert#0\\right\\vert",{latex:"\\larr",shift:"\\lArr",variants:[{latex:"\\impliedby",aside:"implied by"},{latex:"\\gets",aside:"gets"},"\\lArr","\\vdash",{latex:"\\models",aside:"models"}]},{latex:"\\forall",shift:"\\lnot",variants:[{latex:"\\land",aside:"and"},{latex:"\\lor",aside:"or"},{latex:"\\oplus",aside:"xor"},{latex:"\\lnot",aside:"not"},{latex:"\\downarrow",aside:"nor"},{latex:"\\uparrow",aside:"nand"},{latex:"\\curlywedge",aside:"nor"},{latex:"\\bar\\curlywedge",aside:"nand"}]},{latex:"\\ni",shift:"\\not\\owns"},"\\cap",{latex:"\\overline{#@}",shift:"\\underline{#@}",variants:["\\overbrace{#@}","\\overlinesegment{#@}","\\overleftrightarrow{#@}","\\overrightarrow{#@}","\\overleftarrow{#@}","\\overgroup{#@}","\\underbrace{#@}","\\underlinesegment{#@}","\\underleftrightarrow{#@}","\\underrightarrow{#@}","\\underleftarrow{#@}","\\undergroup{#@}"]},{class:"hide-shift small",latex:"\\int",shift:"\\iint",variants:[{latex:"\\int_{#?}^{#?}",class:"small"},{latex:"\\int",class:"small"},{latex:"\\smallint",class:"small"},{latex:"\\iint",class:"small"},{latex:"\\iiint",class:"small"},{latex:"\\oint",class:"small"},"\\intop","\\iiint","\\oiint","\\oiiint","\\intclockwise","\\varointclockwise","\\ointctrclockwise","\\intctrclockwise"]},{latex:"\\pi",shift:"\\tau",variants:["\\tau"]}],[{latex:"\\tan",shift:"\\tan^{-1}",variants:[{class:"small",latex:"\\tanh"},{class:"small",latex:"\\tan^{-1}"},{class:"small",latex:"\\operatorname{artanh}"},{class:"small",latex:"\\arctan"},{class:"small",latex:"\\operatorname{arctg}"},{class:"small",latex:"\\operatorname{tg}"}]},{latex:"\\exp",insert:"\\exp\\left(#0\\right)",variants:["\\exponentialE^{#0}"]},"\\left\\Vert#0\\right\\Vert",{latex:"\\lrArr",shift:"\\leftrightarrow",variants:[{latex:"\\iff",aside:"if and only if"},"\\leftrightarrow","\\leftrightarrows","\\Leftrightarrow",{latex:"^\\biconditional",aside:"biconditional"}]},{latex:"\\vert",shift:"!"},{latex:"#@^{\\complement}",aside:"complement",variants:[{latex:"\\setminus",aside:"set minus"},{latex:"\\smallsetminus",aside:"small set minus"}]},{latex:"\\subset",shift:"\\subseteq",variants:["\\subset","\\subseteq","\\subsetneq","\\varsubsetneq","\\subsetneqq","\\nsubset","\\nsubseteq","\\supset","\\supseteq","\\supsetneq","\\supsetneqq","\\nsupset","\\nsupseteq"]},{latex:"#@^{\\prime}",shift:"#@^{\\doubleprime}",variants:["#@^{\\doubleprime}","#@\\degree"]},{latex:"\\mathrm{d}",shift:"\\partial",variants:["\\mathrm{d}x",{latex:"\\dfrac{\\mathrm{d}}{\\mathrm{d} x}",class:"small"},{latex:"\\frac{\\partial}{\\partial x}",class:"small"},"\\partial"]},{latex:"\\infty",variants:["\\aleph_0","\\aleph_1","\\omega","\\mathfrak{m}"]}],[{label:"[shift]",width:2},{class:"box",latex:",",shift:";",variants:[";","?"]},{class:"box",latex:"\\colon",shift:"\\Colon",variants:[{latex:"\\Colon",aside:"such that",class:"box"},{latex:":",aside:"ratio",class:"box"},{latex:"\\vdots",aside:"",class:"box"},{latex:"\\ddots",aside:"",class:"box"},{latex:"\\ldotp",aside:"low dot",class:"box"},{latex:"\\cdotp",aside:"center dot",class:"box"},{latex:"\\ldots",aside:"low ellipsis",class:"box"},{latex:"\\cdots",aside:"center ellipsis",class:"box"},{latex:"\\therefore",aside:"therefore",class:"box"},{latex:"\\because",aside:"because",class:"box"}]},{class:"box",latex:"\\cdot",aside:"centered dot",shift:"\\ast",variants:["\\circ","\\bigcirc","\\bullet","\\odot","\\oslash","\\circledcirc","\\ast","\\star","\\times","\\doteq","\\doteqdot"]},"[separator]","[left]","[right]",{label:"[backspace]",width:1,class:"action hide-shift"},{label:"[action]",width:1}]]},compact:{label:"compact",rows:[["[+]","[-]","[*]","[/]","[=]","[.]","[(]","[)]","\\sqrt{#0}","#@^{#?}"],["[1]","[2]","[3]","[4]","[5]","[6]","[7]","[8]","[9]","[0]"],["[hr]"],["[undo]","[redo]","[separator]","[separator]","[separator]","[left]","[right]",{label:"[backspace]",class:"action hide-shift"},"[hide-keyboard]"]]},minimalist:{label:"minimalist",layers:[{style:` + div.minimalist-backdrop { + display: flex; + justify-content: center; + } + div.minimalist-container { + --keycap-height: 40px; + --keycap-max-width: 53px; + --keycap-small-font-size: 12px; + background: var(--keyboard-background); + padding: 20px 20px 0px 20px; + border-top-left-radius: 8px; + border-top-right-radius: 8px; + border: 1px solid var(--keyboard-border); + box-shadow: 0 0 32px rgb(0 0 0 / 30%); + } + `,backdrop:"minimalist-backdrop",container:"minimalist-container",rows:[["+","-","\\times",{latex:"\\frac{#@}{#0}",class:"small"},"=","[.]","(",")",{latex:"\\sqrt{#0}",class:"small"},{latex:"#@^{#?}",class:"small"}],["1","2","3","4","5","6","7","8","9","0"],["[hr]"],["[undo]","[redo]","[separator]","[separator]","[separator]","[left]","[right]",{label:"[backspace]",class:"action hide-shift"},"[hide-keyboard]"]]}]},"numeric-only":{label:"123",labelClass:"MLK__tex-math",tooltip:"keyboard.tooltip.numeric",id:"numeric-only",rows:[["7","8","9","[separator]",{label:"[backspace]",width:2}],["4","5","6","[separator]","[separator]","[separator]"],["1","2","3","[separator]","[separator]","[separator]"],["0",{label:"[.]",variants:[]},"-","[separator]","[left]","[right]"]]}};var ys={0:["\\varnothing","\\infty"],1:["\\frac{1}{#@}","#@^{-1}","\\times 10^{#?}","\\phi","\\imaginaryI"],2:["\\frac{1}{2}","#@^2","\\sqrt2","\\exponentialE"],3:["\\frac{1}{3}","#@^3","\\sqrt3","\\pi"],4:["\\frac{1}{4}","#@^4"],5:["\\frac{1}{5}","#@^5","\\sqrt5"],6:["\\frac{1}{6}","#@^6"],7:["\\frac{1}{7}","#@^7"],8:["\\frac{1}{8}","#@^8"],9:["\\frac{1}{9}","#@^9"],".":[".",",",";","\\colon"],",":["{,}",".",";","\\colon"],a:[{latex:"\\aleph",aside:"aleph"},{latex:"\\forall",aside:"for all"},"\xE5","\xE0","\xE1","\xE2","\xE4","\xE6"],A:[{latex:"\\aleph",aside:"aleph"},{latex:"\\forall",aside:"for all"},"\xC5","\xC0","\xC1","\xC2","\xC4","\xC6"],b:[{latex:"\\beth",aside:"beth"}],c:[{latex:"\\C",aside:"set of complex numbers"},"\xE7"],d:[{latex:"\\daleth",aside:"daleth"}],e:[{latex:"\\exponentialE",aside:"exponential e"},{latex:"\\exists",aside:"there is"},{latex:"\\nexists",aside:"there isn\u2019t"},"\xE8","\xE9","\xEA","\xEB"],E:[{latex:"\\exponentialE",aside:"exponential e"},{latex:"\\exists",aside:"there is"},{latex:"\\nexists",aside:"there isn\u2019t"},"\xC8","\xC9","\xCA","\xCB"],g:[{latex:"\\gimel",aside:"gimel"}],h:[{latex:"\\hbar",aside:"h bar"},{latex:"\\hslash",aside:"h slash"}],i:[{latex:"\\imaginaryI",aside:"imaginary i"},"\xEC","\xED","\xEE","\xEF"],I:[{latex:"\\imaginaryI",aside:"imaginary i"},"\xCC","\xCD","\xCE","\xCF"],j:[{latex:"\\imaginaryJ",aside:"imaginary j"}],l:[{latex:"\\ell",aside:"ell"}],n:[{latex:"\\mathbb{N}",aside:"set of natural numbers"},"\xF1"],o:["\xF8","\u0153","\xF2","\xF3","\xF4","\xF6"],O:["\xF8","\u0152","\xD2","\xD3","\xD4","\xD6"],p:[{latex:"\\mathbb{P}",aside:"set of primes"}],q:[{latex:"\\mathbb{Q}",aside:"set of rational numbers"}],r:[{latex:"\\mathbb{R}",aside:"set of real numbers"}],u:["\xF9","\xFA","\xFB","\xFC"],U:["\xD9","\xDA","\xDB","\xDC"],z:[{latex:"\\mathbb{Z}",aside:"set of integers"}],y:["\xFD","\xFF"],Y:["\u0178"],space:[{latex:'\\char"203A\\!\\char"2039',insert:"\\!",aside:"negative thin space
    \u207B\xB3\u29F8\u2081\u2088 em"},{latex:'\\char"203A\\,\\char"2039',insert:"\\,",aside:"thin space
    \xB3\u29F8\u2081\u2088 em"},{latex:'\\char"203A\\:\\char"2039',insert:"\\:",aside:"medium space
    \u2074\u29F8\u2081\u2088 em"},{latex:'\\char"203A\\;\\char"2039',insert:"\\;",aside:"thick space
    \u2075\u29F8\u2081\u2088 em"},{latex:'\\char"203A\\ \\char"2039',insert:"\\ ",aside:"\u2153 em"},{latex:'\\char"203A\\enspace\\char"2039',insert:"\\enspace",aside:"\xBD em"},{latex:'\\char"203A\\quad\\char"2039',insert:"\\quad",aside:"1 em"},{latex:'\\char"203A\\qquad\\char"2039',insert:"\\qquad",aside:"2 em"}]},vn;function xs(t,e){var m,p,f,y,v;let r=Fe.singleton;if(!r)return;let i=Mi(t),n="";if(window.mathVirtualKeyboard.isShifted){let b=(m=r.getKeycap(i==null?void 0:i.id))==null?void 0:m.shift;typeof b=="object"&&"variants"in b&&(n=(p=b.variants)!=null?p:"")}else n=(y=(f=r.getKeycap(i==null?void 0:i.id))==null?void 0:f.variants)!=null?y:"";if(typeof n=="string"&&!vs(n)||Array.isArray(n)&&n.length===0){e==null||e();return}let o={},a="";for(let b of eb(n)){let k=go(b),S=Date.now().toString(36).slice(-2)+Math.floor(Math.random()*1e5).toString(36);o[S]=k;let[A,E]=_n(k);a+=`
    ${A}
    `}let s=document.createElement("div");s.setAttribute("aria-hidden","true"),s.className="MLK__variant-panel",s.style.height="auto";let l=Object.keys(o).length,c=5;l===1?c=1:l===2||l===4?c=2:l===3||l===5||l===6?c=3:l>=7&&l<14&&(c=4),s.style.width=`calc(var(--variant-keycap-length) * ${c} + 12px)`,s.innerHTML=xn.createHTML(a),Te.open({root:(v=r==null?void 0:r.container)==null?void 0:v.querySelector(".ML__keyboard"),child:s}),vn=new AbortController;let{signal:u}=vn,d=t==null?void 0:t.getBoundingClientRect();if(d){d.top-s.clientHeight<0&&(s.style.width="auto",l<=6?s.style.height="56px":l<=12?s.style.height="108px":l<=18?s.style.height="205px":s.classList.add("compact"));let b=Math.max(0,Math.min(window.innerWidth-s.offsetWidth,(d.left+d.right-s.offsetWidth)/2)),k=d.top-s.clientHeight+5;s.style.left=`${b}px`,s.style.top=`${k}px`,s.classList.add("is-visible"),requestAnimationFrame(()=>{var S;s.addEventListener("pointerup",A=>{let E=Mi(A.target);!(E!=null&&E.id)||!o[E.id]||(_s(o[E.id]),Hr(),e==null||e(),A.preventDefault())},{capture:!0,passive:!1,signal:u}),s.addEventListener("pointerenter",A=>{let E=Mi(A.target);!(E!=null&&E.id)||!o[E.id]||E.classList.add("is-active")},{capture:!0,signal:u}),s.addEventListener("pointerleave",A=>{let E=Mi(A.target);A.target&&"tagName"in A.target&&typeof A.target.tagName=="string"&&A.target.tagName.toUpperCase()==="ASIDE"||!(E!=null&&E.id)||!o[E.id]||E.classList.remove("is-active")},{capture:!0,signal:u}),(S=r.getKeycap(i==null?void 0:i.id))!=null&&S.stickyVariantPanel?window.addEventListener("pointerdown",A=>{if(!(A.target instanceof Node))return;let E=s.contains(A.target);A.target===s||E||(Hr(),e==null||e())},{signal:u}):(window.addEventListener("pointercancel",()=>{Hr(),e==null||e()},{signal:u}),window.addEventListener("pointerup",()=>{Hr(),e==null||e()},{signal:u}))})}}function Hr(){vn==null||vn.abort(),vn=null,Te.state==="open"&&Te.close()}function Qg(t){if(t==="foreground-color"){let e=[];for(let r of Object.keys(er))e.push({class:"swatch-button",label:'',command:["applyStyle",{color:r}]});return e}if(t==="background-color"){let e=[];for(let r of Object.keys(Qt))e.push({class:"swatch-button",label:'',command:["applyStyle",{backgroundColor:r}]});return e}}function vs(t){return ys[t]!==void 0}function eb(t){var e;return typeof t!="string"?t:(ys[t]||(ys[t]=(e=Qg(t))!=null?e:[]),ys[t])}function tb(t){return typeof t=="string"?t:Object.entries(t).map(([e,r])=>`${e}:${r} !important`).join(";")}function rb(t){return Object.keys(t).map(e=>`${e} {${tb(t[e])}}`).join("")}function bo(t){if(!t)return"";let e=new P,r=new x({mode:"math",type:"root",body:be(t,{context:e,args:n=>n==="@"?"{\\class{ML__box-placeholder}{\\blacksquare}}":"\\placeholder{}"})}),i=Or(Ht(new w(r.render(e),{classes:"ML__base"}),e));return Br(i,{classes:"ML__latex"}).toMarkup()}function Ms(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}function ib(t){return t.replace(/<\/?[^>]+(>|$)/g," ")}function nb(t){var i,n,o,a;let e=(a=(o=(n=(i=t.tooltip)!=null?i:typeof t.label=="string"?ib(t.label):void 0)!=null?n:t.insert)!=null?o:t.latex)!=null?a:t.key;return e&&e.replace(/\s+/g," ").trim()||null}function ob(t){if(typeof t=="undefined"||t===null)return null;try{return JSON.stringify(t)}catch(e){return null}}function ab(t){var r,i;let e=(i=(r=t.insert)!=null?r:t.latex)!=null?i:t.key;return e!=null?e:null}function yo(t){var r;if(Array.isArray(t))return t.map(i=>yo(i)).flat();let e=typeof t=="string"?{markup:t}:t;return"rows"in e&&Array.isArray(e.rows)&&(e.rows=e.rows.map(i=>i.map(n=>go(n)))),(r=e.id)!=null||(e.id="ML__layer_"+Date.now().toString(36).slice(-2)+Math.floor(Math.random()*1e5).toString(36)),[e]}function sb(){var o,a;let e=window.mathVirtualKeyboard.alphabeticLayout;if(e==="auto"){let s=yr();s&&(e=s.virtualLayout),(!e||e==="auto")&&(e=(o={fr:"azerty",be:"azerty",al:"qwertz",ba:"qwertz",cz:"qwertz",de:"qwertz",hu:"qwertz",sk:"qwertz",ch:"qwertz"}[F.locale.slice(0,2)])!=null?o:"qwerty")}let r={qwerty:["qwertyuiop"," asdfghjkl ","^zxcvbnm~"],azerty:["azertyuiop","qsdfghjklm","^ wxcvbn ~"],qwertz:["qwertzuiop"," asdfghjkl ","^yxcvbnm~"],dvorak:["^ pyfgcrl ","aoeuidhtns","qjkxbmwvz~"],colemak:[" qwfpgjluy ","arstdhneio","^zxcvbkm~"]},i=(a=r[e])!=null?a:r.qwerty,n=e==="azerty"?[[{label:"1",variants:"1"},{label:"2",shift:{latex:"\xE9"},variants:"2"},{label:"3",shift:{latex:"\xF9"},variants:"3"},{label:"4",variants:"4"},{label:"5",shift:{label:"(",latex:"("},variants:"5"},{label:"6",shift:{label:")",latex:")"},variants:"6"},{label:"7",shift:{latex:"\xE8"},variants:"7"},{label:"8",shift:{latex:"\xEA"},variants:"8"},{label:"9",shift:{latex:"\xE7"},variants:"9"},{label:"0",shift:{latex:"\xE0"},variants:"0"}]]:[[{label:"1",variants:"1"},{label:"2",variants:"2"},{label:"3",variants:"3"},{label:"4",variants:"4"},{label:"5",shift:{latex:"\\frac{#@}{#?}"},variants:"5"},{label:"6",shift:{latex:"#@^#?"},variants:"6"},{label:"7",variants:"7"},{label:"8",shift:{latex:"\\times"},variants:"8"},{label:"9",shift:{label:"(",latex:"("},variants:"9"},{label:"0",shift:{label:")",latex:")"},variants:"0"}]];for(let s of i){let l=[];for(let c of s)/[a-z]/.test(c)?l.push({label:c,class:"hide-shift",shift:{label:c.toUpperCase(),variants:vs(c.toUpperCase())?c.toUpperCase():void 0},variants:vs(c)?c:void 0}):c==="~"?e!=="dvorak"?l.push("[backspace]"):l.push({label:"[backspace]",width:1}):c==="^"?l.push("[shift]"):c===" "&&l.push("[separator-5]");n.push(l)}return n.push(["[-]","[+]","[=]",{label:" ",width:1.5},{label:",",shift:";",variants:".",class:"hide-shift"},"[.]","[left]","[right]",{label:"[action]",width:1.5}]),{label:"abc",labelClass:"MLK__tex-math",tooltip:"keyboard.tooltip.alphabetic",layers:yo({rows:n})}}function Ec(t){if(t==="alphabetic")return sb();if(typeof t=="string")return Cc[t],`${t}`,Ec(Cc[t]);let e;if("rows"in t&&Array.isArray(t.rows)){"layers"in t||"markup"in t;let n=t,{rows:a}=n,s=Ti(n,["rows"]);e=g(h({},s),{layers:yo({rows:t.rows})})}else if("markup"in t&&typeof t.markup=="string"){let o=t,{markup:a}=o,s=Ti(o,["markup"]);e=g(h({},s),{layers:yo(t.markup)})}else e=h({},t),"layers"in t?e.layers=yo(t.layers):console.error('MathLive 0.111.1: provide either a "rows", "markup" or "layers" property');let r=!1,i=!1;for(let a of e.layers)if(a.rows)for(let s of a.rows.flat()){Mn(s)&&(r=!0);let l=s.command;typeof l=="string"&&["undo","redo","cut","copy","paste"].includes(l)&&(i=!0)}return(!("displayShiftedKeycaps"in t)||t.displayShiftedKeycaps===void 0)&&(e.displayShiftedKeycaps=r),(!("displayEditToolbar"in t)||t.displayEditToolbar===void 0)&&(e.displayEditToolbar=!i),e}function lb(t,e){var i,n;let r='
    ';if(t.normalizedLayouts.length>1)for(let[o,a]of t.normalizedLayouts.entries()){let s=a,l=[o===e?"selected":"layer-switch"];s.tooltip&&l.push("MLK__tooltip"),s.labelClass&&l.push(...s.labelClass.split(" ")),r+=`
    ${(n=s.label)!=null?n:"untitled"}
    `}return r+="
    ",r}function Uh(t,e){let r="";if(t.editToolbar==="none")return"";let n=[];e.selectionIsCollapsed?n.push("undo","redo","pasteFromClipboard"):n.push("cutToClipboard","copyToClipboard","pasteFromClipboard");let o={undo:`
    + +
    `,redo:`
    + +
    `,cutToClipboard:` +
    + +
    + `,copyToClipboard:` +
    + +
    + `,pasteFromClipboard:` +
    + +
    + `};return r+=n.map(a=>o[a]).join(""),r}function cb(t){for(let e of t)ub(e)}function ub(t){let e=Fe.singleton;if(!e)return;let r={};if(!t.id){if(t.hasAttribute("data-label")&&(r.label=t.dataset.label),t.hasAttribute("data-latex")&&(r.latex=t.dataset.latex),t.hasAttribute("data-key")&&(r.key=t.dataset.key),t.hasAttribute("data-insert")&&(r.insert=t.dataset.insert),t.hasAttribute("data-variants")&&(r.variants=t.dataset.variants),t.hasAttribute("data-aside")&&(r.aside=t.dataset.aside),t.className&&(r.class=t.className),!r.label&&!r.latex&&!r.key&&!r.insert&&(r.latex=t.innerText,r.label=t.innerHTML),t.hasAttribute("data-command"))try{r.command=JSON.parse(t.dataset.command)}catch(i){console.warn("Invalid JSON in data-command attribute",i)}t.id=e.registerKeycap(r)}if(!t.innerHTML){let[i,n]=_n(r);t.innerHTML=globalThis.MathfieldElement.createHTML(i)}}function db(){Ge("virtual-keyboard"),Ge("core"),hr()}function Gh(){ot("core"),ot("virtual-keyboard")}var mb=` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`;function jh(t){t.resetKeycapRegistry(),db();let e=document.createElement("div");e.className="ML__keyboard";let r=document.createElement("div");r.className="MLK__plate",r.innerHTML=globalThis.MathfieldElement.createHTML(mb+t.normalizedLayouts.map((a,s)=>hb(t,a,s)).join(""));let i=document.createElement("div");i.className="MLK__backdrop",i.appendChild(r),e.appendChild(i),e.addEventListener("pointerdown",fb,{passive:!1});let n=e.querySelectorAll(".ML__edit-toolbar");if(n)for(let a of n)a.addEventListener("click",s=>{var u,d;let l=s.target,c="";for(;l&&!c;)c=(u=l==null?void 0:l.getAttribute("data-command"))!=null?u:"",l=(d=l==null?void 0:l.parentElement)!=null?d:null;c&&t.executeCommand(JSON.parse(c))});cb(e.querySelectorAll(".MLK__keycap, .action, .fnbutton, .bigfnbutton"));let o=e.querySelectorAll(".MLK__layer");o.length>0;for(let a of o)a.addEventListener("pointerdown",s=>s.preventDefault());return t.currentLayer=t.latentLayer,e}function hb(t,e,r){var n;let i=[];if(!("layers"in e))return"";for(let o of e.layers)i.push(`
    `),(t.normalizedLayouts.length>1||e.displayEditToolbar)&&(i.push("")),i.push(pb(t,o)),i.push("
    ");return i.join("")}function pb(t,e){if(typeof e=="string")return e;let r="";if(typeof e.style=="string"?r+=``:typeof e.style=="object"&&(r+=``),e.backdrop&&(r+=`
    `),e.container&&(r+=`
    `),e.rows){r+="
    ";for(let i of e.rows){r+='
    ';for(let n of i)if(n){let o=t.registerKeycap(n),[a,s]=_n(n);/(^|\s)separator/.test(s)?r+=`
    ${a}
    `}r+="
    "}r+="
    "}else e.markup&&(r+=e.markup);return e.container&&(r+="
    "),e.backdrop&&(r+="
    "),r}function _n(t,e={shifted:!1}){var n,o,a,s,l,c,u;let r="",i=(n=t.class)!=null?n:"";if(e.shifted&&Mn(t)&&(i+=" is-active"),e.shifted&&"shift"in t)typeof t.shift=="string"?r=bo(t.shift):typeof t.shift=="object"&&(r=t.shift.label?t.shift.label:(o=bo(t.shift.latex||t.shift.insert||"")||t.shift.key)!=null?o:""),typeof t.shift=="object"&&(i=(s=(a=t.shift.class)!=null?a:t.class)!=null?s:"");else{if(r=t.label?t.label:(l=bo(t.latex||t.insert||"")||t.key)!=null?l:"",t.shift){let d;typeof t.shift=="string"?d=bo(t.shift):t.shift.label?d=t.shift.label:d=(c=bo(t.shift.latex||t.shift.insert||"")||t.shift.key)!=null?c:"",r+=`${d}`}t.aside&&(r+=``)}return t.layer&&!/layer-switch/.test(i)&&(i+=" layer-switch"),/(^|\s)(separator|action|shift|fnbutton|bigfnbutton)($|\s)/.test(i)||(i+=" MLK__keycap"),!/\bw[0-9]+\b/.test(i)&&t.width&&(i+=(u={0:" w0",.5:" w5",1.5:" w15",2:" w20",5:" w50"}[t.width])!=null?u:""),[r,i||"MLK__keycap"]}var jt={"[left]":{class:"action hide-shift",label:"",command:"performWithFeedback(moveToPreviousChar)",shift:{label:"",command:"performWithFeedback(extendSelectionBackward)"}},"[right]":{class:"action hide-shift",label:"",command:"performWithFeedback(moveToNextChar)",shift:{label:"",command:"performWithFeedback(extendSelectionForward)"}},"[up]":{class:"action hide-shift",label:"\u2191",command:"performWithFeedback(moveUp)",shift:{label:"\u219F",command:"performWithFeedback(extendSelectionUpward)"}},"[down]":{class:"action hide-shift",label:"\u2193",command:"performWithFeedback(moveDown)",shift:{label:"\u21A1",command:"performWithFeedback(extendSelectionDownward)"}},"[return]":{class:"action hide-shift",command:"performWithFeedback(commit)",shift:{command:"performWithFeedback(addRowAfter)"},width:1.5,label:""},"[action]":{class:"action hide-shift",command:"performWithFeedback(commit)",shift:{label:"",command:"performWithFeedback(addRowAfter)"},width:1.5,label:""},"[hr]":{class:"separator horizontal-rule"},"[hide-keyboard]":{class:"action",command:["hideVirtualKeyboard"],width:1.5,label:""},"[.]":{variants:".",command:"performWithFeedback(insertDecimalSeparator)",shift:",",class:"big-op hide-shift",label:"."},"[,]":{variants:",",command:"performWithFeedback(insertDecimalSeparator)",shift:".",class:"big-op hide-shift",label:","},"[+]":{variants:[{latex:"\\sum_{#0}^{#0}",class:"small"},"\\oplus"],latex:"+",label:"+",class:"big-op hide-shift",shift:{latex:"\\sum",insert:"\\sum",class:"small"}},"[-]":{variants:["\\pm","\\ominus"],latex:"-",label:"−",shift:"\\pm",class:"big-op hide-shift"},"[/]":{class:"big-op hide-shift",shift:{class:"",latex:"\\frac{1}{#@}"},variants:["/","\\div","\\%","\\oslash"],latex:"\\frac{#@}{#?}",label:"÷"},"[*]":{variants:[{latex:"\\prod_{#0}^{#0}",class:"small"},"\\otimes","\\cdot"],latex:"\\cdot",label:"×",shift:{latex:"\\times"},class:"big-op hide-shift"},"[=]":{variants:["\\neq","\\equiv","\\varpropto","\\thickapprox","\\lt","\\gt","\\le","\\ge"],latex:"=",label:"=",shift:{label:"\u2260",latex:"\\ne"},class:"big-op hide-shift"},"[backspace]":{class:"action bottom right hide-shift",width:1.5,command:"performWithFeedback(deleteBackward)",label:"",shift:{class:"action warning",label:"",command:"deleteAll"}},"[undo]":{class:"ghost if-can-undo",command:"undo",label:"",tooltip:"tooltip.undo"},"[redo]":{class:"ghost if-can-redo",command:"redo",label:"",tooltip:"tooltip.redo"},"[(]":{variants:[{latex:"\\lbrack",key:"["},"\\langle","\\lfloor","\\lceil",{latex:"\\lbrace",key:"{"}],key:"(",label:"(",shift:{label:"[",key:"["},class:"hide-shift"},"[)]":{variants:[{latex:"\\rbrack",key:"]"},"\\rangle","\\rfloor","\\rceil",{latex:"\\rbrace",key:"}"}],key:")",label:")",shift:{label:"]",latex:"\\rbrack"},class:"hide-shift"},"[0]":{variants:"0",latex:"0",label:"0",shift:"\\infty",class:"hide-shift"},"[1]":{variants:"1",latex:"1",label:"1",shift:"#@^{-1}",class:"hide-shift"},"[2]":{variants:"2",latex:"2",label:"2",shift:"#@^2",class:"hide-shift"},"[3]":{variants:"3",latex:"3",label:"3",shift:"#@^3",class:"hide-shift"},"[4]":{variants:"4",latex:"4",label:"4",shift:"#@^4",class:"hide-shift"},"[5]":{variants:"5",latex:"5",label:"5",shift:"#@^5",class:"hide-shift"},"[6]":{variants:"6",latex:"6",label:"6",shift:"#@^6",class:"hide-shift"},"[7]":{variants:"7",latex:"7",label:"7",shift:"#@^7",class:"hide-shift"},"[8]":{variants:"8",latex:"8",label:"8",shift:"#@^8",class:"hide-shift"},"[9]":{variants:"9",latex:"9",label:"9",shift:"#@^9",class:"hide-shift"},"[separator-5]":{class:"separator",width:.5},"[separator]":{class:"separator"},"[separator-10]":{class:"separator"},"[separator-15]":{class:"separator",width:1.5},"[separator-20]":{class:"separator",width:2},"[separator-50]":{class:"separator",width:5},"[shift]":{class:"shift bottom left",width:1.5,label:""},"[foreground-color]":{variants:"foreground-color",command:["applyStyle",{color:"red"}],label:""},"[background-color]":{variants:"background-color",command:["applyStyle",{backgroundColor:"yellow"}],label:""}};function go(t){var r;if(typeof t=="string"){if(t==="[.]"&&globalThis.MathfieldElement.decimalSeparator===","&&(t="[,]"),!jt[t])return{latex:t};t={label:t}}let e;return"label"in t&&t.label&&jt[t.label]&&(e=g(h(h({},jt[t.label]),t),{label:jt[t.label].label})),"key"in t&&t.key&&jt[t.key]&&(e=g(h(h({},jt[t.key]),t),{key:jt[t.key].key})),e?(e.command==="insertDecimalSeparator"&&(e.label=(r=globalThis.MathfieldElement.decimalSeparator)!=null?r:"."),(e.tooltip===void 0||e.tooltip===null||e.tooltip===!1)&&delete e.tooltip,(e.tooltip===void 0||e.tooltip===null||e.tooltip===!1)&&delete e.tooltip,(e.aside===void 0||e.aside===null||e.aside===!1)&&delete e.aside,(e.variants===void 0||e.variants===null||e.variants===!1)&&delete e.variants,(e.shift===void 0||e.shift===null||e.shift===!1)&&delete e.shift,e):t}var xo;function fb(t){var l,c,u,d;if(t.button!==0)return;let e=Fe.singleton;if(!e)return;let r=t.target;for(;r&&!r.getAttribute("data-layer");)r=r.parentElement;if(r){e.currentLayer=(l=r.getAttribute("data-layer"))!=null?l:"",t.preventDefault();return}let i=Mi(t.target);if(!(i!=null&&i.id))return;let n=e.getKeycap(i.id);if(!n)return;t.type;let o=e;if(!o.connectedMathfieldWindow){let m=(c=window.focusedMathfield)==null?void 0:c.call(window);if(m){let p=(d=(u=m.element)==null?void 0:u.ownerDocument)==null?void 0:d.defaultView;p&&p!==window&&(o.connectedMathfieldWindow=p)}}let a=new AbortController,s=a.signal;i.classList.add("is-pressed"),i.addEventListener("pointerenter",ws(a),{capture:!0,signal:s}),i.addEventListener("pointerleave",ws(a),{capture:!0,signal:s}),i.addEventListener("pointercancel",ws(a),{signal:s}),i.addEventListener("pointerup",ws(a),{signal:s}),Mn(n)&&(i.classList.add("is-active"),e.shiftPressCount++),n.variants&&(xo&&clearTimeout(xo),xo=setTimeout(()=>{i.classList.contains("is-pressed")&&(i.classList.remove("is-pressed"),i.classList.add("is-active"),t.target&&"releasePointerCapture"in t.target&&t.target.releasePointerCapture(t.pointerId),xs(i,()=>{a.abort(),i==null||i.classList.remove("is-active")}))},n.stickyVariantPanel?0:300)),t.preventDefault()}function ws(t){return e=>{let r=Mi(e.target);if(!(r!=null&&r.id))return;let i=Fe.singleton;if(!i)return;let n=i.getKeycap(r.id);if(n){if(e.type==="pointerenter"&&e.target===r&&e.isPrimary&&r.classList.add("is-pressed"),e.type==="pointercancel"){r.classList.remove("is-pressed"),Mn(n)&&(i.shiftPressCount--,r.classList.toggle("is-active",i.isShifted)),t.abort();return}if(e.type==="pointerleave"&&e.target===r){r.classList.remove("is-pressed"),Mn(n)&&(i.shiftPressCount--,r.classList.toggle("is-active",i.isShifted));return}if(e.type==="pointerup"){xo&&clearTimeout(xo),Mn(n)?r.classList.toggle("is-active",i.isShifted):r.classList.contains("is-pressed")&&(r.classList.remove("is-pressed"),i.isShifted&&n.shift?typeof n.shift=="string"?i.executeCommand(["insert",n.shift,{focus:!0,feedback:!0,scrollIntoView:!0,mode:"math",format:"latex"}]):_s(n.shift):_s(n),i.shiftPressCount===1&&!e.shiftKey&&(i.shiftPressCount=0)),t.abort(),e.preventDefault();return}}}}function _s(t){let e=t.command;!e&&t.insert&&(e=["insert",t.insert,{focus:!0,feedback:!0,scrollIntoView:!0,mode:"math",format:"latex"}]),!e&&t.key&&(e=["typedText",t.key,{focus:!0,feedback:!0,simulateKeystroke:!0}]),!e&&t.latex&&(e=["insert",t.latex,{focus:!0,feedback:!0,scrollIntoView:!0,mode:"math",format:"latex"}]),e||(e=["typedText",t.label,{focus:!0,feedback:!0,simulateKeystroke:!0}]),Fe.singleton&&Fe.singleton.executeCommand(e)}function gb(t){if(t.nodeType!==1)return!1;let e=t.classList;return e.contains("MLK__keycap")||e.contains("shift")||e.contains("action")||e.contains("fnbutton")||e.contains("bigfnbutton")}function Mi(t){if(!t)return;let e=t;for(;e&&!gb(e);)e=e.parentElement;return e!=null?e:void 0}function Mn(t){return!!t.class&&/(^|\s)shift($|\s)/.test(t.class)}var Fe=class t{constructor(){this.originalContainerBottomPadding=null;this.keycapRegistry={};this._shiftPressCount=0;this.isSandbox=!1;var e;this.targetOrigin=window.origin,this.originValidator="none",this._alphabeticLayout="auto",this._layouts=Object.freeze(["default"]),this._editToolbar="default",this._container=void 0,this._visible=!1,this._rebuilding=!1,this.observer=new ResizeObserver(r=>{this.adjustBoundingRect(),this.dispatchEvent(new Event("geometrychange")),this.sendMessage("geometry-changed",{boundingRect:this.boundingRect})}),this.listeners={};try{(e=window.top)==null||e.addEventListener("message",this)}catch(r){window.addEventListener("message",this)}Uo()&&document.addEventListener("focusin",r=>{let i=r.target;i!=null&&i.isConnected&&setTimeout(()=>{let n=Jh();n&&n.mathVirtualKeyboardPolicy==="auto"&&n.hasEditableContent&&this.show({animate:!0})},300)}),document.addEventListener("focusout",r=>{r.target instanceof lt&&r.target.mathVirtualKeyboardPolicy!=="manual"&&setTimeout(()=>{Jh()||this.hide()},300)})}get currentLayer(){var e,r,i;return(i=(r=(e=this._element)==null?void 0:e.querySelector(".MLK__layer.is-visible"))==null?void 0:r.id)!=null?i:""}set currentLayer(e){var i;if(!this._element){this.latentLayer=e;return}let r=e?this._element.querySelector(`#${e}.MLK__layer`):null;r||(r=this._element.querySelector(".MLK__layer")),r&&((i=this._element.querySelector(".MLK__layer.is-visible"))==null||i.classList.remove("is-visible"),r.classList.add("is-visible")),this.render()}get shiftPressCount(){return this._shiftPressCount}set shiftPressCount(e){var r;this._shiftPressCount=e>2||e<0?0:e,(r=this._element)==null||r.classList.toggle("is-caps-lock",this.shiftPressCount===2),this.render()}get isShifted(){return this._shiftPressCount>0}resetKeycapRegistry(){this.keycapRegistry={}}registerKeycap(e){let r="ML__k"+Date.now().toString(36).slice(-2)+Math.floor(Math.random()*1e5).toString(36);return this.keycapRegistry[r]=e,r}setKeycap(e,r){jt[e]=go(r),this.rebuild()}getKeycap(e){var r;return e?(r=jt[e])!=null?r:this.keycapRegistry[e]:void 0}getLayer(e){let r=this.normalizedLayouts;for(let i of r)for(let n of i.layers)if(n.id===e)return n}get alphabeticLayout(){return this._alphabeticLayout}set alphabeticLayout(e){this._alphabeticLayout=e,this._normalizedLayouts=void 0,this.rebuild()}get layouts(){return this._layouts}set layouts(e){this.updateNormalizedLayouts(e),this.rebuild()}updateNormalizedLayouts(e){let r=Array.isArray(e)?[...e]:[e],i=r.findIndex(n=>n==="default");i>=0&&r.splice(i,1,"numeric","symbols","alphabetic","greek"),this._layouts=Object.freeze(r),this._normalizedLayouts=r.map(n=>Ec(n))}get normalizedLayouts(){return this._normalizedLayouts||this.updateNormalizedLayouts(this._layouts),this._normalizedLayouts}get editToolbar(){return this._editToolbar}set editToolbar(e){this._editToolbar=e,this.rebuild()}get container(){return this._container===void 0?window.document.body:this._container}set container(e){this._container=e,this.rebuild()}static get singleton(){if(this._singleton===void 0)try{this._singleton=new t}catch(e){this._singleton=null}return this._singleton}get style(){return this._style}addEventListener(e,r,i){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].has(r)||this.listeners[e].add(r)}dispatchEvent(e){return!this.listeners[e.type]||this.listeners[e.type].size===0?!0:(this.listeners[e.type].forEach(r=>{typeof r=="function"?r(e):r==null||r.handleEvent(e)}),!e.defaultPrevented)}removeEventListener(e,r,i){this.listeners[e]&&this.listeners[e].delete(r)}get element(){return this._element}set element(e){var r;this._element!==e&&((r=this._element)==null||r.remove(),this._element=e)}get visible(){return this._visible}set visible(e){e?this.show():this.hide()}get boundingRect(){var r;if(!this._visible)return new DOMRect;let e=(r=this._element)==null?void 0:r.getElementsByClassName("MLK__plate")[0];return e?e.getBoundingClientRect():new DOMRect}adjustBoundingRect(){if(!this._element)return;let e=this.boundingRect.height;if(this.container===document.body){this._element.style.setProperty("--_keyboard-height",`calc(${e}px + var(--_padding-top) + var(--_padding-bottom))`);let r=e-1;this.container.style.paddingBottom=this.originalContainerBottomPadding?`calc(${this.originalContainerBottomPadding} + ${r}px)`:`${r}px`}else this._element.style.setProperty("--_keyboard-height",`${e}px`)}rebuild(){if(this._rebuilding||!this._element)return;this._rebuilding=!0;let e=this.currentLayer;requestAnimationFrame(()=>{this._rebuilding=!1,this._element&&(this._element.remove(),this._element=void 0),this.visible&&(this.buildAndAttachElement(),this.currentLayer=e,this.render(),this.adjustBoundingRect(),this._element.classList.add("is-visible"))})}render(){var n;if(!this._element)return;let e=this.getLayer(this.currentLayer);this._element.classList.toggle("backdrop-is-transparent",!!(e&&(e.backdrop||e.container)));let r=this._element.querySelectorAll(".MLK__layer.is-visible .MLK__keycap, .MLK__layer.is-visible .action, .fnbutton, .MLK__layer.is-visible .bigfnbutton, .MLK__layer.is-visible .shift");if(!r)return;let i=this.isShifted;for(let o of r){let a=this.getKeycap(o.id);if(a){let[s,l]=_n(a,{shifted:i});o.innerHTML=globalThis.MathfieldElement.createHTML(s),o.className=l,i&&typeof a.shift=="object"&&((n=a.shift)!=null&&n.tooltip)?o.dataset.tooltip=a.shift.tooltip:!i&&a.tooltip&&(o.dataset.tooltip=a.tooltip)}}}show(e){var i;if(this._visible)return;let r=this.container;if(r&&window.mathVirtualKeyboard&&this.stateWillChange(!0)){if(this._element||(this.buildAndAttachElement(),this.adjustBoundingRect()),!this._visible){let n=this._element.getElementsByClassName("MLK__plate")[0];if(n&&this.observer.observe(n),r===window.document.body){let o=r.style.paddingBottom;this.originalContainerBottomPadding=o;let a=n.offsetHeight-1;r.style.paddingBottom=o?`calc(${o} + ${a}px)`:`${a}px`}window.addEventListener("mouseup",this),window.addEventListener("blur",this),window.addEventListener("keydown",this,{capture:!0}),window.addEventListener("keyup",this,{capture:!0}),(i=this._element)==null||i.classList.toggle("is-caps-lock",this.shiftPressCount===2),this.currentLayer=this.latentLayer}this._visible=!0,e!=null&&e.animate?requestAnimationFrame(()=>{this._element&&(this._element.classList.add("animate"),this._element.addEventListener("transitionend",()=>{var n;return(n=this._element)==null?void 0:n.classList.remove("animate")},{once:!0}),this._element.classList.add("is-visible"),this.stateChanged())}):(this._element.classList.add("is-visible"),this.stateChanged())}}hide(e){var i;let r=this.container;if(r&&this._visible&&this.stateWillChange(!1)){if(this._visible=!1,this._element){this.latentLayer=this.currentLayer;let n=this._element.getElementsByClassName("MLK__plate")[0];n&&this.observer.unobserve(n),window.removeEventListener("mouseup",this),window.removeEventListener("blur",this),window.removeEventListener("keydown",this,{capture:!0}),window.removeEventListener("keyup",this,{capture:!0}),window.removeEventListener("contextmenu",this,{capture:!0}),Hr(),Gh(),(i=this._element)==null||i.remove(),this._element=void 0,this.originalContainerBottomPadding!==null&&(r.style.paddingBottom=this.originalContainerBottomPadding)}this.stateChanged()}}get height(){var e,r;return(r=(e=this.element)==null?void 0:e.offsetHeight)!=null?r:0}buildAndAttachElement(){var e;this.element,this.element=jh(this),window.addEventListener("contextmenu",this,{capture:!0}),this.element.addEventListener("contextmenu",r=>{r.shiftKey||((r.ctrlKey||r.button===2)&&xs(r.target),r.preventDefault(),r.stopPropagation())},{capture:!0}),(e=this.container)==null||e.appendChild(this.element)}handleEvent(e){if(fo(e)){if(!rn(e.origin,this.originValidator))throw new DOMException(`Message from unknown origin (${e.origin}) cannot be handled`,"SecurityError");if(e.data.action==="disconnect"){if(this._visible)return;this.connectedMathfieldWindow=void 0}else e.data.action!=="update-setting"&&e.data.action!=="proxy-created"&&e.data.action!=="execute-command"&&(e.source,this.connectedMathfieldWindow=e.source);this.handleMessage(e.data,e.source)}if(this._element)switch(e.type){case"mouseup":case"blur":document.body.style.userSelect="",this.shiftPressCount=0;break;case"contextmenu":e.button!==2&&e.preventDefault();break;case"keydown":{e.key==="Shift"&&!e.repeat&&(this.shiftPressCount=1);break}case"keyup":{(e.key==="Shift"||!e.getModifierState("Shift")&&this.shiftPressCount!==2)&&(this.shiftPressCount=0);break}}}handleMessage(e,r){let{action:i}=e;if(i==="execute-command"){let{command:n}=e,o=pr(n);if(window===window.top&&r!==window||r===window&&o!=="virtual-keyboard")return;this.executeCommand(n);return}if((i==="connect"||i==="show")&&this.sendMessage("synchronize-proxy",{boundingRect:this.boundingRect,alphabeticLayout:this._alphabeticLayout,layouts:this._layouts,editToolbar:this._editToolbar},r),i!=="disconnect"&&!this.isSandbox){if(i==="show"){typeof e.animate!="undefined"?this.show({animate:e.animate}):this.show();return}if(i==="hide"){typeof e.animate!="undefined"?this.hide({animate:e.animate}):this.hide();return}if(i==="update-setting"){if(e.alphabeticLayout&&(this.alphabeticLayout=e.alphabeticLayout),e.layouts&&(this.layouts=e.layouts),e.editToolbar&&(this.editToolbar=e.editToolbar),e.setKeycap){let{keycap:n,value:o}=e.setKeycap;this.setKeycap(n,o),this.render()}return}if(i==="proxy-created"){this.sendMessage("synchronize-proxy",{boundingRect:this.boundingRect,alphabeticLayout:this._alphabeticLayout,layouts:this._layouts,editToolbar:this._editToolbar},r);return}}}sendMessage(e,r,i){if(r.command&&this.dispatchEvent(new CustomEvent("math-virtual-keyboard-command",{detail:r.command})),i||(i=this.connectedMathfieldWindow),this.targetOrigin===null||this.targetOrigin==="null"||i===window){window.dispatchEvent(new MessageEvent("message",{source:window,origin:window.origin,data:h({type:po,action:e},r)}));return}if(i)i.postMessage(h({type:po,action:e},r),{targetOrigin:this.targetOrigin});else if(e==="execute-command"&&Array.isArray(r.command)&&r.command[0]==="insert"){let n=r.command[1].split("");for(let o of n)this.dispatchEvent(new KeyboardEvent("keydown",{key:o,bubbles:!0})),this.dispatchEvent(new KeyboardEvent("keyup",{key:o,bubbles:!0}))}}stateWillChange(e){return this.dispatchEvent(new CustomEvent("before-virtual-keyboard-toggle",{detail:{visible:e},bubbles:!0,cancelable:!0,composed:!0}))}stateChanged(){this.dispatchEvent(new Event("virtual-keyboard-toggle")),this._visible||(this.dispatchEvent(new Event("geometrychange")),this.sendMessage("geometry-changed",{boundingRect:this.boundingRect}))}focus(){this.sendMessage("focus",{})}blur(){this.sendMessage("blur",{})}updateToolbar(e){let r=this._element;if(!r)return;r.classList.toggle("is-math-mode",e.mode==="math"),r.classList.toggle("is-text-mode",e.mode==="text"),r.classList.toggle("can-undo",e.canUndo),r.classList.toggle("can-redo",e.canRedo),r.classList.toggle("can-copy",!e.selectionIsCollapsed),r.classList.toggle("can-cut",!e.selectionIsCollapsed),r.classList.toggle("can-paste",!0);let i=r.querySelectorAll(".ML__edit-toolbar");if(i)for(let n of i)n.innerHTML=Uh(this,e)}update(e){this._style=e.style,this.updateToolbar(e)}connect(){this.connectedMathfieldWindow=window}disconnect(){this._visible||(this.connectedMathfieldWindow=void 0)}executeCommand(e){if(e=_i(e),!e)return!1;let r,i=[],n=pr(e);return ee(e)?(r=e[0],r==="performWithFeedback"&&(n=pr(e.slice(1))),i=e.slice(1)):r=e,n==="virtual-keyboard"?Mt[r].fn(void 0,...i):(this.sendMessage("execute-command",{command:e}),!1)}dispose(){window.removeEventListener("mouseup",this),window.removeEventListener("blur",this),window.removeEventListener("message",this)}};function Jh(){let t=Ut(),e=null;for(;t;){if("host"in t&&t.host instanceof lt){e=t.host;break}t=t.parentNode}return e}Le()&&!("mathVirtualKeyboard"in window)&&(window===window.top?vo():Object.defineProperty(window,"mathVirtualKeyboard",{get:()=>ho.singleton,configurable:!0}));function vo(){let t=Fe.singleton;return window.mathVirtualKeyboard!==t&&Object.defineProperty(window,"mathVirtualKeyboard",{get:()=>t}),t}function wn(t){let e={};for(let r of Object.keys(t))switch(r){case"scriptDepth":let i=t.scriptDepth;if(ee(i))e.scriptDepth=[i[0],i[1]];else if(typeof i=="number")e.scriptDepth=[i,i];else if(typeof i=="string"){let[o,a]=i.split(",").map(s=>parseInt(s.trim()));e.scriptDepth=[o,a]}else throw new TypeError("Unexpected value for scriptDepth");break;case"mathVirtualKeyboardPolicy":let n=t.mathVirtualKeyboardPolicy.toLowerCase();if(n==="sandboxed"){let o=vo();o&&(o.isSandbox=!0),n="manual"}e.mathVirtualKeyboardPolicy=n;break;case"letterShapeStyle":t.letterShapeStyle==="auto"?F.locale.startsWith("fr")?e.letterShapeStyle="french":e.letterShapeStyle="tex":e.letterShapeStyle=t.letterShapeStyle;break;case"defaultMode":["text","math","inline-math"].includes(t.defaultMode)?e.defaultMode=t.defaultMode:(console.error('MathLive 0.111.1: valid values for defaultMode are "text", "math" or "inline-math"'),e.defaultMode="math");break;case"macros":e.macros=ei(t.macros);break;default:ee(t[r])?e[r]=[...t[r]]:typeof t[r]=="object"&&!(t[r]instanceof Element)&&r!=="computeEngine"?e[r]=h({},t[r]):e[r]=t[r]}return e}function fr(t,e){let r;typeof e=="string"?r=[e]:e===void 0?r=Object.keys(t):r=e;let i={};for(let n of r)t[n]===null?i[n]=null:ee(t[n])?i[n]=[...t[n]]:typeof t[n]=="object"&&!(t[n]instanceof Element)&&n!=="computeEngine"?i[n]=h({},t[n]):i[n]=t[n];return typeof e=="string"?i[e]:i}function Sn(){return{readOnly:!1,defaultMode:"math",macros:{},registers:{},colorMap:Yr,backgroundColorMap:Bi,letterShapeStyle:F.locale.startsWith("fr")?"french":"tex",minFontScale:0,maxMatrixCols:10,smartMode:!1,smartFence:!0,smartSuperscript:!0,scriptDepth:[1/0,1/0],removeExtraneousParentheses:!0,isImplicitFunction:t=>["\\sin","\\cos","\\tan","\\arcsin","\\arccos","\\arctan","\\arcsec","\\arccsc","\\arsinh","\\arcosh","\\artanh","\\arcsech","\\arccsch","\\arg","\\ch","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\sec","\\sinh","\\sh","\\tanh","\\tg","\\th","\\lg","\\lb","\\log","\\ln"].includes(t),mathModeSpace:"",placeholderSymbol:"\u25A2",contentPlaceholder:"",popoverPolicy:"auto",environmentPopoverPolicy:"off",keybindings:Q0,inlineShortcuts:Za,inlineShortcutTimeout:0,mathVirtualKeyboardPolicy:"auto",originValidator:"none",onInsertStyle:co,onInlineShortcut:()=>"",onScrollIntoView:null,onExport:Y0,value:""}}function Tc(t){return t.defaultMode==="inline-math"?"math":t.defaultMode}var Xh="⁡",Ss="⁢";function De(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")}function re(t,e){return!t||!e.generateID?"":` extid="${t}"`}function bb(t,e,r){var d,m,p,f,y,v,b,k;let i=!1;e=e!=null?e:t.atoms.length;let n="",o="",a=t.atoms[t.index],s=(d=a.style)==null?void 0:d.variant,l=(m=a.style)==null?void 0:m.variantStyle,c="";if(a.value&&(s||l)){let S=(p=Bn(a.value,s,l))!=null?p:a.value;if(S!==a.value)return t.index+=1,n=`${S}`,Jt(n,t,r)||(t.mathML+=n,t.lastType="mi"),!0;c=(f={upnormal:"normal",boldnormal:"bold",italicmain:"italic",bolditalicmain:"bold-italic","updouble-struck":"double-struck","double-struck":"double-struck",boldfraktur:"bold-fraktur",calligraphic:"script",upcalligraphic:"script",script:"script",boldscript:"bold-script",boldcalligraphic:"bold-script",fraktur:"fraktur","upsans-serif":"sans-serif","boldsans-serif":"bold-sans-serif","italicsans-serif":"sans-serif-italic","bolditalicsans-serif":"sans-serif-bold-italic",monospace:"monospace"}[(l!=null?l:"")+(s!=null?s:"")])!=null?f:"",c&&(c=` mathvariant="${c}"`)}let u={"\\exponentialE":"ⅇ","\\imaginaryI":"ⅈ","\\differentialD":"ⅆ","\\capitalDifferentialD":"ⅅ","\\alpha":"α","\\pi":"π","\\infty":"∞","\\forall":"∀","\\nexists":"∄","\\exists":"∃","\\hbar":"\u210F","\\cdotp":"\u22C5","\\ldots":"\u2026","\\cdots":"\u22EF","\\ddots":"\u22F1","\\vdots":"\u22EE","\\ldotp":"."};if(a.command==="!")return t.index+=1,n="!",Jt(n,t,r)||(t.mathML+=n,t.lastType="mo"),!0;if(u[a.command]){t.index+=1;let S=`${u[a.command]}`;return(t.lastType==="mi"||t.lastType==="mn"||t.lastType==="mtext"||t.lastType==="fence")&&(S=Ss+S),Jt(S,t,r)||(t.mathML+=S,t.lastType="mi"),!0}if(a.command==="\\operatorname")o=kn(a.body),t.index+=1;else if(s||l)for(;t.index0){i=!0,n=`${o}`;let S=t.lastType;n.endsWith(">f")||n.endsWith(">g")?(n+=Xh,t.lastType="applyfunction"):t.lastType=/^(.*)<\/mo>$/.test(n)?"mo":"mi",Jt(n,t,r)||((S==="mi"||S==="mn"||S==="mtext"||S==="fence")&&(n=Ss+n),t.mathML+=n)}return i}function Zh(t){return t.index${t}${a}${o}`:o?s=`${t}${o}`:a&&(s=`${t}${a}`),e.mathML+=s,e.lastType="",!0}function yb(t,e,r){e=e!=null?e:t.atoms.length;let i=t.index,n="",o=Yh(t);for(o>=0&&o0?(n=`${De(n)}`,o<0&&Zh(t)&&(o=t.index,t.index+=1),Jt(n,t,r)||(t.mathML+=n,t.lastType="mtext"),!0):!1}function xb(t,e,r){e=e!=null?e:t.atoms.length;let i=t.index,n="",o=Yh(t);for(o>=0&&o"+n+"",o<0&&Zh(t)&&(o=t.index,t.index+=1),Jt(n,t,r)||(t.mathML+=n,t.lastType="mn"),!0)}function vb(t,e,r){let i=!1;e=e!=null?e:t.atoms.length;let n="",o="";if(t.index",n+=wi(t.atoms[l],r),n+=G(t.atoms,r,l+1,c),n+=wi(t.atoms[c],r),n+="",t.index=c+1,(t.lastType==="mi"||t.lastType==="mn"||t.lastType==="mfrac"||t.lastType==="fence")&&(t.mathML+=Ss),Jt(n,t,r)&&(i=!0,t.lastType="",n=""),o="fence")}return n.length>0&&(i=!0,t.mathML+=n,t.lastType=o),i}function _b(t,e,r){let i=!1;e=e!=null?e:t.atoms.length;let n="",o="",a=t.atoms[t.index];if(!a)return!1;let s={"\\ne":"≠","\\neq":"≠","\\pm":"±","\\times":"×","\\colon":":","\\vert":"|","\\Vert":"\u2225","\\mid":"\u2223","\\{":"{","\\}":"}","\\lbrace":"{","\\rbrace":"}","\\lbrack":"[","\\rbrack":"]","\\lparen":"(","\\rparen":")","\\langle":"\u27E8","\\rangle":"\u27E9","\\lfloor":"\u230A","\\rfloor":"\u230B","\\lceil":"\u2308","\\rceil":"\u2309"};if(s[a.command]){t.index+=1;let l=`${s[a.command]}`;return Jt(l,t,r)||(t.mathML+=l,t.lastType="mo"),!0}if(t.index"):a.superscript?(n+=""+l,n+=G(a.superscript,r),n+=""):a.subscript&&(n+=""+l,n+=G(a.subscript,r),n+=""),t.mathML+=n,t.lastType="mo",t.index+=1,!0}{let l=t.atoms[t.index],c=l.value==="\\operatorname",u=c?'"+kn(l.value)+"":wi(l,r);n+=u,!c&&!/^(.*)<\/mo>$/.test(u)?(n+=Xh,o="applyfunction"):o=c?"mi":"mo"}(t.lastType==="mi"||t.lastType==="mn")&&!/^(.*)<\/mo>$/.test(n)&&(n=Ss+n),t.index+=1}return n.length>0&&(i=!0,Jt(n,t,r)||(t.mathML+=n,t.lastType=o)),i}function G(t,e,r,i){e!=null||(e={});let n={atoms:[],index:r!=null?r:0,mathML:"",lastType:""};if(typeof t=="number"||typeof t=="boolean")n.mathML=t.toString();else if(typeof t=="string")n.mathML=t;else if(t instanceof x)n.mathML=Dc(t,e);else if(Array.isArray(t)){n.atoms=t;let o=0;for(i=i||(t?t.length:0);n.index0&&n.atoms[n.index].type==="genfrac"&&(a="⁤"+a),n.atoms[n.index].type==="genfrac"?n.lastType="mfrac":n.lastType="",n.index+=1,Jt(a,n,e)?o+=1:a.length>0&&(n.mathML+=a,o+=1)}o>1&&(n.mathML=""+n.mathML+"")}return n.mathML}function wi(t,e){let r="",i=kn(t.value);return i&&(r=""+i+""),r}function kn(t){if(!t)return"";if(typeof t=="string")return De(t);if(!Array.isArray(t)&&typeof t.body=="string")return De(t.body);let e="";for(let r of t)typeof r.value=="string"&&(e+=r.value);return De(e)}function Dc(t,e){var y,v,b,k,S,A,E,C,_,O,I,V,K,N,j,D,W,ie,X,ye,xe,Pe,Ct;if(t.mode==="text")return`${De(t.value)}`;let r={widehat:"^",widecheck:"\u02C7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",longleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",longrightarrow:"\u2192",underbrace:"\u23DF",overbrace:"\u23DE",overgroup:"\u23E0",undergroup:"\u23E1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21D2",xRightarrow:"\u21D2",overleftharpoon:"\u21BC",xleftharpoonup:"\u21BC",overrightharpoon:"\u21C0",xrightharpoonup:"\u21C0",xLeftarrow:"\u21D0",xLeftrightarrow:"\u21D4",xhookleftarrow:"\u21A9",xhookrightarrow:"\u21AA",xmapsto:"\u21A6",xrightharpoondown:"\u21C1",xleftharpoondown:"\u21BD",xrightleftharpoons:"\u21CC",longrightleftharpoons:"\u21CC",xleftrightharpoons:"\u21CB",xtwoheadleftarrow:"\u219E",xtwoheadrightarrow:"\u21A0",xlongequal:"=",xtofrom:"\u21C4",xleftrightarrows:"\u21C4",xRightleftharpoons:"\u21CC",longRightleftharpoons:"\u21CC",xLeftrightharpoons:"\u21CB",longLeftrightharpoons:"\u21CB"},i={"\\!":-3/18,"\\ ":6/18,"\\,":3/18,"\\:":4/18,"\\>":4/18,"\\;":5/18,"\\enspace":.5,"\\quad":1,"\\qquad":2,"\\enskip":.5},n="",o="",a,s,l,c,u,d,{command:m}=t;if(t.command==="\\error")return`${G(t.body,e)}`;let p={"\\vert":"|","\\Vert":"\u2225","\\mid":"\u2223","\\lbrack":"[","\\rbrack":"]","\\{":"{","\\}":"}","\\lbrace":"{","\\rbrace":"}","\\lparen":"(","\\rparen":")","\\langle":"\u27E8","\\rangle":"\u27E9","\\lfloor":"\u230A","\\rfloor":"\u230B","\\lceil":"\u2308","\\rceil":"\u2309"},f={"\\vec":"⃗","\\acute":"´","\\grave":"`","\\dot":"˙","\\ddot":"¨","\\tilde":"~","\\bar":"¯","\\breve":"˘","\\check":"ˇ","\\hat":"^"};switch(t.type){case"first":break;case"error":if(t.command==="\\\\")break;n=`${G(t.body,e)}`;break;case"group":case"root":n=G(t.body,e);break;case"array":let ue=t;if((ue.leftDelim&&ue.leftDelim!=="."||ue.rightDelim&&ue.rightDelim!==".")&&(n+="",ue.leftDelim&&ue.leftDelim!=="."&&(n+=`${De(p[ue.leftDelim]||ue.leftDelim)}`)),n+="",a=0;a"+G(ue.rows[s][a],e)+"";n+=""}n+="",(ue.leftDelim&&ue.leftDelim!=="."||ue.rightDelim&&ue.rightDelim!==".")&&(ue.rightDelim&&ue.rightDelim!=="."&&(n+=`${De(p[ue.rightDelim]||ue.rightDelim)}`),n+="");break;case"genfrac":let we=t;if((we.leftDelim||we.rightDelim)&&(n+=""),we.leftDelim&&we.leftDelim!=="."&&(n+=""+De(p[we.leftDelim]||we.leftDelim)+""),we.hasBarLine){let Oe=we.barThickness;Oe&&"dimension"in Oe?n+=``:n+="",n+=G(t.above,e)||" ",n+=G(t.below,e)||" ",n+=""}else n+="",n+=""+G(t.above,e)+"",n+=""+G(t.below,e)+"",n+="";we.rightDelim&&we.rightDelim!=="."&&(n+=""+De(p[we.rightDelim]||we.rightDelim)+""),(we.leftDelim||we.rightDelim)&&(n+="");break;case"surd":t.hasEmptyBranch("above")?(n+="",n+=G(t.body,e),n+=""):(n+="",n+=G(t.body,e),n+=G(t.above,e),n+="");break;case"leftright":let Xr=t,br=Xr.leftDelim;n="",br&&br!=="."&&(n+=`${De((y=p[br])!=null?y:br)}`),t.body&&(n+=G(t.body,e));let Vo=Xr.matchingRightDelim();Vo&&Vo!=="."&&(n+=`${De((v=p[Vo])!=null?v:Vo)}`),n+="";break;case"sizeddelim":case"delim":n+=`${De(p[t.value]||t.value)}`;break;case"accent":let nf=t;n+='",n+=G(t.body,e),n+=""+(f[m]||nf.accent)+"",n+="";break;case"line":case"overlap":break;case"overunder":let je=t;u=t.above,c=t.below,(je.svgAbove||u)&&(je.svgBelow||c)?d=t.body:u&&u.length>0?(d=t.body,(k=(b=t.body)==null?void 0:b[0])!=null&&k.below?(c=t.body[0].below,d=t.body[0].body):((A=(S=t.body)==null?void 0:S[0])==null?void 0:A.type)==="first"&&((C=(E=t.body)==null?void 0:E[1])!=null&&C.below)&&(c=t.body[1].below,d=t.body[1].body)):c&&c.length>0&&(d=t.body,(O=(_=t.body)==null?void 0:_[0])!=null&&O.above?(u=t.body[0].above,d=t.body[0].body):((V=(I=t.body)==null?void 0:I[0])==null?void 0:V.type)==="first"&&((N=(K=t.body)==null?void 0:K[1])!=null&&N.above)&&(u=t.body[1].above,d=t.body[1].body)),(je.svgAbove||u)&&(je.svgBelow||c)?(n+=``,n+=(j=r[je.svgBody])!=null?j:G(d,e),n+=(D=r[je.svgBelow])!=null?D:G(c,e),n+=(W=r[je.svgAbove])!=null?W:G(u,e),n+=""):je.svgAbove||u?(n+=``+((ie=r[je.svgBody])!=null?ie:G(d,e)),n+=(X=r[je.svgAbove])!=null?X:G(u,e),n+=""):(je.svgBelow||c)&&(n+=``+((ye=r[je.svgBody])!=null?ye:G(d,e)),n+=(xe=r[je.svgBelow])!=null?xe:G(c,e),n+="");break;case"placeholder":n+="?";break;case"mord":{if(n=typeof t.value=="string"?t.value:m,n.length>0&&n.startsWith("\\"))typeof t.value=="string"&&t.value.charCodeAt(0)>255?n=String.fromCodePoint(t.value.codePointAt(0)):typeof t.value=="string"&&(n=t.value.charAt(0));else if(t.command==="\\char"){let rl=(Pe=t.args)==null?void 0:Pe[0];if(rl!==void 0&&"number"in rl){let qo=rl.number;typeof qo=="number"&&qo>=0&&qo<=1114111&&(n=String.fromCodePoint(qo))}}else typeof t.value=="string"?n=t.value:(console.error("Did not expect this"),n="");let Oe=/\d/.test(n)?"mn":"mi";n=`<${Oe}${re(t.id,e)}>${De(n)}`;break}case"mbin":case"mrel":case"minner":n=wi(t,e);break;case"mpunct":n='"+m+"";break;case"mop":case"operator":case"extensible-symbol":t.value!=="\u200B"&&(n="",n+=m==="\\operatorname"?t.body:m||t.body,n+="");break;case"box":let el=t;n='"+G(t.body,e)+"";break;case"spacing":n+='';break;case"enclose":let tl=t;n=''+G(t.body,e)+"";break;case"prompt":n=''+G(t.body,e)+"";break;case"space":n+=" ";break;case"subsup":break;case"phantom":break;case"composition":break;case"rule":break;case"chem":break;case"mopen":n+=wi(t,e);break;case"mclose":n+=wi(t,e);break;case"macro":{let Oe=t.command+kn(t.macroArgs);Oe&&(n+=`${Oe}`)}break;case"latexgroup":n+=G(t.body,e);break;case"latex":n+=""+De(t.value)+"";break;case"tooltip":n+=G(t.body,e);break;case"text":n+=`${De(t.value)}`;break;default:if(t.command==="\\displaystyle")return`${G(t.body,e)}`;if(t.command==="\\textstyle")return`${G(t.body,e)}`;console.info("Unexpected element in conversion to MathML:",t)}return n}var Ln={"\\alpha":"alpha ","\\mu":"mew ","\\sigma":"sigma ","\\pi":"pie ","\\imaginaryI":"imaginary eye ","\\imaginaryJ":"imaginary jay ","\\sum":"Summation ","\\prod":"Product ","+":"plus ","-":"minus ",";":' semi-colon ',",":' comma ',"|":'Vertical bar',"(":'Open paren. ',")":' Close paren. ',"=":"equals ","<":"is less than ","\\lt":"is less than ","<=":"is less than or equal to ","\\le":"is less than or equal to ","\\gt":"is greater than ",">":"is greater than ","\\pm":"plus or minus","\\mp":"minus or plus","\\ge":"is greater than or equal to ","\\geq":"is greater than or equal to ","\\leq":"is less than or equal to ","\\ne":"is not equal to ","\\neq":"is not equal to ","!":"factorial ","\\sin":"sine ","\\cos":"cosine ","\u200B":"","\u2212":"minus ",":":' such that ',"\\colon":' such that ',"\\hbar":"etch bar ","\\iff":'if, and only if, ',"\\Longleftrightarrow":'if, and only if, ',"\\land":"and ","\\lor":"or ","\\neg":"not ","\\div":"divided by ","\\forall":"for all ","\\exists":"there exists ","\\nexists":"there does not exists ","\\in":"element of ","\\N":'the set n',"\\C":'the set c',"\\Z":'the set z',"\\Q":'the set q',"\\infty":"infinity ","\\nabla":"nabla ","\\partial":"partial derivative of ","\\cdot":"times ","\\cdots":"dot dot dot ","\\Rightarrow":"implies ","\\lparen":'open paren',"\\rparen":'close paren',"\\lbrace":'open brace',"\\{":'open brace',"\\rbrace":'close brace',"\\}":'close brace',"\\langle":'left angle bracket',"\\rangle":'right angle bracket',"\\lfloor":'open floor',"\\rfloor":'close floor',"\\lceil":'open ceiling',"\\rceil":'close ceiling',"\\vert":'vertical bar',"\\mvert":'divides',"\\lvert":'left vertical bar',"\\rvert":'right vertical bar',"\\lbrack":' open square bracket ',"\\rbrack":' close square bracket ',mm:"millimeters",cm:"centimeters",km:"kilometers",kg:"kilograms"},Oc={array:"array",matrix:"matrix",pmatrix:"parenthesis matrix",bmatrix:"square brackets matrix",Bmatrix:"braces matrix",vmatrix:"bars matrix",Vmatrix:"double bars matrix","matrix*":"matrix",smallmatrix:"small matrix"};function Mb(t){let e="";return t.startsWith("\\")&&(e=" "+t.replace("\\","")+" "),e}function _o(t){let e=0;if(ee(t))for(let r of t)r.type!=="first"&&(e+=1);return e===1}function wb(t){if(ee(t)){for(let e of t)if(e.type!=="first"&&e.id)return e.id.toString()}return""}function Qh(t){let e="";if(ee(t))for(let r of t)r.type!=="first"&&typeof r.value=="string"&&(e+=r.value);return e}function Sb(t){return t?t.map(e=>e.value).join(""):""}function ks(t){if(t&&!t.some(e=>e.type!=="first"&&e.value===void 0))return t.map(e=>e.value).join("")}function Bc(t){return`${t}`}function kb(t,e){var o;let r="",i=!1,n=!1;for(let a=0;a/g,">"):t:""}function q(t,e){var c,u,d,m,p,f,y,v;function r(b){return globalThis.MathfieldElement.textToSpeechMarkup?/[a-z]/.test(b)?` ${b}`:/[A-Z]/.test(b)?`capital ${b.toLowerCase()}`:b:/[a-z]/.test(b)?" '"+b.toUpperCase()+"'":/[A-Z]/.test(b)?" 'capital "+b.toUpperCase()+"'":b}if(!e)return"";if(ee(e))return kb(t,e);let i="";if(e.id&&t==="math"&&(i+=''),e.mode==="text")return i+ep(e.value);let n="",o="",a="",s=!1,{command:l}=e;switch(l){case"\\vec":return"vector "+q(t,e.body);case"\\acute":return q(t,e.body)+" acute";case"\\grave":return q(t,e.body)+" grave";case"\\dot":return"dot over"+q(t,e.body);case"\\ddot":return"double dot over"+q(t,e.body);case"\\mathring":return"ring over"+q(t,e.body);case"\\tilde":case"\\widetilde":return"tilde over"+q(t,e.body);case"\\bar":return q(t,e.body)+" bar";case"\\breve":return q(t,e.body)+" breve";case"\\check":case"\\widecheck":return"check over "+q(t,e.body);case"\\hat":case"\\widehat":return"hat over"+q(t,e.body);case"\\overarc":case"\\overparen":case"\\wideparen":return"arc over "+q(t,e.body);case"\\underarc":case"\\underparen":return"arc under "+q(t,e.body);case"\\mathop":return(c=ks(e.body))!=null?c:q(t,e.body);case"\\mathit":return(u=ks(e.body))!=null?u:q(t,e.body);case"\\mathrm":return(d=ks(e.body))!=null?d:q(t,e.body);case"\\mathbb":return"blackboard"+((m=ks(e.body))!=null?m:q(t,e.body))}switch(e.type){case"prompt":let b=e.body.length>1?'start input . '+q(t,e.body)+'. end input':"blank";i+=' '+b+'. '+((p=e.correctness)!=null?p:"")+' . ';break;case"array":let k=e.rows,S=e.environmentName;if(Object.keys(Oc).includes(S)){i+=` begin ${Oc[S]} `;for(let C=0;C0&&(i+=","),i+=` row ${C+1} `;for(let _=0;_0&&(i+=","),i+=` column ${_+1}: `,i+=q("math",k[C][_])}i+=` end ${Oc[S]} `}break;case"group":l==="\\ne"?i+=" not equal ":(l==="\\not"&&(i+=" not "),i+=q("math",e.body));break;case"root":i+=q("math",e.body);break;case"genfrac":if(n=q("math",e.above),o=q("math",e.below),_o(e.above)&&_o(e.below)){let _={"1/2":" half ","1/3":" one third ","2/3":" two third","1/4":" one quarter ","3/4":" three quarter ","1/5":" one fifth ","2/5":" two fifths ","3/5":" three fifths ","4/5":" four fifths ","1/6":" one sixth ","5/6":" five sixths ","1/8":" one eight ","3/8":" three eights ","5/8":" five eights ","7/8":" seven eights ","1/9":" one ninth ","2/9":" two ninths ","4/9":" four ninths ","5/9":" five ninths ","7/9":" seven ninths ","8/9":" eight ninths "}[Qh(e.above)+"/"+Qh(e.below)];_?i=_:i+=n+" over "+o}else i+=' the fraction '+n+' over '+o+'. End fraction.';break;case"surd":if(a=q("math",e.body),e.hasEmptyBranch("above"))i+=_o(e.body)?" the square root of "+a+" , ":' the square root of '+a+'. End square root';else{let C=q("math",e.above);C=C.trim();let _=C.replace(//g,"");_==="3"?i+=' the cube root of '+a+'. End cube root':_==="n"?i+=' the nth root of '+a+'. End root':i+=' the root with index: '+C+', of '+a+'. End root'}break;case"leftright":{let C=e;i+=(f=C.leftDelim?Ln[C.leftDelim]:void 0)!=null?f:C.leftDelim,i+=q("math",e.body),i+=(y=C.rightDelim?Ln[C.rightDelim]:void 0)!=null?y:C.rightDelim}break;case"rule":break;case"overunder":break;case"overlap":break;case"macro":let A=l.replace(/^\\/g,""),E=Ri()[A];E!=null&&E.expand?i+=q("math",e.body):i+=`${A} `;break;case"placeholder":i+="placeholder ";break;case"delim":case"sizeddelim":case"mord":case"minner":case"mbin":case"mrel":case"mpunct":case"mopen":case"mclose":{if(l==="\\mathbin"||l==="\\mathrel"||l==="\\mathopen"||l==="\\mathclose"||l==="\\mathpunct"||l==="\\mathord"||l==="\\mathinner"){i=q(t,e.body);break}let C=e.isDigit()?e.asDigit():e.value,_=e.command;if((e.type==="delim"||e.type==="sizeddelim")&&(_=e.value,C=_),t==="text")i+=ep(C);else{if(e.type==="mbin"&&(i+=''),C){let O=Ln[C]||(_?Ln[_.trim()]:"");if(O)i+=" "+O;else{let I=_?Mb(_.trim()):"";i+=I||r(C)}}else i+=q("math",e.body);e.type==="mbin"&&(i+='')}break}case"mop":case"operator":case"extensible-symbol":if(e.value!=="\u200B"){let C=e.command;if(C==="\\sum")if(!e.hasEmptyBranch("superscript")&&!e.hasEmptyBranch("subscript")){let _=q("math",e.superscript);_=_.trim();let O=q("math",e.subscript);O=O.trim(),i+=' the summation from '+O+' to '+_+' of ',s=!0}else if(e.hasEmptyBranch("subscript"))i+=" the summation of";else{let _=q("math",e.subscript);_=_.trim(),i+=' the summation from '+_+' of ',s=!0}else if(C==="\\prod")if(!e.hasEmptyBranch("superscript")&&!e.hasEmptyBranch("subscript")){let _=q("math",e.superscript);_=_.trim();let O=q("math",e.subscript);O=O.trim(),i+=' the product from '+O+' to '+_+' of ',s=!0}else if(e.hasEmptyBranch("subscript"))i+=" the product of ";else{let _=q("math",e.subscript);_=_.trim(),i+=' the product from '+_+' of ',s=!0}else if(C==="\\int")if(!e.hasEmptyBranch("superscript")&&!e.hasEmptyBranch("subscript")){let _=q("math",e.superscript);_=_.trim();let O=q("math",e.subscript);O=O.trim(),i+=' the integral from '+Bc(O)+' to '+Bc(_)+' of ',s=!0}else i+=' the integral of ';else if(C==="\\operatorname"||C==="\\operatorname*")i+=Sb(e.body)+" ";else if(typeof e.value=="string"){let _=(v=Ln[e.value])!=null?v:e.command?Ln[e.command]:void 0;i+=_||" "+e.value}else e.command&&(e.command==="\\mathop"?i+=q("math",e.body):i+=e.command.startsWith("\\")?" "+e.command.slice(1):" "+e.command)}break;case"enclose":a=q("math",e.body),i+=" crossed out "+a+". End crossed out.";break;case"space":case"spacing":break}if(!s&&!e.hasEmptyBranch("superscript")){let b=q(t,e.superscript);b=b.trim();let k=b.replace(/<[^>]*>/g,"");if(_o(e.superscript)){if(t==="math"){let S=wb(e.superscript);S&&(i+='')}k==="\u2032"?i+=" prime ":k==="2"?i+=" squared ":k==="3"?i+=" cubed ":Number.isNaN(Number.parseInt(k))?i+=" to the "+b+"; ":i+=' to the '+k+" power; "}else Number.isNaN(Number.parseInt(k))?i+=" raised to the "+b+"; ":i+=' raised to the '+k+" power; "}if(!s&&!e.hasEmptyBranch("subscript")){let b=q("math",e.subscript);b=b.trim(),i+=_o(e.subscript)?" sub "+b:" subscript "+b+". End subscript. "}return i}function wt(t){var i,n;let e=globalThis.MathfieldElement;if(e.textToSpeechRules==="sre"&&("sre"in window||"SRE"in window)){let o=G(t);if(o){e.textToSpeechMarkup&&(e.textToSpeechRulesOptions=(i=e.textToSpeechRulesOptions)!=null?i:{},e.textToSpeechRulesOptions=g(h({},e.textToSpeechRulesOptions),{markup:e.textToSpeechMarkup}),e.textToSpeechRulesOptions.markup==="ssml"&&(e.textToSpeechRulesOptions=g(h({},e.textToSpeechRulesOptions),{markup:"ssml_step"})),e.textToSpeechRulesOptions=g(h({},e.textToSpeechRulesOptions),{rate:e.speechEngineRate}));let a=(n=window.SRE)!=null?n:globalThis.sre.System.getInstance();e.textToSpeechRulesOptions&&a.setupEngine(e.textToSpeechRulesOptions);let s="";try{s=a.toSpeech(o)}catch(l){console.error("MathLive 0.111.1: `SRE.toSpeech()` runtime error",l)}return s}return""}let r=q("math",t);if(e.textToSpeechMarkup==="ssml"){let o="";e.speechEngineRate&&(o=''),r=''+o+"

    "+r+"

    "+(o?"
    ":"")+""}else e.textToSpeechMarkup==="mac"&&Et()==="macos"?r=r.replace(//g,"").replace(//g,"[[emph+]]").replace(/<\/emphasis>/g,"").replace(//g,"[[slc $1]]").replace(/]*>/g,"").replace(/<\/say-as>/g,""):r=r.replace(/<[^>]*>/g,"").replace(/\s{2,}/g," ");return r}function Wr(t,e){return typeof t=="string"?t+wt(e):wt(t)}var tp="math input field";function Kc(t,e){var i;if(t===e)return"";if(t.nodeType===Node.TEXT_NODE)return(i=t.textContent)!=null?i:"";let r="";for(let n of Array.from(t.childNodes))r+=Kc(n,e);return r}function Rc(t){var l;if(!t)return tp;let e=t.getRootNode(),r=c=>(c!=null?c:"").replace(/\s+/g," ").trim(),i=t.getAttribute("aria-labelledby");if(i&&typeof e.getElementById=="function"){let c=r(i.split(/\s+/).map(u=>e.getElementById(u)).map(u=>u?Kc(u,t):"").join(" "));if(c)return c}let n=r(t.getAttribute("aria-label"));if(n)return n;let o=[];if(t.id&&typeof e.querySelectorAll=="function")for(let c of Array.from(e.querySelectorAll("label[for]")))c.getAttribute("for")===t.id&&o.push(c);let a=(l=t.parentElement)==null?void 0:l.closest("label");a&&o.push(a);let s=r(o.map(c=>Kc(c,t)).join(" "));return s||r(t.getAttribute("title"))||tp}function Pc(t){var r;let e;if(t.parent.type==="prompt")t.parentBranch==="body"&&(e="prompt");else if(t.parentBranch==="body"){if(t.type==="first"&&(t.parent.type==="root"?e="mathfield":t.parent.type==="surd"?e="radicand":t.parent.type==="genfrac"?e="fraction":t.parent.type==="sizeddelim"&&(e="delimiter"),e))return e;t.type==="subsup"?t.superscript&&t.subscript?e="superscript and subscript":t.superscript?e="superscript":t.subscript&&(e="subscript"):t.type&&(e=(r={accent:"accented",array:"array",box:"box",chem:"chemical formula",delim:"delimiter",enclose:"cross out","extensible-symbol":"extensible symbol",error:"error",first:"first",genfrac:"fraction",group:"group",latex:"LaTeX",leftright:"delimiter",line:"line",subsup:"subscript-superscript",operator:"operator",overunder:"over-under",placeholder:"placeholder",rule:"rule",sizeddelim:"delimiter",space:"space",spacing:"spacing",surd:"square root",text:"text",prompt:"prompt",root:"math field",mop:"operator"}[t.type])!=null?r:"parent")}else if(t.parent.type==="genfrac"){if(t.parentBranch==="above")return"numerator";if(t.parentBranch==="below")return"denominator"}else t.parent.type==="surd"?t.parentBranch==="above"&&(e="index"):t.parentBranch==="superscript"?e="superscript":t.parentBranch==="subscript"&&(e="subscript");return e!=null?e:"parent"}function rp(t,e,r,i){let n="";if(e==="plonk"){globalThis.MathfieldElement.playSound("plonk"),t.flushInlineShortcutBuffer();return}if(e==="delete")n=Wr("deleted: ",i);else if(e==="focus"||e.includes("move"))n=Lb(t.model,r),n+=Ab(t.model);else if(e==="replacement")n=Wr(t.model.at(t.model.position));else if(e==="line"){let o=Wr(t.model.root).trim(),a=Rc(t.host);t.keyboardDelegate.setAriaLabel(o?`${a}: ${o}`:a)}else n=i?Wr(e+" ",i):e;if(n&&t.ariaLiveText){let o=t.ariaLiveText.textContent.includes("\xA0")?" \u202F ":" \xA0 ";t.ariaLiveText.textContent=n+o}}function Lb(t,e){if(Number.isNaN(e))return"";let r=t.at(e);if(!r||r.treeDepth<=t.at(t.position).treeDepth)return"";let i="",n=r.parent,o=t.at(t.position).parent;for(;n!==t.root&&n!==o;)i+=`out of ${Pc(n)};`,n=n.parent;return i}function Ab(t){if(!t.selectionIsCollapsed)return`selected: ${Wr(t.getAtoms(t.selection))}`;let e="",r=t.at(t.position);if(r.isFirstSibling&&(e=`start of ${Pc(r)}: `),r.isLastSibling){if(!r.isFirstSibling){if(!r.parent.parent)return`${Wr(r)}; end of mathfield`;e=`${Wr(r)}; end of ${Pc(r)}`}}else e+=Wr(r);return e}function ip(t,e){let r=t.at(t.position);if(r.type==="composition")r.value=e;else{let{caret:i}=r;r.caret=void 0;let n=new sn(e,{mode:r.mode});n.caret=i,r.parent.addChildAfter(n,r),t.position+=1}}function np(t){let e=t.at(t.position);e.type==="composition"&&(e.parent.removeChild(e),t.position-=1)}function Cb(t){let e=t.at(t.position);for(;e&&!Ze(e.parentBranch);)e=e.parent;return[e.firstSibling,e.lastSibling]}function Eb(t,e){let r=t.at(t.position);for(;r&&!(r.parent instanceof z);)r=r.parent;if((r==null?void 0:r.type)==="array"&&r.environmentName,!r||!(r.parent instanceof z)){let i=t.at(t.position);if(r=i,!r.parent.parent){let n=t.extractAtoms([t.position,t.lastOffset]),o=t.extractAtoms([0,t.position]),a;return e.endsWith("column")?(o.length===0&&(o=As()),n.length===0&&(n=As()),a=ze("split",[[o,n]]),t.root=a,Mo(a,0,0)?An(t,a,0,0):Mo(a,0,1)?An(t,a,0,1):t.position=t.offsetOf(i)):(a=ze("lines",[[o],[n]]),t.root=a,An(t,a,1,0)),[void 0,[0,0]]}if(r.parent instanceof J){let n=r.parent,o=t.extractAtoms([t.position,t.offsetOf(n.lastChild)]),a=t.extractAtoms([t.offsetOf(n.firstChild),t.position]);a.length===0&&(a=As()),o.length===0&&(o=As());let s="pmatrix",l=n.leftDelim,c=n.rightDelim;l==="("&&(c===")"||c==="?")?s="pmatrix":(l==="["||l==="\\lbrack")&&(c==="]"||c==="\\rbrack"||c==="?")?s="bmatrix":l==="\\vert"&&c==="\\vert"?s="vmatrix":l==="\\Vert"&&c==="\\Vert"?s="Vmatrix":(l==="{"||l==="\\lbrace")&&(c==="."||c==="?")&&(s="cases");let u=ze(s,e.endsWith("column")?[[a,o]]:[[a],[o]]);return n.parent.addChildBefore(u,n),n.parent.removeChild(n),Mo(u,0,0)?An(t,u,0,0):e.endsWith("column")?Mo(u,0,1)?An(t,u,0,1):t.position=t.offsetOf(r):Mo(u,1,0)?An(t,u,1,0):t.position=t.offsetOf(r),[void 0,[0,0]]}}return r&&r.parent instanceof z?[r.parent,r.parentBranch]:[void 0,[0,0]]}function Mo(t,e,r){let i=t.getCell(e,r);return(i==null?void 0:i.length)!==2?!1:i[1].type==="placeholder"}function Tb(t,e,r,i){let n=e.getCell(r,i);return n?[t.offsetOf(n[0]),t.offsetOf(n[n.length-1])]:-1}function An(t,e,r,i){let n=Tb(t,e,r,i);typeof n!="number"&&t.setSelection(n)}function Ls(t,e,r,i,n){let o=e.getCell(r,i);o&&t.setPositionHandlingPlaceholder(t.offsetOf(o[n==="start"?0:o.length-1]))}function wo(t,e){let[r,[i,n]]=Eb(t,e);if(r)switch(e){case"after row":r.addRowAfter(i),Ls(t,r,i+1,0,"end");break;case"after column":if(r.maxColumns<=r.colCount){t.announce("plonk");return}r.addColumnAfter(n),Ls(t,r,i,n+1,"end");break;case"before row":r.addRowBefore(i),Ls(t,r,i,0,"start");break;case"before column":if(r.maxColumns<=r.colCount){t.announce("plonk");return}r.addColumnBefore(n),Ls(t,r,i,n,"start");break}}function Ic(t){var r;let e=t.at(t.position);if(!Ze(e.parentBranch)&&e.parent!==t.root&&t.root.type!=="root")return t.announce("plonk"),!1;if(!t.contentWillChange({inputType:"insertText"}))return!1;if((r=t.parentEnvironment)!=null&&r.isMultiline){t.selectionIsCollapsed||t.deleteAtoms(de(t.selection));let[i,n]=Cb(t),o=t.extractAtoms([t.position,t.offsetOf(n)]),a=t.extractAtoms([t.offsetOf(i),t.position]),s=i.parent,[l,c]=i.parentBranch;return s.setCell(l,c,a),wo(t,"after row"),s.setCell(l+1,c,o),t.position=t.offsetOf(s.getCell(l+1,c)[0]),t.contentDidChange({inputType:"insertText"}),!0}return wo(t,"after row"),t.contentDidChange({inputType:"insertText"}),!0}function Db(t){return t.contentWillChange({inputType:"insertText"})?(wo(t,"before row"),t.contentDidChange({inputType:"insertText"}),!0):!1}function zc(t){return t.contentWillChange({inputType:"insertText"})?(wo(t,"after column"),t.contentDidChange({inputType:"insertText"}),!0):!1}function Ob(t){return t.contentWillChange({inputType:"insertText"})?(wo(t,"before column"),t.contentDidChange({inputType:"insertText"}),!0):!1}function Nc(t,e){if(!t.contentWillChange({}))return!1;t.mathfield.snapshot();let r=".",i=".";switch(e){case"pmatrix":case"pmatrix*":r="(",i=")";break;case"bmatrix":case"bmatrix*":r="[",i="]";break;case"Bmatrix":case"Bmatrix*":r="\\lbrace",i="\\rbrace";break;case"vmatrix":case"vmatrix*":r="\\vert",i="\\vert";break;case"Vmatrix":case"Vmatrix*":r="\\Vert",i="\\Vert";break;case"matrix":case"matrix*":r=".",i=".";break;case"cases":case"dcases":r="\\lbrace";break;case"rcases":i="\\rbrace";break}let n=t.at(t.position),o=n.type==="array"?n:t.parentEnvironment;return o.environmentName=e,o.leftDelim=r,o.rightDelim=i,t.contentDidChange({}),!0}function op(t,e){let r=t.at(t.position);for(;r&&!(Array.isArray(r.parentBranch)&&r.parent instanceof z);)r=r.parent;if(Array.isArray(r==null?void 0:r.parentBranch)&&(r==null?void 0:r.parent)instanceof z){let i=r.parent,n=r.parentBranch,o;switch(e){case"row":if(i.rowCount>1){i.removeRow(n[0]);let a=i.getCell(Math.max(0,n[0]-1),n[1]);o=t.offsetOf(a[a.length-1])}break;case"column":if(i.colCount>i.minColumns){i.removeColumn(n[1]);let a=i.getCell(n[0],Math.max(0,n[1]-1));o=t.offsetOf(a[a.length-1])}break}o!==void 0&&t.setPositionHandlingPlaceholder(o)}}function Bb(t){return t.contentWillChange({inputType:"deleteContent"})?(op(t,"row"),t.contentDidChange({inputType:"deleteContent"}),!0):!1}function Kb(t){return t.contentWillChange({inputType:"deleteContent"})?(op(t,"column"),t.contentDidChange({inputType:"deleteContent"}),!0):!1}fe({addRowAfter:Ic,addColumnAfter:zc,addRowBefore:Db,addColumnBefore:Ob,removeRow:Bb,removeColumn:Kb,setEnvironment:Nc},{target:"model",canUndo:!0,changeContent:!0,changeSelection:!0});function As(){return[new Me]}var Es=class Es{constructor(e){this.recording=!1;this.model=e,this.reset()}reset(){this.stack=[],this.index=-1,this.lastOp=""}startRecording(){this.recording=!0}stopRecording(){this.recording=!1}canUndo(){return this.index-1>=0}canRedo(){return this.stack.length-1>this.index}stopCoalescing(e){e&&this.index>=0&&(this.stack[this.index].selection=e),this.lastOp=""}undo(){if(!this.canUndo())return!1;let e=this.stack[this.index-1];return this.index-=1,this.lastOp="",this.model.setState(e,{silenceNotifications:!1,type:"undo"}),!0}redo(){if(!this.canRedo())return!1;let e=this.stack[this.index+1];return this.index+=1,this.lastOp="",this.model.setState(e,{silenceNotifications:!1,type:"redo"}),!0}pop(){this.canUndo()&&(this.stack.splice(this.index,this.stack.length-this.index),this.index-=1)}snapshot(e){return this.recording?(e&&e===this.lastOp&&this.pop(),this.stack.splice(this.index+1,this.stack.length-this.index-1),this.stack.push(this.model.getState()),this.index+=1,this.stack.length>Es.maximumDepth&&(this.stack.shift(),this.index-=1),this.lastOp=e!=null?e:"",!0):!1}};Es.maximumDepth=1e3;var Cs=Es;function So(t,e,r,i){var o,a,s,l,c,u;let n=r.parent;if(Ze(i)&&r instanceof z&&r.isMultiline&&Pb(t,r,i[0],e))return!0;if(n&&r instanceof J){let d=!i&&e==="forward"||i==="body"&&e==="backward",m=d?t.offsetOf(r.firstChild):t.offsetOf(r.lastChild);return d?r.rightDelim!=="?"&&r.rightDelim!=="."?(r.leftDelim=".",r.isDirty=!0):(n.addChildrenAfter(r.removeBranch("body"),r),n.removeChild(r),m--):r.leftDelim!=="?"&&r.leftDelim!=="."?(r.rightDelim=".",r.isDirty=!0):(n.addChildrenAfter(r.removeBranch("body"),r),n.removeChild(r),m--),t.position=m,!0}if(n&&r.type==="surd"){if(e==="forward"&&!i||e==="backward"&&i==="body"){let d=r.leftSibling;r.hasChildren&&n.addChildrenAfter(r.removeBranch("body"),r),n.removeChild(r),t.position=t.offsetOf(d)}else e==="forward"&&i==="body"?t.position=t.offsetOf(r):!i&&e==="backward"?r.hasChildren?t.position=t.offsetOf(r.lastChild):(t.position=Math.max(0,t.offsetOf(r)-1),n.removeChild(r)):i==="above"&&(r.hasEmptyBranch("above")&&r.removeBranch("above"),e==="backward"?t.position=t.offsetOf(r.leftSibling):t.position=t.offsetOf(r.body[0]));return!0}if(n&&(r.type==="box"||r.type==="enclose")){let d=i&&e==="backward"||!i&&e==="forward"?r.leftSibling:r.lastChild;return n.addChildrenAfter(r.removeBranch("body"),r),n.removeChild(r),t.position=t.offsetOf(d),!0}if(r.type==="genfrac"||r.type==="overunder"){if(!i)return r.type==="overunder"&&r.hasEmptyBranch("body")||r.type==="genfrac"&&r.hasEmptyBranch("below")&&r.hasEmptyBranch("above")?!1:(t.position=t.offsetOf(e==="forward"?r.firstChild:r.lastChild),!0);let d=lt.fractionNavigationOrder==="numerator-denominator"?"above":"below",m=d==="above"?"below":"above";if(n&&(e==="forward"&&i===d||e==="backward"&&i===m)){let p=r.removeBranch(d),f=r.removeBranch(m);return n.addChildrenAfter([...p,...f],r),n.removeChild(r),t.position=t.offsetOf(p.length>0?p[p.length-1]:f[0]),!0}return e==="backward"?t.position=t.offsetOf(r.leftSibling):t.position=t.offsetOf(r),!0}if(r.type==="extensible-symbol"||r.type==="subsup"||r.type==="operator"){if(!i&&e==="forward")return!1;if(!i){if(r.subscript||r.superscript){let d=e==="forward"?(s=(o=r.subscript)==null?void 0:o[0])!=null?s:(a=r.superscript)==null?void 0:a[0]:(u=(l=r.superscript)==null?void 0:l[0].lastSibling)!=null?u:(c=r.subscript)==null?void 0:c[0].lastSibling;return d&&(t.position=t.offsetOf(d)),!0}return!1}if(!r.hasChildren&&r.type==="subsup"){let d=e==="forward"?t.offsetOf(r):Math.max(0,t.offsetOf(r)-1);return r.parent.removeChild(r),t.position=d,!0}if(i&&r.hasEmptyBranch(i)){if(r.removeBranch(i),r.type==="subsup"&&!r.subscript&&!r.superscript){let d=e==="forward"?t.offsetOf(r):Math.max(0,t.offsetOf(r)-1);return r.parent.removeChild(r),t.position=d,!0}return i==="subscript"&&e==="backward"?t.position=t.offsetOf(r.firstChild)-1:i==="superscript"&&e==="backward"?r.subscript?t.position=t.offsetOf(r.subscript[0].lastSibling):t.position=t.offsetOf(r.firstChild)-1:t.position=t.offsetOf(r),!0}if(i==="subscript")if(e==="backward"){let d=t.offsetOf(r.firstChild)-1;d>=0,t.position=d}else r.superscript?t.position=t.offsetOf(r.superscript[0]):t.position=t.offsetOf(r);else i==="superscript"&&(e==="backward"&&r.subscript?t.position=t.offsetOf(r.subscript[0].lastSibling):e==="backward"?t.position=t.offsetOf(r.firstChild)-1:t.position=t.offsetOf(r));return!0}if((n==null?void 0:n.type)==="genfrac"&&!i&&r.type!=="first"){let d=t.offsetOf(r.leftSibling);return n.removeChild(r),n.hasEmptyBranch("above")&&n.hasEmptyBranch("below")?(d=t.offsetOf(n.leftSibling),n.parent.removeChild(n),t.announce("delete",void 0,[n]),t.position=d,!0):(t.announce("delete",void 0,[r]),t.position=d,!0)}if(e==="backward"&&((n==null?void 0:n.command)==="\\ln"||(n==null?void 0:n.command)==="\\log")&&r.parentBranch!=="body"){let d=t.offsetOf(n.leftSibling);return n.parent.removeChild(n),t.announce("delete",void 0,[n]),t.position=d,!0}return!1}function ap(t){return!t.mathfield.isSelectionEditable||!t.contentWillChange({inputType:"deleteContentBackward"})?!1:t.selectionIsCollapsed?t.deferNotifications({content:!0,selection:!0,type:"deleteContentBackward"},()=>{var i;let e=t.at(t.position);if(e&&So(t,"backward",e))return;if(e!=null&&e.isFirstSibling){if(So(t,"backward",e.parent,e.parentBranch))return;e=null}if(!e){t.announce("plonk");return}let r=e.parent;if(t.position=t.offsetOf(e.leftSibling),r.removeChild(e),t.announce("delete",void 0,[e]),r.type==="latexgroup"&&r.hasEmptyBranch("body")){let n=t.offsetOf(r.leftSibling);(i=r.parent)==null||i.removeChild(r),t.position=Math.max(0,n)}t.root.hasEmptyBranch("body")&&t.mathfield.flushInlineShortcutBuffer()}):ct(t,de(t.selection),"deleteContentBackward")}function sp(t){return!t.mathfield.isSelectionEditable||!t.contentWillChange({inputType:"deleteContentForward"})?!1:t.selectionIsCollapsed?t.deferNotifications({content:!0,selection:!0,type:"deleteContentForward"},()=>{var n,o,a;let e=t.at(t.position).rightSibling;if(e&&So(t,"forward",e))return;if(e){if(t.at(t.position).isLastSibling&&So(t,"forward",e.parent,e.parentBranch))return}else{if(e=t.at(t.position),e.isLastSibling&&So(t,"forward",e.parent,e.parentBranch))return;e=void 0}if(t.position===t.lastOffset||!e){t.announce("plonk");return}let r=e.parent;r.removeChild(e);let i=(n=t.at(t.position))==null?void 0:n.rightSibling;for(;(i==null?void 0:i.type)==="subsup";)i.parent.removeChild(i),i=(o=t.at(t.position))==null?void 0:o.rightSibling;if(t.announce("delete",void 0,[e]),r.type==="latexgroup"&&r.hasEmptyBranch("body")){let s=t.offsetOf(r.leftSibling);(a=r.parent)==null||a.removeChild(r),t.position=Math.max(0,s)}t.root.hasEmptyBranch("body")&&t.mathfield.flushInlineShortcutBuffer()}):ct(t,de(t.selection),"deleteContentForward")}function ct(t,e,r){let i=t.getAtoms(e);if(i.length>0&&i[0].parent){let n=i[0];for(;n&&!(n instanceof z);)n=n.parent;let o=i[i.length-1];for(;o&&!(o instanceof z);)o=o.parent;if(n&&n instanceof z){let u=n;if(u&&o===u&&u.isMultiline){let[d,m]=[Math.min(t.position,t.anchor),Math.max(t.position,t.anchor)],[p,f]=t.at(d).parentBranch,[y,v]=t.at(m).parentBranch;if(y-p+1>=2)return t.deferNotifications({content:!0,selection:!0,type:r},()=>{var _;let k=u.getCell(p,f),S=u.getCell(y,v);if(!k||!S)return;t.extractAtoms([d,m]);let A=u.getCell(p,f),E=u.getCell(y,v);for(let O=y-1;O>p;O--)u.removeRow(O);if(p!==y){let O=u.getCell(p+1,f);if(A&&O){let I=[...A.filter(V=>V.type!=="first"),...O.filter(V=>V.type!=="first")];u.setCell(p,f,I),u.removeRow(p+1)}}let C=u.getCell(p,f);if(C){let O=A?A.filter(I=>I.type!=="first").length:0;t.position=t.offsetOf((_=C[O])!=null?_:C[0])}else t.position=d;u.isDirty=!0})}}let a=i[0].parent.firstChild;a.type==="first"&&(a=a.rightSibling);let s=i[i.length-1].parent.lastChild,l=i[0];l.type==="first"&&(l=l.rightSibling);let c=i[i.length-1];if(l===a&&c===s){let u=i[0].parent;u.parent&&u.type!=="prompt"&&(e=[t.offsetOf(u.leftSibling),t.offsetOf(u)])}if(i.length===1&&i[0].type==="placeholder"&&i[0].parent.type==="genfrac"){let u=i[0].parent,d=i[0].parentBranch==="below"?"above":"below",m=t.offsetOf(u.leftSibling);return t.deferNotifications({content:!0,selection:!0,type:r},()=>{var f,y;let p=u.removeBranch(d);if(p.length===1&&p[0].type==="placeholder")(y=u.parent)==null||y.removeChild(u),t.position=Math.max(0,m);else{let v=u.parent.addChildrenAfter(p,u);(f=u.parent)==null||f.removeChild(u),t.position=t.offsetOf(v)}})}}return t.deferNotifications({content:!0,selection:!0,type:r},()=>{let n=new Map;if(i.length>0){let a=i[0],s=i[i.length-1],l=new Set,c=a.parent;for(;c;)(c.type==="surd"||c.type==="box"||c.type==="enclose"||c.type==="leftright"||c.type==="genfrac"||c.type==="overunder")&&c.parent&&l.add(c),c=c.parent;let u=new Set;for(c=s.parent;c;)(c.type==="surd"||c.type==="box"||c.type==="enclose"||c.type==="leftright"||c.type==="genfrac"||c.type==="overunder")&&c.parent&&u.add(c),c=c.parent;for(let d of i)for(c=d.parent;c;){if((c.type==="surd"||c.type==="box"||c.type==="enclose"||c.type==="leftright"||c.type==="genfrac"||c.type==="overunder")&&c.parent){n.has(c)||n.set(c,{containsStart:l.has(c),containsEnd:u.has(c)});break}c=c.parent}}let o=Math.min(...e);t.deleteAtoms(e);for(let[a,s]of n){if(!a.parent)continue;let l=s.containsStart!==s.containsEnd;if(a.type==="surd"||a.type==="box"||a.type==="enclose"||a.type==="leftright"){let c=a.branch("body");if(!c||c.length===0||c.length===1&&c[0].type==="placeholder"){let d=t.offsetOf(a.leftSibling);a.parent.removeChild(a),t.position=Math.max(0,d)}else if(l&&!s.containsStart&&s.containsEnd){let d=t.offsetOf(a.leftSibling),m=a.removeBranch("body");m&&m.length>0&&a.parent.addChildrenAfter(m,a),a.parent.removeChild(a),t.position=Math.max(0,d)}}if(a.type==="genfrac"){let c=a.branch("above"),u=a.branch("below"),d=!c||c.length===0||c.length===1&&c[0].type==="placeholder",m=!u||u.length===0||u.length===1&&u[0].type==="placeholder";if(d&&m){let p=t.offsetOf(a.leftSibling);a.parent.removeChild(a),t.position=Math.max(0,p)}else if(d&&!m){let p=t.offsetOf(a.leftSibling),f=a.removeBranch("below");f&&f.length>0&&a.parent.addChildrenAfter(f,a),a.parent.removeChild(a),t.position=Math.max(0,p)}else if(!d&&m){let p=t.offsetOf(a.leftSibling),f=a.removeBranch("above");f&&f.length>0&&a.parent.addChildrenAfter(f,a),a.parent.removeChild(a),t.position=Math.max(0,p)}else if(l&&!s.containsStart&&s.containsEnd&&!d&&!m){let p=t.offsetOf(a.leftSibling),f=a.removeBranch("above");f&&f.length>0&&a.parent.addChildrenAfter(f,a),a.parent.removeChild(a),t.position=Math.max(0,p)}}}n.size===0&&(t.position=o),t.root.hasEmptyBranch("body")&&t.mathfield.flushInlineShortcutBuffer()})}function Pb(t,e,r,i){if(!(e instanceof z)||!e.isMultiline||e.rows.length===1||e.rows[r].length>1)return!1;let n=e.getCell(r,0);if(!n)return!1;if(e.removeRow(r),i==="backward"){let o=e.getCell(r-1,0);if(!o)return t.position=t.offsetOf(e),!0;o.length>0?t.position=t.offsetOf(o[o.length-1]):t.position=t.offsetOf(e),e.setCell(r-1,0,[...o,...n])}else{let o=e.getCell(r,0);if(!o)return t.position=t.offsetOf(e),!0;o.length>0?t.position=t.offsetOf(o[0]):t.position=t.offsetOf(e),e.setCell(r,0,[...n,...o])}return!0}function Rb(t,e,r){var o,a;if(t.at(e).mode!=="text")return e;let i=r==="backward"?-1:1,n;if(Qr.test(t.at(e).value)){let s=e,l;do l=t.at(s).mode==="text"&&Qr.test(t.at(s).value),s+=i;while(t.at(s)&&l);n=t.at(s)?s-2*i:s-i}else if(/\s/.test(t.at(e).value)){let s=e;for(;((o=t.at(s))==null?void 0:o.mode)==="text"&&/\s/.test(t.at(s).value);)s+=i;if(!t.at(s))n=s-i;else{let l=!0;do l=t.at(s).mode==="text"&&!/\s/.test(t.at(s).value),s+=i;while(t.at(s)&&l);n=t.at(s)?s-2*i:s-i}}else{let s=e;for(;((a=t.at(s))==null?void 0:a.mode)==="text"&&!/\s/.test(t.at(s).value);)s+=i;n=t.at(s)?s:s-i;let l=!0;for(;t.at(s)&&l;)l=t.at(s).mode==="text"&&/\s/.test(t.at(s).value),l&&(n=s),s+=i;n=t.at(s)?s-2*i:s-i}return n-(i>0?0:1)}function St(t,e,r){var a,s,l,c,u,d,m,p;let i=t.position;(a=r==null?void 0:r.extend)!=null&&a||t.collapseSelection(e);let n=t.at(t.position);if(e==="forward"&&(n.type==="subsup"?(n=n.rightSibling,n||(n=t.at(t.position+1))):n=t.at(t.position+1)),!n)return t.announce("plonk"),!1;let o=t.offsetOf(n);if(n instanceof We)o=Rb(t,o,e);else if(n instanceof he)if(n.isSuggestion)for(;n&&n instanceof he;)n.isSuggestion=!1,o=t.offsetOf(n),n=n.rightSibling;else if(e==="forward"){if(n=n.rightSibling,!n||!(n instanceof he))return t.announce("plonk"),!1;for(;n&&n instanceof he&&/[a-zA-Z\*]/.test(n.value);)o=t.offsetOf(n),n=n.rightSibling}else{if(n=n.leftSibling,!n||!(n instanceof he))return t.announce("plonk"),!1;for(;n&&n instanceof he&&/[a-zA-Z\*]/.test(n.value);)o=t.offsetOf(n),n=n.leftSibling}else if(e==="forward"&&n.type==="mopen"){let f=0;do n.type==="mopen"?f+=1:n.type==="mclose"&&(f-=1),n=n.rightSibling;while(!n.isLastSibling&&f!==0);o=t.offsetOf(n.leftSibling)}else if(e==="backward"&&n.type==="mclose"){let f=0;do n.type==="mopen"?f+=1:n.type==="mclose"&&(f-=1),n=n.leftSibling;while(!n.isFirstSibling&&f!==0);o=t.offsetOf(n)}else if(e==="backward")if(n.type==="first")for(;o>0&&n.type==="first";)o-=1,n=t.at(o);else{let f=n.type;n.type==="subsup"&&(o=t.offsetOf(t.at(o).leftSibling)),o-=1;let y=(s=t.at(o))==null?void 0:s.type;for(;o>=0&&y===f;)((l=t.at(o))==null?void 0:l.type)==="subsup"?o=t.offsetOf(t.at(o).leftSibling):o-=1,y=t.at(o).type}else{let{type:f}=n,y=(c=t.at(o))==null?void 0:c.type,{lastOffset:v}=t;for(;o<=v&&(y===f||y==="subsup");){for(;((u=t.at(o).rightSibling)==null?void 0:u.type)==="subsup";)o=t.offsetOf(t.at(o).rightSibling);o+=1,y=(d=t.at(o))==null?void 0:d.type}o-=1}if((m=r==null?void 0:r.extend)!=null&&m){if(!t.setSelection(t.anchor,o))return t.announce("plonk"),!1;t.announce("move",i)}else{if(o===t.position)return t.announce("plonk"),!1;(p=r==null?void 0:r.delete)!=null&&p?e==="forward"?ct(t,[i,o],"deleteWordForward"):(ct(t,[i,o],"deleteWordBackward"),t.position=o):(t.position=o,t.announce("move",i))}return t.mathfield.stopCoalescingUndo(),!0}function ut(t,e,r){var o,a;if(r=r!=null?r:{extend:!1},t.mathfield.styleBias=e==="backward"?"right":"left",e!=="forward"){let[s,l]=ps(t);s!==void 0&&l!==void 0&&t.deleteAtoms([s,l])}if(e==="upward")return zb(t,r);if(e==="downward")return Nb(t,r);if(r.extend){let s=Ts(t,t.position,e);s<0&&(s=0),s>t.lastOffset&&(s=t.lastOffset);let l=t.setSelection(t.anchor,s);return t.mathfield.stopCoalescingUndo(),l}if(t.selectionIsPlaceholder){t.collapseSelection(e);let s=ut(t,e);return t.mathfield.stopCoalescingUndo(),s}let i=t.position,n=i;if(t.collapseSelection(e)?(i=t.position,lp(t,i)||(i=Ts(t,i,e))):i=Ts(t,i,e),i<0||i>t.lastOffset){let s=!0;return t.silenceNotifications||(s=(a=(o=t.mathfield.host)==null?void 0:o.dispatchEvent(new CustomEvent("move-out",{detail:{direction:e},cancelable:!0,bubbles:!0,composed:!0})))!=null?a:!0),s&&t.announce("plonk"),s}return t.setPositionHandlingPlaceholder(i),t.mathfield.stopCoalescingUndo(),t.announce("move",n),!0}function Ts(t,e,r){return e=e+(r==="forward"?1:-1),e<0||e>t.lastOffset||lp(t,e)?e:Ts(t,e,r)}function lp(t,e){var n;let r=t.at(e),i=r.parent;for(;i&&!i.inCaptureSelection;)i=i.parent;return!(i!=null&&i.inCaptureSelection||(n=r.parent)!=null&&n.skipBoundary&&(!r.isFirstSibling&&r.isLastSibling||r.type==="first")||t.mathfield.hasEditablePrompts&&!r.parentPrompt)}function Ib(t,e,r){let i=1/0,n=0;for(;nc.type==="prompt"&&!c.captureSelection):r,s=pc(t.mathfield.getHTMLElement(e)).right,l=t.offsetOf(Ib(t.mathfield,a,s))-(o?1:0);if(i){let[c,u]=t.selection.ranges[0],d;l<(n==="up"?c:u)?d={ranges:[[l,u]],direction:"backward"}:d={ranges:[[c,l]],direction:"forward"},t.setSelection(d)}else t.setPositionHandlingPlaceholder(l);t.announce(`move ${n}`)}function zb(t,e){var a,s;let r=(a=e==null?void 0:e.extend)!=null?a:!1;r||t.collapseSelection("backward");let i=()=>{var c,u;let l=!0;return t.silenceNotifications||(l=(u=(c=t.mathfield.host)==null?void 0:c.dispatchEvent(new CustomEvent("move-out",{detail:{direction:"upward"},cancelable:!0,bubbles:!0,composed:!0})))!=null?u:!0),t.announce(l?"line":"plonk"),l},n=t.at(t.position),o=n;for(;o&&o.parentBranch!=="below"&&!(Array.isArray(o.parentBranch)&&o.parent instanceof z);)o=o.parent;if(Array.isArray(o==null?void 0:o.parentBranch)&&o.parent instanceof z){let l=o.parent;if(o.parentBranch[0]<1)return i();let c=o.parentBranch[0]-1,u=l.getCell(c,o.parentBranch[1]);if(!u.some(m=>m.type==="prompt"&&!m.captureSelection)&&t.mathfield.hasEditablePrompts)return i();Ds(t,n,u,r,"up")}else if(o){let l=(s=o.parent.branch("above"))!=null?s:o.parent.createBranch("above");if(!l.some(u=>u.type==="prompt"&&u.placeholderId)&&t.mathfield.hasEditablePrompts)return i();Ds(t,n,l,r,"up")}else return i();return t.mathfield.stopCoalescingUndo(),!0}function Nb(t,e){var a,s;let r=(a=e==null?void 0:e.extend)!=null?a:!1;r||t.collapseSelection("forward");let i=()=>{var c,u;let l=!0;return t.silenceNotifications||(l=(u=(c=t.mathfield.host)==null?void 0:c.dispatchEvent(new CustomEvent("move-out",{detail:{direction:"downward"},cancelable:!0,bubbles:!0,composed:!0})))!=null?u:!0),t.announce(l?"line":"plonk"),l},n=t.at(t.position),o=n;for(;o&&o.parentBranch!=="above"&&!(Ze(o.parentBranch)&&o.parent instanceof z);)o=o.parent;if(Ze(o==null?void 0:o.parentBranch)&&o.parent instanceof z){let l=o.parent;if(o.parentBranch[0]+1>l.rows.length-1)return i();let c=o.parentBranch[0]+1,u=l.getCell(c,o.parentBranch[1]);if(!u.some(m=>m.type==="prompt"&&!m.captureSelection)&&t.mathfield.hasEditablePrompts)return i();Ds(t,n,u,r,"down")}else if(o){let l=(s=o.parent.branch("below"))!=null?s:o.parent.createBranch("below");if(!l.some(u=>u.type==="prompt")&&t.mathfield.hasEditablePrompts)return i();Ds(t,n,l,r,"down")}else return i();return!0}function $c(t){let e=t.position,r=t.at(e).parent;return r!=null&&r.parent?(t.position=t.offsetOf(r),t.mathfield.stopCoalescingUndo(),t.announce("move",e),!0):(t.announce("plonk"),!1)}function Fb(t){let e=0,r=t.at(t.position),i=!1;for(;r;)r.hasEmptyBranch("superscript")?r.hasEmptyBranch("subscript")||(i=!1):(e+=1,i=!0),r=r.parent;return i?e:0}function $b(t){let e=0,r=t.at(t.position),i=!1;for(;r;)r.hasEmptyBranch("subscript")?r.hasEmptyBranch("superscript")||(i=!1):(e+=1,i=!0),r=r.parent;return i?e:0}function cp(t){if(t.collapseSelection(),Fb(t)>=t.mathfield.options.scriptDepth[1])return t.announce("plonk"),!1;let e=t.at(t.position);if(e.subsupPlacement===void 0){let r=e.rightSibling;(r==null?void 0:r.type)!=="subsup"&&(r=new cr({style:e.style}),e.parent.addChildAfter(r,e)),e=r}return e.createBranch("superscript"),t.setSelection(t.getSiblingsRange(t.offsetOf(e.superscript[0]))),!0}function up(t){if(t.collapseSelection(),$b(t)>=t.mathfield.options.scriptDepth[0])return t.announce("plonk"),!1;let e=t.at(t.position);if(e.subsupPlacement===void 0){let r=e.rightSibling;(r==null?void 0:r.type)!=="subsup"&&(r=new cr({style:e.style}),e.parent.addChildAfter(r,e)),e=r}return e.createBranch("subscript"),t.setSelection(t.getSiblingsRange(t.offsetOf(e.subscript[0]))),!0}function Vb(){function t(l){let c=[],u=[];return[...l.querySelectorAll(`input, select, textarea, a[href], button, + [tabindex], audio[controls], video[controls], + [contenteditable]:not([contenteditable="false"]), details>summary`)].filter(e).forEach((m,p)=>{let f=i(m);f===0?c.push(m):u.push({documentOrder:p,tabIndex:f,node:m})}),u.sort((m,p)=>m.tabIndex===p.tabIndex?m.documentOrder-p.documentOrder:m.tabIndex-p.tabIndex).map(m=>m.node).concat(c)}function e(l){return!(!r(l)||n(l)||i(l)<0)}function r(l){return!(l.disabled||l.type==="hidden"&&l.tagName.toUpperCase()==="INPUT"||s(l))}function i(l){var u;let c=Number.parseInt((u=l.getAttribute("tabindex"))!=null?u:"NaN",10);return Number.isNaN(c)?l.contentEditable==="true"||(l.nodeName==="AUDIO"||l.nodeName==="VIDEO")&&l.getAttribute("tabindex")===null?0:l.tabIndex:c}function n(l){return l.tagName.toUpperCase()==="INPUT"&&l.type==="radio"&&!a(l)}function o(l,c){for(let u of l)if(u.checked&&u.form===c)return u;return null}function a(l){var m;if(!l.name)return!0;let u=((m=l.form)!=null?m:l.ownerDocument).querySelectorAll('input[type="radio"][name="'+l.name+'"]'),d=o(u,l.form);return!d||d===l}function s(l){if(!Le()||l===document.activeElement||l.contains(document.activeElement))return!1;if(getComputedStyle(l).visibility==="hidden")return!0;let c=l.getBoundingClientRect();if(c.width===0||c.height===0)return!0;for(;l;){if(getComputedStyle(l).display==="none")return!0;l=l.parentElement}return!1}return Le()?t(document.body):[]}function Ke(t,e,r="forward"){let i=t.position;if(ee(e)){let n=t.offsetOf(e[0]),o=t.offsetOf(e[e.length-1]);return r==="forward"?t.setSelection(n,o):t.setSelection(o,n),t.announce("move",i),t.mathfield.stopCoalescingUndo(),!0}return r==="forward"?Ke(t,[e.leftSibling,e]):Ke(t,[e,e.leftSibling])}function kt(t,e){let r=t.position;if(typeof e=="number"&&(e=t.at(e)),e.type==="prompt")t.setSelection(t.offsetOf(e.firstChild),t.offsetOf(e.lastChild));else{let i=t.offsetOf(e);e.type==="placeholder"?t.setSelection(i-1,i):t.position=i}return t.announce("move",r),t.mathfield.stopCoalescingUndo(),!0}function Cn(t,e){var a,s;let r=e==="forward"?1:-1;t.at(t.anchor).type==="placeholder"&&ut(t,e);let i,n=t.at(t.anchor).parentPrompt;n?e==="forward"?i=t.offsetOf(n)+1:i=t.offsetOf(n.leftSibling):i=Math.max(t.position+r,0);let o=Fc(t,i,e);if(!o||e==="forward"&&t.offsetOf(o)i){if(!((s=(a=t.mathfield.host)==null?void 0:a.dispatchEvent(new CustomEvent("move-out",{detail:{direction:e},cancelable:!0,bubbles:!0,composed:!0})))!=null?s:!0))return t.announce("plonk"),!1;let c=Vb();if(!document.activeElement||c.length<=1)return t.announce("plonk"),!1;let u=c.indexOf(document.activeElement)+r;return u<0&&(u=c.length-1),u>=c.length&&(u=0),c[u].focus(),t.mathfield.stopCoalescingUndo(),!0}return kt(t,o),!0}function Fc(t,e=0,r="forward"){return t.findAtom(i=>i.type==="placeholder"||i.type==="prompt"||!t.mathfield.readOnly&&i.treeDepth>2&&i.isFirstSibling&&i.isLastSibling,e,r)}fe({moveToOpposite:t=>{let e={superscript:"subscript",subscript:"superscript",above:"below",below:"above"},r=t.at(t.position),{parent:i}=r;if(!i)return t.announce("plonk"),!1;let n=r.parentBranch,o;if(typeof n=="string"&&(o=e[n]),!o){let s=r.subsupPlacement?up(t):cp(t);return t.mathfield.stopCoalescingUndo(),s}i.branch(o)||i.createBranch(o);let a=t.setSelection(t.getBranchRange(t.offsetOf(i),o));return t.mathfield.stopCoalescingUndo(),a},moveBeforeParent:t=>{let{parent:e}=t.at(t.position);return e?(t.position=t.offsetOf(e),t.mathfield.stopCoalescingUndo(),!0):(t.announce("plonk"),!1)},moveAfterParent:t=>$c(t),moveToNextChar:t=>ut(t,"forward"),moveToPreviousChar:t=>ut(t,"backward"),moveUp:t=>ut(t,"upward"),moveDown:t=>ut(t,"downward"),moveToNextWord:t=>St(t,"forward"),moveToPreviousWord:t=>St(t,"backward"),moveToGroupStart:t=>{let e=t.offsetOf(t.at(t.position).firstSibling);return e===t.position?(t.announce("plonk"),!1):(t.position=e,t.mathfield.stopCoalescingUndo(),!0)},moveToGroupEnd:t=>{let e=t.offsetOf(t.at(t.position).lastSibling);return e===t.position?(t.announce("plonk"),!1):(t.position=e,t.mathfield.stopCoalescingUndo(),!0)},moveToNextGroup:t=>{var l,c,u,d;if(t.position===t.lastOffset&&t.anchor===t.lastOffset)return Cn(t,"forward");let e=t.at(t.position);if(e.mode==="text"){if(t.selectionIsCollapsed){let m=e;for(;(m==null?void 0:m.mode)==="text";)m=m.leftSibling;let p=e;for(;((l=p.rightSibling)==null?void 0:l.mode)==="text";)p=p.rightSibling;if(m&&p)return Ke(t,[m,p])}if(e.rightSibling.mode==="text"){let m=e;for(;(m==null?void 0:m.mode)==="text";)m=m.rightSibling;return m?(kt(t,(c=m.leftSibling)!=null?c:m),t.mathfield.switchMode("math"),!0):kt(t,t.lastOffset)}}let i=t.at(t.anchor).parentPrompt,n=i?t.offsetOf(i)+1:Math.max(t.position+1,0),o=Fc(t,n,"forward");if(o&&t.offsetOf(o)m.type==="leftright"||m.type==="text","forward");if(a){if(a.mode==="text"){let m=a;for(;(m==null?void 0:m.mode)==="text";)m=m.rightSibling;return Ke(t,[(u=a.leftSibling)!=null?u:a,(d=m.leftSibling)!=null?d:m])}return Ke(t,a)}let s=e.parent;if(s){if(s.type==="leftright"||s.type==="surd")return Ke(t,s);if(e.parentBranch==="subscript"&&s.superscript)return Ke(t,s.superscript);if(e.parentBranch==="above"&&s.below)return Ke(t,s.below);if(e.parentBranch==="superscript"||e.parentBranch==="subscript")return kt(t,s);if(e.parentBranch==="above"||e.parentBranch==="below")return Ke(t,s)}return kt(t,t.lastOffset)},moveToPreviousGroup:t=>{var a;if(t.position===0&&t.anchor===0)return Cn(t,"backward");let e=t.at(t.position),r=e.mode;if(r==="text"){if(t.selectionIsCollapsed){let s=e;for(;(s==null?void 0:s.mode)==="text";)s=s.leftSibling;let l=e;for(;((a=l.rightSibling)==null?void 0:a.mode)==="text";)l=l.rightSibling;if(s&&l)return Ke(t,[s,l])}for(;(e==null?void 0:e.mode)==="text";)e=e.leftSibling;return e?kt(t,e):kt(t,0)}let i=t.at(t.anchor).parentPrompt,n=i?t.offsetOf(i.leftSibling):Math.max(t.position-1,0),o=Fc(t,n,"backward");if(o&&t.offsetOf(o)>n)return Cn(t,"backward");if(o)return kt(t,o);if(r==="math"){let s=dp(t,e,c=>c.type==="leftright"||c.type==="text","backward");if(s){if(s.mode==="text"){let c=s;for(;(c==null?void 0:c.mode)==="text";)c=c.leftSibling;return Ke(t,[s,c])}return Ke(t,s)}let l=e.parent;if(l){if(l.type==="leftright"||l.type==="surd")return Ke(t,l);if(e.parentBranch==="superscript"&&l.subscript)return Ke(t,l.subscript);if(e.parentBranch==="below"&&l.above)return Ke(t,l.above);if(e.parentBranch==="superscript"||e.parentBranch==="subscript")return kt(t,l);if(e.parentBranch==="above"||e.parentBranch==="below")return Ke(t,l)}return kt(t,0)}return!1},moveToMathfieldStart:t=>t.selectionIsCollapsed&&t.position===0?(t.announce("plonk"),!1):(t.position=0,t.mathfield.stopCoalescingUndo(),!0),moveToMathfieldEnd:t=>t.selectionIsCollapsed&&t.position===t.lastOffset?(t.announce("plonk"),!1):(t.position=t.lastOffset,t.mathfield.stopCoalescingUndo(),!0),moveToSuperscript:cp,moveToSubscript:up},{target:"model",changeSelection:!0});fe({moveToNextPlaceholder:t=>Cn(t,"forward"),moveToPreviousPlaceholder:t=>Cn(t,"backward")},{target:"model",changeSelection:!0,audioFeedback:"return"});function dp(t,e,r,i){if(i==="forward"){let o=e.rightSibling;for(;o&&!r(o);)o=o.rightSibling;return o}let n=e.leftSibling;for(;n&&!r(n);)n=n.leftSibling;return n}function Os(t,e,r){typeof e=="function"&&(r=e,e=1/0),e===void 0&&(e=1/0);let i=t.position,n=!1,o="";for(;!n;){let a=t.at(i);n=e===0||a===void 0||a.type==="first"||a.mode!=="math"||!(a.type&&/mord|mpunct|operator/.test(a.type)||a.type==="mop"&&/[a-zA-Z ]+/.test(a.value))||!a.hasEmptyBranch("superscript")||!a.hasEmptyBranch("subscript")||typeof r=="function"&&!r(a),n||(a.mode="text",a.command=a.value,a.verbatimLatex=void 0,o+=a.value),i-=1,e-=1}t.contentDidChange({data:o,inputType:"insertText"})}function Si(t,e,r){typeof e=="function"&&(r=e,e=1/0),e===void 0&&(e=1/0);let i=t.position,n=!1,o=[];for(;!n;){let a=t.at(i);n=e===0||!a||a.type==="first"||a.isFirstSibling||a.mode!=="text"||a.value===" "||typeof r=="function"&&!r(a),n||(o.push(x.serialize([a],{defaultMode:"math"})),a.mode="math"),i-=1,e-=1}Bs(t),t.contentDidChange({data:R(o),inputType:"insertText"})}function Bs(t){var r;let e=t.position-1;for(;e>=0&&((r=t.at(e))==null?void 0:r.mode)==="math";)e-=1;if(!(e<0)&&t.at(e).mode==="text"&&t.at(e).value===" "&&t.at(e-1).mode==="math"){t.at(e-1).parent.removeChild(t.at(e-1));let i=t.silenceNotifications;t.silenceNotifications=!0,t.position-=1,t.silenceNotifications=i,t.contentDidChange({inputType:"deleteContent"})}}function qb(t){let e="",r=t.position,i=!1;for(;!i;){let n=t.at(r);i=!(n&&(n.mode==="text"||n.mode==="math"&&n.type&&/mord|mpunct/.test(n.type))),i||(e=n.value+e),r-=1}return e}function mp(t,e,r){let{model:i}=t;if(i.mode==="latex"||!i.at(i.position).isLastSibling||!r||!dr(r))return!1;let n=Fr(r);if(!i.selectionIsCollapsed)return!!(t.model.mode==="text"&&/[/_^]/.test(n));let o=qb(i)+n;if(t.model.mode==="text"){if(e==="Esc"||/[/\\]/.test(n))return!0;if(/[\^_]/.test(n))return/(^|\s)[a-zA-Z][^_]$/.test(o)&&Si(i,1),!0;let a={")":"(","}":"{","]":"["}[n],{parent:s}=i.at(i.position);if(a&&s instanceof J&&s.leftDelim===a)return!0;if(/(^|[^a-zA-Z])(a|I) $/.test(o))return!1;if(/[$€£₤₺¥¤฿¢₡₧₨₹₩₱]/u.test(n))return!0;if(/(^|[^a-zA-Z'’])[a-zA-Z] $/.test(o))return Si(i,1),!1;if(/\D\.[^\d\s]$/.test(o)){Si(i,1);let l=i.at(i.position);return l.value="\u22C5",l.style.variant="normal",l.command="\\cdot",l.verbatimLatex=void 0,i.contentDidChange({data:"\\cdot",inputType:"insertText"}),!0}if(/(^|\s)[a-zA-Z][^a-zA-Z]$/.test(o)||/\.\d$/.test(o)||/\([\d+\-.]$/.test(o))return Si(i,1),!0;if(/\([a-z][,;]$/.test(o))return Si(i,2),!0;if(/[\d+\-=><*|]$/.test(n))return Bs(i),!0}else{if(e==="[Space]")return Os(i,void 0,a=>/[a-z][:,;.]$/.test(a.value)),!0;if(/[a-zA-Z]{3,}$/.test(o)&&!/(dxd|abc|xyz|uvw)$/.test(o))return Os(i,void 0,a=>/[a-zA-Z]/.test(a.value)),!0;if(/(^|\W)(if)$/i.test(o))return Os(i,1),!0;if(/(\u0393|\u0394|\u0398|\u039B|\u039E|\u03A0|\u03A3|\u03A5|\u03A6|\u03A8|\u03A9|[\u03B1-\u03C9]|\u03D1|\u03D5|\u03D6|\u03F1|\u03F5){3,}$/u.test(o)&&!/(αβγ)$/.test(o))return Os(i,void 0,a=>/(:|,|;|.|\u0393|\u0394|\u0398|\u039B|\u039E|\u03A0|\u03A3|\u03A5|\u03A6|\u03A8|\u03A9|[\u03B1-\u03C9]|\u03D1|\u03D5|\u03D6|\u03F1|\u03F5)/u.test(a.value)),!0;if(n==="?"||n==="."&&!/[\d-+]\.$/.test(o))return!0}return!1}function hp(t,e){if(!t.isSelectionEditable||!t.keystrokeCaptionVisible)return;let r=fp(),i=t.element.getBoundingClientRect();r.style.left=`${i.left}px`,r.style.top=`${i.top-64}px`,r.innerHTML=globalThis.MathfieldElement.createHTML(""+(gn(e)||e)+""+r.innerHTML),r.style.visibility="visible",setTimeout(()=>{r.childNodes.length>0&&r.childNodes[r.childNodes.length-1].remove(),r.childNodes.length===0&&(r.style.visibility="hidden")},3e3)}function pp(t){if(t.keystrokeCaptionVisible=!t.keystrokeCaptionVisible,t.keystrokeCaptionVisible){let e=fp();e.innerHTML=""}else{let e=vi("mathlive-keystroke-caption-panel");e.style.visibility="hidden"}return!1}function fp(){let t=document.getElementById("mathlive-keystroke-caption-panel");return t||(Ge("keystroke-caption"),Ge("core"),vi("mathlive-keystroke-caption-panel"))}function gp(){document.getElementById("mathlive-keystroke-caption-panel")&&(qr("mathlive-keystroke-caption-panel"),ot("core"),ot("keystroke-caption"))}function qc(t,e){var m,p,f,y;let{model:r}=t,i=hs(e);if(e.isTrusted){Eu(e);let v=yr();t.keyboardLayout!==v.id&&(t.keyboardLayout=v.id,t._keybindings=void 0)}if(clearTimeout(t.inlineShortcutBufferFlushTimer),t.inlineShortcutBufferFlushTimer=0,hp(t,i),e.isTrusted&&e.defaultPrevented)return t.flushInlineShortcutBuffer(),!1;let n,o=0,a="",s=0,l=t.inlineShortcutBuffer,c=!1;if(t.isSelectionEditable&&r.selectionIsPlaceholder&&dr(e)&&(t.flushInlineShortcutBuffer(),r.deleteAtoms(de(r.selection)),t.snapshot("delete"),c=!0),t.isSelectionEditable){if(r.mode==="math"&&(!r.selectionIsPlaceholder||c))if(i==="[Backspace]")t.undoManager.lastOp==="insert-shortcut"?a="undo":l.pop();else if(!dr(e))t.flushInlineShortcutBuffer();else{let v=Fr(e),b=[...(p=(m=l[l.length-1])==null?void 0:m.keystrokes)!=null?p:[],v];l.push({state:r.getState(),keystrokes:b,leftSiblings:Ub(t)}),o=0;let k="";for(;!n&&o(H.insert(r,n,{format:"latex",style:v}),Bs(t.model),n.endsWith(" ")&&(t.switchMode("text"),H.insert(r," ",{style:v,mode:"text"})),t.snapshot(),r.selectionIsCollapsed||t.flushInlineShortcutBuffer(),!0)),t.dirty=!0,r.announce("replacement")}return t.scrollIntoView(),e.preventDefault&&e.preventDefault(),!1}function Hb(t){var p,f;let{position:e}=t,r=e,i=[];for(;r>0;){let y=t.at(r),v=y.value;if(y.type==="mord"||y.type==="mbin"&&(v==="+"||v==="-"||v==="\u2212"))i.unshift(y),r--;else break}if(i.length===0)return null;let n=i.map(y=>y.value).join(""),a=((f=(p=globalThis.MathfieldElement)==null?void 0:p.decimalSeparator)!=null?f:".")==="."?"\\.":",",s=new RegExp(`^(\\d+(?:${a}\\d*)?)[eE]([+\\-\u2212]?)(\\d+)$`),l=n.match(s);if(!l)return null;let c=l[1],u=l[2],d=l[3],m=u+d;return{startOffset:r,endOffset:e,significand:c,exponent:m}}function Wb(t,e){var n;let r=(n=globalThis.MathfieldElement)==null?void 0:n.scientificNotationTemplate;if(!r||r===""||!r.includes("#1")||!r.includes("#2"))return null;let i=r.replace("#1",t);return i=i.replace("#2",e),i}function bp(t){let{model:e}=t;if(e.mode!=="math")return!1;let r=Hb(e);if(!r)return!1;let i=Wb(r.significand,r.exponent);return i?(e.deferNotifications({content:!0,selection:!0,type:"insertText"},()=>{e.selection={ranges:[[r.startOffset,r.endOffset]],direction:"forward"},H.insert(e,i,{insertionMode:"replaceSelection",selectionMode:"after"})}),t.snapshot("format-scientific-notation"),t.dirty=!0,t.scrollIntoView(),!0):!1}function ko(t,e,r){let{model:i}=t;if(!t.isSelectionEditable){i.announce("plonk");return}r!=null||(r={}),r.focus&&t.focus(),r.feedback&&(globalThis.MathfieldElement.keypressVibration&&Di()&&navigator.vibrate(mo),globalThis.MathfieldElement.playSound("keypress")),typeof r.mode=="string"&&(t.switchMode(r.mode),t.snapshot());let n=qa(e),o=window.mathVirtualKeyboard;if(o!=null&&o.isShifted&&(n=typeof n=="string"?n.toUpperCase():n.map(a=>a.toUpperCase())),r.simulateKeystroke){let a=!0;for(let s of n)qc(t,new KeyboardEvent("keypress",{key:s}))&&(a=!1);if(a)return}if(i.mode==="latex"){if(i.deferNotifications({content:!0,selection:!0,data:e,type:"insertText"},()=>{xi(t);for(let a of n)H.insert(i,a,{insertionMode:"replaceSelection"});t.snapshot("insert-latex"),Vr(t)}),e==="}"){let s=yi(i).map(c=>c.value).join(""),l=s.match(/^\\([a-zA-Z]+)/);if(l){let c="\\"+l[1],u=ne(c,"math");if((u==null?void 0:u.definitionType)==="function"){let d=u.params.filter(m=>!m.isOptional).length;if(d>0){let m=0,p=0,f=!0;for(let y=0;y0?t.options.inlineShortcutTimeout:1e3;clearTimeout(t.scientificNotationTimer),t.scientificNotationTimer=setTimeout(()=>{bp(t)},l)}}function jb(t){var r,i,n,o;if(t.selectionIsCollapsed)return(i=(r=t.at(t.position))==null?void 0:r.style)!=null?i:{};let e=de(t.selection)[0];return(o=(n=t.at(e+1))==null?void 0:n.style)!=null?o:{}}function xp(t,e,r){var l;if(!e||t.mode!=="math")return!1;let i=t.at(t.position),{parent:n}=i,o={"(":"(",")":")","{":"\\lbrace","}":"\\rbrace","[":"\\lbrack","]":"\\rbrack","|":"|"}[e];if(!o)return!1;let a=on[o],s=nn[o];if(!t.selectionIsCollapsed){t.mathfield.snapshot();let[c,u]=de(t.selection),d=t.extractAtoms([c,u]);d=d.filter(p=>p.type!=="first");let m=n.addChildrenAfter([new J("left...right",d,{leftDelim:o,rightDelim:s})],t.at(c));return t.setSelection(t.offsetOf(m.firstChild),t.offsetOf(m.lastChild)),t.mathfield.snapshot("insert-fence"),t.contentDidChange({data:o,inputType:"insertText"}),!0}if(o==="|"){let c=n instanceof J?n.leftDelim+n.rightDelim:"";if(c==="\\lbrace\\rbrace"||c==="\\{\\}"||c==="\\lbrace?")return t.mathfield.snapshot(),H.insert(t,"\\,\\middle\\vert\\,",{format:"latex",style:r}),t.mathfield.snapshot("insert-fence"),t.contentDidChange({data:o,inputType:"insertText"}),!0}if(s){if(n instanceof J&&n.firstChild===i&&(n.leftDelim==="?"||n.leftDelim==="."))return n.leftDelim=o,n.isDirty=!0,t.mathfield.snapshot(),t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0;if(!(n instanceof J)){let m=i;for(;m&&!(m.type==="mclose"&&m.value===s);)m=m.rightSibling;if(m){t.mathfield.snapshot();let p=t.extractAtoms([t.offsetOf(i),t.offsetOf(m)]);p.pop(),p=p.filter(y=>y.type!=="first");let f=new J("left...right",p,{leftDelim:o,rightDelim:s});return n.addChildrenAfter([f],i),t.position=t.offsetOf(f.firstChild),t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0}}let c=t.offsetOf(i.lastSibling),u;for(u=t.position;u<=c;u++){let m=t.at(u);if(m instanceof J&&(m.leftDelim==="?"||m.leftDelim===".")&&yp(o,m.rightDelim))break}let d=t.at(u);if(u<=c&&d instanceof J){d.leftDelim=o,t.mathfield.snapshot();let m=t.extractAtoms([t.position,u-1]);return m=m.filter(p=>p.type!=="first"),d.addChildren(m,d.parentBranch),t.position+=1,t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0}if(n instanceof J&&(n.leftDelim==="?"||n.leftDelim===".")&&yp(o,n.rightDelim)){n.isDirty=!0,n.leftDelim=o,t.mathfield.snapshot();let m=t.extractAtoms([t.offsetOf(i.firstSibling),t.position]);for(let p of m)n.parent.addChildBefore(p,n);return t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0}if(!(n instanceof J&&n.leftDelim==="|")){if(o==="("){let m=t.position-1,p=!1;for(;m>=0;){let f=t.at(m);if(f.type==="first")break;if(f.type==="mord"&&f.value&&/^[\d]$/.test(f.value)){m-=1;continue}if(f.type==="group"&&((l=f.body)==null?void 0:l.length)===2&&f.body[0].type==="first"&&f.body[1].value===","){p=!0;break}if(f.type==="mord"&&(f.value===","||f.value===".")){p=!0;break}break}if(p)return!1}if(t.mathfield.snapshot(),H.insert(t,`\\left${o}\\right?`,{format:"latex",style:r}),i.lastSibling.type!=="first"){let m=t.offsetOf(i.lastSibling),p=t.extractAtoms([t.position,m]);t.at(t.position).body=p,t.position-=1}return t.mathfield.snapshot("insert-fence"),!0}}if(a){if(o===")"){let f=t.position-1,y=!1;for(;f>=0;){let v=t.at(f);if(v.type==="first")break;if(v.type==="mord"&&v.value&&/^[\d]$/.test(v.value)){y=!0,f-=1;continue}break}if(y&&t.at(f).type==="mopen"&&t.at(f).value==="(")return!1}let c=i;for(;c;){if(c.type==="mopen"&&c.value===a){t.mathfield.snapshot();let f=c.leftSibling,y=t.extractAtoms([t.offsetOf(c.leftSibling),t.offsetOf(i)]);[,...y]=y;let v=new J("left...right",y,{leftDelim:a,rightDelim:o});return n.addChildrenAfter([v],f),t.position=t.offsetOf(v),t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0}c=c.leftSibling}if(n instanceof J&&i.isLastSibling&&Vc(n.leftDelim,o))return t.mathfield.snapshot(),n.isDirty=!0,n.rightDelim=o,t.position+=1,t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0;let u=t.offsetOf(i.firstSibling),d;for(d=t.position;d>=u;d--){let f=t.at(d);if(f instanceof J&&(f.rightDelim==="?"||f.rightDelim===".")&&Vc(f.leftDelim,o))break}let m=t.at(d);if(d>=u&&m instanceof J)return t.mathfield.snapshot(),m.rightDelim=o,m.addChildren(t.extractAtoms([d,t.position]),m.parentBranch),t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0;if(n instanceof J&&(n.rightDelim==="?"||n.rightDelim===".")&&Vc(n.leftDelim,o))return t.mathfield.snapshot(),n.isDirty=!0,n.rightDelim=o,n.parent.addChildren(t.extractAtoms([t.position,t.offsetOf(i.lastSibling)]),n.parentBranch),t.position=t.offsetOf(n),t.contentDidChange({data:o,inputType:"insertText"}),t.mathfield.snapshot("insert-fence"),!0;let p=n.parent;return p instanceof J&&(p.rightDelim==="?"||p.rightDelim===".")&&t.at(t.position).isLastSibling?(t.position=t.offsetOf(p),xp(t,o,r)):!1}return!1}function Vc(t,e){return t?["(","\\lparen","{","\\{","\\lbrace","[","\\lbrack"].includes(t)?[")","\\rparen","}","\\}","\\rbrace","]","\\rbrack"].includes(e):nn[t]===e:!0}function yp(t,e){return e?[")","\\rparen","}","\\}","\\rbrace","]","\\rbrack"].includes(e)?["(","\\lparen","{","\\{","\\lbrace","[","\\lbrack"].includes(t):on[e]===t:!0}fe({scrollIntoView:t=>(t.scrollIntoView(),!0),scrollToStart:t=>(t.field.scroll(0,0),!0),scrollToEnd:t=>{let e=t.field.getBoundingClientRect();return t.field.scroll(e.left-window.scrollX,0),!0},toggleKeystrokeCaption:pp,toggleContextMenu:t=>{let e=t.toggleContextMenu();return e||t.model.announce("plonk"),e},plonk:t=>(t.model.announce("plonk"),!0),switchMode:(t,e,r,i)=>(t.switchMode(e,r,i),!0)});fe({undo:t=>(t.undo(),!0),redo:t=>(t.redo(),!0)},{target:"mathfield",changeContent:!0});fe({insert:(t,e,r)=>t.insert(e,r),typedText:(t,e,r)=>(ko(t,e,r),!0),insertDecimalSeparator:t=>{let e=t.model;return e.mode==="math"&&globalThis.MathfieldElement.decimalSeparator===","&&e.at(Math.max(e.position,e.anchor)).isDigit()?(t.insert("{,}",{format:"latex"}),t.snapshot("insert-mord"),!0):(t.insert("."),!0)},commit:t=>{var r,i;let e=t.model;return e.contentWillChange({inputType:"insertLineBreak"})&&((r=t.host)==null||r.dispatchEvent(new Event("change",{bubbles:!0,composed:!0})),(i=e.parentEnvironment)!=null&&i.isMultiline&&t.executeCommand("addRowAfter"),e.contentDidChange({inputType:"insertLineBreak"})),!0},insertPrompt:(t,e,r)=>{let i=t.getPrompts(),n="prompt-"+Date.now().toString(36).slice(-2)+Math.floor(Math.random()*1e5).toString(36),o=0;for(;i.includes(n)&&o<100;){if(o===99)return console.error("could not find a unique ID after 100 tries"),!1;n="prompt-"+Date.now().toString(36).slice(-2)+Math.floor(Math.random()*1e5).toString(36),o++}return t.insert(`\\placeholder[${e!=null?e:n}]{}`,r),!0}},{target:"mathfield",canUndo:!0,changeContent:!0,changeSelection:!0});fe({copyToClipboard:t=>(t.focus(),t.model.selectionIsCollapsed&&t.select(),"queryCommandSupported"in document&&document.queryCommandSupported("copy")&&document.execCommand("copy")||t.element.querySelector(".ML__keyboard-sink").dispatchEvent(new ClipboardEvent("copy",{bubbles:!0,composed:!0})),!1)},{target:"mathfield"});fe({cutToClipboard:t=>(t.focus(),"queryCommandSupported"in document&&document.queryCommandSupported("cut")&&document.execCommand("cut")||t.element.querySelector(".ML__keyboard-sink").dispatchEvent(new ClipboardEvent("cut",{bubbles:!0,composed:!0})),!0),pasteFromClipboard:t=>(t.focus(),"queryCommandSupported"in document&&document.queryCommandSupported("paste")?(document.execCommand("paste"),!0):(navigator.clipboard.readText().then(e=>{e&&t.model.contentWillChange({inputType:"insertFromPaste",data:e})?(t.stopCoalescingUndo(),t.stopRecording(),t.insert(e,{mode:t.model.mode})&&(Vr(t),t.startRecording(),t.snapshot("paste"),t.model.contentDidChange({inputType:"insertFromPaste"}),Y(t))):t.model.announce("plonk"),t.startRecording()}).catch(()=>{t.model.announce("plonk"),t.startRecording()}),!0))},{target:"mathfield",canUndo:!0,changeContent:!0,changeSelection:!0});function Ks(t){let[e,r]=de(t.selection);if(e=vp(t,e,"backward"),r=vp(t,r,"forward"),e===r){let i=t.at(e);if(i.type==="leftright")return t.setSelection(t.offsetOf(i.firstChild)-1,r);if(i.type==="first"&&(i.parent.type==="leftright"||i.parent.type==="surd"))return t.setSelection(e-1,t.offsetOf(i.parent.lastChild)+1);t.setSelection(e-1,r)}else t.setSelection(e,r);return!0}function vp(t,e,r){var o;let i=t.at(e);if(!i)return e;let n=r==="forward"?1:-1;if(i.mode==="text"){for(;i&&!(i.mode!=="text"||!Qr.test(i.value));)e+=n,i=t.at(e);return r==="backward"?e-1:e}if(i.mode==="latex"){if(/[a-zA-Z\\*]/.test(i.value))if(r==="backward")for(;(i==null?void 0:i.mode)==="latex"&&i.value!=="\\"&&/[a-zA-Z]/.test(i.value);)e+=n,i=t.at(e);else for(;(i==null?void 0:i.mode)==="latex"&&/[a-zA-Z\\*]/.test(i.value);)e+=n,i=t.at(e);else if(i.value==="{"){if(r==="forward"){for(;(i==null?void 0:i.mode)==="latex"&&i.value!=="}";)e+=n,i=t.at(e);return e}return e-1}else if(i.value==="}"){if(r==="backward"){for(;(i==null?void 0:i.mode)==="latex"&&i.value!=="{";)e+=n,i=t.at(e);return e-1}return e}return e-1}if(i.mode==="math"){if(i.isDigit()){for(;(o=t.at(e+n))!=null&&o.isDigit();)e+=n;return r==="backward"?e-1:e}if(i.style.variant||i.style.variantStyle){let a=i.style.variant,s=i.style.variantStyle;for(;;){let l=t.at(e+n);if(!l||l.style.variant!==a||l.style.variantStyle!==s)break;e+=n}return r==="backward"?e-1:e}return e}return e}fe({selectGroup:t=>{let e=Ks(t);return e||t.announce("plonk"),e},selectAll:t=>t.setSelection(0,t.lastOffset),extendSelectionForward:t=>ut(t,"forward",{extend:!0}),extendSelectionBackward:t=>ut(t,"backward",{extend:!0}),extendToNextWord:t=>St(t,"forward",{extend:!0}),extendToPreviousWord:t=>St(t,"backward",{extend:!0}),extendSelectionUpward:t=>ut(t,"upward",{extend:!0}),extendSelectionDownward:t=>ut(t,"downward",{extend:!0}),extendToNextBoundary:t=>St(t,"forward",{extend:!0}),extendToPreviousBoundary:t=>St(t,"backward",{extend:!0}),extendToGroupStart:t=>{let e=t.setSelection(t.anchor,t.offsetOf(t.at(t.position).firstSibling));return e||t.announce("plonk"),e},extendToGroupEnd:t=>{let e=t.setSelection(t.anchor,t.offsetOf(t.at(t.position).lastSibling));return e||t.announce("plonk"),e},extendToMathFieldStart:t=>{let e=t.setSelection(t.anchor,0);return e||t.announce("plonk"),e},extendToMathFieldEnd:t=>{let e=t.setSelection(t.anchor,t.lastOffset);return e||t.announce("plonk"),e}},{target:"model",changeSelection:!0});var ki=null,Lo=0,Li=class t{static start(e,r,i,n){var a;t.element=e,(a=t.controller)==null||a.abort(),t.controller=new AbortController;let o={signal:t.controller.signal};"PointerEvent"in window?(e.addEventListener("pointermove",i,o),e.addEventListener("pointerup",n,o),e.addEventListener("pointercancel",n,o),Wc(r)&&(t.pointerId=r.pointerId,e.setPointerCapture(r.pointerId))):(window.addEventListener("mousemove",i,o),window.addEventListener("blur",n,o),window.addEventListener("mouseup",n,o))}static stop(){var e;(e=t.controller)==null||e.abort(),t.controller=void 0,typeof t.pointerId=="number"&&(t.element.releasePointerCapture(t.pointerId),t.pointerId=void 0)}};function Wc(t){return t!==null&&globalThis.PointerEvent!==void 0&&t instanceof PointerEvent}function Hc(t,e,r){return t>=r.left&&t<=r.right&&e>=r.top&&e<=r.bottom}function _p(t,e,r){return tr?r:t}function Uc(t,e){var O,I,V,K,N,j;if(e.buttons>1)return;t.atomBoundsCache?t.atomBoundsCache.clear():t.atomBoundsCache=new Map;let r=t,i,n=!1,o=!1,a="none",s=!1,l=!1,c=e.clientX,u=e.clientY,d=Date.now(),m=r.field,p=setInterval(()=>{s?m.scroll({top:0,left:m.scrollLeft-16}):l&&m.scroll({top:0,left:m.scrollLeft+16})},32);function f(){Li.stop(),n=!1,clearInterval(p),t.element.classList.remove("tracking"),e&&e.preventDefault()}function y(D){if(!r.hasFocus()){f();return}let W=D.clientX,ie=D.clientY,X=Wc(D)&&D.pointerType==="touch"?20:5;if(Date.now()ye.right,s=W=0&&Pe>=0&&(r.model.extendSelectionTo(xe,Pe),Y(t)),o&&Ks(r.model)}ki&&Math.abs(ki.x-c)<5&&Math.abs(ki.y-u)<5&&Date.now()=0){if(t.element.classList.add("tracking"),e.shiftKey){let D=t.model.selectionIsCollapsed;t.model.extendSelectionTo(t.model.anchor,i),gs(t.model)||D?a="all":a="selection"}else if(t.model.at(i).type==="placeholder"||t.model.at(i).type==="prompt"){let D=t.model.at(i);D.hasChildren&&D.firstChild?t.model.position=t.model.offsetOf(D.firstChild):t.model.setSelection(i-1,i),a="selection"}else if(((N=t.model.at(i).rightSibling)==null?void 0:N.type)==="placeholder"||((j=t.model.at(i).rightSibling)==null?void 0:j.type)==="prompt"){let D=t.model.at(i).rightSibling;D.hasChildren&&D.firstChild?t.model.position=t.model.offsetOf(D.firstChild):t.model.setSelection(i,i+1),a="selection"}else{let D=t.model.at(i);if(D.captureSelection&&D.hasChildren&&D.body&&D.body.length>0){let W=D.body.find(ie=>ie.type!=="first");W&&(W.type==="placeholder"||W.type==="prompt")&&W.hasChildren&&W.firstChild?(t.model.position=t.model.offsetOf(W.firstChild),a="selection"):(t.model.position=i,gs(t.model)?a="all":a="selection")}else t.model.position=i,gs(t.model)?a="all":a="selection"}e.detail===3||Lo>2?(f(),(e.detail===3||Lo===3)&&(t.model.selection={ranges:[[0,t.model.lastOffset]]},a="all")):n||(n=!0,Li.start(m,e,y,f),(e.detail===2||Lo===2)&&(o=!0,Ks(t.model),a="all"))}t.hasFocus()||(a="none",t.onFocus(),t.model.announce("line"))}else ki=null;t.stopCoalescingUndo(),a!=="none"&&(t.model.selectionIsCollapsed&&(a="all"),Y(t)),e.preventDefault()}function Jb(t,e,r){if(t>=r.left&&t<=r.right&&e>=r.top&&e<=r.bottom)return 0;let i=t-(r.left+r.right)/2,n=e-(r.top+r.bottom)/2;return i*i+n*n}function Ao(t,e,r,i,n){if(!r.id)return[1/0,null];if(e.has(r.id))return e.get(r.id);let o=ar(t,r);if(!o)return[1/0,null];let a=[1/0,null],s=t.model;if(r instanceof z){let l=-1,c=1/0;for(let d=0;df?y=n-f:y=0,y=0?[r.rows[l]]:r.rows;for(let d of u)for(let m of d)if(m)for(let p of m){let f=Ao(t,e,p,i,n);f[0]<=a[0]&&(a=f)}if(!r.isMultiline)for(let d of r.children){let m=Ao(t,e,d,i,n);m[0]<=a[0]&&(a=m)}}else if(r.hasChildren&&!r.captureSelection&&i>=o.left&&i<=o.right){let l=r.children;for(let c of l){let u=Ao(t,e,c,i,n);u[0]<=a[0]&&(a=u)}for(let c of r.branches){let u=r.branch(c);if(!u||u.length===0)continue;let d=[s.offsetOf(u[0]),s.offsetOf(u[u.length-1])],m=th(t,d);if(n>=m.top&&n<=m.bottom)for(let p of u){let f=Ao(t,e,p,i,n);f[0]<=a[0]&&(a=f)}}}return a[1]||(a=[Jb(i,n,o),r]),e.set(r.id,a),a}function Xb(t,e,r){let[,i]=Ao(t,new Map,t.model.root,e,r);return i}function Co(t,e,r,i){var c;let n=t.field.querySelector(".ML__latex").getBoundingClientRect();if(!n)return 0;if(e>n.right||r>n.bottom+8)return t.model.lastOffset;if(e0?(u.push(d),d=[y]):d.push(y);d.length>0&&u.push(d);let m=Number(c.parentBranch[0]),p=Number(c.parentBranch[1]),f=c.parent.maxColumns;for(;c.parent.colCount-p=f&&(p=0,c.parent.addRowAfter(m),m++),c.parent.setCell(m,p,u[y])}else c.parent.addChildrenAfter(s.filter(u=>u.type!=="first"),c);return l.position=l.offsetOf(s[s.length-1]),l.contentDidChange({inputType:"insertFromPaste"}),Y(e),!0}}catch(a){}if(o=typeof r!="string"?r.getData("application/json"):"",o&&globalThis.MathfieldElement.computeEngine)try{let a=JSON.parse(o);if(typeof a=="object"&&"latex"in a&&a.latex&&(i=a.latex),!i){let s=globalThis.MathfieldElement.computeEngine.box(a);s&&!s.has("Error")&&(i=s.latex)}i||(n="latex")}catch(a){}if(!i&&typeof r!="string"&&(i=r.getData("application/x-latex"),i&&(n="latex")),i||(i=typeof r=="string"?r:r.getData("text/plain")),i){let a;return[a,i]=Ya(i),n==="auto"&&a&&(n="latex"),e.stopCoalescingUndo(),e.stopRecording(),this.insert(e.model,i,{format:n})&&(e.startRecording(),e.snapshot("paste"),Y(e)),e.startRecording(),!0}return!1}insert(e,r,i){var k,S,A,E;let n=typeof r=="string"?r:(S=(k=globalThis.MathfieldElement.computeEngine)==null?void 0:k.box(r).latex)!=null?S:"";if(!i.silenceNotifications&&!e.contentWillChange({data:n,inputType:"insertText"}))return!1;i.insertionMode||(i.insertionMode="replaceSelection"),i.selectionMode||(i.selectionMode="placeholder"),i.format||(i.format="auto");let{silenceNotifications:o}=e;i.silenceNotifications&&(e.silenceNotifications=!0);let a=e.silenceNotifications;e.silenceNotifications=!0;let s={"?":"\\placeholder{}","@":"\\placeholder{}"};s[0]=i.insertionMode==="replaceAll"?"":e.getValue(e.selection,"latex-unstyled"),i.insertionMode==="replaceSelection"?e.deleteAtoms(de(e.selection)):i.insertionMode==="replaceAll"?e.deleteAtoms():i.insertionMode==="insertBefore"?e.collapseSelection("backward"):i.insertionMode==="insertAfter"&&e.collapseSelection("forward");let l=e.at(e.position);l&&!l.isLastSibling&&((A=e.at(e.position+1))==null?void 0:A.type)==="placeholder"?e.deleteAtoms([e.position,e.position+1]):(l==null?void 0:l.type)==="placeholder"&&e.deleteAtoms([e.position-1,e.position]);let c=-1;s[0]?s["@"]=s[0]:typeof r=="string"&&/(^|[^\\])#@/.test(r)&&(c=Zb(e),c>=0&&(s["@"]=e.getValue(c,e.position,"latex"))),s[0]||(s[0]=s["?"]);let u=!1,d=C=>(u=!0,s[C]),[m,p]=Mp(e,r,d,i);if(!p)return!1;let f=p.length===1&&p[0].type==="genfrac",y=e.at(e.position);f&&c>=0&&typeof e.mathfield.options.isImplicitFunction=="function"&&y&&e.mathfield.options.isImplicitFunction(y.command)&&(s["@"]=s["?"],u=!1,[m,p]=Mp(e,r,d,i));let v=e.position;if(p.length===1&&p[0].isRoot)e.root=p[0];else{let C=e.at(e.position),_=(E=C==null?void 0:C.parent)!=null?E:e.root,O=_.hasEmptyBranch("body");if(f&&m!=="latex"&&e.mathfield.options.removeExtraneousParentheses&&_ instanceof J&&_.leftDelim==="("&&O){let V=_.parent,K=_.parentBranch;V.removeChild(_),V.setChildren(p,K)}let I=e.at(e.position);if(I)I.parent.addChildrenAfter(p,I);else{let V=_.branch("body"),K=V==null?void 0:V[0];K?_.addChildrenAfter(p,K):_.setChildren(p,"body")}if(c>=0){e.deleteAtoms([c,v]);let V=e.root.branch("body");if(V)for(let K of V)K.parent!==e.root&&(K.parent=e.root,K.parentBranch="body")}m==="latex"&&typeof r=="string"&&(_==null?void 0:_.type)==="root"&&O&&!u&&(_.verbatimLatex=r)}e.silenceNotifications=a;let b=p[p.length-1];if(i.selectionMode==="placeholder"){let C;if(p.length===1&&p[0].type==="genfrac"){let _=p[0].branch("above");if(C=_==null?void 0:_.find(O=>O.type==="placeholder"),!C){let O=p[0].branch("below");C=O==null?void 0:O.find(I=>I.type==="placeholder")}}if(C||(C=p.flatMap(_=>[_,..._.children]).find(_=>_.type==="placeholder")),C){let _=e.offsetOf(C);e.setSelection(_-1,_),e.announce("move")}else if(b){let _=b.body,O=b.hasEmptyBranch("body");_&&O?e.setSelection(e.offsetOf(_[0]),e.offsetOf(_[_.length-1])+1):e.position=e.offsetOf(b)}}else i.selectionMode==="before"||(i.selectionMode==="after"?b&&(e.position=e.offsetOf(b)):i.selectionMode==="item"&&e.setSelection(e.anchor,e.offsetOf(b)));return e.contentDidChange({data:n,inputType:"insertText"}),e.silenceNotifications=o,!0}};function Mp(t,e,r,i){var a;let n,o=[];if(typeof e!="string"){let s=globalThis.MathfieldElement.computeEngine;if(!s)return["latex",[]];[n,e]=["latex",s.box(e).latex],o=be(e,{context:t.mathfield.context})}else typeof e=="string"&&i.format==="ascii-math"?([n,e]=or(e,{format:"ascii-math",inlineShortcuts:t.mathfield.options.inlineShortcuts}),o=be(e,{context:t.mathfield.context}),n!=="latex"&&t.mathfield.options.removeExtraneousParentheses&&(o=o.map(s=>Ps(s)))):(i.format==="auto"||(a=i.format)!=null&&a.startsWith("latex"))&&(i.format==="auto"&&([n,e]=or(e,{format:"auto",inlineShortcuts:t.mathfield.options.inlineShortcuts})),i.format==="latex"&&([,e]=Ya(e)),o=be(e,{context:t.mathfield.context,args:r}),i.format!=="latex"&&t.mathfield.options.removeExtraneousParentheses&&(o=o.map(s=>Ps(s))));return oo(o,i.style),[n!=null?n:"latex",o]}function Ps(t){var e;if(t instanceof J&&t.leftDelim!=="("&&t.rightDelim===")"){let r=(e=t.body)==null?void 0:e.filter(i=>i.type!=="first");if((r==null?void 0:r.length)===1&&r[0].type==="genfrac")return r[0]}for(let r of t.branches)t.hasEmptyBranch(r)||t.setChildren(t.branch(r).map(i=>Ps(i)),r);return t instanceof z&&t.forEachCell((r,i,n)=>{t.setCell(i,n,r.map(o=>Ps(o)))}),t}function Zb(t){let e=t.at(t.position);if(!e)return-1;if(e.mode==="text"){for(;!e.isFirstSibling&&e.mode==="text";)e=e.leftSibling;return t.offsetOf(e)}let r=e,i=!1;if(e.type==="mclose"){let n=on[e.value];for(;!e.isFirstSibling&&!(e.type==="mopen"&&e.value===n);){let o=e.leftSibling;if(!o)break;e=o}if(!e.isFirstSibling){let o=e.leftSibling;o&&(e=o)}i=!0}else if(e.type==="leftright"){let n=e.leftSibling;n&&(e=n),i=!0}if(i)for(;!e.isFirstSibling&&(e.isFunction||wp(e));){let n=e.leftSibling;if(!n)break;e=n}else{let n=[];for(;!e.isFirstSibling&&(wp(e)||n.length>0);){e.type==="mclose"&&n.unshift(e.value),e.type==="mopen"&&n.length>0&&e.value===on[n[0]]&&n.shift();let o=e.leftSibling;if(!o)break;e=o}}return r===e?-1:t.offsetOf(e)}function Yb(t){if(t.type==="mord"&&t.value==="e"){let e=t.leftSibling;if(e&&e.isDigit())return!0}if(t.type==="mbin"&&(t.value==="+"||t.value==="-"||t.value==="\u2212")){let e=t.leftSibling,r=t.rightSibling;if((e==null?void 0:e.type)==="mord"&&e.value==="e"&&r&&r.isDigit()){let i=e.leftSibling;if(i&&i.isDigit())return!0}}if(t.type==="subsup"){let e=t.leftSibling;if(e&&e.isDigit()&&e.value==="0"){let r=e.leftSibling;if(r&&r.isDigit()&&r.value==="1"){let i=r.leftSibling;if((i==null?void 0:i.type)==="mbin"&&(i.value==="\xD7"||i.value==="\\times")){let n=i.leftSibling;if(n&&n.isDigit())return!0}}}}if(t.isDigit()&&t.value==="0"){let e=t.leftSibling,r=t.rightSibling;if(e&&e.isDigit()&&e.value==="1"&&(r==null?void 0:r.type)==="subsup"){let i=e.leftSibling;if((i==null?void 0:i.type)==="mbin"&&(i.value==="\xD7"||i.value==="\\times")){let n=i.leftSibling;if(n&&n.isDigit())return!0}}}if(t.isDigit()&&t.value==="1"){let e=t.rightSibling;if(e&&e.isDigit()&&e.value==="0"){let r=e.rightSibling;if((r==null?void 0:r.type)==="subsup"){let i=t.leftSibling;if((i==null?void 0:i.type)==="mbin"&&(i.value==="\xD7"||i.value==="\\times")){let n=i.leftSibling;if(n&&n.isDigit())return!0}}}}if(t.type==="mbin"&&(t.value==="\xD7"||t.value==="\\times")){let e=t.leftSibling,r=t.rightSibling;if(e&&e.isDigit()&&r&&r.isDigit()&&r.value==="1"){let i=r.rightSibling;if(i&&i.isDigit()&&i.value==="0"){let n=i.rightSibling;if((n==null?void 0:n.type)==="subsup")return!0}}}return!1}function wp(t){return t.isDigit()||Yb(t)?!0:t.type&&/^(mord|surd|subsup|leftright|mop|mclose)$/.test(t.type)?t.type!=="extensible-symbol":!1}new Gc;var jc=class extends H{constructor(){super("text")}onPaste(e,r){if(!r)return!1;let i=typeof r=="string"?r:r.getData("text/plain");return i&&e.model.contentWillChange({inputType:"insertFromPaste",data:i})?(e.stopCoalescingUndo(),e.stopRecording(),this.insert(e.model,i)&&(e.model.contentDidChange({inputType:"insertFromPaste"}),e.startRecording(),e.snapshot("paste"),Y(e)),e.startRecording(),!0):!1}insert(e,r,i={}){if(!e.contentWillChange({data:r,inputType:"insertText"}))return!1;i.insertionMode||(i.insertionMode="replaceSelection"),i.selectionMode||(i.selectionMode="placeholder"),i.format||(i.format="auto");let{silenceNotifications:n}=e;i.silenceNotifications&&(e.silenceNotifications=!0);let o=e.silenceNotifications;e.silenceNotifications=!0,i.insertionMode==="replaceSelection"&&!e.selectionIsCollapsed?e.deleteAtoms(de(e.selection)):i.insertionMode==="replaceAll"?(e.root.setChildren([],"body"),e.position=0):i.insertionMode==="insertBefore"?e.collapseSelection("backward"):i.insertionMode==="insertAfter"&&e.collapseSelection("forward");let a=Qb(r,e.mathfield.context);if(oo(a,i.style),!a)return!1;let s=e.at(e.position),l=s.parent.addChildrenAfter(a,s);return e.silenceNotifications=o,i.selectionMode==="before"||(i.selectionMode==="item"?e.setSelection(e.anchor,e.offsetOf(l)):l&&(e.position=e.offsetOf(l))),e.contentDidChange({data:r,inputType:"insertText"}),e.silenceNotifications=n,!0}};function Qb(t,e){if(t.includes("$")){let r=[],i=0,n=!1,o="";for(;i` + + + + + `,Sp=(t,e)=>` + + + + + `,zs=(t,e,r)=>` + + + + + + `,ty=` + + + + + ${zs(2*(se+ve),2*se+3*ve,0)} + + + ${zs(2*(se+ve),2*se+ve,180)} + + + ${zs(2*se+3*ve,2*(se+ve),-90)} + + + ${zs(2*se+ve,2*(se+ve),90)} + + + + + ${Is(2*se+ve,se)} + + + ${Sp(2*se+2*ve,se)} + + + ${Is(2*se+3*ve,se)} + + + ${Is(se,2*se+ve)} + + + ${Sp(se,2*se+2*ve)} + + + ${Is(se,2*se+3*ve)} + +`,ry=t=>` + + + + + `,iy=t=>` + + + + + + + `,kp=t=>` + + + + + + + +`,ny=t=>` + + + + + + + +`,oy=t=>` + + + + + + + +`,ay=t=>` + + + + + + + + + +`,sy=t=>` + + + + + + + +`,ly=t=>` + + + + + + + +`,Jc={matrix:ry,pmatrix:iy,bmatrix:ny,Bmatrix:kp,vmatrix:oy,Vmatrix:ay},Xc={cases:sy,rcases:ly,Bmatrix:kp};function cy(t){var m,y;let e=(m=t.model.parentEnvironment)==null?void 0:m.rows;if(!e)return;let r=0;e.forEach(v=>{(!r||v.length>r)&&(r=v.length)});let i=document.getElementById("mathlive-environment-popover");i||(i=vi("mathlive-environment-popover"),Ge("environment-popover"),Ge("core"),i.setAttribute("aria-hidden","true"));let n,o=i.querySelector(".MLEP__environment-controls");o?n=o:(n=document.createElement("div"),i.innerHTML="",i.appendChild(n)),n.className="MLEP__environment-controls",n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.boxSizing="border-box",n.innerHTML=ty;let a=[],s="",l=t.model.parentEnvironment.environmentName;if(rs(l)){let v=uy(l);s=Jc[v]("active");let p=Jc,{[v]:b}=p,k=Ti(p,[nl(v)]);a=Object.values(k).map(S=>S("inactive"))}else if(xh(l)){let v=dy(l);s=Xc[v]("active");let f=Xc,{[v]:b}=f,k=Ti(f,[nl(v)]);a=Object.values(k).map(S=>S("inactive"))}else vh(l)&&(s=Jc.matrix("active"),a=Object.values(Xc).map(v=>v("inactive")));let c=document.createElement("div");c.className="MLEP__environment-delimiter-controls",c.style.display="flex",c.style.flexDirection="column",c.innerHTML=` +
    + ${s} + ${a.join("")} +
    `,s&&n.appendChild(c),n.querySelectorAll("[data-command]").forEach(v=>{let b=v.dataset.command,k=b;try{k=JSON.parse(b)}catch(S){}v.addEventListener("mousedown",S=>S.preventDefault()),k&&v.addEventListener("click",()=>t.executeCommand(k))});let d=(y=t.field)==null?void 0:y.getBoundingClientRect();d&&(i.style.top=`${window.scrollY+(d.top-i.clientHeight-15)}px`,i.style.left=`${d.left+20}px`,i.classList.add("is-visible"))}function Ns(){let t=document.getElementById("mathlive-environment-popover");t==null||t.classList.remove("is-visible")}function Lp(){document.getElementById("mathlive-environment-popover")&&(qr("mathlive-environment-popover"),ot("environment-popover"),ot("core"))}function Eo(t){if(!t.hasFocus())return;let e=!1;if(t.model.mode==="math"){let r=t.model.parentEnvironment;if(r!=null&&r.rows&&yh(r.environmentName)){let i=t.options.environmentPopoverPolicy;e=i==="auto"||i==="on"}}e?cy(t):Ns()}function uy(t){return t.replace("*","")}function dy(t){return t==="dcases"?"cases":t}function Fs(t){let e=getComputedStyle(t).direction;return e==="ltr"||e==="rtl"?e:"ltr"}function Yc(t,e,r){return e==="left"||e==="leading"&&r==="ltr"||e==="trailing"&&r==="rtl"?t.left:t.right}function Zc(t,e,r,i){return r==="middle"?t-e/2:r==="start"&&i==="rtl"||r==="end"&&i==="ltr"||r==="top"||r==="right"?Math.max(0,t-e):t}function my(t,e,r,i){return r==="middle"?t-e/2:r==="start"&&i==="ltr"||r==="end"&&i==="rtl"||r==="top"||r==="right"?t:t-e}function Ap(t,e){var u,d,m;let r=(u=Fs(t))!=null?u:"ltr";t.style.position="fixed",t.style.left="",t.style.top="",t.style.right="",t.style.bottom="",t.style.height="",t.style.width="";let i=t.getBoundingClientRect(),n=Number.isFinite(e.maxHeight)?Math.min(e.maxHeight,window.innerHeight):window.innerHeight,o=Math.min(n,(d=e.height)!=null?d:i.height),a=Zc(e.location.y,o,e.verticalPos,r);a+o>window.innerHeight-8&&(e.alternateLocation?(a=Zc(e.alternateLocation.y,o,e.verticalPos,r),a+o>window.innerHeight-8&&(a=void 0)):a=void 0),Number.isFinite(a)||(a=Math.max(8,window.innerHeight-8-o),8+o>window.innerHeight-8&&(t.style.bottom="8px")),o=Math.min(a+o,window.innerHeight-8)-a;let s=Number.isFinite(e.maxWidth)?Math.min(e.maxWidth,window.innerWidth):window.innerWidth,l=Math.min(s,(m=e.width)!=null?m:i.width),c=Zc(e.location.x,l,e.horizontalPos,r);c+l>window.innerWidth-8&&(e.alternateLocation?(c=my(e.alternateLocation.x,l,e.verticalPos,r),c+l>window.innerWidth-8&&(c=void 0)):c=void 0),Number.isFinite(c)||(c=Math.max(8,window.innerWidth-8-l),8+l>window.innerWidth-8&&(t.style.right="8px")),l=Math.min(c+l,window.innerWidth-8)-c,r==="rtl"?t.style.right=`${Math.ceil(window.innerWidth-c-l).toString()}px`:t.style.left=`${Math.ceil(c).toString()}px`,t.style.top=`${Math.ceil(a).toString()}px`,o!==i.height&&(t.style.height=`${Math.ceil(o).toString()}px`),l!==i.width&&(t.style.width=`${Math.ceil(l).toString()}px`)}function Cp(t,e){return Math.hypot(e.x-t.x,e.y-t.y)}function Ur(t){return"submenu"in t}function Lt(t){return"type"in t&&t.type==="command"||"onMenuSelect"in t||"id"in t}function To(t){return"type"in t&&t.type==="divider"}function $s(t){return"type"in t&&t.type==="heading"}var Ep={};function Vs(t){let e=Ep[t];if(!e){let r;switch(t){case"checkmark":r=``;break;case"trailing-chevron":r='';break;case"mixedmark":r=''}if(r){let i=document.createElement("template");i.innerHTML=r,Ep[t]=i,e=i}}if(e){if("content"in e)return e.content.cloneNode(!0);let r=document.createElement("svg");return r.innerHTML=e.innerHTML,r}}var Tp=80,En=class{constructor(e,r){this._className="";this._element=null;var i;this.parentMenu=r,this._declaration=e,Object.freeze(this._declaration),Ur(e)?(this.type="submenu",this.submenu=new Tn(e.submenu,{parentMenu:r,submenuClass:e.submenuClass,columnCount:e.columnCount})):this.type=(i=e.type)!=null?i:"command",this.hasCheck=Lt(e)&&e.checked!==void 0}get rootMenu(){return this.parentMenu.rootMenu}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}dispose(){var e,r;(e=this._abortController)==null||e.abort(),this._abortController=void 0,(r=this._element)==null||r.remove(),this._element=null,this.submenu&&this.submenu.dispose(),this.submenu=void 0}get menuItem(){return this._declaration}get label(){var e;return(e=this._label)!=null?e:""}set label(e){e===void 0&&(e=""),e!==this._label&&(this._label=e,this.dirty=!0)}get visible(){return this._visible}set visible(e){e!==this._visible&&(this._visible=e,this.dirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.element&&(e?this.element.removeAttribute("aria-disabled"):this.element.setAttribute("aria-disabled","true")),this.dirty=!0}get checked(){return this._checked}set checked(e){this._checked=e,this.dirty=!0}get tooltip(){return this._tooltip}set tooltip(e){e!==this._tooltip&&(this._tooltip=e,this.dirty=!0)}get ariaLabel(){return this._ariaLabel}set ariaLabel(e){e!==this._ariaLabel&&(this._ariaLabel=e,this.dirty=!0)}get active(){var e,r;return(r=(e=this.element)==null?void 0:e.classList.contains("active"))!=null?r:!1}set active(e){this.element&&this.element.classList.toggle("active",e)}updateState(e){var i,n,o;let r=this._declaration;if(To(r)){this.enabled=!1,this.checked=!1;return}$s(r)&&(this.enabled=!1,this.checked=!1,this.visible=!0),Lt(r)&&(this.checked=(i=Ai(r.checked,e))!=null?i:!1),(Lt(r)||Ur(r))&&(this.enabled=(n=Ai(r.enabled,e))!=null?n:!0,this.visible=(o=Ai(r.visible,e))!=null?o:!0,this.visible&&this.enabled&&this.submenu&&(this.submenu.updateState(e),this.submenu.visible||(this.visible=!1))),(Lt(r)||$s(r)||Ur(r))&&(this.label=Ai(r.label,e),this._className=Ai(r.class,e),this.tooltip=Ai(r.tooltip,e),this.ariaLabel=Ai(r.ariaLabel,e)),this._element&&this.updateElement()}set dirty(e){e&&this.parentMenu&&(this.parentMenu.dirty=!0)}updateElement(){var i;if(!this.visible||!this.element)return;let e=this.element;e.textContent="",e.className="",e.className=(i=this._className)!=null?i:"",this.enabled?e.removeAttribute("aria-disabled"):e.setAttribute("aria-disabled","true"),this.checked===!0?(e.setAttribute("aria-checked","true"),e.append(Vs("checkmark"))):this.checked==="mixed"?(e.setAttribute("aria-checked","mixed"),e.append(Vs("mixedmark"))):e.removeAttribute("aria-checked"),this.ariaLabel&&e.setAttribute("aria-label",this.ariaLabel);let r=document.createElement("span");if(r.className=this.parentMenu.hasCheck?"label indent":"label",this.type==="heading"&&r.classList.add("heading"),r.innerHTML=this.label,e.append(r),this._tooltip&&e.setAttribute("data-tooltip",this._tooltip),Lt(this._declaration)&&this._declaration.keyboardShortcut){let n=document.createElement("kbd");n.innerHTML=gn(this._declaration.keyboardShortcut),e.append(n)}this.type==="submenu"&&e.append(Vs("trailing-chevron"))}get element(){if(this._element)return this._element;if(To(this._declaration)){let i=document.createElement("li");return i.setAttribute("part","menu-divider"),i.setAttribute("role","divider"),this._element=i,i}let e=document.createElement("li");this._element=e,(Lt(this._declaration)||$s(this._declaration)||Ur(this._declaration))&&e.setAttribute("part","menu-item"),e.setAttribute("tabindex","-1"),this.hasCheck?e.setAttribute("role","menuitemcheckbox"):e.setAttribute("role","menuitem"),this.type==="submenu"&&(e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false"));let r=this.abortController.signal;return e.addEventListener("pointerenter",this,{signal:r}),e.addEventListener("pointerleave",this,{signal:r}),e.addEventListener("pointerup",this,{signal:r}),e.addEventListener("click",this,{signal:r}),this._element}dispatchSelect(){var i;if(!Lt(this._declaration))return;let e=new CustomEvent("menu-select",{cancelable:!0,bubbles:!0,detail:{modifiers:this.rootMenu.modifiers,id:this._declaration.id,data:this._declaration.data}});this.parentMenu.dispatchEvent(e)&&typeof this._declaration.onMenuSelect=="function"&&this._declaration.onMenuSelect({target:(i=this.parentMenu.host)!=null?i:void 0,modifiers:this.rootMenu.modifiers,id:this._declaration.id,data:this._declaration.data})}handleEvent(e){var r;if(!(!this.visible||!this.enabled)){if(e.type==="click"){this.rootMenu.state==="modal"&&this.select(),e.stopPropagation(),e.preventDefault();return}if(e.type==="pointerenter"){let i=e;this.rootMenu.cancelDelayedOperation(),this.parentMenu.isSubmenuOpen&&((r=this.parentMenu.activeMenuItem)!=null&&r.movingTowardSubmenu(i))?this.rootMenu.scheduleOperation(()=>{this.parentMenu.activeMenuItem=this,this.openSubmenu()}):(this.parentMenu.activeMenuItem=this,this.openSubmenu({withDelay:!0}));return}if(e.type==="pointerleave"){this.rootMenu.activeSubmenu===this.parentMenu&&(this.parentMenu.activeMenuItem=null);return}if(e.type==="pointerup"){this.rootMenu.state!=="modal"&&this.select(),e.stopPropagation(),e.preventDefault();return}}}select(){if(this.rootMenu.cancelDelayedOperation(),this.type==="submenu"){this.openSubmenu();return}this.active=!1,setTimeout(()=>{this.active=!0,setTimeout(()=>{this.active=!1,this.rootMenu.hide(),this.dispatchSelect()},Tp)},Tp)}openSubmenu(e){var n;if(this.type!=="submenu"||!this.element)return;if((n=e==null?void 0:e.withDelay)!=null&&n){this.rootMenu.scheduleOperation(()=>this.openSubmenu());return}let r=this.element.getBoundingClientRect(),i=Fs(this.element);this.submenu.show({container:this.rootMenu.element.parentNode,location:{x:Yc(r,"trailing",i),y:r.top-4},alternateLocation:{x:Yc(r,"leading",i),y:r.top-4}})}movingTowardSubmenu(e){if(!this.element||this.type!=="submenu")return!1;let r=this.rootMenu.lastMoveEvent;if(!r)return!1;let i=e.timeStamp-r.timeStamp;if(i>500)return!1;let n=e.clientX-r.clientX;if(hy(n,r.clientY-e.clientY,i)<=.2)return!1;let a="right";if(this.submenu.element){let s=this.submenu.element.getBoundingClientRect(),l=this.element.getBoundingClientRect();s.left0:n<0}};function hy(t,e,r){return Math.hypot(t,e)/r}function Ai(t,e){return t===void 0||typeof t!="function"?t:(e!=null||(e={alt:!1,control:!1,shift:!1,meta:!1}),t(e))}var Tn=class t{constructor(e,r){this._element=null;this._activeMenuItem=null;this._dirty=!0;var i,n;this.parentMenu=(i=r==null?void 0:r.parentMenu)!=null?i:null,this._submenuClass=r==null?void 0:r.submenuClass,this.columnCount=(n=r==null?void 0:r.columnCount)!=null?n:1,this.isSubmenuOpen=!1,this.menuItems=e}get children(){return Object.freeze([...this._menuItems])}set menuItems(e){let r=this.parentMenu;this.dispose(),this.parentMenu=r,e=[...e],this._menuItems=e.map(i=>i.onCreate?i.onCreate(i,this):new En(i,this)),this.hasCheck=void 0,this.dirty=!0}dispose(){var e;this.hide(),this._element&&this._element.remove(),this._abortController&&this._abortController.abort(),(e=this._menuItems)==null||e.forEach(r=>r.dispose()),this._menuItems=[],this._activeMenuItem=null,this.parentMenu=null}handleEvent(e){if(e.type==="wheel"&&this._element){let r=e;this._element.scrollBy(0,r.deltaY),e.stopPropagation()}}dispatchEvent(e){return this.rootMenu.dispatchEvent(e)}get host(){return this.rootMenu.host}get rootMenu(){return this.parentMenu.rootMenu}updateState(e){var a,s,l;this._menuItems.forEach(c=>c.updateState(e));let r=this.hasCheck;this.hasCheck=this._menuItems.some(c=>c.visible&&c.hasCheck),this.hasCheck!==r&&this._menuItems.forEach(c=>c.updateState(e));let i,n=0;for(let c of this._menuItems)c.type==="heading"?(i&&n===0&&(i.visible=!1),i=c,n=0):c.type==="divider"&&i?(i.visible=n>0,i=void 0,n=0):i&&c.visible&&(n+=1);i&&(i.visible=n>0);let o=!0;for(let c of this._menuItems)c.type==="divider"?(c.visible=!o,o=!0):c.visible&&(o=!1);(a=this.activeMenuItem)!=null&&a.visible||(this.activeMenuItem=null),!((s=this.activeMenuItem)!=null&&s.enabled)&&((l=this.activeMenuItem)==null?void 0:l.type)==="submenu"&&this._activeMenuItem.submenu.hide(),this._dirty=!1}get enabled(){return this.updateIfDirty(),this._menuItems.some(e=>e.type!=="divider"&&e.visible&&e.enabled)}get visible(){return this.updateIfDirty(),this._menuItems.some(e=>e.type!=="divider"&&e.visible)}set dirty(e){this._dirty!==e&&e&&this.parentMenu&&(this._dirty=!0,this.parentMenu.dirty=!0)}updateIfDirty(){this._dirty&&this.updateState(this.rootMenu.modifiers)}updateElement(){var e;if(this._element){this._element.textContent="";for(let{element:r,visible:i}of this._menuItems)r&&i&&this._element.append(r);(e=this._element.querySelector("li:first-of-type"))==null||e.setAttribute("tabindex","0")}}get element(){if(this._element)return this._element;let e=document.createElement("menu");e.setAttribute("role","menu"),e.setAttribute("tabindex","-1"),e.setAttribute("aria-orientation","vertical"),e.setAttribute("part","ui-menu-container"),this._submenuClass&&e.classList.add(this._submenuClass),e.classList.add("ui-menu-container"),this._abortController||(this._abortController=new AbortController);let r=this._abortController.signal;return e.addEventListener("focus",this,{signal:r}),e.addEventListener("wheel",this,{passive:!0,signal:r}),this._element=e,this.updateElement(),e}get activeMenuItem(){return this._activeMenuItem}set activeMenuItem(e){var r,i,n,o;if(this.rootMenu.cancelDelayedOperation(),e!==this._activeMenuItem){if(this.activeMenuItem){let a=this.activeMenuItem;a.active=!1,(r=a.submenu)==null||r.hide()}if(!((i=e==null?void 0:e.visible)==null||i)){this._activeMenuItem=null;return}this._activeMenuItem=e,e&&(e.active=!0)}e?(n=e.element)==null||n.focus({preventScroll:!0}):(o=this._element)==null||o.focus({preventScroll:!0})}get firstMenuItem(){this.updateIfDirty();let e=0,r=!1,i=this._menuItems;for(;!r&&e<=i.length-1;){let n=i[e];r=n.type!=="divider"&&n.visible&&n.enabled,e+=1}return r?i[e-1]:null}get lastMenuItem(){this.updateIfDirty();let e=this._menuItems,r=e.length-1,i=!1;for(;!i&&r>=0;){let n=e[r];i=n.type!=="divider"&&n.visible&&n.enabled,r-=1}return i?e[r+1]:null}nextMenuItem(e){if(e===0)return this._activeMenuItem;if(!this._activeMenuItem)return e>0?this.firstMenuItem:this.lastMenuItem;if(!this.firstMenuItem||!this.lastMenuItem||!this._activeMenuItem)return null;this.updateIfDirty();let r=this._menuItems.indexOf(this.firstMenuItem),i=this._menuItems.indexOf(this.lastMenuItem),n=this._menuItems.indexOf(this._activeMenuItem),o=1;for(;n>=r&&n<=i;){n+=e>0?1:-1;let a=this._menuItems[n];if(!a)break;if(a.visible&&a.enabled){if(o===Math.abs(e))return this._menuItems[n];o+=1}}return e>0?this.lastMenuItem:this.firstMenuItem}getMenuItemColumn(e){this.updateIfDirty();let i=this._menuItems.filter(n=>n.visible&&n.enabled).indexOf(e);return i<0?-1:i%this.columnCount}static get collator(){return t._collator||(t._collator=new Intl.Collator(void 0,{usage:"search",sensitivity:"base"})),t._collator}findMenuItem(e){var a;this.updateIfDirty();let r=this._menuItems.filter(s=>s.type!=="divider"&&s.visible&&s.enabled);if(r.length===0)return null;let i=Math.max(...r.map(s=>s.label.length))-e.length;if(i<0)return null;let n=null,o=0;for(;ot.collator.compare(e,s.label.substring(o,e.length))===0))!=null?a:null,o++;return n}show(e){return!this.visible||!e.container?!1:(this.updateElement(),e.container.appendChild(this.element),ol()&&(this.element.popover="manual",this.element.showPopover()),e.location&&Ap(this.element,{location:e.location,alternateLocation:e.alternateLocation,verticalPos:"bottom",horizontalPos:"start"}),Dp(),this.element.focus({preventScroll:!0}),Op(),this.parentMenu&&(this.parentMenu.openSubmenu=this),!0)}hide(){var e,r,i,n,o,a;this.openSubmenu=null,this.activeMenuItem=null,this.parentMenu&&(this.parentMenu.openSubmenu=null),!(!((e=this._element)!=null&&e.isConnected)||!this._element.parentElement)&&(ol()&&((r=this._element)!=null&&r.popover)&&this._element.hidePopover(),Dp(),(n=(i=this.parentMenu)==null?void 0:i.element)==null||n.focus(),(a=(o=this._element)==null?void 0:o.parentNode)==null||a.removeChild(this._element),Op())}set openSubmenu(e){var i,n,o,a;let r=e!==null;((i=this.activeMenuItem)==null?void 0:i.type)==="submenu"&&((n=this.activeMenuItem.element)==null||n.setAttribute("aria-expanded",r.toString())),(a=(o=this.activeMenuItem)==null?void 0:o.element)==null||a.classList.toggle("is-submenu-open",r),this.isSubmenuOpen=r}};function Dp(){document.addEventListener("focusin",Gr,!0),document.addEventListener("focusout",Gr,!0),document.addEventListener("focus",Gr,!0),document.addEventListener("blur",Gr,!0)}function Gr(t){t.stopImmediatePropagation(),t.preventDefault()}function Op(){document.removeEventListener("focusin",Gr,!0),document.removeEventListener("focusout",Gr,!0),document.removeEventListener("focus",Gr,!0),document.removeEventListener("blur",Gr,!0)}var qs=class qs extends Tn{constructor(r,i){var n;super(r);this.state="closed";this.typingBufferResetTimer=0;this.hysteresisTimer=0;this._updating=!1;this._host=(n=i==null?void 0:i.host)!=null?n:null,this.isDynamic=r.some(Bp),this._modifiers={shift:!1,control:!1,alt:!1,meta:!1},this.typingBuffer="",this.state="closed"}get modifiers(){return this._modifiers}set modifiers(r){Dh(this._modifiers,r)||(this._modifiers=r,this.dirty=!0)}get activeSubmenu(){let r=this;for(;r.isSubmenuOpen;)r=r.activeMenuItem.submenu;return r}set dirty(r){this._updating||this._dirty!==r&&(this._dirty=!0,r&&setTimeout(()=>{this.updateState(this.modifiers),this.updateElement()}))}updateState(r){this._updating=!0,this.modifiers=r!=null?r:this.modifiers,super.updateState(this.modifiers),this._updating=!1}handleKeyupEvent(r){this.isDynamic&&(this.modifiers=Wt(r)),r.stopImmediatePropagation()}handleKeydownEvent(r){var a,s,l;if(r.key==="Tab"||r.key==="Escape"){this.hide();return}this.isDynamic&&(this.modifiers=Wt(r));let i=!0,n=this.activeSubmenu,o=n.activeMenuItem;switch(r.key){case" ":case"Space":case"Return":case"Enter":o==null||o.select(Wt(r));break;case"ArrowRight":if((o==null?void 0:o.type)==="submenu")o.select(Wt(r)),this.activeSubmenu.activeMenuItem=this.activeSubmenu.firstMenuItem;else if(!o)n.activeMenuItem=n.firstMenuItem;else{let c=(a=n.getMenuItemColumn(o))!=null?a:-1;if(c>=0&&c<((s=n.columnCount)!=null?s:1)-1){let u=n.nextMenuItem(1);u&&(n.activeMenuItem=u)}}break;case"ArrowLeft":if(n===this.rootMenu)o||(n.activeMenuItem=n.firstMenuItem);else if((o&&(l=n.getMenuItemColumn(o))!=null?l:-1)<=0||!o){n.hide();let u=n.parentMenu.activeMenuItem;if(u){let{element:d}=u;d==null||d.focus(),d==null||d.classList.remove("is-submenu-open")}}else{let u=n.nextMenuItem(-1);u&&(n.activeMenuItem=u)}break;case"ArrowDown":n.activeMenuItem=n.nextMenuItem(n.columnCount);break;case"ArrowUp":n.activeMenuItem=n.nextMenuItem(-n.columnCount);break;case"Home":case"PageUp":n.activeMenuItem=n.firstMenuItem;break;case"End":case"PageDown":n.activeMenuItem=n.lastMenuItem;break;case"Backspace":if(this.typingBuffer&&(this.typingBuffer=this.typingBuffer.slice(0,-1),this.typingBuffer)){clearTimeout(this.typingBufferResetTimer);let c=n.findMenuItem(this.typingBuffer);c&&(n.activeMenuItem=c),this.typingBufferResetTimer=setTimeout(()=>{this.typingBuffer=""},500)}break;default:if(dr(r)){isFinite(this.typingBufferResetTimer)&&clearTimeout(this.typingBufferResetTimer),this.typingBuffer+=r.key;let c=n.findMenuItem(this.typingBuffer);c&&(n.activeMenuItem=c),this.typingBufferResetTimer=setTimeout(()=>{this.typingBuffer=""},500)}else i=!1}i&&(r.preventDefault(),r.stopPropagation())}handleEvent(r){if(r.type==="keydown")this.handleKeydownEvent(r);else if(r.type==="keyup")this.handleKeyupEvent(r);else if(r.type==="pointermove")this.lastMoveEvent=r;else if(r.type==="pointerup")Number.isFinite(this.rootMenu._openTimestamp)&&Date.now()-this.rootMenu._openTimestamp<120?this.state="modal":this.state==="modal"&&r.target===this.scrim&&this.hide();else if(r.type==="contextmenu"){r.preventDefault(),r.stopPropagation();return}super.handleEvent(r)}dispatchEvent(r){return this._host?this._host.dispatchEvent(r):!0}get host(){return this._host}get scrim(){return Te.element}connectScrim(r){let i=this.scrim;i.addEventListener("pointerup",this,!0),i.addEventListener("contextmenu",this),i.addEventListener("keydown",this),i.addEventListener("keyup",this),i.addEventListener("pointermove",this),Te.open({root:r,onDismiss:()=>this.hide()})}disconnectScrim(){let r=this.scrim;r.removeEventListener("pointerup",this,!0),r.removeEventListener("contextmenu",this),r.removeEventListener("keydown",this),r.removeEventListener("keyup",this),r.removeEventListener("pointermove",this),Te.state==="open"&&Te.scrim.close()}get rootMenu(){return this}show(r){return this._onDismiss=r==null?void 0:r.onDismiss,r!=null&&r.modifiers&&(this.modifiers=r.modifiers),this.updateState(),this.connectScrim(r==null?void 0:r.target),super.show(g(h({},r),{container:this.scrim}))?(this._openTimestamp=Date.now(),this.state="open",!0):(this.disconnectScrim(),!1)}hide(){this.cancelDelayedOperation(),this.state!==void 0&&(this.state!=="closed"&&(this.activeMenuItem=null,Te.element.parentElement.focus(),super.hide(),this.state="closed",this.disconnectScrim()),this._onDismiss&&(this._onDismiss(),this._onDismiss=void 0))}scheduleOperation(r){this.cancelDelayedOperation();let i=qs.SUBMENU_DELAY;if(i<=0){r();return}this.hysteresisTimer=setTimeout(()=>{this.hysteresisTimer=0,r()},i)}cancelDelayedOperation(){this.hysteresisTimer&&(clearTimeout(this.hysteresisTimer),this.hysteresisTimer=0)}};qs.SUBMENU_DELAY=120;var Do=qs;function Bp(t){return To(t)?!1:typeof t.label=="function"||typeof t.ariaLabel=="function"||typeof t.tooltip=="function"||(Lt(t)||Ur(t))&&(typeof t.enabled=="function"||typeof t.visible=="function")||Lt(t)&&typeof t.checked=="function"?!0:Ur(t)?t.submenu.some(Bp):!1}var Dn=class{};Dn.DELAY=300,Dn.MAX_DISTANCE=10;function Kp(t){return new Promise((e,r)=>{let i=bn(t);i||e(!1);let n=i,o=setTimeout(()=>{a.abort(),e(Cp(n,i){if(c.type==="pointerup"||c.type==="pointercancel")clearTimeout(o),a.abort(),e(!1);else if(c.type==="pointermove"){let u=bn(c);u&&(n=u)}},{passive:!0,signal:s})})}async function Qc(t,e,r){if(t.defaultPrevented)return!1;if(t.type==="contextmenu"){let i=t;if(t.preventDefault(),t.stopPropagation(),r.show({target:e,location:bn(i),modifiers:Wt(i)}))return!0}if(t.type==="keydown"){let i=t;if(i.code==="ContextMenu"||i.code==="F10"&&i.shiftKey){let n=e==null?void 0:e.getBoundingClientRect();if(Pp(e)&&n&&r.show({target:e,location:{x:Math.ceil(n.left+n.width/2),y:Math.ceil(n.top+n.height/2)},modifiers:Wt(i)}))return t.preventDefault(),t.stopPropagation(),!0}}if(t.type==="pointerdown"&&t.pointerType!=="mouse"&&t.button===0){let i=t.target;for(;i&&e!==i;)i=i.parentNode;if(!i||!r.visible)return!1;let n=bn(t);if(await Kp(t))return r.state!=="closed"||!Pp(e)?!1:(r.show({target:e,location:n}),!0)}return!1}function Pp(t){return t.dispatchEvent(new Event("contextmenu",{cancelable:!0}))}var Zt={"\\ne":"\u2260","\\neq":"\u2260","\u2212":"-","-":"-","\\alpha":"alpha","\\beta":"beta","\\gamma":"gamma","\\delta":"delta","\\epsilon":"epsilon","\\varepsilon":"varepsilon","\\zeta":"zeta","\\eta":"eta","\\theta":"theta","\\vartheta":"vartheta","\\iota":"iota","\\kappa":"kappa","\\lambda":"lambda","\\mu":"mu","\\nu":"nu","\\xi":"xi","\\pi":"pi","\\rho":"rho","\\sigma":"sigma","\\tau":"tau","\\upsilon":"upsilon","\\phi":"phi","\\varphi":"varphi","\\chi":"chi","\\psi":"psi","\\omega":"omega","\\Gamma":"Gamma","\\Delta":"Delta","\\Theta":"Theta","\\Lambda":"Lambda","\\Xi":"Xi","\\Pi":"Pi","\\Sigma":"Sigma","\\Phi":"Phi","\\Psi":"Psi","\\Omega":"Omega","\\exponentialE":"e","\\imaginaryI":"i","\\imaginaryJ":"j","\\!":" ","\\,":" ","\\:":" ","\\>":" ","\\;":" ","\\enskip":" ","\\enspace":" ","\\qquad":" ","\\quad":" ","\\infty":"oo","\\R":"RR","\\mathbb{R}":"RR","\\N":"NN","\\mathbb{N}":"NN","\\Z":"ZZ","\\mathbb{Z}":"ZZ","\\Q":"QQ","\\mathbb{Q}":"QQ","\\C":"CC","\\mathbb{C}":"CC","\\emptyset":"O/","\\varnothing":"O/","\\varDelta":"Delta","\\varTheta":"Theta","\\varLambda":"Lambda","\\varXi":"Xi","\\varPi":"Pi","\\varSigma":"Sigma","\\varUpsilon":"Upsilon","\\varPhi":"Phi","\\varPsi":"Psi","\\varOmega":"Omega"},Oo={"\\pm":"+-","\\colon":" : ","\\sum":" sum ","\\prod":" prod ","\\bigcap":" nnn ","\\bigcup":" uuu ","\\int":" int ","\\oint":" oint ","\\ge":">=","\\le":"<=","\\ne":"!=","\\neq":"!=","\\lt":"<","\\gt":">","\\gets":"<-","\\to":"->","\\land":" and ","\\lor":" or ","\\lnot":" not ","\\forall":" AA ","\\exists":" EE ","\\in":" in ","\\notin":" !in ","\\mapsto":"|->","\\implies":"=>","\\iff":"<=>","\\cdot":" * ","\\ast":" ** ","\\star":" *** ","\\times":" * ","\\div":" -: ","\\ltimes":" |>< ","\\rtimes":" ><| ","\\bowtie":" |><| ","\\circ":"@"},Hs={"\\vert":"|","\\Vert":"||","\\mid":"|","\\lbrack":"[","\\rbrack":"]","\\lbrace":"{","\\rbrace":"}","\\lparen":"(","\\rparen":")","\\langle":"(:","\\rangle":":)"};function py(t){let e="";for(let r of t){let i=e[e.length-1];i!==void 0&&(/\d$/.test(i)&&/^\d/.test(r)||/[a-zA-Z]$/.test(i)&&/^[a-zA-Z]/.test(r))&&(e+=" "),e+=r}return e}function le(t,e){var a,s,l,c,u,d,m,p,f,y,v,b,k,S,A,E,C,_,O;if(!t)return"";if(ee(t)){if(t.length===0)return"";if(t[0].mode==="latex")return t.map(K=>le(K)).join("");if(t[0].mode==="text"){let K=0,N="";for(;((a=t[K])==null?void 0:a.mode)==="text";)N+=t[K].body?le(t[K].body,e):t[K].value,K++;return e!=null&&e.plain?N+le(t.slice(K),e):`"${N}" ${le(t.slice(K))}`}let I=0,V=[];for(;((s=t[I])==null?void 0:s.mode)==="math";){let K="";for(;((l=t[I])==null?void 0:l.type)==="mord"&&/\d/.test(t[I].value);)K+=t[I++].value;K?V.push(K):V.push(le(t[I++],e))}return V.push(le(t.slice(I),e)),py(V)}if(t.mode==="text")return e!=null&&e.plain?t.value:`"${t.value}"`;let r="",{command:i}=t,n;if(i==="\\placeholder")return`(${le(t.body,e)})`;let o=x.serialize([t],{expandMacro:!1,defaultMode:"math"});switch(t.type){case"accent":let I={"\\vec":"vec","\\dot":"dot","\\ddot":"ddot","\\bar":"bar","\\hat":"hat","\\acute":"acute;","\\grave":"grave","\\tilde":"tilde","\\breve":"breave","\\check":"check"}[i];r=`${I!=null?I:""} ${le(t.body,e)} `;break;case"first":return"";case"latexgroup":return t.body.map(K=>K.value).join("");case"group":case"root":r=(c=Zt[i])!=null?c:le(t.body,e);break;case"genfrac":{let K=t;(K.leftDelim||K.rightDelim)&&(r=K.leftDelim==="."||!K.leftDelim?"{:":K.leftDelim),K.hasBarLine?(r+="(",r+=le(K.above,e),r+=")/(",r+=le(K.below,e),r+=")"):(r+="((",r+=le(K.above,e),r+=") choose (",r+=le(K.below,e),r+="))"),(K.leftDelim||K.rightDelim)&&(r+=K.rightDelim==="."||!K.rightDelim?"{:":K.rightDelim)}break;case"surd":t.hasEmptyBranch("above")?r+=`sqrt(${le(t.body,e)})`:r+=`root(${le(t.above,e)})(${le(t.body,e)})`;break;case"latex":r=t.value;break;case"leftright":{let K=t,N=K.leftDelim;N&&Hs[N]&&(N=Hs[N]),r+=N==="."||!N?"{:":N,r+=le(K.body,e);let j=K.matchingRightDelim();j&&Hs[j]&&(j=Hs[j]),r+=j==="."||!j?":}":j}break;case"sizeddelim":case"delim":r=t.value;break;case"overlap":break;case"overunder":break;case"mord":if(Zt[o])return Zt[o];r=(m=(d=(u=Zt[i])!=null?u:i)!=null?d:i)!=null?m:typeof t.value=="string"?t.value:"",r.startsWith("\\")&&(r+=" "),n=i?i.match(/{?\\char"([\dabcdefABCDEF]+)}?/):null,n?r=String.fromCodePoint(Number.parseInt("0x"+n[1])):r.length>0&&r.startsWith("\\")&&(r=typeof t.value=="string"?t.value.charAt(0):t.command),r=fy(r,t.style);break;case"mbin":case"mrel":case"minner":r=(y=(f=(p=Zt[o])!=null?p:Zt[i])!=null?f:Oo[i])!=null?y:t.value;break;case"mopen":case"mclose":r=t.value;break;case"mpunct":r=(v=Oo[i])!=null?v:i;break;case"mop":case"operator":case"extensible-symbol":t.value!=="\u200B"&&(Oo[i]?r=Oo[i]:r=i==="\\operatorname"?le(t.body,e):(b=t.value)!=null?b:i,r+=" ");break;case"array":let V=t.environmentName;if(t.isMultiline)r=t.rows.map(N=>N.map(j=>le(j,e)).join("")).join(` +`);else{let K=(k={bmatrix:["[","]"],"bmatrix*":["[","]"]}[V])!=null?k:["(",")"],N=[],j=t.rows;for(let W of j){let ie=[];for(let X of W)ie.push(le(X,e));N.push(K[0]+ie.join(",")+K[1])}let D=(S={bmatrix:["[","]"],"bmatrix*":["[","]"],cases:["{",":}"]}[V])!=null?S:["(",")"];r=D[0]+N.join(",")+D[1]}break;case"box":break;case"spacing":r=(E=(A=Zt[o])!=null?A:Zt[i])!=null?E:" ";break;case"enclose":r="("+le(t.body,e)+")";break;case"space":r=" ";break;case"subsup":r="";break;case"macro":r=(O=(_=(C=Zt[o])!=null?C:Zt[i])!=null?_:Oo[i])!=null?O:le(t.body,e);break}if(!t.hasEmptyBranch("subscript")){r+="_";let I=le(t.subscript,e);r+=I.length!==1?`(${I})`:I}if(!t.hasEmptyBranch("superscript")){r+="^";let I=le(t.superscript,e);r+=I.length!==1?`(${I})`:I}return r}function fy(t,e){if(!e)return t;let r=t;return e.variant==="double-struck"&&(r=`bbb "${r}"`),e.variant==="script"&&(r=`cc "${r}"`),e.variant==="fraktur"&&(r=`fr "${r}"`),e.variant==="sans-serif"&&(r=`sf "${r}"`),e.variant==="monospace"&&(r=`tt "${r}"`),e.variantStyle==="bold"&&(r=`bb "${r}"`),e.color?`color({${e.color}})(${r})`:r}function pe(t,e){var u;let r=g(h({},Qn()),{renderPlaceholder:()=>new w(160,{maxFontSize:1})});if(e!=null&&e.letterShapeStyle&&(e==null?void 0:e.letterShapeStyle)!=="auto"&&(r.letterShapeStyle=e.letterShapeStyle),e!=null&&e.macros){let d=ei(e==null?void 0:e.macros);r.getMacro=m=>ti(m,d)}e!=null&&e.registers&&(r.registers=h(h({},r.registers),e.registers));let i=(u=e==null?void 0:e.defaultMode)!=null?u:"math",n="math",o="displaystyle";i==="inline-math"?o="textstyle":i==="math"?o="displaystyle":i==="text"&&(o="textstyle",n="text");let a=new P({from:r}),l=new x({type:"root",mode:n,body:be(t,{context:a,parseMode:n,mathstyle:o})}).render(a);return l?(Or(Ht(l,a)),Br(l,{classes:"ML__latex"}).toMarkup()):""}function gy(t,e){let r=h({},Qn());if(e!=null&&e.macros){let i=ei(e.macros);r.getMacro=n=>ti(n,i)}return ss(t,{context:r})}function Bo(t,e={}){return G(be(t,{parseMode:"math",args:()=>"",mathstyle:"displaystyle"}),e)}function Ko(t){let e=be(t,{parseMode:"math",mathstyle:"displaystyle"});return wt(e)}function by(t,e="math"){return le(new x({type:"root",body:be(t,{parseMode:e})}))}function eu(t){return or(t,{format:"ascii-math"})[1]}function Po(t){if(typeof t=="string"){let e=yy(t);if(!e)throw new Error(`Invalid color: ${t}`);return e}return"C"in t?vy(t):"a"in t?Rp(t):t}function Ci(t){return t<0?0:t>255?255:Math.round(t)}function yy(t){if(!t||t[0]!=="#")return;t=t.slice(1);let e;return t.length<=4?(e={r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16)},t.length===4&&(e.a=parseInt(t[3]+t[3],16)/255)):(e={r:parseInt(t[0]+t[1],16),g:parseInt(t[2]+t[3],16),b:parseInt(t[4]+t[5],16)},t.length===8&&(e.a=parseInt(t[6]+t[7],16)/255)),typeof(e==null?void 0:e.a)=="undefined"&&(e.a=1),e}function nu(t){let[e,r,i]=[t.L,t.C,t.H],n=i*Math.PI/180,o={L:e,a:r*Math.cos(n),b:r*Math.sin(n)};return t.alpha!==void 0&&(o.alpha=t.alpha),o}function xy(t){let[e,r,i]=[t.L,t.a,t.b],n=Math.sqrt(r*r+i*i),a=Math.atan2(i,r)*180/Math.PI,s={L:e,C:n,H:a};return t.alpha!==void 0&&(s.alpha=t.alpha),s}function tu(t){let[e,r,i]=[t.L,t.a,t.b],n=Math.pow(.9999999984505198*e+.39633779217376786*r+.2158037580607588*i,3),o=Math.pow(1.00000000888176*e-.10556134232365635*r-.0638541747717059*i,3),a=Math.pow(e*1.000000054672411-.0894841820949657*r-1.2914855378640917*i,3),s=4.076741661347994*n-3.307711590408193*o+.230969928729428*a,l=-1.2684380040921763*n+2.6097574006633715*o-.3413193963102197*a,c=-.004196086541837188*n-.7034186144594493*o+1.7076147009309444*a,u=d=>{let m=Math.abs(d);return m<=.0031308?d*12.92:(Math.sign(d)||1)*(1.055*Math.pow(m,1/2.4)-.055)};return[u(s),u(l),u(c)]}function ru(t){let[e,r,i]=t;return e>=0&&e<=1&&r>=0&&r<=1&&i>=0&&i<=1}function iu(t,e){let[r,i,n]=t;return r=Ci(r*255),i=Ci(i*255),n=Ci(n*255),e!==void 0?{r,g:i,b:n,alpha:e}:{r,g:i,b:n}}function Rp(t){let[e,r,i]=tu(t);if(ru([e,r,i]))return iu([e,r,i],t.alpha);let n=xy(t);if(n.C=0,[e,r,i]=tu(nu(n)),!ru([e,r,i]))return iu([e,r,i],t.alpha);let o=0,a=t.L,s=(o+a)/2;n.C=s;let l=.36/Math.pow(2,12);for(;a-o>l;)s=(o+a)/2,n.C=s,[e,r,i]=tu(nu(n)),ru([e,r,i])?o=s:a=s;return iu([e,r,i],t.alpha)}function vy(t){return Rp(nu(t))}function Ip(t,e){let r=Po(t),i=Po(e),n=.56,o=.57,a=.62,s=.65,l=.022,c=1.414,u=.1,d=5e-4,m=1.14,p=.027,f=1.14,y=.027;function v(_){return _>=l?_:_+(l-_)**c}function b(_){return(_<0?-1:1)*Math.pow(Math.abs(_),2.4)}let k=v(b(i.r/255)*.2126729+b(i.g/255)*.7151522+b(i.b/255)*.072175),S=v(b(r.r/255)*.2126729+b(r.g/255)*.7151522+b(r.b/255)*.072175),A,E,C;return Math.abs(S-k)k?(A=S**n-k**o,E=A*m):(A=S**s-k**a,E=A*f),Math.abs(E)0?C=E-y:C=E+p,C*100}function ou(t,e,r){r!=null||(r="#fff"),e!=null||(e="#000");let i=Ip(t,r),n=Ip(t,e);return Math.abs(i)>Math.abs(n)?r:e}function zp(t){let e=Po(t),r=((1<<24)+(Ci(e.r)<<16)+(Ci(e.g)<<8)+Ci(e.b)).toString(16).slice(1);return e.alpha!==void 0&&e.alpha<1&&(r+=("00"+Math.round(e.alpha*255).toString(16)).slice(-2)),r[0]===r[1]&&r[2]===r[3]&&r[4]===r[5]&&r[6]===r[7]&&(r=r[0]+r[2]+r[4]+(e.alpha!==void 0&&e.alpha<1?r[6]:"")),"#"+r}function oe(t){let e=Np(t),r="";for(let i of e){if(typeof i.value!="string")return"";r+=i.value}return r}function Np(t){let r=t.model.selection.ranges;if(r.length!==1)return[];let i=t.model.getAtoms(r[0]);return i.length===1&&i[0].isRoot&&(i=i[0].children),i.filter(n=>n.type!=="first")}function _y(t,e){let r=Np(t);if(r.length!==1)return!1;let i=ms[e];return i?!!i.test(r[0].value):!1}function My(t){return[su(t,"double-struck","mathbb","tooltip.blackboard"),su(t,"fraktur","mathfrak","tooltip.fraktur"),su(t,"calligraphic","mathcal","tooltip.caligraphic"),lu(t,"up","mathrm","tooltip.roman-upright"),lu(t,"bold","bm","tooltip.bold"),lu(t,"italic","mathit","tooltip.italic")]}function wy(t){return[{id:"accent-vec",class:"ML__center-menu",label:()=>pe(`\\vec{${oe(t)}}`),visible:()=>oe(t).length===1,onMenuSelect:()=>t.insert("\\vec{#@}",{selectionMode:"item"})},{id:"accent-overrightarrow",class:"ML__center-menu",label:()=>pe(`\\overrightarrow{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\overrightarrow{#@}",{selectionMode:"item"})},{id:"accent-overleftarrow",class:"ML__center-menu",label:()=>pe(`\\overleftarrow{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\overleftarrow{#@}",{selectionMode:"item"})},{id:"accent-dot",class:"ML__center-menu",label:()=>pe(`\\dot{${oe(t)}}`),visible:()=>oe(t).length===1,onMenuSelect:()=>t.insert("\\dot{#@}",{selectionMode:"item"})},{id:"accent-ddot",class:"ML__center-menu",label:()=>pe(`\\ddot{${oe(t)}}`),visible:()=>oe(t).length===1,onMenuSelect:()=>t.insert("\\ddot{#@}",{selectionMode:"item"})},{id:"accent-bar",class:"ML__center-menu",label:()=>pe(`\\bar{${oe(t)}}`),visible:()=>oe(t).length===1,onMenuSelect:()=>t.insert("\\bar{#@}",{selectionMode:"item"})},{id:"accent-overline",class:"ML__center-menu",label:()=>pe(`\\overline{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\overline{#@}",{selectionMode:"item"})},{id:"accent-overgroup",class:"ML__center-menu",label:()=>pe(`\\overgroup{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\overgroup{#@}",{selectionMode:"item"})},{id:"accent-overbrace",class:"ML__center-menu",label:()=>pe(`\\overbrace{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\overbrace{#@}",{selectionMode:"item"})},{id:"accent-underline",class:"ML__center-menu",label:()=>pe(`\\underline{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\underline{#@}",{selectionMode:"item"})},{id:"accent-undergroup",class:"ML__center-menu",label:()=>pe(`\\undergroup{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\undergroup{#@}",{selectionMode:"item"})},{id:"accent-underbrace",class:"ML__center-menu",label:()=>pe(`\\underbrace{${oe(t)}}`),visible:()=>oe(t).length>0,onMenuSelect:()=>t.insert("\\underbrace{#@}",{selectionMode:"item"})}]}function Sy(t){return[{id:"decoration-boxed",label:()=>pe(`\\boxed{${t.getValue(t.model.selection)}}}`),onMenuSelect:()=>t.insert("\\boxed{#@}",{selectionMode:"item"})},{id:"decoration-red-box",label:()=>pe(`\\bbox[5px, border: 2px solid red]{${t.getValue(t.model.selection)}}`),onMenuSelect:()=>t.insert("\\bbox[5px, border: 2px solid red]{#@}",{selectionMode:"item"})},{id:"decoration-dashed-black-box",label:()=>pe(`\\bbox[5px, border: 2px dashed black]{${t.getValue(t.model.selection)}}`),onMenuSelect:()=>t.insert("\\bbox[5px, border: 2px dashed black]{#@}",{selectionMode:"item"})}]}function ky(t){let e=[];for(let r of Object.keys(Qt))e.push({id:`background-color-${r}`,class:(zp(ou(Qt[r]))==="#000"?"dark-contrast":"light-contrast")+" menu-swatch",label:``,ariaLabel:()=>{var i;return(i=$(r))!=null?i:r},checked:()=>{var i;return(i={some:"mixed",all:!0}[t.queryStyle({backgroundColor:r})])!=null?i:!1},onMenuSelect:()=>t.applyStyle({backgroundColor:r},{operation:"toggle"})});return e}function Ly(t){let e=[];for(let r of Object.keys(er))e.push({id:`color-${r}`,class:(ou(er[r])==="#000"?"dark-contrast":"light-contrast")+" menu-swatch",label:``,ariaLabel:()=>{var i;return(i=$(r))!=null?i:r},checked:()=>{var i;return(i={some:"mixed",all:!0}[t.queryStyle({color:r})])!=null?i:!1},onMenuSelect:()=>t.applyStyle({color:r},{operation:"toggle"})});return e}var cu=class extends En{constructor(e,r,i,n){super(e,r),this.row=i,this.col=n}set active(e){let r=this.parentMenu.children;if(e)for(let i of r)i.element.classList.toggle("active",i.row<=this.row&&i.col<=this.col);else for(let i of r)i.element.classList.remove("active")}};function Ay(t){let e=[];for(let r=1;r<=5;r++)for(let i=1;i<=5;i++)e.push({id:`insert-matrix-${r}x${i}`,onCreate:(n,o)=>new cu(n,o,r,i),label:"\u2610",tooltip:()=>$("tooltip.row-by-col",r,i),data:{row:r,col:i},onMenuSelect:()=>{t.insert(`\\begin{pmatrix}${Array(r).fill(Array(i).fill("#?").join(" & ")).join("\\\\")}\\end{pmatrix}`,{selectionMode:"item"})}});return e}function Fp(t){return[{label:()=>$("menu.array.add row above"),id:"add-row-above",onMenuSelect:()=>t.executeCommand("addRowBefore"),keyboardShortcut:"shift+alt+[Return]",visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return e!==i}},{label:()=>$("menu.array.add row below"),id:"add-row-below",onMenuSelect:()=>t.executeCommand("addRowAfter"),keyboardShortcut:"alt+[Return]",visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return e!==i}},{label:()=>$("menu.array.add column before"),id:"add-column-before",onMenuSelect:()=>t.executeCommand("addColumnBefore"),visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return r!==n},keyboardShortcut:"shift+alt+[Tab]",enabled:()=>{let e=t.model.parentEnvironment;if(!e)return!1;let[r,i]=au(t);return r$("menu.array.add column after"),id:"add-column-after",onMenuSelect:()=>t.executeCommand("addColumnAfter"),keyboardShortcut:"alt+[Tab]",visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return r!==n}},{type:"divider"},{label:()=>$("menu.array.delete row"),id:"delete-row",onMenuSelect:()=>t.executeCommand("removeRow"),enabled:()=>{let[e,r]=jr(t),[i,n]=au(t);return i>e},visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return e!==i}},{label:()=>$("menu.array.delete column"),id:"delete-column",onMenuSelect:()=>t.executeCommand("removeColumn"),enabled:()=>{let[e,r]=jr(t),[i,n]=au(t);return n>r},visible:()=>{if(!t.isSelectionEditable||!Ei(t))return!1;let[e,r]=jr(t),[i,n]=On(t);return r!==n}},{type:"divider"},{label:()=>$("menu.borders"),visible:()=>(Cy(t)||Ei(t))&&t.isSelectionEditable,submenu:[{label:" \u22F1 ",id:"environment-no-border",onMenuSelect:()=>Ro(t,"matrix")},{label:"(\u22F1)",id:"environment-parentheses",onMenuSelect:()=>Ro(t,"pmatrix")},{label:"[\u22F1]",id:"environment-brackets",onMenuSelect:()=>Ro(t,"bmatrix")},{label:"|\u22F1|",id:"environment-bar",onMenuSelect:()=>Ro(t,"vmatrix")},{label:"{\u22F1}",id:"environment-braces",onMenuSelect:()=>Ro(t,"Bmatrix")}],submenuClass:"border-submenu"},{type:"divider"},{label:()=>$("menu.insert matrix"),id:"insert-matrix",visible:()=>t.isSelectionEditable,submenu:Ay(t),submenuClass:"insert-matrix-submenu",columnCount:5},{type:"divider"},{label:()=>$("menu.insert"),id:"insert",submenu:Ey(t)},{type:"divider"},{label:()=>$("menu.mode"),id:"mode",visible:()=>t.isSelectionEditable&&t.model.selectionIsCollapsed,submenu:[{label:()=>$("menu.mode-math"),id:"mode-math",onMenuSelect:()=>{Qe(t,"accept-all"),t.executeCommand(["switchMode","math"])},checked:()=>t.model.mode==="math"},{label:()=>$("menu.mode-text"),id:"mode-text",onMenuSelect:()=>{Qe(t,"accept-all"),t.executeCommand(["switchMode","text"])},checked:()=>t.model.mode==="text"},{label:()=>$("menu.mode-latex"),id:"mode-latex",onMenuSelect:()=>t.executeCommand(["switchMode","latex"]),checked:()=>t.model.mode==="latex"}]},{type:"divider"},{label:()=>$("menu.font-style"),id:"variant",visible:()=>t.isSelectionEditable,submenu:My(t),submenuClass:"variant-submenu"},{label:()=>$("menu.color"),id:"color",visible:()=>t.isSelectionEditable,submenu:Ly(t),columnCount:4,submenuClass:"swatches-submenu"},{label:()=>$("menu.background-color"),id:"background-color",visible:()=>t.isSelectionEditable,submenu:ky(t),columnCount:4,submenuClass:"swatches-submenu"},{label:()=>$("menu.accent"),id:"accent",visible:()=>t.isSelectionEditable,submenu:wy(t),submenuClass:"variant-submenu"},{label:()=>$("menu.decoration"),id:"decoration",visible:()=>t.isSelectionEditable&&oe(t).length>0,submenu:Sy(t),submenuClass:"variant-submenu"},{type:"divider"},{label:()=>$("menu.cut"),id:"cut",onMenuSelect:()=>t.executeCommand("cutToClipboard"),visible:()=>!t.options.readOnly&&t.isSelectionEditable,keyboardShortcut:"meta+X"},{label:()=>$("menu.copy"),id:"copy",submenu:[{label:()=>$("menu.copy-as-latex"),id:"copy-latex",onMenuSelect:()=>H.copyToClipboard(t,"latex"),keyboardShortcut:"meta+C"},{label:()=>$("menu.copy-as-typst"),id:"copy-latex",onMenuSelect:()=>H.copyToClipboard(t,"typst")},{label:()=>$("menu.copy-as-ascii-math"),id:"copy-ascii-math",onMenuSelect:()=>H.copyToClipboard(t,"ascii-math")},{label:()=>$("menu.copy-as-mathml"),id:"copy-math-ml",onMenuSelect:()=>H.copyToClipboard(t,"math-ml")}]},{label:()=>$("menu.paste"),id:"paste",onMenuSelect:()=>t.executeCommand("pasteFromClipboard"),visible:()=>t.hasEditableContent,keyboardShortcut:"meta+V"},{label:()=>$("menu.select-all"),id:"select-all",keyboardShortcut:"meta+A",onMenuSelect:()=>t.executeCommand("selectAll")}]}function Ei(t){var r,i;let e=(i=(r=t.model.parentEnvironment)==null?void 0:r.environmentName)!=null?i:"";return["array","matrix","pmatrix","bmatrix","vmatrix","Bmatrix","cases","dcases","rcases"].includes(e)}function Cy(t){let e=t.model.at(t.model.position);if(e.type!=="array")return!1;let r=e.environmentName;return["matrix","pmatrix","bmatrix","vmatrix","Bmatrix"].includes(r)}function au(t){var r;let e=(r=t.model.parentEnvironment)==null?void 0:r.rows;return e?[e.length,e.reduce((i,n)=>Math.max(i,n.length),0)]:[0,0]}function jr(t){let e=t.model.parentEnvironment;return e?[e.minRows,e.minColumns]:[0,0]}function On(t){let e=t.model.parentEnvironment;return e?[e.maxRows,e.maxColumns]:[0,0]}function Ro(t,e){xi(t),t.flushInlineShortcutBuffer(),Nc(t.model,e),Y(t)}function su(t,e,r,i){return{id:`variant-${e}`,label:()=>{var o;return oe(t).length<12?pe(`\\${r}{${oe(t)}}`):(o=$(i))!=null?o:i},class:"ML__xl",tooltip:()=>{var n;return(n=$(i))!=null?n:i},visible:()=>_y(t,e),checked:()=>{var n;return(n={some:"mixed",all:!0}[t.queryStyle({variant:e})])!=null?n:!1},onMenuSelect:()=>t.applyStyle({variant:e},{operation:"toggle"})}}function lu(t,e,r,i){return{id:`variant-style-${e}`,label:()=>{var o;let n=oe(t);return n.length>0&&n.length<12?pe(`\\${r}{${oe(t)}}`):(o=$(i))!=null?o:i},class:()=>{let n=oe(t);return n.length>0&&n.length<12?"ML__xl":""},tooltip:()=>{var n;return(n=$(i))!=null?n:i},visible:!0,checked:()=>{var n;return(n={some:"mixed",all:!0}[t.queryStyle({variantStyle:e})])!=null?n:!1},onMenuSelect:()=>t.applyStyle({variantStyle:e},{operation:"toggle"})}}function Ey(t){return[{label:()=>et("abs"),id:"insert-abs",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("|#?|")},{label:()=>et("nth-root"),id:"insert-nth-root",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\sqrt[#?]{#?}")},{label:()=>et("log-base"),id:"insert-log-base",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\log_{#?}{#?}")},{type:"heading",label:()=>$("menu.insert.heading-calculus")},{label:()=>et("derivative"),id:"insert-derivative",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\dfrac{\\mathrm{d}}{\\mathrm{d}x}#?\\bigm|_{x=#?}")},{label:()=>et("nth-derivative"),id:"insert-nth-derivative",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\dfrac{\\mathrm{d}^#?}{\\mathrm{d}x^#?}#?\\bigm|_{x=#?}")},{label:()=>et("integral"),id:"insert-integral",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\int_#?^#?#?\\,\\mathrm{d}#?")},{label:()=>et("sum"),id:"insert-sum",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\sum_#?^#?#?")},{label:()=>et("product"),id:"insert-product",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\prod_#?^#?#?")},{type:"heading",label:()=>$("menu.insert.heading-complex-numbers")},{label:()=>et("modulus"),id:"insert-modulus",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\lvert#?\\rvert")},{label:()=>et("argument"),id:"insert-argument",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\arg(#?)")},{label:()=>et("real-part"),id:"insert-real-part",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\Re(#?)")},{label:()=>et("imaginary-part"),id:"insert-imaginary-part",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\Im(#?)")},{label:()=>et("conjugate"),id:"insert-conjugate",visible:()=>t.isSelectionEditable,onMenuSelect:()=>t.insert("\\overline{#?}")}]}function et(t){return` ${pe($(`menu.insert.${t}-template`))}${$(`menu.insert.${t}`)}`}var Ve={"\\ne":"!=","\\neq":"!=","\u2212":"-","-":"-","\\alpha":"alpha","\\beta":"beta","\\gamma":"gamma","\\delta":"delta","\\epsilon":"epsilon.alt","\\varepsilon":"epsilon","\\zeta":"zeta","\\eta":"eta","\\theta":"theta.alt","\\vartheta":"theta","\\iota":"iota","\\kappa":"kappa","\\lambda":"lambda","\\mu":"mu","\\nu":"nu","\\xi":"xi","\\pi":"pi","\\rho":"rho","\\sigma":"sigma","\\tau":"tau","\\upsilon":"upsilon","\\phi":"phi.alt","\\varphi":"phi","\\chi":"chi","\\psi":"psi","\\omega":"omega","\\Gamma":"Gamma","\\Delta":"Delta","\\Theta":"Theta","\\Lambda":"Lambda","\\Xi":"Xi","\\Pi":"Pi","\\Sigma":"Sigma","\\Phi":"Phi","\\Psi":"Psi","\\Omega":"Omega","\\exponentialE":"e","\\imaginaryI":"i","\\imaginaryJ":"j","\\!":" #h(-1em/6) ","\\,":" thin ","\\:":" med ","\\>":" med ","\\;":" thick ","\\enskip":"space.en","\\enspace":"space.en","\\qquad":"space.quad space.quad","\\quad":"space.quad","\\infty":"infinity","\\R":"RR","\\mathbb{R}":"RR","\\N":"NN","\\mathbb{N}":"NN","\\Z":"ZZ","\\mathbb{Z}":"ZZ","\\Q":"QQ","\\mathbb{Q}":"QQ","\\C":"CC","\\mathbb{C}":"CC","\\emptyset":"emptyset","\\varnothing":"nothing","\\varDelta":"Delta","\\varTheta":"Theta","\\varLambda":"Lambda","\\varXi":"Xi","\\varPi":"Pi","\\varSigma":"Sigma","\\varUpsilon":"Upsilon","\\varPhi":"Phi","\\varPsi":"Psi","\\varOmega":"Omega","\\vert":" | ","\\Vert":" || ","\\mid":" divides ","\\lbrack":" bracket.l ","\\rbrack":" bracket.r ","\\lbrace":" brace.l ","\\rbrace":" brace.r ","\\lparen":" paren.l ","\\rparen":" paren.r ","\\langle":" angle.l ","\\rangle":" angle.r ","\\differentialD":" dif ","\\diamond":" diamond.stroked.small ","\\square":" square.stroked.small ","\\lceil":" ceil.l ","\\rceil":" ceil.r ","\\lfloor":" floor.l ","\\rfloor":" floor.r ","\\aleph":" aleph ","\\bet":" bet ","\\gimel":" gimel ","\\dalet":" dalet ","\\mod":" mod ","\\equiv":" equiv ","\\subset":" subset ","\\supset":" supset ","\\subseteq":" subset.eq ","\\supseteq":" supset.eq ","\\subsetneq":" subset.neq ","\\supsetneq":" supset.neq ","\\supsetneqq":" supset.neq ","\\nsubset":" subset.not ","\\nsupset":" supset.not ","\\nsubseteq":" subset.eq.not ","\\nsupseteq":" supset.eq.not ","\\approx":" approx ","\\uparrow":" arrow.t ","\\downarrow":" arrow.b ","\\rightarrow":" arrow.r ","\\leftarrow":" arrow.l ","\\longmapsto":" mapsto.long ","\\longmapsfrom":" arrow.l.bar.long ","/":"\\/","&":"&"},$p={"[":" bracket.l ","]":" bracket.r ","{":" brace.l ","}":" brace.r ","(":" paren.l ",")":" paren.r ","<":" angle.l ",">":" angle.r ",".":""},Vp={" bracket.l ":"["," bracket.r ":"]"," brace.l ":"{"," brace.r ":"}"," paren.l ":"("," paren.r ":")"," angle.l ":" angle.l "," angle.r ":" angle.r "},Io={"\\pm":"plus.minus","\\colon":" : ","\\sum":" sum ","\\prod":" product ","\\bigcap":" inter.big ","\\bigcup":" union.big ","\\int":" integral ","\\iint":" integral.double ","\\iiint":" integral.triple ","\\intop":" integral ","\\oint":" integral.cont ","\\oiint":" integral.surf ","\\oiiint":" integral.vol ","\\setminus":" without ","\\vdots":" without ","\\ddots":" dots.down ","\\ge":">=","\\le":"<=","\\ne":"!=","\\neq":"!=","\\lt":"<","\\gt":">","\\gets":"<-","\\to":"->","\\land":" and ","\\lor":" or ","\\lnot":" not ","\\forall":" forall ","\\exists":" exists ","\\in":" in ","\\notin":" in.not ","\\mapsto":"|->","\\implies":"==>","\\iff":"<==>","\\cdot":" dot.op ","\\ast":" * ","\\star":" star.op ","\\times":" times ","\\div":" div ","\\ltimes":" times.l ","\\rtimes":" times.r ","\\bowtie":" \u22C8 ","\\circ":" circle.stroked.small "},Ty={underarc:"underparen",underparen:"underparen",underbrace:"underbrace",underline:"underline",overarc:"overparen",overparen:"overparen",overbrace:"overbrace",overline:"overline",cancel:"cancel",displaystyle:"display",textstyle:"inline"},Dy={longrightarrow:t=>`arrow.r.long^(${ae(t.above)})`,longleftarrow:t=>`arrow.l.long^(${ae(t.above)})`};function Oy(t){let e="";for(let r of t){let i=e[e.length-1];i!==void 0&&(/\d$/.test(i)&&/^\d/.test(r)||/[a-zA-Z]$/.test(i)&&/^[a-zA-Z]/.test(r))&&(e+=" "),e+=r}return e}function ae(t){var o,a,s,l,c,u,d,m,p,f,y,v,b,k,S,A,E,C,_,O,I,V,K;if(!t)return"";if(ee(t)){if(t.length===0)return"";if(t[0].mode==="latex")return t.map(D=>ae(D)).join("");if(t[0].mode==="text"){let D=0,W="";for(;((o=t[D])==null?void 0:o.mode)==="text";)W+=t[D].body?ae(t[D].body):t[D].value,D++;return` "${W}" ${ae(t.slice(D))}`}let N=0,j=[];for(;((a=t[N])==null?void 0:a.mode)==="math";){let D="";for(;((s=t[N])==null?void 0:s.type)==="mord"&&/\d/.test(t[N].value);)D+=t[N++].value;D?j.push(D):j.push(ae(t[N++]))}return j.push(ae(t.slice(N))),Oy(j)}if(t.mode==="text")return`"${t.value}"`;let e="",{command:r}=t,i;if(r==="\\placeholder")return`"${ae(t.body)}"`;let n=x.serialize([t],{expandMacro:!0,defaultMode:"math"});switch(t.type){case"accent":let N={"\\vec":"arrow","\\dot":"dot","\\ddot":"dot.double","\\bar":"overline","\\hat":"hat","\\acute":"acute","\\grave":"grave","\\tilde":"tilde","\\breve":"breve","\\check":"caron"}[r];e=`${N!=null?N:""}(${ae(t.body)}) `;break;case"first":return"";case"latexgroup":return t.body.map(D=>D.value).join("");case"group":case"root":e=(l=Ve[r])!=null?l:ae(t.body);break;case"genfrac":{let D=t;D.hasBarLine?(e+="(",e+=ae(D.above),e+=")/(",e+=ae(D.below),e+=")"):e+=`binom(${ae(D.above)}, ${ae(D.below)})`}break;case"surd":t.hasEmptyBranch("above")?e+=`sqrt(${ae(t.body)})`:e+=`root(${ae(t.above)}, ${ae(t.body)})`;break;case"latex":e=t.value;break;case"leftright":{let D=t,W=D.leftDelim;W&&Ve[W]&&(W=Ve[W]);let ie=D.matchingRightDelim();ie&&Ve[ie]&&(ie=Ve[ie]),W&&(W=(c=$p[W])!=null?c:W),ie&&(ie=(u=$p[ie])!=null?u:ie),W&&ie?e=`lr(${(d=Vp[W])!=null?d:W}${ae(D.body)}${(m=Vp[ie])!=null?m:ie})`:e=`lr(${W}${ae(D.body)}${ie})`}break;case"sizeddelim":case"delim":e=t.value;break;case"overlap":break;case"mord":if(Ve[n])return Ve[n];e=(y=(f=(p=Ve[r])!=null?p:r)!=null?f:r)!=null?y:typeof t.value=="string"?t.value:"",e.startsWith("\\")&&(e+=" "),i=r?r.match(/{?\\char"([\dabcdefABCDEF]+)}?/):null,i?e=String.fromCodePoint(Number.parseInt("0x"+i[1])):e.length>0&&e.startsWith("\\")&&(e=typeof t.value=="string"?t.value.charAt(0):t.command),e=By(e,t.style),e=` ${e} `;break;case"mbin":case"mrel":case"minner":e=(k=(b=(v=Ve[n])!=null?v:Ve[r])!=null?b:Io[r])!=null?k:t.value;break;case"mopen":case"mclose":e=(S=Ve[n])!=null?S:t.value;break;case"mpunct":e=(A=Io[r])!=null?A:r;break;case"mop":case"operator":case"extensible-symbol":t.value!=="\u200B"&&(Io[r]?e=Io[r]:e=r==="\\operatorname"?ae(t.body):(E=t.value)!=null?E:r,e+=" ");break;case"array":let j=t.environmentName;if(t.isMultiline)e=t.rows.map(W=>W.map(ie=>ae(ie)).join("")).join(` +`);else{let D=t.rows,W=D.map(X=>X.map(ae).join(", ")),ie={pmatrix:'"("',bmatrix:'"["',"bmatrix*":'"["',Bmatrix:'"{"',vmatrix:'"|"',matrix:"#none"}[j];ie?e=`mat(delim: ${ie}, ${W.join(" ; ")})`:j==="cases"||j==="rcases"?e=`cases(reverse: #${j==="rcases"}, ${W.join(", ")})`:j==="aligned"?e=D.map(X=>X.map(ae).join(" & ")).join(" \\ "):e=D.map(X=>X.map(ae).join("")).join("")}break;case"box":break;case"spacing":e=(_=(C=Ve[n])!=null?C:Ve[r])!=null?_:" ";break;case"space":e=" ";break;case"subsup":e=(O=t.leftSibling)!=null&&O.value?"":'""';break;case"macro":e=(K=(V=(I=Ve[n])!=null?I:Ve[r])!=null?V:Io[r])!=null?K:ae(t.body);break;case"overunder":break}if(!e){let N=Ty[t.command.slice(1)];N&&(e=`${N}(${ae(t.body)})`)}if(!e){let N=Dy[t.command.slice(1)];N&&(e=N(t))}if(!t.hasEmptyBranch("subscript")){e+="_";let N=ae(t.subscript);e+=N.length!==1?`(${N})`:N}if(!t.hasEmptyBranch("superscript")){e+="^";let N=ae(t.superscript);e+=N.length!==1?`(${N})`:N}return e}function By(t,e){if(!e)return t;let r=t;return e.variant==="double-struck"&&(r=`bb(${r})`),e.variant==="script"&&(r=`cal(${r})`),e.variant==="fraktur"&&(r=`frak(${r})`),e.variant==="sans-serif"&&(r=`sans(${r})`),e.variant==="monospace"&&(r=`mono(${r})`),e.variantStyle==="bold"&&(r=`bold(${r})`),r}var Us=class{constructor(e,r,i){this.mathfield=e,this.mode=r,this.silenceNotifications=!1,this._selection={ranges:[[0,0]],direction:"none"},this._anchor=0,this._position=0,this.root=i}dispose(){this.mathfield=void 0}getState(){let e={ranges:[...this._selection.ranges]};return this.selection.direction&&this.selection.direction!=="none"&&(e.direction=this.selection.direction),{content:this.root.toJson(),selection:e,mode:this.mode}}setState(e,r){var o;let i=this.silenceNotifications;this.silenceNotifications=(o=r==null?void 0:r.silenceNotifications)!=null?o:!0;let n={};if((r==null?void 0:r.type)==="undo"&&(n={inputType:"historyUndo"}),(r==null?void 0:r.type)==="redo"&&(n={inputType:"historyRedo"}),this.contentWillChange(n)){let a=this.silenceNotifications;this.silenceNotifications=!0,this.mode=e.mode,this.root=xt(e.content),this.selection=e.selection,this.silenceNotifications=a,this.contentDidChange(n),this.selectionDidChange()}this.silenceNotifications=i}get atoms(){return this.root.children}get selection(){return this._selection}set selection(e){this.setSelection(e)}setSelection(e,r){return!this.mathfield.contentEditable&&this.mathfield.userSelect==="none"?!1:this.deferNotifications({selection:!0,content:!0},()=>{var c,u,d,m;let i=this.normalizeSelection(e,r);if(i===void 0)throw new TypeError("Invalid selection");if(i.ranges.length===1&&i.ranges[0][0]===i.ranges[0][1]){let p=i.ranges[0][0];if(!this.mathfield.dirty&&!((c=this.at(p))!=null&&c.parentPrompt)&&this.mathfield.hasEditablePrompts){if((u=this.at(p-1))!=null&&u.parentPrompt){this._anchor=this.normalizeOffset(p-1),this._position=this._anchor,this._selection=this.normalizeSelection(this._anchor);return}if((d=this.at(p+1))!=null&&d.parentPrompt){this._anchor=this.normalizeOffset(p+1),this._position=this._anchor,this._selection=this.normalizeSelection(this._anchor);return}this._anchor=0,this._position=0,this._selection={ranges:[[0,0]]};return}this._anchor=p,this._position=p,this._selection=i;return}let n=de(i);n=Ky(this,n),i.direction==="backward"?[this._position,this._anchor]=n:[this._anchor,this._position]=n;let o=n[0]+1;for(;o<=this.lastOffset&&((m=this.at(o))==null?void 0:m.type)==="first"&&o=0&&this._position<=this.lastOffset})}setPositionHandlingPlaceholder(e){var i;let r=this.at(e);(r==null?void 0:r.type)==="placeholder"?this.setSelection(e-1,e):((i=r==null?void 0:r.rightSibling)==null?void 0:i.type)==="placeholder"?this.setSelection(e,e+1):this.position=e,r instanceof he&&r.isSuggestion&&(r.isSuggestion=!1),this.mathfield.stopCoalescingUndo()}get position(){return this._position}set position(e){this.setSelection(e,e)}get anchor(){return this._anchor}get selectionIsCollapsed(){return this._anchor===this._position}get selectionIsPlaceholder(){return Math.abs(this._anchor-this._position)===1?this.at(Math.max(this._anchor,this._position)).type==="placeholder":!1}collapseSelection(e="forward"){return this._anchor===this._position?!1:(e==="backward"?this.position=Math.min(this._anchor,this._position):this.position=Math.max(this._anchor,this._position),!0)}get lastOffset(){return this.atoms.length-1}at(e){return this.atoms[e]}offsetOf(e){return this.atoms.indexOf(e)}getSiblingsRange(e){let r=this.at(e),{parent:i}=r;if(!i)return[0,this.lastOffset];let n=r.parent.branch(r.parentBranch);return[this.offsetOf(n[0]),this.offsetOf(n[n.length-1])]}getBranchRange(e,r){let i=this.at(e).branch(r);return[this.offsetOf(i[0]),this.offsetOf(i[i.length-1])]}getCellRange(e){var n,o;let r=this.getParentCell(e),i=this.at(e);if(i){for(;i&&((n=i.parent)==null?void 0:n.type)!=="array";)i=i.parent;if(((o=i==null?void 0:i.parent)==null?void 0:o.type)==="array")return[this.offsetOf(i.firstSibling),this.offsetOf(i.lastSibling)]}}getAtoms(e,r,i){let n=i!=null?i:{};if(Qi(e)){if(n=r!=null?r:{},e.ranges.length>1)return e.ranges.reduce((m,p)=>[...m,...this.getAtoms(p,n)],[]);e=e.ranges[0]}let o,a;if(zt(e)){if(o=e,!zt(r))return[];a=r}else[o,a]=e,Object.keys(n).length===0&&(n=r!=null?r:{});if(!Number.isFinite(o))return[];n.includeChildren===void 0&&(n.includeChildren=!1),o<0&&(o=this.lastOffset-o+1),a<0&&(a=this.lastOffset+a+1);let s=Math.min(o,a),l=Math.max(o,a),c=s===0?0:s+1,u=l;if(!n.includeChildren&&s===0&&l===this.lastOffset)return[this.root];let d=[];for(let m=c;m<=u;m++){let p=this.atoms[m];qp(this,p,c,u,n.includeFirstAtoms)&&d.push(p)}return n.includeChildren||(d=d.filter(m=>{let p=!1,{parent:f}=m;for(;f&&!p;)p=qp(this,f,c,u,n.includeFirstAtoms),f=f.parent;return!p})),d}findAtom(e,r=0,i="forward"){let n,o=this.lastOffset;if(i==="forward"){for(let a=r;a<=o;a++)if(n=this.atoms[a],e(n))return n;for(let a=0;a=0;a--)if(n=this.atoms[a],e(n))return n;for(let a=o;a>r;a--)if(n=this.atoms[a],e(n))return n}extractAtoms(e){var i;let r=this.getAtoms(e);r.length===1&&!r[0].parent&&r[0].isRoot&&(r[0]instanceof z?r=r[0].rows.flatMap(n=>n.flatMap(o=>o)):r=[...(i=r[0].body)!=null?i:r[0].children],r=r.filter(n=>n.type!=="first"));for(let n of r)n.parent.removeChild(n);return r}deleteAtoms(e){if(e!=null||(e=[0,-1]),this.extractAtoms(e),e[0]===0&&e[1]===-1&&this.root instanceof z)for(;this.root.rowCount>1;)this.root.removeRow(1);this.position=e[0]}atomToString(e,r){let i=r!=null?r:"latex";if(i.startsWith("latex"))return x.serialize([e],{expandMacro:i==="latex-expanded",skipStyles:i==="latex-unstyled",skipPlaceholders:i==="latex-without-placeholders",defaultMode:this.mathfield.options.defaultMode});if(i==="math-ml")return G(e);if(i==="spoken")return wt(e);if(i==="spoken-text"){let n=globalThis.MathfieldElement.textToSpeechMarkup;globalThis.MathfieldElement.textToSpeechMarkup="";let o=wt(e);return globalThis.MathfieldElement.textToSpeechMarkup=n,o}if(i==="spoken-ssml"||i==="spoken-ssml-with-highlighting"){let n=globalThis.MathfieldElement.textToSpeechMarkup;globalThis.MathfieldElement.textToSpeechMarkup="ssml";let o=wt(e);return globalThis.MathfieldElement.textToSpeechMarkup=n,o}return i==="typst"?ae(e):i==="plain-text"?le(e,{plain:!0}):i==="ascii-math"?le(e):(console.error(`MathLive 0.111.1: Unexpected format "${i}`),"")}getValue(e,r,i){if(e===void 0)return this.atomToString(this.root,"latex");if(typeof e=="string")return this.atomToString(this.root,e);let n,o;if(zt(e)&&zt(r)?(n=[this.normalizeRange([e,r])],o=i):di(e)?(n=[this.normalizeRange(e)],o=r):Qi(e)?(n=e.ranges,o=r):(n=[this.normalizeRange([0,-1])],o="latex"),o!=null||(o="latex"),o.startsWith("latex")){let a={expandMacro:o==="latex-expanded",skipStyles:o==="latex-unstyled",skipPlaceholders:o==="latex-without-placeholders",defaultMode:this.mathfield.options.defaultMode};return R(n.map(s=>x.serialize(this.getAtoms(s),a)))}return n.map(a=>this.getAtoms(a).map(s=>this.atomToString(s,o)).join("")).join("")}extendSelectionTo(e,r){return!this.mathfield.contentEditable&&this.mathfield.userSelect==="none"?!1:this.deferNotifications({selection:!0},()=>{let i=this.normalizeRange([e,r]),[n,o]=i,a=new Set(["genfrac","subsup","accent","box","overlap","overunder"]),{parent:s}=this.at(o);if(s!=null&&s.type&&a.has(s.type))for(;s!=null&&s.type&&a.has(s.type)&&Ws(this,s,[n,o]);)o=this.offsetOf(s),s=s.parent;for(s=this.at(n).parent;s!=null&&s.type&&a.has(s.type)&&Ws(this,s,[n,o]);)n=this.offsetOf(s.leftSibling),s=s.parent;if(s=this.at(o).parent,s!=null&&s.type&&a.has(s.type))for(;s!=null&&s.type&&a.has(s.type)&&Ws(this,s,[n,o]);)o=this.offsetOf(s),o>=0,s=s.parent;this._position=this.normalizeOffset(r),this._selection={ranges:[[n,o]],direction:"none"}})}announce(e,r,i=[]){var o,a;((a=(o=this.mathfield.host)==null?void 0:o.dispatchEvent(new CustomEvent("announce",{detail:{command:e,previousPosition:r,atoms:i},cancelable:!0,bubbles:!0,composed:!0})))==null||a)&&rp(this.mathfield,e,r,i)}deferNotifications(e,r){let i=this._selection,n=this._anchor,o=this._position,a=this.silenceNotifications;this.silenceNotifications=!0;let s=this.root.changeCounter;r(),this.silenceNotifications=a;let l=n!==this._anchor||o!==this._position||j0(this._selection,i)==="different";e.selection&&l&&this.selectionDidChange();let c=this.root.changeCounter!==s;return e.content&&c&&this.contentDidChange({inputType:e.type}),c||l}normalizeOffset(e){return e>0?e=Math.min(e,this.lastOffset):e<0&&(e=this.lastOffset+e+1),e}normalizeRange(e){let[r,i]=e;return r=this.normalizeOffset(r),i=this.normalizeOffset(i),rthis.normalizeRange(o)),direction:(n=e.direction)!=null?n:"none"});return i}get parentEnvironment(){let e=this.at(this.position).parent;if(e){for(;e.parent&&e.type!=="array";)e=e.parent;if(e.type==="array")return e}}get parentCell(){return this.getParentCell(this.position)}getParentCell(e){var i,n;let r=this.at(e);if(r){for(;r&&((i=r.parent)==null?void 0:i.type)!=="array";)r=r.parent;if(((n=r==null?void 0:r.parent)==null?void 0:n.type)==="array")return r.parentBranch}}contentWillChange(e={}){if(this.silenceNotifications||!this.mathfield)return!0;let r=this.silenceNotifications;this.silenceNotifications=!0;let i=this.mathfield.onContentWillChange(e);return this.silenceNotifications=r,i}contentDidChange(e){var i;if(window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.update(Xt(this.mathfield)),this.silenceNotifications||!((i=this.mathfield)!=null&&i.host))return;let r=this.silenceNotifications;this.silenceNotifications=!0,setTimeout(()=>{var n;!this.mathfield||!Ye(this.mathfield)||!this.mathfield.host||this.mathfield.host.dispatchEvent(new InputEvent("input",g(h({},e),{data:e.data?e.data:(n=e.inputType)!=null?n:"",bubbles:!0,composed:!0})))},0),this.silenceNotifications=r}selectionDidChange(){if(!this.mathfield)return;let e=this.silenceNotifications;e||(this.silenceNotifications=!0,this.mathfield.onSelectionDidChange()),this.silenceNotifications=e}};function qp(t,e,r,i,n){let o=t.offsetOf(e);if(oi)return!1;if(!e.hasChildren)return!0;let a=n?e.firstChild:Hp(e);if(!a)return!0;let s=n?e.lastChild:Wp(e);if(!s)return!0;let l=t.offsetOf(a);if(l>=r&&l<=i){let c=t.offsetOf(s);if(c>=r&&c<=i)return!0}return!1}function Ws(t,e,r){if(!(e!=null&&e.hasChildren))return!1;let[i,n]=r,o=Hp(e);if(!o)return!1;let a=Wp(e);if(!a)return!1;let s=t.offsetOf(o),l=t.offsetOf(a);return s>=i&&s<=n&&l>=s&&l<=n}function Ky(t,e){let[r,i]=e,n=i+1;if(n>t.lastOffset)return e;let o=t.at(n);return Py(t,o,r,i)&&(i=t.offsetOf(o)),[r,i]}function Py(t,e,r,i){if((e==null?void 0:e.type)!=="subsup"||!Ws(t,e,[r,i]))return!1;let n=e.leftSibling;if(!n)return!1;let o=t.offsetOf(n);return o>r&&o<=i}function Hp(t){for(let e of t.children)if(e.type!=="first")return e}function Wp(t){let{children:e}=t;for(let r=e.length-1;r>=0;r--)if(e[r].type!=="first")return e[r]}fe({deleteAll:t=>t.contentWillChange({inputType:"deleteContent"})&&ct(t,[0,-1],"deleteContent"),deleteForward:t=>sp(t),deleteBackward:t=>ap(t),deleteNextWord:t=>t.contentWillChange({inputType:"deleteWordForward"})&&St(t,"forward",{delete:!0}),deletePreviousWord:t=>t.contentWillChange({inputType:"deleteWordBackward"})&&St(t,"backward",{delete:!0}),deleteToGroupStart:t=>{if(!t.contentWillChange({inputType:"deleteSoftLineBackward"}))return!1;let e=t.offsetOf(t.at(t.position).firstSibling);return e===t.position?(t.announce("plonk"),!1):(t.deferNotifications({content:!0,selection:!0,type:"deleteSoftLineBackward"},()=>t.deleteAtoms([t.anchor,e])),t.position=e,!0)},deleteToGroupEnd:t=>{if(!t.contentWillChange({inputType:"deleteSoftLineForward"}))return!1;let e=t.offsetOf(t.at(t.position).lastSibling);return e===t.position?(t.announce("plonk"),!1):(t.deferNotifications({content:!0,selection:!0,type:"deleteSoftLineForward"},()=>t.deleteAtoms([t.anchor,e])),!0)},deleteToMathFieldStart:t=>t.contentWillChange({inputType:"deleteHardLineBackward"})&&ct(t,[t.anchor,0],"deleteHardLineBackward"),deleteToMathFieldEnd:t=>t.contentWillChange({inputType:"deleteHardLineForward"})&&ct(t,[t.anchor,-1],"deleteHardLineForward")},{target:"model",audioFeedback:"delete",canUndo:!0,changeContent:!0,changeSelection:!0});var Ry=``,Iy=``,Gs=class t{constructor(e,r){this.focusBlurInProgress=!1;this.programmaticFocusInProgress=!1;this.connectedToVirtualKeyboard=!1;var m,p,f;this.options=h(g(h({},Sn()),{macros:Ri(),registers:Xa()}),wn(r)),this.eventController=new AbortController;let i=this.eventController.signal;r.eventSink&&(this.host=r.eventSink),this.element=e,e.mathfield=this,this.blurred=!0,this.keystrokeCaptionVisible=!1,this.suggestionIndex=0,this.inlineShortcutBuffer=[],this.inlineShortcutBufferFlushTimer=0,this.scientificNotationTimer=0,this.defaultStyle={},this.styleBias="left",this.options.defaultMode==="inline-math"?this.element.classList.add("ML__is-inline"):this.element.classList.remove("ML__is-inline"),this.dirty=!1;let n=(p=(m=r.value)!=null?m:this.element.textContent)!=null?p:"";n=n.trim();let o=Tc(this.options),a=be(n,{context:this.context}),s;a.length===1&&a[0].isRoot?s=a[0]:s=new x({type:"root",mode:o,body:a}),this.model=new Us(this,o,s),this.undoManager=new Cs(this.model);let l=[];if(l.push(""),l.push('"),l.push(""),l.push(""),l.push(""),this.element.innerHTML=globalThis.MathfieldElement.createHTML(l.join("")),!this.element.children){console.error("%cMathLive 0.111.1: Something went wrong and the mathfield could not be created.%c\nIf you are using Vue, this may be because you are using the runtime-only build of Vue. Make sure to include `runtimeCompiler: true` in your Vue configuration. There may a warning from Vue in the log above.","color:red;font-family:system-ui;font-size:1.2rem;font-weight:bold","color:inherit;font-family:system-ui;font-size:inherit;font-weight:inherit");return}this._l10Subscription=F.subscribe(()=>F.update(this.element)),F.update(this.element),this.container=this.element.querySelector("[part=container]"),this.field=this.container.querySelector("[part=content]"),this.field.addEventListener("click",y=>y.stopImmediatePropagation(),{capture:!1,signal:i}),this.field.addEventListener("wheel",this,{passive:!1,signal:i});let c=this.element;if("PointerEvent"in window?c.addEventListener("pointerdown",this,{signal:i}):c.addEventListener("mousedown",this,{signal:i}),this.host){let y=v=>{v.target===this.host&&this.handleEvent(v)};"PointerEvent"in window?this.host.addEventListener("pointerdown",y,{signal:i}):this.host.addEventListener("mousedown",y,{signal:i})}let u=this.element.querySelector("[part=virtual-keyboard-toggle]");u==null||u.addEventListener("pointerdown",y=>{y.currentTarget===u&&(window.mathVirtualKeyboard.visible?window.mathVirtualKeyboard.hide():(window.mathVirtualKeyboard.show({animate:!0}),window.mathVirtualKeyboard.update(Xt(this)),setTimeout(()=>this.scrollIntoView(),300)),y.preventDefault(),y.stopPropagation(),this.hasFocus()||this.focus({preventScroll:!0}))},{signal:i}),this.field.addEventListener("contextmenu",this,{signal:i});let d=this.element.querySelector("[part=menu-toggle]");d==null||d.addEventListener("pointerdown",y=>{if(y.currentTarget!==d)return;let v=this.menu;if(v.state!=="closed")return;this.element.classList.add("tracking");let b=d.getBoundingClientRect();v.modifiers=Wt(y),v.show({target:d,location:{x:b.left,y:b.bottom},onDismiss:()=>this.element.classList.remove("tracking")}),y.preventDefault(),y.stopPropagation()},{signal:i}),(this.disabled||this.readOnly&&!this.hasEditableContent||this.userSelect==="none")&&(d.style.display="none"),this.ariaLiveText=(f=this.element.querySelector("[role=status]"))!=null?f:void 0,this.keyboardDelegate=Oh(this.element.querySelector(".ML__keyboard-sink"),this.element,this),this.updateAccessibleName(),this.updateAccessibleReadOnly(),window.addEventListener("resize",this,{signal:i}),document.addEventListener("scroll",this,{signal:i}),this.resizeObserver=new ResizeObserver(y=>{if(this.resizeObserverStarted){this.resizeObserverStarted=!1;return}this.updateToggleLayout(),Y(this)}),this.resizeObserverStarted=!0,this.resizeObserver.observe(this.field),this.resizeObserver.observe(this.container),setTimeout(()=>this.updateToggleLayout(),100),window.mathVirtualKeyboard.addEventListener("virtual-keyboard-toggle",this,{signal:i}),Yt&&!F.locale.startsWith(Yt.locale)&&jo(F.locale),Ne!=="ready"&&document.fonts.ready.then(()=>uo(this)),e.querySelector("[part=container]").style.removeProperty("visibility"),this.undoManager.startRecording(),this.undoManager.snapshot("set-value"),Y(this)}connectToVirtualKeyboard(){this.connectedToVirtualKeyboard||(this.connectedToVirtualKeyboard=!0,window.addEventListener("message",this,{signal:this.eventController.signal}),window.mathVirtualKeyboard.connect(),window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.update(Xt(this)),Eo(this))}disconnectFromVirtualKeyboard(){this.connectedToVirtualKeyboard&&(window.removeEventListener("message",this),window.mathVirtualKeyboard.disconnect(),this.connectedToVirtualKeyboard=!1,Ns())}showMenu(e){var o,a;let r=(a=(o=e==null?void 0:e.location)!=null?o:tn(this.field))!=null?a:void 0,i=e==null?void 0:e.modifiers,n=this.element.querySelector("[part=container]");return this._menu.show({target:n,location:r,modifiers:i})}get colorMap(){return e=>{var r,i,n;return(n=(i=(r=this.options).colorMap)==null?void 0:i.call(r,e))!=null?n:Yr(e)}}get backgroundColorMap(){return e=>{var r,i,n,o,a,s;return(s=(a=(i=(r=this.options).backgroundColorMap)==null?void 0:i.call(r,e))!=null?a:(o=(n=this.options).colorMap)==null?void 0:o.call(n,e))!=null?s:Bi(e)}}get smartFence(){var e;return(e=this.options.smartFence)!=null?e:!1}get readOnly(){var e;return(e=this.options.readOnly)!=null?e:!1}updateAccessibleName(){var e;(e=this.keyboardDelegate)==null||e.setAriaLabel(Rc(this.host))}updateAccessibleReadOnly(){var e;(e=this.keyboardDelegate)==null||e.setAriaReadOnly(this.readOnly&&!this.hasEditablePrompts)}get disabled(){var e,r;return(r=(e=this.host)==null?void 0:e.disabled)!=null?r:!1}get contentEditable(){return this.host?this.host.getAttribute("contenteditable")!=="false":!1}get userSelect(){if(!this.host)return"";let e=getComputedStyle(this.host);return e.getPropertyValue("user-select")||e.getPropertyValue("-webkit-user-select")}get hasEditableContent(){return this.disabled||!this.contentEditable?!1:!this.readOnly||this.hasEditablePrompts}get hasEditablePrompts(){return this.readOnly&&!this.disabled&&this.contentEditable&&this.model.findAtom(e=>e.type==="prompt"&&!e.locked)!==void 0}get isSelectionEditable(){if(this.disabled||!this.contentEditable)return!1;if(!this.readOnly)return!0;let e=this.model.at(this.model.anchor),r=this.model.at(this.model.position),i=x.commonAncestor(e,r);return!!((i==null?void 0:i.type)==="prompt"||i!=null&&i.parentPrompt)}get letterShapeStyle(){var e;return(e=this.options.letterShapeStyle)!=null?e:"tex"}get minFontScale(){return this.options.minFontScale}get maxMatrixCols(){return this.options.maxMatrixCols}queryStyle(e){let r=fs(this,e);"verbatimColor"in r&&delete r.verbatimColor,"verbatimBackgroundColor"in r&&delete r.verbatimBackgroundColor;let i=Object.keys(r).length;if(i===0)return"all";if(i>1){for(let c of Object.keys(r)){let u=this.queryStyle({[c]:r[c]});if(u==="none")return"none";if(u==="some")return"some"}return"all"}let n=Object.keys(r)[0],o=r[n];if(this.model.selectionIsCollapsed)return Gt(this)[n]===o?"all":"none";let a=this.model.getAtoms(this.model.selection,{includeChildren:!0}),s=a.length;if(s===0)return"none";let l=0;for(let c of a){if(c.type==="first"){s-=1;continue}c.style[n]===o&&(l+=1)}return l===0?"none":l===s?"all":"some"}get keybindings(){var i,n;if(this._keybindings)return this._keybindings;let[e,r]=Rh(this.options.keybindings,(i=yr())!=null?i:Du());return((n=yr())==null?void 0:n.score)>0&&(this._keybindings=e,r.length>0&&console.error("MathLive 0.111.1: Invalid keybindings for current keyboard layout",r)),e}get menu(){var e;return(e=this._menu)!=null||(this._menu=new Do(Fp(this),{host:this.host})),this._menu}set menuItems(e){this._menu?this._menu.menuItems=e:this._menu=new Do(e,{host:this.host})}setOptions(e){var n;this.options=h(h({},this.options),wn(e)),this._keybindings=void 0,this.options.defaultMode==="inline-math"?this.element.classList.add("ML__is-inline"):this.element.classList.remove("ML__is-inline");let r=this.options.defaultMode;r==="inline-math"&&(r="math"),((n=this.model.root.firstChild)==null?void 0:n.mode)!==r&&(this.model.root.firstChild.mode=r),this.options.readOnly&&this.hasFocus()&&window.mathVirtualKeyboard.visible&&this.executeCommand("hideVirtualKeyboard"),"readOnly"in e&&this.updateAccessibleReadOnly();let i=x.serialize([this.model.root],{expandMacro:!1,defaultMode:this.options.defaultMode});("macros"in e||this.model.getValue()!==i)&&kc(this),("value"in e||"registers"in e||"colorMap"in e||"backgroundColorMap"in e||"letterShapeStyle"in e||"minFontScale"in e||"maxMatrixCols"in e||"readOnly"in e||"contentPlaceholder"in e||"placeholderSymbol"in e)&&Y(this)}getOptions(e){return fr(this.options,e)}getOption(e){return fr(this.options,e)}async handleEvent(e){var r,i,n;if(Ye(this)){if(fo(e)){if(!rn(e.origin,(r=this.options.originValidator)!=null?r:"none"))throw new DOMException(`Message from unknown origin (${e.origin}) cannot be handled`,"SecurityError");let{action:o}=e.data;if(o==="execute-command"){let a=_i(e.data.command);if(!a||pr(a)==="virtual-keyboard")return;this.executeCommand(a)}else o==="update-state"||(o==="focus"?this.focus({preventScroll:!0}):o==="blur"&&this.blur());return}switch(e.type){case"focus":this.programmaticFocusInProgress||this.onFocus({suppressEvents:!0});break;case"blur":this.onBlur({dispatchEvents:!1});break;case"mousedown":this.userSelect!=="none"&&!((i=e.target)!=null&&i.closest("[part=virtual-keyboard-toggle],[part=menu-toggle]"))&&Uc(this,e);break;case"pointerdown":!e.defaultPrevented&&this.userSelect!=="none"&&!((n=e.target)!=null&&n.closest("[part=virtual-keyboard-toggle],[part=menu-toggle]"))&&(Uc(this,e),e.shiftKey===!1&&await Qc(e,this.container,this.menu)&&Li.stop());break;case"contextmenu":this.userSelect!=="none"&&e.shiftKey===!1&&await Qc(e,this.container,this.menu)&&Li.stop();break;case"virtual-keyboard-toggle":this.hasFocus()&&Eo(this),this.hasFocus()&&this.options.mathVirtualKeyboardPolicy!=="manual"&&(this.focusBlurInProgress=!0,this.keyboardDelegate.blur(),this.keyboardDelegate.focus(),this.focusBlurInProgress=!1);break;case"resize":this.geometryChangeTimer&&cancelAnimationFrame(this.geometryChangeTimer),this.geometryChangeTimer=requestAnimationFrame(()=>Ye(this)&&this.onGeometryChange());break;case"scroll":this.geometryChangeTimer&&cancelAnimationFrame(this.geometryChangeTimer),this.geometryChangeTimer=requestAnimationFrame(()=>Ye(this)&&this.onGeometryChange());break;case"wheel":this.onWheel(e);break;case"message":break;default:console.warn("Unexpected event type",e.type)}}}updateToggleLayout(){if(!this.element||!this.host)return;let e=this.element.querySelector(".ML__toggles");if(!e)return;let r=this.host.offsetHeight,i=e.classList.contains("ML__toggles--vertical");r>=100&&!i?e.classList.add("ML__toggles--vertical"):r<100&&i&&e.classList.remove("ML__toggles--vertical")}dispose(){if(!Ye(this))return;t._globallyFocusedMathfield===this&&(t._globallyFocusedMathfield=void 0),F.unsubscribe(this._l10Subscription),this.keyboardDelegate.dispose(),this.keyboardDelegate=void 0,this.eventController.abort(),this.eventController=void 0,this.resizeObserver.disconnect(),window.mathVirtualKeyboard.removeEventListener("virtual-keyboard-toggle",this),this.disconnectFromVirtualKeyboard(),this.model.dispose();let e=this.element;delete e.mathfield,this.element=void 0,this.host=void 0,this.field=void 0,this.ariaLiveText=void 0,gp(),Fh(),Lp()}flushInlineShortcutBuffer(e){if(e!=null||(e={defer:!1}),!e.defer){this.inlineShortcutBuffer.length=0,clearTimeout(this.inlineShortcutBufferFlushTimer),this.inlineShortcutBufferFlushTimer=0;return}this.options.inlineShortcutTimeout>0&&(clearTimeout(this.inlineShortcutBufferFlushTimer),this.inlineShortcutBufferFlushTimer=setTimeout(()=>this.flushInlineShortcutBuffer(),this.options.inlineShortcutTimeout))}executeCommand(e){return pr(e)==="virtual-keyboard"?(this.focus({preventScroll:!0}),window.mathVirtualKeyboard.executeCommand(e),requestAnimationFrame(()=>window.mathVirtualKeyboard.update(Xt(this))),!1):Wh(this,e)}get errors(){return ss(this.model.getValue(),{context:this.context})}getValue(e,r,i){return this.model.getValue(e,r,i)}setValue(e,r){var n;r=r!=null?r:{mode:"math"},r.insertionMode===void 0&&(r.insertionMode="replaceAll"),(r.format===void 0||r.format==="auto")&&(r.format="latex"),(r.mode===void 0||r.mode==="auto")&&(r.mode=(n=J0(this.model,this.model.position))!=null?n:"math");let i=this.undoManager.canUndo();H.insert(this.model,e,r)&&(Y(this),i||this.undoManager.reset(),this.undoManager.snapshot("set-value"))}scrollIntoView(){var i;if(!this.element)return;if(this.host){if(this.options.onScrollIntoView)this.options.onScrollIntoView(this);else if(this.host.scrollIntoView({block:"nearest",inline:"nearest"}),window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.container===window.document.body){let n=window.mathVirtualKeyboard.boundingRect,o=this.host.getBoundingClientRect();o.bottom>n.top&&((i=window.document.scrollingElement)==null||i.scrollBy(0,o.bottom-n.top+8))}}this.dirty&&_t(this,{interactive:!0});let e=this.field.getBoundingClientRect(),r=null;if(this.model.selectionIsCollapsed)r=tn(this.field);else{let n=Qa(this);if(n.length>0){let o=-1/0,a=1/0,s=-1/0;for(let c of n)c.right>o&&(o=c.right),c.tops&&(s=c.bottom);let l=s-a;r={x:o+e.left-this.field.scrollLeft,y:a+e.top-this.field.scrollTop,height:l}}}if(this.host&&r){let n=this.host.getBoundingClientRect(),o=20,a=r.y,s=r.y+r.height,l=this.host.scrollTop;an.bottom-o&&(l=s-n.bottom+this.host.scrollTop+o),l!==this.host.scrollTop&&this.host.scroll({top:l,behavior:"auto"})}if(r){let n=r.x-window.scrollX,o=this.field.scrollLeft;ne.right&&(o=n-e.right+this.field.scrollLeft+20),this.field.scroll({top:this.field.scrollTop,left:o})}}insert(e,r){if(typeof e!="string"||e.length===0&&((r==null?void 0:r.insertionMode)==="insertBefore"||(r==null?void 0:r.insertionMode)==="insertAfter")||e.length===0&&this.model.selectionIsCollapsed)return!1;if(this.flushInlineShortcutBuffer(),r=r!=null?r:{mode:"math"},r.focus&&this.focus(),r.feedback&&(globalThis.MathfieldElement.keypressVibration&&Di()&&navigator.vibrate(mo),globalThis.MathfieldElement.playSound("keypress")),e==="\\\\")Ic(this.model);else if(e==="&")zc(this.model);else if(this.model.selectionIsCollapsed){let i=h({},Gt(this));!/^[a-zA-Z0-9]$/.test(e)&&this.styleBias!=="none"&&(i.variant="normal",i.variantStyle=void 0),H.insert(this.model,e,h({style:i},r))}else H.insert(this.model,e,r);return this.snapshot(`insert-${this.model.at(this.model.position).type}`),Y(this),r.scrollIntoView&&this.scrollIntoView(),!0}switchMode(e,r="",i=""){if(this.model.mode===e||!this.hasEditableContent||!this.contentEditable||this.disabled)return;let{model:n}=this,o=n.mode;if(n.mode=e,this.host&&!this.host.dispatchEvent(new Event("mode-change",{bubbles:!0,composed:!0,cancelable:!0}))){n.mode=o;return}n.mode=o,n.deferNotifications({content:!!i||!!r,selection:!0,type:"insertText"},()=>{let a=n.at(n.position),s=(d,m)=>{if(!d)return;let p=n.mode==="math"?be(or(d,{format:"ascii-math"})[1],{context:this.context}):[...d].map(f=>new We(f,f,{}));if(m.select){let f=a.parent.addChildrenAfter(p,a);n.setSelection(n.offsetOf(p[0].leftSibling),n.offsetOf(f))}else n.position=n.offsetOf(a.parent.addChildrenAfter(p,a));u=!0},l=(d,m)=>{let p=new $t(d);a.parent.addChildAfter(p,a),m.select?n.setSelection(n.offsetOf(p.firstChild),n.offsetOf(p.lastChild)):n.position=n.offsetOf(p.lastChild),u=!0},c=()=>{let d=e==="latex"?"latex":e==="math"?"plain-text":"ascii-math",m=de(n.selection),p=this.model.getValue(m,d),f=this.model.extractAtoms(m);return f.length===1&&f[0].type==="placeholder"&&(p=i),a=n.at(m[0]),p},u=!1;if(this.flushInlineShortcutBuffer(),this.stopCoalescingUndo(),Qe(this,"accept"),n.selectionIsCollapsed)s(r,{select:!1}),n.mode=e,e==="latex"?l(i,{select:!1}):s(i,{select:!1});else{let d=c();n.mode=e,e==="latex"?l(d,{select:!0}):s(d,{select:!0})}return Y(this),this.undoManager.snapshot(e==="latex"?"insert-latex":"insert"),u}),n.mode=e,window.mathVirtualKeyboard.update(Xt(this))}hasFocus(){return!this.blurred}focus(e){var r;this.disabled||this.focusBlurInProgress||(this.hasFocus()||(this.programmaticFocusInProgress=!0,this.onFocus(),this.model.announce("line")),(r=e==null?void 0:e.preventScroll)!=null&&r||this.scrollIntoView())}blur(){this.disconnectFromVirtualKeyboard(),this.hasFocus()&&this.keyboardDelegate.blur()}select(){this.model.selection={ranges:[[0,this.model.lastOffset]]},this.focus()}applyStyle(e,r={}){var s;let i,n="set",o=!1;di(r)?i=r:(r.operation==="toggle"&&(n="toggle"),i=r.range,o=(s=r.silenceNotifications)!=null?s:!1),i&&(i=this.model.normalizeRange(i)),i&&i[0]===i[1]&&(i=void 0);let a=fs(this,e);if(i===void 0&&this.model.selectionIsCollapsed){if(n==="set"){let u=h({},this.defaultStyle);"color"in a&&delete u.verbatimColor,"backgroundColor"in a&&delete u.verbatimBackgroundColor,this.defaultStyle=h(h({},u),a),this.styleBias="none";return}let l=Gt(this),c=h({},this.defaultStyle);for(let u of Object.keys(a))l[u]===a[u]?(u==="color"&&delete c.verbatimColor,u==="backgroundColor"&&delete c.verbatimBackgroundColor,delete c[u]):c[u]=a[u];this.defaultStyle=c,this.styleBias="none";return}this.model.deferNotifications({content:!o,type:"insertText"},()=>{if(i===void 0)for(let l of this.model.selection.ranges)ao(this.model,l,a,{operation:n});else ao(this.model,i,a,{operation:n})}),Y(this)}toggleContextMenu(){var n;let e=this.menu;if(!e.visible)return!1;if(e.state==="open")return e.hide(),!0;let r=(n=es(this,this.model.position))==null?void 0:n.bounds;if(!r)return!1;let i={x:r.right,y:r.bottom};return e.show({target:this.element.querySelector("[part=container]"),location:i,onDismiss:()=>{var o;return(o=this.element)==null?void 0:o.focus()}}),!0}getPrompt(e){let r=this.model.findAtom(i=>i.type==="prompt"&&i.placeholderId===e);return r}getPromptValue(e,r){let i=this.getPrompt(e);if(!i)return"";let n=this.model.offsetOf(i.firstChild),o=this.model.offsetOf(i.lastChild);return this.model.getValue(n,o,r)}getPrompts(e){return this.model.atoms.filter(r=>r.type!=="prompt"?!1:e?!(e.id&&r.placeholderId!==e.id||e.locked&&r.locked!==e.locked||e.correctness==="undefined"&&r.correctness||e.correctness&&r.correctness!==e.correctness):!0).map(r=>r.placeholderId)}setPromptValue(e,r,i){if(r!==void 0){let n=this.getPrompt(e);if(!n){console.error(`MathLive 0.111.1: unknown prompt ${e}`);return}let o=this.model.getBranchRange(this.model.offsetOf(n),"body");this.model.setSelection(o),this.insert(r,g(h({},i),{insertionMode:"replaceSelection"}))}i!=null&&i.silenceNotifications&&(this.valueOnFocus=this.getValue()),Y(this)}setPromptState(e,r,i){let n=this.getPrompt(e);if(!n){console.error(`MathLive 0.111.1: unknown prompt ${e}`);return}r==="undefined"?n.correctness=void 0:typeof r=="string"&&(n.correctness=r),typeof i=="boolean"&&(n.locked=i,n.captureSelection=i),Y(this)}getPromptState(e){let r=this.getPrompt(e);return r?[r.correctness,r.locked]:(console.error(`MathLive 0.111.1: unknown prompt ${e}`),[void 0,!0])}getPromptRange(e){let r=this.getPrompt(e);return r?this.model.getBranchRange(this.model.offsetOf(r),"body"):(console.error(`MathLive 0.111.1: unknown prompt ${e}`),[0,0])}canUndo(){return this.undoManager.canUndo()}canRedo(){return this.undoManager.canRedo()}popUndoStack(){this.undoManager.pop(),window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.update(Xt(this))}snapshot(e){var r;this.undoManager.snapshot(e)&&(window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.update(Xt(this)),(r=this.host)==null||r.dispatchEvent(new CustomEvent("undo-state-change",{bubbles:!0,composed:!0,detail:{type:"snapshot"}})))}stopCoalescingUndo(){this.undoManager.stopCoalescing(this.model.selection)}stopRecording(){this.undoManager.stopRecording()}startRecording(){this.undoManager.startRecording()}undo(){var e;this.undoManager.undo()&&((e=this.host)==null||e.dispatchEvent(new CustomEvent("undo-state-change",{bubbles:!0,composed:!0,detail:{type:"undo"}})))}redo(){var e;this.undoManager.redo()&&((e=this.host)==null||e.dispatchEvent(new CustomEvent("undo-state-change",{bubbles:!0,composed:!0,detail:{type:"redo"}})))}resetUndo(){var e;(e=this.undoManager)==null||e.reset()}onSelectionDidChange(){var r,i;let e=this.model;if(e.mathfield.hasFocus()&&this.keyboardDelegate.setValue(e.getValue(e.selection,"latex-expanded")),e.selectionIsCollapsed){let n=lo(e),o=e.position,a=e.at(o),s=(r=a.mode)!=null?r:Tc(this.options);if(n&&(oe.offsetOf(n.lastChild))){Qe(this,"accept",{mode:s});let l=e.offsetOf(a);l>=0&&(e.position=l)}else{let l=e.at(o+1);(l==null?void 0:l.type)==="first"&&l.mode==="latex"?e.position=o+1:n&&(l==null?void 0:l.mode)!=="latex"?e.position=o-1:this.switchMode(s)}}(i=this.host)==null||i.dispatchEvent(new Event("selection-change",{bubbles:!0,composed:!0})),window.mathVirtualKeyboard.visible&&window.mathVirtualKeyboard.update(Xt(this)),Eo(this)}onContentWillChange(e){var r,i,n;return(n=(i=this.host)==null?void 0:i.dispatchEvent(new InputEvent("beforeinput",g(h({},e),{data:e.data?e.data:(r=e.inputType)!=null?r:"",cancelable:!0,bubbles:!0,composed:!0}))))!=null?n:!0}onFocus(e){if(this.disabled||this.focusBlurInProgress||!this.blurred)return;let r=t._globallyFocusedMathfield;r&&r!==this&&Ye(r)&&!r.disabled&&r.hasFocus()&&r.onBlur({dispatchEvents:!0}),this.focusBlurInProgress=!0,this.blurred=!1,this.updateAccessibleName(),this.updateAccessibleReadOnly(),t._globallyFocusedMathfield=this,this.stopCoalescingUndo(),this.valueOnFocus=this.model.getValue(),this.hasEditablePrompts&&!this.model.at(this.model.anchor).parentPrompt&&this.executeCommand("moveToNextPlaceholder"),_t(this,{interactive:!0});let i=Ut();setTimeout(()=>{var s,l,c,u,d;if(!Ye(this))return;let n=Ut(),o=((s=this.element)==null?void 0:s.contains(n))||((c=(l=this.element)==null?void 0:l.shadowRoot)==null?void 0:c.contains(n));if(t._globallyFocusedMathfield!==this||n!==i&&!o){this.focusBlurInProgress=!1,this.programmaticFocusInProgress=!1,this.onBlur({dispatchEvents:!1});return}if((u=e==null?void 0:e.suppressEvents)!=null?u:!1){let m=new AbortController,p=m.signal,f=y=>{y.preventDefault(),y.stopPropagation()};for(let y of["focus","focusin"])(d=this.host)==null||d.addEventListener(y,f,{capture:!0,signal:p});this.focusBlurInProgress=!1,this.keyboardDelegate.focus(),this.connectToVirtualKeyboard(),setTimeout(()=>m.abort(),0)}else this.focusBlurInProgress=!1,this.keyboardDelegate.focus(),this.connectToVirtualKeyboard(),setTimeout(()=>{this.programmaticFocusInProgress=!1},0)},60)}onBlur(e){var i,n,o,a;if(this.focusBlurInProgress||this.blurred)return;if(this.focusBlurInProgress=!0,this.stopCoalescingUndo(),this.blurred=!0,t._globallyFocusedMathfield===this&&(t._globallyFocusedMathfield=void 0),this.ariaLiveText&&(this.ariaLiveText.textContent=""),$r(this),this.model.getValue()!==this.valueOnFocus&&((i=this.host)==null||i.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))),this.disconnectFromVirtualKeyboard(),((n=e==null?void 0:e.dispatchEvents)==null||n)&&((o=this.host)==null||o.dispatchEvent(new Event("blur",{bubbles:!1,composed:!0})),(a=this.host)==null||a.dispatchEvent(new UIEvent("focusout",{bubbles:!0,composed:!0}))),Y(this),this.focusBlurInProgress=!1,Ns(),xn.restoreFocusWhenDocumentFocused){let s=new AbortController,l=s.signal;window.addEventListener("blur",()=>{window.addEventListener("focus",()=>{Ye(this)&&this.focus({preventScroll:!0})},{once:!0,signal:l})},{once:!0,signal:l}),document.addEventListener("focusin",()=>s.abort(),{once:!0}),document.addEventListener("click",()=>s.abort(),{once:!0})}}onInput(e){ko(this,e)}onKeystroke(e){return qc(this,e)}onCompositionStart(e){ct(this.model,de(this.model.selection),"insertText");let r=tn(this.field);r&&requestAnimationFrame(()=>{_t(this),this.keyboardDelegate.moveTo(r.x,r.y-r.height)})}onCompositionUpdate(e){ip(this.model,e),Y(this)}onCompositionEnd(e){np(this.model),ko(this,e,{simulateKeystroke:!0})}onCut(e){if(!this.isSelectionEditable){this.model.announce("plonk");return}this.model.contentWillChange({inputType:"deleteByCut"})&&(this.stopCoalescingUndo(),e.clipboardData?H.onCopy(this,e):H.copyToClipboard(this,"latex"),ct(this.model,de(this.model.selection),"deleteByCut"),this.snapshot("cut"),Y(this))}onCopy(e){e.clipboardData?H.onCopy(this,e):H.copyToClipboard(this,"latex")}onPaste(e){let r=this.isSelectionEditable;return r&&(r=H.onPaste(this.model.at(this.model.position).mode,this,e.clipboardData)),r||this.model.announce("plonk"),e.preventDefault(),e.stopPropagation(),r}onGeometryChange(){var e;(e=this._menu)==null||e.hide(),yn(this),Eo(this)}onWheel(e){let r=5*e.deltaX;if(!Number.isFinite(r)||r===0)return;let i=this.field;r<0&&i.scrollLeft===0||r>0&&i.offsetWidth+i.scrollLeft>=i.scrollWidth||(i.scrollBy({top:0,left:r}),e.preventDefault(),e.stopPropagation())}getHTMLElement(e){let r=e;for(;!r.id&&r.hasChildren;)r=e.children[0];return this.field.querySelector(`[data-atom-id="${r.id}"]`)}get context(){var e,r;return{registers:(e=this.options.registers)!=null?e:{},smartFence:this.smartFence,letterShapeStyle:this.letterShapeStyle,minFontScale:this.minFontScale,maxMatrixCols:this.maxMatrixCols,placeholderSymbol:(r=this.options.placeholderSymbol)!=null?r:"\u25A2",colorMap:i=>this.colorMap(i),backgroundColorMap:i=>this.backgroundColorMap(i),getMacro:i=>ti(i,this.options.macros),atomIdsSettings:{seed:"random",groupNumbers:!1}}}};fe({speak:(t,e,r)=>zy(t,e,r)},{target:"mathfield"});function zy(t,e,r){var c;r=r!=null?r:{withHighlighting:!1};let{model:i}=t;function n(u){let d=null;switch(u){case"all":d=i.root;break;case"selection":d=i.getAtoms(i.selection);break;case"left":{d=i.getAtoms(i.offsetOf(i.at(i.position).leftSibling),i.position);break}case"right":{d=i.getAtoms(i.position,i.offsetOf(i.at(i.position).rightSibling));break}case"group":d=i.getAtoms(i.getSiblingsRange(i.position));break;case"parent":{let{parent:m}=i.at(i.position);m!=null&&m.parent?d=m:d=i.root;break}default:d=i.root}return d}function o(u){let d="";switch(u){case"all":console.error("Internal failure: speak all failed");break;case"selection":d="no selection";break;case"left":d="at start";break;case"right":d="at end";break;case"group":console.error("Internal failure: speak group failed");break;case"parent":d="no parent";break;default:console.error('unknown speak_ param value: "'+u+'"');break}return d}let a=globalThis.MathfieldElement,s=n(e);if(s===null)return(c=a.speakHook)==null||c.call(a,o(e)),!1;(r.withHighlighting||a.speechEngine==="amazon")&&(a.textToSpeechMarkup=globalThis.sre&&a.textToSpeechRules==="sre"?"ssml_step":"ssml");let l=wt(s);return Le()&&r.withHighlighting?(At().readAloudMathfield=t,_t(t,{forHighlighting:!0}),a.readAloudHook&&a.readAloudHook(t.field,l)):a.speakHook&&a.speakHook(l),!1}function Up(t){var r,i;if(!Le())return;let e=globalThis.MathfieldElement;if(!e.speechEngine||e.speechEngine==="local"){let n=new SpeechSynthesisUtterance(t);globalThis.speechSynthesis.speak(n)}else if(e.speechEngine==="amazon")if(!("AWS"in window))console.error("MathLive 0.111.1: AWS SDK not loaded. See https://www.npmjs.com/package/aws-sdk");else{let n=new globalThis.AWS.Polly({apiVersion:"2016-06-10"}),o={OutputFormat:"mp3",VoiceId:(r=e.speechEngineVoice)!=null?r:"Joanna",Engine:["Amy","Emma","Brian","Ivy","Joanna","Kendra","Kimberly","Salli","Joey","Justin","Matthew"].includes((i=e.speechEngineVoice)!=null?i:"Joanna")?"neural":"standard",Text:t,TextType:"ssml"};n.synthesizeSpeech(o,(a,s)=>{if(a)console.trace(`MathLive 0.111.1: \`polly.synthesizeSpeech()\` error: ${a}`);else if(s!=null&&s.AudioStream){let l=new Uint8Array(s.AudioStream),c=new Blob([l.buffer],{type:"audio/mpeg"}),u=URL.createObjectURL(c);new Audio(u).play().catch(m=>console.error(m))}})}else e.speechEngine==="google"&&console.error("MathLive 0.111.1: The Google speech engine is not supported yet. Please come again.")}function Gp(t){if(t&&(t.classList.remove("ML__highlight"),t.children))for(let e of t.children)Gp(e)}function uu(t,e){var r;t&&(!e||((r=t.dataset)==null?void 0:r.atomId)===e?(t.classList.add("ML__highlight"),t.children&&t.children.length>0&&[...t.children].forEach(i=>{i instanceof HTMLElement&&uu(i)})):(t.classList.remove("ML__highlight"),t.children&&t.children.length>0&&[...t.children].forEach(i=>{i instanceof HTMLElement&&uu(i,e)})))}function jp(t,e){var n;if(!Le())return;if(globalThis.MathfieldElement.speechEngine!=="amazon"){console.error("MathLive 0.111.1: Use Amazon TTS Engine for synchronized highlighting"),typeof globalThis.MathfieldElement.speakHook=="function"&&globalThis.MathfieldElement.speakHook(e);return}if(!globalThis.AWS){console.error("MathLive 0.111.1: AWS SDK not loaded. See https://www.npmjs.com/package/aws-sdk");return}let r=new globalThis.AWS.Polly({apiVersion:"2016-06-10"}),i={OutputFormat:"json",VoiceId:(n=globalThis.MathfieldElement.speechEngineVoice)!=null?n:"Joanna",Engine:"standard",Text:e,TextType:"ssml",SpeechMarkTypes:["ssml"]};At().readAloudElement=t,r.synthesizeSpeech(i,(o,a)=>{if(o){console.trace(`MathLive 0.111.1: \`polly.synthesizeSpeech()\` error: ${o}`);return}if(!(a!=null&&a.AudioStream))return;let s=new TextDecoder("utf-8").decode(new Uint8Array(a.AudioStream));At().readAloudMarks=s.split(` +`).map(l=>l?JSON.parse(l):{}),At().readAloudTokens=[];for(let l of At().readAloudMarks)l.value&&At().readAloudTokens.push(l.value);At().readAloudCurrentMark="",i.OutputFormat="mp3",i.SpeechMarkTypes=[],r.synthesizeSpeech(i,(l,c)=>{if(l){console.trace(`MathLive 0.111.1: \`polly.synthesizeSpeech("${e}") error:${l}`);return}if(!(c!=null&&c.AudioStream))return;let u=new Uint8Array(c.AudioStream),d=new Blob([u.buffer],{type:"audio/mpeg"}),m=URL.createObjectURL(d),p=At();p.readAloudAudio?p.readAloudAudio.pause():(p.readAloudAudio=new Audio,p.readAloudAudio.addEventListener("ended",()=>{let f=p.readAloudMathfield;p.readAloudStatus="ended",document.body.dispatchEvent(new Event("read-aloud-status-change",{bubbles:!0,composed:!0})),f?(_t(f),p.readAloudElement=null,p.readAloudMathfield=null,p.readAloudTokens=[],p.readAloudMarks=[],p.readAloudCurrentMark=""):Gp(p.readAloudElement)}),p.readAloudAudio.addEventListener("timeupdate",()=>{let f="",y=p.readAloudAudio.currentTime*1e3+100;for(let v of p.readAloudMarks)v.time0){console.group("%cMathLive 0.111.1: %cInvalid Options","color:#12b; font-size: 1.1rem","color:#db1111; font-size: 1.1rem"),console.warn("Some of the options passed to `new MathfieldElement(...)` are invalid. \n See mathfield/changelog/ for details.");for(let n of i)console.warn(n);console.groupEnd()}}if(Js()&&(this._internals=this.attachInternals(),this._internals.role="group"),this.attachShadow({mode:"open",delegatesFocus:!0}),this.shadowRoot&&"adoptedStyleSheets"in this.shadowRoot){this.shadowRoot.adoptedStyleSheets=[sr("core"),sr("mathfield"),sr("mathfield-element"),sr("ui"),sr("menu")],this.shadowRoot.appendChild(document.createElement("span"));let i=document.createElement("slot");i.style.display="none",this.shadowRoot.appendChild(i)}else this.shadowRoot.innerHTML="';r&&this._setOptions(r)}static get formAssociated(){return Js()}static get optionsAttributes(){return{"default-mode":"string","letter-shape-style":"string","min-font-scale":"number","max-matrix-cols":"number","popover-policy":"string","math-mode-space":"string","read-only":"boolean","remove-extraneous-parentheses":"on/off","smart-fence":"on/off","smart-mode":"on/off","smart-superscript":"on/off","inline-shortcut-timeout":"string","script-depth":"string",placeholder:"string","virtual-keyboard-target-origin":"string","math-virtual-keyboard-policy":"string"}}static get observedAttributes(){return[...Object.keys(this.optionsAttributes),"contenteditable","disabled","readonly","read-only","aria-label","aria-labelledby","title"]}static get fontsDirectory(){return this._fontsDirectory}static set fontsDirectory(r){r!==this._fontsDirectory&&(this._fontsDirectory=r,qh())}get fontsDirectory(){throw new Error("Use MathfieldElement.fontsDirectory instead")}set fontsDirectory(r){throw new Error("Use MathfieldElement.fontsDirectory instead")}static get soundsDirectory(){return this._soundsDirectory}static set soundsDirectory(r){this._soundsDirectory=r,this.audioBuffers={}}get soundsDirectory(){throw new Error("Use MathfieldElement.soundsDirectory instead")}set soundsDirectory(r){throw new Error("Use MathfieldElement.soundsDirectory instead")}static get keypressSound(){return this._keypressSound}static set keypressSound(r){var i,n,o;this.audioBuffers={},r===null?this._keypressSound={spacebar:null,return:null,delete:null,default:null}:typeof r=="string"?this._keypressSound={spacebar:r,return:r,delete:r,default:r}:typeof r=="object"&&"default"in r&&(this._keypressSound={spacebar:(i=r.spacebar)!=null?i:r.default,return:(n=r.return)!=null?n:r.default,delete:(o=r.delete)!=null?o:r.default,default:r.default})}static get plonkSound(){return this._plonkSound}static set plonkSound(r){this.audioBuffers={},this._plonkSound=r}static get audioContext(){return this._audioContext||(this._audioContext=new AudioContext),this._audioContext}static get speechEngine(){return this._speechEngine}static set speechEngine(r){this._speechEngine=r}static get speechEngineRate(){return this._speechEngineRate}static set speechEngineRate(r){this._speechEngineRate=r}static get speechEngineVoice(){return this._speechEngineVoice}static set speechEngineVoice(r){this._speechEngineVoice=r}static get textToSpeechMarkup(){return this._textToSpeechMarkup}static set textToSpeechMarkup(r){this._textToSpeechMarkup=r}static get textToSpeechRules(){return this._textToSpeechRules}static set textToSpeechRules(r){this._textToSpeechRules=r}static get textToSpeechRulesOptions(){return this._textToSpeechRulesOptions}static set textToSpeechRulesOptions(r){this._textToSpeechRulesOptions=r}static get locale(){return F.locale}static set locale(r){r==="auto"&&(r=navigator.language.slice(0,5)),F.locale=r}get locale(){throw new Error("Use MathfieldElement.locale instead")}set locale(r){throw new Error("Use MathfieldElement.locale instead")}static get strings(){return F.strings}static set strings(r){F.merge(r)}get strings(){throw new Error("Use MathfieldElement.strings instead")}set strings(r){throw new Error("Use MathfieldElement.strings instead")}static get decimalSeparator(){return this._decimalSeparator}static set decimalSeparator(r){this._decimalSeparator=r,this._computeEngine&&console.warn("MathLive 0.111.1: setting MathfieldElement.decimalSeparator after the Compute Engine has been created has no effect on the engine. Reassign MathfieldElement.computeEngine with a freshly configured instance to apply the new separator.")}get decimalSeparator(){throw new Error("Use MathfieldElement.decimalSeparator instead")}set decimalSeparator(r){throw new Error("Use MathfieldElement.decimalSeparator instead")}static set scientificNotationTemplate(r){this._scientificNotationTemplate=r}static get scientificNotationTemplate(){return this._scientificNotationTemplate}static get fractionNavigationOrder(){return pn.fractionNavigationOrder}static set fractionNavigationOrder(r){if(r!=="numerator-denominator"&&r!=="denominator-numerator")throw new Error("Invalid value");pn.fractionNavigationOrder!==r&&(pn.fractionNavigationOrder=r,Lc())}static get computeEngine(){var r,i;if(this._computeEngine===void 0){let n=window[Symbol.for("io.cortexjs.compute-engine")],o=n==null?void 0:n.ComputeEngine;if(!o)return null;if(this._computeEngine=new o,this._computeEngine&&this.decimalSeparator===","){let[a,s]=String((r=n==null?void 0:n.version)!=null?r:"").split(".").map(l=>parseInt(l,10));(a>0||a===0&&s>=58)&&(this._computeEngine.latexOptions=g(h({},this._computeEngine.latexOptions),{decimalSeparator:"{,}"}))}}return(i=this._computeEngine)!=null?i:null}static set computeEngine(r){this._computeEngine=r}get computeEngine(){throw new Error("Use MathfieldElement.computeEngine instead")}set computeEngine(r){throw new Error("Use MathfieldElement.computeEngine instead")}static get isFunction(){return typeof this._isFunction!="function"?()=>!1:this._isFunction}static set isFunction(r){this._isFunction=r,Lc()}static async loadSound(r){delete this.audioBuffers[r];let i="";switch(r){case"keypress":i=this._keypressSound.default;break;case"return":i=this._keypressSound.return;break;case"spacebar":i=this._keypressSound.spacebar;break;case"delete":i=this._keypressSound.delete;break;case"plonk":i=this.plonkSound;break}if(typeof i!="string")return;i=i.trim();let n=this.soundsDirectory;if(!(n==null||n==="null"||i==="none"||i==="null"))try{let a=await(await fetch(await bs(`${n}/${i}`))).arrayBuffer(),s=await this.audioContext.decodeAudioData(a);this.audioBuffers[r]=s}catch(o){}}static async playSound(r){if((this.audioContext.state==="suspended"||this.audioContext.state==="interrupted")&&await this.audioContext.resume(),this.audioBuffers[r]||await this.loadSound(r),!this.audioBuffers[r])return;let i=this.audioContext.createBufferSource();i.buffer=this.audioBuffers[r];let n=this.audioContext.createGain();n.gain.value=Ny,i.connect(n).connect(this.audioContext.destination),i.start()}showMenu(r){var i,n;return(n=(i=this._mathfield)==null?void 0:i.showMenu(r))!=null?n:!1}get mathVirtualKeyboard(){throw new Error("The `mathVirtualKeyboard` property is not available on the MathfieldElement. Use `window.mathVirtualKeyboard` instead.")}onPointerDown(){window.addEventListener("pointerup",r=>{let i=this._mathfield;if(i&&r.target===this&&!i.disabled){this.dispatchEvent(new MouseEvent("click",{altKey:r.altKey,button:r.button,buttons:r.buttons,clientX:r.clientX,clientY:r.clientY,ctrlKey:r.ctrlKey,metaKey:r.metaKey,movementX:r.movementX,movementY:r.movementY,relatedTarget:r.relatedTarget,screenX:r.screenX,screenY:r.screenY,shiftKey:r.shiftKey}));let n=this.getOffsetFromPoint(r.clientX,r.clientY);n>=0&&ce.openUrl(rh(i,n)),r.pointerType==="touch"&&this.selectionIsCollapsed&&(this.position=n)}},{once:!0})}getPromptValue(r,i){var n,o;return(o=(n=this._mathfield)==null?void 0:n.getPromptValue(r,i))!=null?o:""}setPromptValue(r,i,n){var o;(o=this._mathfield)==null||o.setPromptValue(r,i,n)}getPromptRange(r){var i,n;return(n=(i=this._mathfield)==null?void 0:i.getPromptRange(r))!=null?n:null}getPrompts(r){var i,n;return(n=(i=this._mathfield)==null?void 0:i.getPrompts(r))!=null?n:[]}get hasEditableContent(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.hasEditableContent)!=null?i:!1}get form(){var r;return(r=this._internals)==null?void 0:r.form}get name(){var r;return(r=this.getAttribute("name"))!=null?r:""}get type(){return this.localName}get mode(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.model.mode)!=null?i:this.defaultMode==="text"?"text":"math"}set mode(r){var i;(i=this._mathfield)==null||i.switchMode(r)}get errors(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.errors)!=null?i:[]}_getOptions(r){return this._mathfield?fr(this._mathfield.options,r):Q.has(this)?h({},fr(h(h({},Sn()),wn(Q.get(this).options)),r)):null}getOptions(r){return console.warn("%cMathLive 0.111.1: %cDeprecated Usage%c\n `mf.getOptions()` is deprecated. Read the property directly on the mathfield instead.\n See mathfield/changelog/ for details.","color:#12b; font-size: 1.1rem","color:#db1111; font-size: 1.1rem","color: inherit, font-size: 1rem"),this._mathfield?fr(this._mathfield.options,r):Q.has(this)?fr(h(h({},Sn()),wn(Q.get(this).options)),r):null}reflectAttributes(){let r=Sn(),i=this._getOptions();Object.keys(ce.optionsAttributes).forEach(n=>{let o=n==="placeholder"?"contentPlaceholder":gr(n);ce.optionsAttributes[n]==="on/off"?r[o]!==i[o]?this.setAttribute(n,i[o]?"on":"off"):this.removeAttribute(n):r[o]!==i[o]&&(ce.optionsAttributes[n]==="boolean"?i[o]?this.setAttribute(n,""):this.removeAttribute(n):(typeof i[o]=="string"||typeof i[o]=="number")&&this.setAttribute(n,i[o].toString()))})}getOption(r){return console.warn("%cMathLive 0.111.1: %cDeprecated Usage%c\n `mf.getOption()` is deprecated. Read the property directly on the mathfield instead.\n See mathfield/changelog/ for details.","color:#12b; font-size: 1.1rem","color:#db1111; font-size: 1.1rem","color: inherit, font-size: 1rem"),this._getOptions([r])[r]}_getOption(r){return this._getOptions([r])[r]}_setOptions(r){if(this._mathfield)this._mathfield.setOptions(r);else if(Q.has(this)){let i=h(h({},Q.get(this).options),r);Q.set(this,g(h({},Q.get(this)),{selection:{ranges:i.readOnly?[[0,0]]:[[0,-1]]},options:i}))}else Q.set(this,{value:void 0,selection:{ranges:[[0,0]]},options:r,menuItems:void 0});this.reflectAttributes()}setOptions(r){console.group("%cMathLive 0.111.1: %cDeprecated Usage","color:#12b; font-size: 1.1rem","color:#db1111; font-size: 1.1rem"),console.warn(" `mf.setOptions()` is deprecated. Set the property directly on the mathfield instead.\n See mathfield/changelog/ for details.");for(let i of Object.keys(r))Jr[i]&&console.warn(`\`mf.setOptions({${i}:...})\` -> ${Jr[i]}`);console.groupEnd(),this._setOptions(r)}executeCommand(...r){var n,o;let i;if(r.length===1?i=r[0]:i=[r[0],...r.slice(1)],i)return(o=(n=this._mathfield)==null?void 0:n.executeCommand(i))!=null?o:!1;throw new Error("Invalid selector")}getValue(r,i,n){var o,a;if(this._mathfield)return this._mathfield.model.getValue(r,i,n);if(Q.has(this)){let s,l,c;if(Qi(r)?([s,l]=r.ranges[0],c=i):di(r)?([s,l]=r,c=i):zt(r)&&zt(i)?(s=r,l=i,c=n):(s=0,l=-1,c=r),(c===void 0||c==="latex")&&s===0&&l===-1)return(a=(o=Q.get(this).value)!=null?o:this.textContent)!=null?a:""}return""}setValue(r,i){if(this._mathfield&&r!==void 0){if(this._mathfield.model.getValue()===r)return;i!=null||(i={silenceNotifications:!0,mode:"math"}),this._mathfield.setValue(r,i);return}if(Q.has(this)){let o=Q.get(this).options;Q.set(this,{value:r,selection:{ranges:[[-1,-1]],direction:"forward"},options:o,menuItems:void 0});return}let n=js(this);Q.set(this,{value:r,selection:{ranges:[[-1,-1]],direction:"forward"},options:n,menuItems:void 0})}hasFocus(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.hasFocus())!=null?i:!1}focus(){var r;this.disabled||(r=this._mathfield)==null||r.focus()}blur(){var r;(r=this._mathfield)==null||r.blur()}select(){var r;(r=this._mathfield)==null||r.select()}insert(r,i){var n,o;return(o=(n=this._mathfield)==null?void 0:n.insert(r,i))!=null?o:!1}applyStyle(r,i){var n;return(n=this._mathfield)==null?void 0:n.applyStyle(r,i)}queryStyle(r){var i,n;return(n=(i=this._mathfield)==null?void 0:i.queryStyle(r))!=null?n:"none"}getOffsetFromPoint(r,i,n){return this._mathfield?Co(this._mathfield,r,i,n):-1}getElementInfo(r){return es(this._mathfield,r)}resetUndo(){var r;(r=this._mathfield)==null||r.resetUndo()}canUndo(){return this._mathfield?this._mathfield.canUndo():!1}canRedo(){return this._mathfield?this._mathfield.canRedo():!1}handleEvent(r){var n,o,a,s,l;if(Te.state!=="closed"||((o=(n=this._mathfield)==null?void 0:n.menu)==null?void 0:o.state)!=="closed"||(r.type==="pointerdown"&&this.onPointerDown(),r.type==="focus")||r.type!=="blur")return;let i=Uo();i&&((a=window==null?void 0:window.mathVirtualKeyboard)!=null&&a.visible)||((s=Te.scrim)==null?void 0:s.state)!=="closed"||i&&fu()||(l=this._mathfield)==null||l.onBlur({dispatchEvents:!1})}connectedCallback(){var l,c,u,d;let r=this.shadowRoot,i=r.host,o=window.getComputedStyle(this).userSelect!=="none";if(o)i.addEventListener("pointerdown",this,!0);else{let m=r.querySelector("span");m.style.pointerEvents="none"}i.addEventListener("focus",this,!0),i.addEventListener("blur",this,!0),this._observer=new MutationObserver(()=>{var m;this.value=(m=this.textContent)!=null?m:""}),this._observer.observe(this,{childList:!0,characterData:!0,subtree:!0}),Js()||this.hasAttribute("role")||this.setAttribute("role","group"),o&&!this.hasAttribute("contenteditable")&&this.setAttribute("contenteditable","true"),this.hasAttribute("tabindex")||this.setAttribute("tabindex","0");let a=r.querySelector("slot:not([name])");if(a)try{this._style=a.assignedElements().filter(m=>m.tagName.toLowerCase()==="style").map(m=>m.textContent).join("")}catch(m){console.error(m)}if(this._style){let m=document.createElement("style");m.textContent=this._style,r.appendChild(m)}let s="";if(this.hasAttribute("value")?s=this.getAttribute("value"):s=(l=a==null?void 0:a.assignedNodes().map(m=>m.nodeType===3?m.textContent:"").join("").trim())!=null?l:"",this._mathfield=new Gs(r.querySelector(":host > span"),g(h({},(u=(c=Q.get(this))==null?void 0:c.options)!=null?u:js(this)),{eventSink:this,value:s})),!Q.has(this)){this.upgradeProperty("disabled"),this.upgradeProperty("readonly");for(let m of Object.keys(ce.optionsAttributes))this.upgradeProperty(gr(m))}if(!((d=this._mathfield)!=null&&d.model)){this._mathfield=null;return}if(Q.has(this)){let m=this._mathfield,p=Q.get(this),f=p.menuItems;m.model.deferNotifications({content:!1,selection:!1},()=>{let y=p.value;y!==void 0&&m.setValue(y),m.model.selection=p.selection,Q.delete(this)}),f&&(this.menuItems=f)}window.queueMicrotask(()=>{this.isConnected&&this.dispatchEvent(new Event("mount",{cancelable:!1,bubbles:!0,composed:!0}))}),hr()}disconnectedCallback(){var i,n,o;if(this.shadowRoot.host.removeEventListener("pointerdown",this,!0),!this._mathfield)return;(i=this._observer)==null||i.disconnect(),this._observer=null,this._mathfield.hasFocus()&&this._mathfield.onBlur({dispatchEvents:!0}),window.queueMicrotask(()=>this.dispatchEvent(new Event("unmount",{cancelable:!1,bubbles:!0,composed:!0})));let r=fr(this._mathfield.options,Object.keys(ce.optionsAttributes).map(a=>gr(a)));Q.set(this,{value:this._mathfield.getValue(),selection:this._mathfield.model.selection,menuItems:(o=(n=this._mathfield.menu)==null?void 0:n.menuItems)!=null?o:void 0,options:r}),this._mathfield.dispose(),this._mathfield=null}upgradeProperty(r){if(this.hasOwnProperty(r)){let i=this[r];delete this[r],(r==="readonly"||r==="read-only")&&(r="readOnly"),this[r]=i}}attributeChangedCallback(r,i,n){var a;if(i===n)return;let o=n!==null;switch(r){case"contenteditable":Y(this._mathfield);break;case"aria-label":case"aria-labelledby":case"title":(a=this._mathfield)==null||a.updateAccessibleName();break;case"placeholder":n===!1&&(n=""),this.placeholder=n;break;case"disabled":this.disabled=o;break;case"read-only":case"readonly":this.readOnly=o;break;default:}}get readonly(){return this.hasAttribute("readonly")||this.hasAttribute("read-only")}set readonly(r){let i=!!r;i?this.setAttribute("readonly",""):(this.removeAttribute("readonly"),this.removeAttribute("read-only")),this._setOptions({readOnly:i})}get disabled(){return this.hasAttribute("disabled")}set disabled(r){var n;let i=!!r;i?this.setAttribute("disabled",""):this.removeAttribute("disabled"),Js()?this._internals.ariaDisabled=i?"true":"false":this.setAttribute("aria-disabled",i?"true":"false"),i&&((n=this._mathfield)!=null&&n.hasFocus)&&window.mathVirtualKeyboard.visible&&this._mathfield.executeCommand("hideVirtualKeyboard")}get value(){return this.getValue()}set value(r){this.setValue(r)}get defaultMode(){return this._getOption("defaultMode")}set defaultMode(r){this._setOptions({defaultMode:r})}get macros(){if(!this._mathfield)throw new Error("Mathfield not mounted");return this._getOption("macros")}set macros(r){this._setOptions({macros:r})}get registers(){if(!this._mathfield)throw new Error("Mathfield not mounted");let r=this;return new Proxy({},{get:(i,n)=>{if(typeof n=="string")return r._getOption("registers")[n]},set(i,n,o){return typeof n!="string"?!1:(r._setOptions({registers:g(h({},r._getOption("registers")),{[n]:o})}),!0)},ownKeys:()=>Reflect.ownKeys(r._getOption("registers")),getOwnPropertyDescriptor:(i,n)=>{let o=r._getOption("registers")[n];if(o!==void 0)return{configurable:!0,enumerable:!0,value:o,writable:!0}}})}set registers(r){this._setOptions({registers:r})}get colorMap(){return this._getOption("colorMap")}set colorMap(r){this._setOptions({colorMap:r})}get backgroundColorMap(){return this._getOption("backgroundColorMap")}set backgroundColorMap(r){this._setOptions({backgroundColorMap:r})}get letterShapeStyle(){return this._getOption("letterShapeStyle")}set letterShapeStyle(r){this._setOptions({letterShapeStyle:r})}get minFontScale(){return this._getOption("minFontScale")}set minFontScale(r){this._setOptions({minFontScale:r})}get maxMatrixCols(){return this._getOption("maxMatrixCols")}set maxMatrixCols(r){this._setOptions({maxMatrixCols:r})}get smartMode(){return this._getOption("smartMode")}set smartMode(r){this._setOptions({smartMode:r})}get smartFence(){return this._getOption("smartFence")}set smartFence(r){this._setOptions({smartFence:r})}get smartSuperscript(){return this._getOption("smartSuperscript")}set smartSuperscript(r){this._setOptions({smartSuperscript:r})}get scriptDepth(){return this._getOption("scriptDepth")}set scriptDepth(r){this._setOptions({scriptDepth:r})}get removeExtraneousParentheses(){return this._getOption("removeExtraneousParentheses")}set removeExtraneousParentheses(r){this._setOptions({removeExtraneousParentheses:r})}get mathModeSpace(){return this._getOption("mathModeSpace")}set mathModeSpace(r){this._setOptions({mathModeSpace:r})}get placeholderSymbol(){return this._getOption("placeholderSymbol")}set placeholderSymbol(r){this._setOptions({placeholderSymbol:r})}get placeholder(){return this._getOption("contentPlaceholder")}set placeholder(r){this._setOptions({contentPlaceholder:r})}get popoverPolicy(){return this._getOption("popoverPolicy")}set popoverPolicy(r){this._setOptions({popoverPolicy:r})}get environmentPopoverPolicy(){return this._getOption("environmentPopoverPolicy")}set environmentPopoverPolicy(r){this._setOptions({environmentPopoverPolicy:r})}get menuItems(){var r;if(!this._mathfield)throw new Error("Mathfield not mounted");return(r=this._mathfield.menu._menuItems.map(i=>i.menuItem))!=null?r:[]}set menuItems(r){var i;if(!this._mathfield)throw new Error("Mathfield not mounted");if(this._mathfield){let n=(i=this._mathfield.element)==null?void 0:i.querySelector("[part=menu-toggle]");n&&(n.style.display=r.length===0?"none":""),this._mathfield.menu.menuItems=r}}get mathVirtualKeyboardPolicy(){return this._getOption("mathVirtualKeyboardPolicy")}set mathVirtualKeyboardPolicy(r){this._setOptions({mathVirtualKeyboardPolicy:r})}get inlineShortcuts(){if(!this._mathfield)throw new Error("Mathfield not mounted");return this._getOption("inlineShortcuts")}set inlineShortcuts(r){if(!this._mathfield)throw new Error("Mathfield not mounted");this._setOptions({inlineShortcuts:r})}get inlineShortcutTimeout(){return this._getOption("inlineShortcutTimeout")}set inlineShortcutTimeout(r){this._setOptions({inlineShortcutTimeout:r})}get keybindings(){if(!this._mathfield)throw new Error("Mathfield not mounted");return this._getOption("keybindings")}set keybindings(r){if(!this._mathfield)throw new Error("Mathfield not mounted");this._setOptions({keybindings:r})}get onInsertStyle(){let r=this._getOption("onInsertStyle");return r===void 0?co:r}set onInsertStyle(r){this._setOptions({onInsertStyle:r})}get onInlineShortcut(){return this._getOption("onInlineShortcut")}set onInlineShortcut(r){this._setOptions({onInlineShortcut:r})}get onScrollIntoView(){return this._getOption("onScrollIntoView")}set onScrollIntoView(r){this._setOptions({onScrollIntoView:r})}get onExport(){return this._getOption("onExport")}set onExport(r){this._setOptions({onExport:r})}get readOnly(){return this._getOption("readOnly")}set readOnly(r){this._setOptions({readOnly:r})}get isSelectionEditable(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.isSelectionEditable)!=null?i:!1}setPromptState(r,i,n){var o;(o=this._mathfield)==null||o.setPromptState(r,i,n)}getPromptState(r){var i,n;return(n=(i=this._mathfield)==null?void 0:i.getPromptState(r))!=null?n:[void 0,!0]}get selection(){return this._mathfield?this._mathfield.model.selection:Q.has(this)?Q.get(this).selection:{ranges:[[0,0]],direction:"forward"}}set selection(r){if(typeof r=="number"&&(r={ranges:[[r,r]]}),this._mathfield){this._mathfield.model.selection=r,Y(this._mathfield);return}if(Q.has(this)){Q.set(this,g(h({},Q.get(this)),{selection:r}));return}Q.set(this,{value:void 0,selection:r,options:js(this),menuItems:void 0})}get selectionIsCollapsed(){let r=this.selection;return r.ranges.length===1&&r.ranges[0][0]===r.ranges[0][1]}get position(){return this._mathfield?this._mathfield.model.position:Q.has(this)?Q.get(this).selection.ranges[0][0]:0}set position(r){if(this._mathfield&&(this._mathfield.model.position=r,Y(this._mathfield)),Q.has(this)){Q.set(this,g(h({},Q.get(this)),{selection:{ranges:[[r,r]]}}));return}Q.set(this,{value:void 0,selection:{ranges:[[r,r]]},options:js(this),menuItems:void 0})}get lastOffset(){var r,i;return(i=(r=this._mathfield)==null?void 0:r.model.lastOffset)!=null?i:-1}};ce.version="0.111.1",ce.openUrl=r=>{if(!r)return;let i=new URL(r);if(!["http:","https:","file:"].includes(i.protocol.toLowerCase())){ce.playSound("plonk");return}window.open(i,"_blank")},ce._fontsDirectory="./fonts/",ce._soundsDirectory="./sounds",ce.keypressVibration=!0,ce._keypressSound={spacebar:"keypress-spacebar.wav",return:"keypress-return.wav",delete:"keypress-delete.wav",default:"keypress-standard.wav"},ce._plonkSound="plonk.wav",ce.audioBuffers={},ce.createHTML=r=>r,ce._speechEngineRate="100%",ce._speechEngineVoice="Joanna",ce._textToSpeechMarkup="",ce._textToSpeechRules="mathlive",ce._textToSpeechRulesOptions={},ce.speakHook=Up,ce.readAloudHook=jp,ce.restoreFocusWhenDocumentFocused=!0,ce._decimalSeparator=".",ce._scientificNotationTemplate="#1\\times10^{#2}",ce._isFunction=r=>{var n,o;let i=globalThis.MathfieldElement.computeEngine;return(o=(n=i==null?void 0:i.parse(r).domain)==null?void 0:n.isFunction)!=null?o:!1};var lt=ce;function gr(t){return t.replace(/[^a-zA-Z\d]+(.)/g,(e,r)=>r.toUpperCase())}function js(t){let e={readOnly:!1},r=lt.optionsAttributes;return Object.keys(r).forEach(i=>{var n;if(t.hasAttribute(i)){let o=t.getAttribute(i);i==="placeholder"?e.contentPlaceholder=o!=null?o:"":r[i]==="boolean"?e[gr(i)]=!0:r[i]==="on/off"?(o=(n=o==null?void 0:o.toLowerCase())!=null?n:"",o==="on"||o==="true"?e[gr(i)]=!0:o==="off"||o==="false"?e[gr(i)]=!1:e[gr(i)]=void 0):r[i]==="number"?e[gr(i)]=Number.parseFloat(o!=null?o:"0"):e[gr(i)]=o}}),e}function Js(){return!(!("ElementInternals"in window)||!HTMLElement.prototype.attachInternals||!("role"in window.ElementInternals.prototype))}var xn=lt,Jp,Xp,Zp,Yp;if(Le()&&!((Jp=window.customElements)!=null&&Jp.get("math-field"))){(Zp=window[Xp=Symbol.for("io.cortexjs.mathlive")])!=null||(window[Xp]={});let t=window[Symbol.for("io.cortexjs.mathlive")];t.version="0.111.1",globalThis.MathfieldElement=lt,(Yp=window.customElements)==null||Yp.define("math-field",lt)}var zo;function Xs(t){var e,r;if(!zo){let i=(e=globalThis[Symbol.for("io.cortexjs.compute-engine")])==null?void 0:e.ComputeEngine;i?zo=new i:console.error(`MathLive 0.111.1: The CortexJS Compute Engine library is not available. + + Load the library, for example with: + + import "https://esm.run/@cortex-js/compute-engine"`)}return(r=zo==null?void 0:zo.box(t).latex)!=null?r:""}var Qp=!1,ef=null;function Fy(){Qp||ef||(ef=hr().then(()=>{Qp=!0}))}var Zs=class extends HTMLElement{constructor(){super();this._hasRendered=!1;if(this._shadowRoot=this.attachShadow({mode:"open"}),"adoptedStyleSheets"in this._shadowRoot)this._shadowRoot.adoptedStyleSheets=[sr("core")];else{let r=document.createElement("style");r.textContent=Ft("core"),this._shadowRoot.appendChild(r)}this._contentSlot=document.createElement("div"),this._contentSlot.style.display="none",this._contentSlot.setAttribute("part","content"),this._renderContainer=document.createElement("div"),this._renderContainer.setAttribute("part","render"),this._renderContainer.setAttribute("aria-hidden","true"),this._errorFallback=document.createElement("div"),this._errorFallback.style.display="none",this._errorFallback.setAttribute("part","error"),this._shadowRoot.appendChild(this._contentSlot),this._shadowRoot.appendChild(this._renderContainer),this._shadowRoot.appendChild(this._errorFallback),this.addEventListener("keydown",this._handleKeydown.bind(this))}static get observedAttributes(){return["mode","format","macros","letter-shape-style","min-font-scale","max-matrix-cols"]}connectedCallback(){Fy(),"IntersectionObserver"in window&&!this._hasRendered?(this._observer=new IntersectionObserver(r=>{var i;r[0].isIntersecting&&!this._hasRendered&&(this.render(),(i=this._observer)==null||i.disconnect())},{rootMargin:"50px"}),this._observer.observe(this)):this.render()}disconnectedCallback(){var r;(r=this._observer)==null||r.disconnect()}attributeChangedCallback(r,i,n){i!==n&&this._hasRendered&&this.render()}_handleKeydown(r){if(this.getAttribute("tabindex")!==null&&(r.key===" "||r.key==="Enter")){r.preventDefault();let n=this.getAttribute("aria-label");if(n&&"speechSynthesis"in window){let o=new SpeechSynthesisUtterance(n);speechSynthesis.speak(o)}}}get mode(){let r=this.getAttribute("mode");return r==="textstyle"||r==="displaystyle"?r:this.getDefaultMathstyle()}set mode(r){this.setAttribute("mode",r)}get format(){let r=this.getAttribute("format");return r==="latex"||r==="ascii-math"||r==="math-json"?r:"latex"}set format(r){this.setAttribute("format",r)}get letterShapeStyle(){let r=this.getAttribute("letter-shape-style");if(r==="auto"||r==="tex"||r==="iso"||r==="french"||r==="upright")return r}set letterShapeStyle(r){r===void 0?this.removeAttribute("letter-shape-style"):this.setAttribute("letter-shape-style",r)}get macros(){var r;return(r=this.getAttribute("macros"))!=null?r:void 0}set macros(r){r===void 0?this.removeAttribute("macros"):this.setAttribute("macros",r)}get minFontScale(){let r=this.getAttribute("min-font-scale");return r?parseFloat(r):void 0}set minFontScale(r){r===void 0?this.removeAttribute("min-font-scale"):this.setAttribute("min-font-scale",String(r))}get maxMatrixCols(){let r=this.getAttribute("max-matrix-cols");return r?parseInt(r,10):void 0}set maxMatrixCols(r){r===void 0?this.removeAttribute("max-matrix-cols"):this.setAttribute("max-matrix-cols",String(r))}render(){var r,i,n;try{let o=(i=(r=this.textContent)==null?void 0:r.trim())!=null?i:"";if(!o){this._renderContainer.innerHTML="",this._errorFallback.style.display="none",this._renderContainer.style.display="none",this._removeMathML();return}this._contentSlot.textContent=o;let a,s=this.format;if(s==="ascii-math")a=eu(o);else if(s==="math-json"){let u=JSON.parse(o);a=Xs(u)}else a=o;let l={defaultMode:this.mode==="displaystyle"?"math":"inline-math"};if(this.letterShapeStyle&&(l.letterShapeStyle=this.letterShapeStyle),this.macros)try{l.macros=JSON.parse(this.macros)}catch(u){console.warn("Invalid macros JSON:",u)}this.minFontScale!==void 0&&(l.minFontScale=this.minFontScale),this.maxMatrixCols!==void 0&&(l.maxMatrixCols=this.maxMatrixCols);let c=pe(a,l);this._renderContainer.innerHTML=c,this._renderContainer.style.display=this.getDefaultDisplay(),this._errorFallback.style.display="none",this._updateAccessibility(a),this._hasRendered=!0,this.dispatchEvent(new CustomEvent("render",{bubbles:!0,composed:!0,detail:{format:s,content:a}}))}catch(o){console.error("MathLive static element render error:",o),this._renderContainer.style.display="none",this._errorFallback.textContent=(n=this.textContent)!=null?n:"",this._errorFallback.style.display="block",this._removeMathML(),this.dispatchEvent(new CustomEvent("render-error",{bubbles:!0,composed:!0,detail:{error:o,content:this.textContent}}))}}_updateAccessibility(r){if(!this.hasAttribute("aria-label"))try{let i=Ko(r);this.setAttribute("aria-label",i)}catch(i){console.warn("Could not generate speakable text:",i)}this.hasAttribute("role")||this.setAttribute("role","img"),this._addMathML(r)}_addMathML(r){try{let i=Bo(r);this._mathMLContainer||(this._mathMLContainer=document.createElement("div"),this._mathMLContainer.style.position="absolute",this._mathMLContainer.style.width="1px",this._mathMLContainer.style.height="1px",this._mathMLContainer.style.overflow="hidden",this._mathMLContainer.style.clip="rect(0, 0, 0, 0)",this._mathMLContainer.setAttribute("aria-hidden","false"),this._shadowRoot.appendChild(this._mathMLContainer)),this._mathMLContainer.innerHTML=""+i+""}catch(i){console.warn("Could not generate MathML:",i)}}_removeMathML(){this._mathMLContainer&&(this._mathMLContainer.remove(),this._mathMLContainer=void 0)}},No=class extends Zs{getDefaultMathstyle(){return"textstyle"}getDefaultDisplay(){return"inline-flex"}},Fo=class extends Zs{getDefaultMathstyle(){return"displaystyle"}getDefaultDisplay(){return"flex"}};function $y(){var t,e,r,i;typeof window!="undefined"&&((t=window.customElements)!=null&&t.get("math-span")||(e=window.customElements)==null||e.define("math-span",No),(r=window.customElements)!=null&&r.get("math-div")||(i=window.customElements)==null||i.define("math-div",Fo))}$y();function Vy(t,e,r){let i=r,n=0,o=t.length;for(;i0&&o.push({type:"text",data:s.slice(0,c)}),l=!1);let d=!1;for(;!d;){if(l){if(u=s.indexOf(e,c),u===-1){d=!0;break}c!==u&&o.push({type:"text",data:s.slice(c,u)}),c=u}else{if(u=Vy(r,s,c+e.length),u===-1){d=!0;break}let m=s.slice(c+e.length,u);n==="ascii-math"&&([,m]=or(m,{format:"ascii-math"})),o.push({type:"math",data:m,mathstyle:i}),c=u+r.length}l=!l}c{r=Ys(r,d,m,"displaystyle")}),(a=(o=e.TeX)==null?void 0:o.delimiters)!=null&&a.inline&&e.TeX.delimiters.inline.forEach(([d,m])=>{r=Ys(r,d,m,"textstyle")}),(l=(s=e.asciiMath)==null?void 0:s.delimiters)!=null&&l.inline&&e.asciiMath.delimiters.inline.forEach(([d,m])=>{r=Ys(r,d,m,"textstyle","ascii-math")}),(u=(c=e.asciiMath)==null?void 0:c.delimiters)!=null&&u.display&&e.asciiMath.delimiters.display.forEach(([d,m])=>{r=Ys(r,d,m,"displaystyle","ascii-math")}),r}function qy(t,e){let r=document.createElement("span");r.setAttribute("translate","no");try{let i=""+e.renderToMathML(t)+"";r.innerHTML=globalThis.MathfieldElement.createHTML(i)}catch(i){console.error(`MathLive 0.111.1: Could not convert "${t}"' to MathML with ${i}`),r.textContent=t}return r.className="ML__sr-only",r}function Hy(t,e,r){try{let i=e.renderToMarkup(t,g(h({},e),{defaultMode:r==="displaystyle"?"math":"inline-math"})),n=document.createElement("span");return n.dataset.latex=t,n.style.display=r==="displaystyle"?"flex":"inline-flex",n.setAttribute("aria-hidden","true"),n.setAttribute("translate","no"),n.innerHTML=globalThis.MathfieldElement.createHTML(i),n}catch(i){return console.error("Could not parse'"+t+"' with ",i),document.createTextNode(t)}}function $o(t,e,r){var o;let i=Hy(t,r,e||"textstyle"),n=(o=r.renderAccessibleContent)!=null?o:"";if(/\b(mathml|speakable-text)\b/i.test(n)){let a=document.createElement("span");if(/\bmathml\b/i.test(n)&&r.renderToMathML&&a.append(qy(t,r)),/\bspeakable-text\b/i.test(n)&&r.renderToSpeakableText){let s=document.createElement("span");s.setAttribute("translate","no");let l=r.renderToSpeakableText(t);globalThis.MathfieldElement.textToSpeechMarkup==="ssml"?s.innerHTML=globalThis.MathfieldElement.createHTML(l):s.textContent=l,s.className="ML__sr-only",a.append(s)}return a.append(i),a}return i}function Wy(t,e){var n;if(/^\s*$/.test(t))return null;if((n=e.TeX)!=null&&n.processEnvironments&&/^\s*\\begin/.test(t))return[$o(t,"",e)];let r=tf(t,e);if(r.length===1&&r[0].type==="text")return null;let i=[];for(let o of r)o.type==="text"?i.push(o.data):i.push($o(o.data,o.mathstyle==="textstyle"?"textstyle":"displaystyle",e));return i}function rf(t,e){var i,n,o,a,s,l,c,u,d,m,p,f,y,v,b,k,S,A;if(t.childNodes.length===1&&t.childNodes[0].nodeType===3){let E=(i=t.childNodes[0].textContent)!=null?i:"";if((n=e.TeX)!=null&&n.processEnvironments&&/^\s*\\begin/.test(E)){t.textContent="",t.append($o(E,"",e));return}let C=tf(E,e);if(C.length===1){let _=C[0];if(_.type==="text")return;t.textContent="",t.append($o(_.data,_.mathstyle==="textstyle"?"textstyle":"displaystyle",e));return}}let r=[...t.childNodes];for(let E of r)if(E.nodeType===3){let C=Wy((o=E.textContent)!=null?o:"",e);C&&E.replaceWith(...C)}else if(E.nodeType===1){let C=E.nodeName.toLowerCase();if(C==="script"){let _=E,O=_.type.toLowerCase();if(O==="module"||O==="javascript")continue;let I;if((a=e.processScriptTypePattern)!=null&&a.test(O))I=(s=_.textContent)!=null?s:"";else if((l=e.processMathJSONScriptTypePattern)!=null&&l.test(O))try{I=(u=e.serializeToLatex)==null?void 0:u.call(e,JSON.parse((c=_.textContent)!=null?c:""))}catch(V){console.error(V)}if(I){let V="textstyle";for(let K of O.split(";")){let[N,j]=K.split("=");N.trim()==="mode"&&(V=j.trim()==="display"?"displaystyle":"textstyle")}du(_,I,V,e)}}else{let _=E;if((d=e.texClassDisplayPattern)!=null&&d.test(_.className)){du(_,(m=_.textContent)!=null?m:"","displaystyle",e);continue}if((p=e.texClassInlinePattern)!=null&&p.test(_.className)){du(_,(f=_.textContent)!=null?f:"","textstyle",e);continue}((v=(y=e.processClassPattern)==null?void 0:y.test(_.className))!=null&&v||!((k=(b=e.skipTags)==null?void 0:b.includes(C))!=null&&k||(A=(S=e.ignoreClassPattern)==null?void 0:S.test(_.className))!=null&&A))&&rf(_,e)}}}var Uy={skipTags:["math-field","noscript","style","textarea","pre","code","annotation","annotation-xml"],processScriptType:"math/tex",processMathJSONScriptType:"math/json",ignoreClass:"^(tex2jax_ignore|ML__latex)$",processClass:"tex2jax_process",renderAccessibleContent:"mathml",asciiMath:{delimiters:{inline:[["`","`"]]}},TeX:{processEnvironments:!0,delimiters:{inline:[["\\(","\\)"]],display:[["$$","$$"],["\\[","\\]"]]}}};function mu(t,e){var r,i,n,o,a,s,l,c;try{let u=h(h({},Uy),e);u.ignoreClassPattern=new RegExp((r=u.ignoreClass)!=null?r:""),u.processClassPattern=new RegExp((i=u.processClass)!=null?i:""),u.processScriptTypePattern=new RegExp((n=u.processScriptType)!=null?n:""),u.processMathJSONScriptTypePattern=new RegExp((o=u.processMathJSONScriptType)!=null?o:""),(s=(a=u.TeX)==null?void 0:a.className)!=null&&s.display&&(u.texClassDisplayPattern=new RegExp(u.TeX.className.display)),(c=(l=u.TeX)==null?void 0:l.className)!=null&&c.inline&&(u.texClassInlinePattern=new RegExp(u.TeX.className.inline)),hr(),Ge("core"),rf(t,u)}catch(u){u instanceof Error?console.error("renderMathInElement(): "+u.message):console.error("renderMathInElement(): Could not render math for element",t)}}function du(t,e,r,i){t.parentNode.replaceChild($o(e,r,i),t)}function Gy(t,e){let r=Fe.singleton;return r?(r.show(),Hr(),r.currentLayer=e,r.render(),r.focus(),!0):!1}function jy(){let t=window.mathVirtualKeyboard;return t.visible?t.hide({animate:!0}):t.show({animate:!0}),!1}fe({switchKeyboardLayer:Gy,toggleVirtualKeyboard:jy,hideVirtualKeyboard:()=>(window.mathVirtualKeyboard.hide({animate:!0}),!1),showVirtualKeyboard:()=>(window.mathVirtualKeyboard.show({animate:!0}),!1)},{target:"virtual-keyboard"});function At(){var t,e;return(e=globalThis[t=Symbol.for("io.cortexjs.mathlive")])!=null||(globalThis[t]={}),globalThis[Symbol.for("io.cortexjs.mathlive")]}function Jy(t){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Qs(document.body,t)):Qs(document.body,t)}function Xy(t){if(typeof t=="string"){let e=document.getElementById(t);if(e===null)throw new Error(`The element with ID "${t}" could not be found.`);return e}return t}function Qs(t,e){var n,o,a,s;if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",()=>Qs(t,e));return}let r=Xy(t);if(!r)return;let i=e!=null?e:{};(n=i.renderToMarkup)!=null||(i.renderToMarkup=pe),(o=i.renderToMathML)!=null||(i.renderToMathML=Bo),(a=i.renderToSpeakableText)!=null||(i.renderToSpeakableText=Ko),(s=i.serializeToLatex)!=null||(i.serializeToLatex=Xs),mu(r,i)}var Zy={mathlive:"0.111.1"};return df(Yy);})(); +Object.assign(exports, MathLive); Object.defineProperty(exports, '__esModule', { value: true });})); diff --git a/mathly2/store.py b/mathly2/store.py index 6bc68a5c8bdf4bda32651673957b679b5a3b3331..b5cffbe504ad099fb00787d514fca11b9d0c0b56 100644 --- a/mathly2/store.py +++ b/mathly2/store.py @@ -1,4 +1,4 @@ -"""Where classes and students are kept. Two stores with the same methods: +"""Where classes, students, roles and learning progress are kept. Two stores with the same methods: InMemoryStore (tests and local development, lost on restart) and SupabaseStore (PostgREST with the secret key).""" from __future__ import annotations @@ -7,8 +7,10 @@ import json import threading import urllib.error import urllib.parse -import urllib.request -from datetime import datetime, timezone +import uuid +from datetime import date, datetime, timezone + +from . import pooled TIMEOUT = 10 @@ -22,70 +24,383 @@ class ClassExists(ValueError): class MemberExists(ValueError): - """The email already belongs to a class.""" + """The email already belongs to this class.""" + + +class TeacherIsStudent(ValueError): + """A class's teacher cannot also be one of its students.""" def _now() -> str: return datetime.now(timezone.utc).isoformat() +# What the server keeps about one student and one skill (table m2_skill_progress). `mastered_at` is set once. +PROGRESS_FIELDS = ("current_key", "current_helped", "started_at", "mastered_at", "round_start") +PROGRESS_DEFAULTS = {"current_key": None, "current_helped": False, "started_at": None, "mastered_at": None, "round_start": None} + + +ATTEMPT_FIELDS = {"answers", "submitted_at", "timed_out", "grade"} + + +def _copy_attempt(row: dict) -> dict: + return {**row, "questions": [dict(q) for q in row["questions"]], "answers": dict(row["answers"])} + + +def _when(value): + if value is None or isinstance(value, datetime): + return value + return datetime.fromisoformat(str(value).replace("Z", "+00:00")) + + +def _attempt_row(row: dict) -> dict: + """A database row as the in-memory store gives it: real datetimes, plain lists and dicts.""" + return {**row, "started_at": _when(row["started_at"]), "due_at": _when(row["due_at"]), "submitted_at": _when(row.get("submitted_at")), + "questions": list(row.get("questions") or []), "answers": dict(row.get("answers") or {})} + + +TEST_FIELDS = {"date", "lessons", "note", "questions", "minutes"} + + +def _check_test(fields: dict) -> None: + """The limits the database enforces too: 1-40 questions, 5-180 minutes, at least one lesson.""" + if "questions" in fields and not 1 <= fields["questions"] <= 40: + raise ValueError("questions must be 1-40") + if "minutes" in fields and not 5 <= fields["minutes"] <= 180: + raise ValueError("minutes must be 5-180") + if "lessons" in fields and not fields["lessons"]: + raise ValueError("a test covers at least one lesson") + + +def _test_row(row: dict) -> dict: + """A database row as the in-memory store gives it: a real date and datetimes, a plain list.""" + day = row["date"] if isinstance(row["date"], date) else date.fromisoformat(str(row["date"])[:10]) + return {**row, "date": day, "lessons": list(row.get("lessons") or []), "created_at": _when(row["created_at"]), "removed_at": _when(row.get("removed_at"))} + + class InMemoryStore: def __init__(self) -> None: self._lock = threading.Lock() self._ids = itertools.count(1) self._classes: dict[int, dict] = {} - self._members: dict[str, dict] = {} # email -> row + self._members: dict[tuple[int, str], dict] = {} # (class_id, email) -> row + self._roles: dict[tuple[str, str], dict] = {} # (email, role) -> row + self._progress: dict[tuple[str, str], dict] = {} # (user_id, skill_id) -> row + self._answers: list[dict] = [] + self._comets: dict[str, dict[str, str]] = {} # user_id -> {comet_id: caught_at} + self._attempts: dict[str, dict] = {} # attempt id -> row + self._reward: dict[str, dict] = {} # user_id -> {last_comet_day, last_catch_day} + self._tests: dict[int, dict] = {} # test id -> row + + # --- classes --- - def create_class(self, teacher_email: str, name: str) -> dict: + def _students(self, class_id: int) -> int: + return sum(1 for (c, _) in self._members if c == class_id) + + def _row(self, row: dict) -> dict: + return {**row, "lessons": list(row["lessons"]), "students": self._students(row["id"])} + + def _taken(self, name: str, except_id: int | None = None) -> bool: + return any(c["name"].lower() == name.lower() and c["id"] != except_id for c in self._classes.values()) + + def create_class(self, created_by: str, name: str, *, lessons=(), teacher_email: str | None = None, + ai_enabled: bool = False, ai_daily_checks: int = 150) -> dict: with self._lock: - if any(c["teacher_email"] == teacher_email and c["name"].lower() == name.lower() for c in self._classes.values()): + if self._taken(name): raise ClassExists(name) - row = {"id": next(self._ids), "name": name, "teacher_email": teacher_email, "created_at": _now()} + row = {"id": next(self._ids), "name": name, "created_by": created_by, "teacher_email": teacher_email, + "lessons": list(lessons), "ai_enabled": ai_enabled, "ai_daily_checks": ai_daily_checks, + "created_at": _now()} self._classes[row["id"]] = row - return dict(row) + return self._row(row) - def classes_of(self, teacher_email: str) -> list[dict]: + def update_class(self, class_id: int, **fields) -> dict: + unknown = set(fields) - {"name", "lessons", "teacher_email", "ai_enabled", "ai_daily_checks"} + if unknown: + raise ValueError(f"unknown class fields {sorted(unknown)}") with self._lock: - rows = [c for c in self._classes.values() if c["teacher_email"] == teacher_email] - return [{**c, "students": sum(1 for m in self._members.values() if m["class_id"] == c["id"])} for c in rows] + row = self._classes.get(class_id) + if row is None: + raise KeyError(class_id) + if "name" in fields and self._taken(fields["name"], class_id): + raise ClassExists(fields["name"]) + teacher = fields.get("teacher_email", row["teacher_email"]) + if teacher and (class_id, teacher) in self._members: + raise TeacherIsStudent(teacher) + row.update({k: (list(v) if k == "lessons" else v) for k, v in fields.items()}) + return self._row(row) + + def delete_class(self, class_id: int) -> bool: + with self._lock: + if self._classes.pop(class_id, None) is None: + return False + for key in [k for k in self._members if k[0] == class_id]: + del self._members[key] + return True def get_class(self, class_id: int) -> dict | None: with self._lock: row = self._classes.get(class_id) - return dict(row) if row else None + return self._row(row) if row else None + + def classes(self) -> list[dict]: + with self._lock: + return [self._row(c) for c in self._classes.values()] + + def classes_taught(self, email: str) -> list[dict]: + with self._lock: + return [self._row(c) for c in self._classes.values() if c["teacher_email"] == email] + + # --- students --- def members(self, class_id: int) -> list[dict]: with self._lock: - rows = [m for m in self._members.values() if m["class_id"] == class_id] + rows = [m for (c, _), m in self._members.items() if c == class_id] return [{"email": m["email"], "user_id": m["user_id"], "added_at": m["added_at"]} - for m in sorted(rows, key=lambda m: m["added_at"])] + for m in sorted(rows, key=lambda m: (m["added_at"], m["email"]))] - def membership(self, email: str) -> dict | None: + def classes_of_student(self, email: str) -> list[dict]: with self._lock: - row = self._members.get(email) - if not row: - return None - return {**row, "class_name": self._classes[row["class_id"]]["name"]} + return [{"id": c["id"], "name": c["name"], "lessons": list(c["lessons"])} + for (cid, e), _ in self._members.items() if e == email for c in [self._classes[cid]]] def add_member(self, class_id: int, email: str) -> None: with self._lock: - if email in self._members: + if self._classes[class_id]["teacher_email"] == email: + raise TeacherIsStudent(email) + if (class_id, email) in self._members: raise MemberExists(email) - self._members[email] = {"class_id": class_id, "email": email, "user_id": None, "added_at": _now()} + user_id = next((m["user_id"] for (_, e), m in self._members.items() if e == email and m["user_id"]), None) + self._members[(class_id, email)] = {"class_id": class_id, "email": email, "user_id": user_id, "added_at": _now()} def remove_member(self, class_id: int, email: str) -> bool: with self._lock: - row = self._members.get(email) - if not row or row["class_id"] != class_id: + return self._members.pop((class_id, email), None) is not None + + def link_user(self, email: str, user_id: str) -> None: + with self._lock: + for (_, e), row in self._members.items(): + if e == email and not row["user_id"]: + row["user_id"] = user_id + + def all_students(self) -> list[dict]: + with self._lock: + found: dict[str, list[str]] = {} + for (cid, email) in self._members: + found.setdefault(email, []).append(self._classes[cid]["name"]) + return [{"email": e, "classes": sorted(names)} for e, names in sorted(found.items())] + + # --- roles (given by an admin; the settings add developers and the first admins) --- + + def roles_of(self, email: str) -> set[str]: + with self._lock: + return {role for (e, role) in self._roles if e == email} + + def give_role(self, email: str, role: str, granted_by: str) -> None: + with self._lock: + self._roles.setdefault((email, role), {"email": email, "role": role, "granted_by": granted_by, "granted_at": _now()}) + + def take_role(self, email: str, role: str, settings_admins: int = 0) -> str: + """"removed", "absent", or "last_admin" (nothing was removed): the last admin keeps the role. + `settings_admins` counts the admins named in the app's settings, who stay admins whatever the table says.""" + with self._lock: + if (email, role) not in self._roles: + return "absent" + if role == "admin": + others = sum(1 for (e, r) in self._roles if r == "admin" and e != email) + if others + settings_admins == 0: + return "last_admin" + del self._roles[(email, role)] + return "removed" + + def accounts(self) -> list[dict]: + """Every email the app knows (a role, a class entry or a class's teacher) with the roles given in the table.""" + with self._lock: + known = {e for (e, _) in self._roles} | {e for (_, e) in self._members} + known |= {c["teacher_email"] for c in self._classes.values() if c["teacher_email"]} + return [{"email": e, "roles": sorted(r for (x, r) in self._roles if x == e)} for e in sorted(known)] + + # --- skill learning --- + + def get_progress(self, user_id: str, skill_id: str) -> dict | None: + with self._lock: + row = self._progress.get((user_id, skill_id)) + return dict(row) if row else None + + def save_progress(self, user_id: str, skill_id: str, **fields) -> dict: + """Create the row if needed, then set the given fields; the others stay as they are.""" + unknown = set(fields) - set(PROGRESS_FIELDS) + if unknown: + raise ValueError(f"unknown progress fields {sorted(unknown)}") + with self._lock: + row = self._progress.setdefault((user_id, skill_id), {"user_id": user_id, "skill_id": skill_id, + **PROGRESS_DEFAULTS}) + row.update(fields) + return dict(row) + + def progress_of(self, user_id: str) -> list[dict]: + with self._lock: + return [dict(r) for (u, _), r in self._progress.items() if u == user_id] + + def add_answer(self, user_id: str, skill_id: str, question_key: str, correct: bool, counted: bool, + mistake_id: str | None, day: date) -> None: + with self._lock: + self._answers.append({"id": len(self._answers) + 1, "user_id": user_id, "skill_id": skill_id, + "question_key": question_key, "correct": correct, "counted": counted, + "mistake_id": mistake_id, "day": day}) + + def last_counted_answers(self, user_id: str, skill_id: str, n: int) -> list[dict]: + """The last `n` answers that were not given with help, oldest first.""" + with self._lock: + rows = [a for a in self._answers if a["user_id"] == user_id and a["skill_id"] == skill_id and a["counted"]] + return [{"question_key": a["question_key"], "correct": a["correct"], "day": a["day"]} for a in rows[-n:]] + + def answer_counts(self, user_id: str, skill_id: str) -> dict[str, int]: + with self._lock: + counts: dict[str, int] = {} + for a in self._answers: + if a["user_id"] == user_id and a["skill_id"] == skill_id: + counts[a["question_key"]] = counts.get(a["question_key"], 0) + 1 + return counts + + def answers_of(self, user_id: str, skill_id: str) -> list[dict]: + """All the student's answers on a skill, oldest first: question_key, correct, counted, day. One read gives what mastery, + the next question and the progress need.""" + with self._lock: + return [{k: a[k] for k in ("question_key", "correct", "counted", "day", "mistake_id")} for a in self._answers + if a["user_id"] == user_id and a["skill_id"] == skill_id] + + def recent_skills(self, user_id: str, n: int = 20) -> list[str]: + """The skills the student answered most recently, newest first, each once (helped and wrong answers count).""" + with self._lock: + found: list[str] = [] + for a in reversed(self._answers): + if a["user_id"] == user_id and a["skill_id"] not in found: + found.append(a["skill_id"]) + if len(found) == n: + break + return found + + def solved_keys(self, user_id: str, skill_id: str) -> set[str]: + """The questions of a skill the student has answered correctly at least once (with or without help).""" + with self._lock: + return {a["question_key"] for a in self._answers + if a["user_id"] == user_id and a["skill_id"] == skill_id and a["correct"]} + + # --- real tests (a teacher sets them for a class) --- + + def create_test(self, class_id: int, test_day: date, lessons: list[str], created_by: str, *, note: str = "", questions: int = 12, + minutes: int = 45, created_at: datetime | None = None) -> dict: + fields = {"lessons": list(lessons), "questions": questions, "minutes": minutes} + _check_test(fields) + with self._lock: + row = {"id": next(self._ids), "class_id": class_id, "date": test_day, **fields, "note": note, "created_by": created_by, + "created_at": created_at or datetime.now(timezone.utc), "removed_at": None} + self._tests[row["id"]] = row + return dict(row, lessons=list(row["lessons"])) + + def get_test(self, test_id: int) -> dict | None: + with self._lock: + row = self._tests.get(test_id) + return dict(row, lessons=list(row["lessons"])) if row else None + + def update_test(self, test_id: int, **fields) -> dict: + unknown = set(fields) - TEST_FIELDS + if unknown: + raise ValueError(f"unknown test fields {sorted(unknown)}") + _check_test(fields) + with self._lock: + row = self._tests.get(test_id) + if row is None or row["removed_at"]: + raise KeyError(test_id) + row.update({k: (list(v) if k == "lessons" else v) for k, v in fields.items()}) + return dict(row, lessons=list(row["lessons"])) + + def remove_test(self, test_id: int, at: datetime | None = None) -> bool: + """Soft delete: the test disappears from lists, grades already earned keep its name.""" + with self._lock: + row = self._tests.get(test_id) + if row is None or row["removed_at"]: return False - del self._members[email] + row["removed_at"] = at or datetime.now(timezone.utc) return True - def link_user(self, email: str, user_id: str) -> None: + def tests_of_classes(self, class_ids, include_removed: bool = False) -> list[dict]: + """The tests of these classes, the nearest date first.""" + wanted = set(class_ids) + with self._lock: + rows = [r for r in self._tests.values() if r["class_id"] in wanted and (include_removed or not r["removed_at"])] + return [dict(r, lessons=list(r["lessons"])) for r in sorted(rows, key=lambda r: (r["date"], r["id"]))] + + # --- timed attempts (quizzes; later exercise tests and the simulation) --- + + def create_attempt(self, user_id: str, kind: str, scope: str, started_at: datetime, due_at: datetime, questions: list[dict]) -> dict: + row = {"id": str(uuid.uuid4()), "user_id": user_id, "kind": kind, "scope": scope, "started_at": started_at, "due_at": due_at, + "submitted_at": None, "timed_out": False, "grade": None, "questions": [dict(q) for q in questions], "answers": {}} + with self._lock: + self._attempts[row["id"]] = row + return _copy_attempt(row) + + def get_attempt(self, attempt_id: str) -> dict | None: + with self._lock: + row = self._attempts.get(str(attempt_id)) + return _copy_attempt(row) if row else None + + def save_attempt(self, attempt_id: str, **fields) -> dict: + """Update `answers`, `submitted_at`, `timed_out` and/or `grade`.""" + unknown = set(fields) - ATTEMPT_FIELDS + if unknown: + raise ValueError(f"unknown attempt fields {sorted(unknown)}") + with self._lock: + row = self._attempts.get(str(attempt_id)) + if row is None: + raise KeyError(attempt_id) + row.update({k: (dict(v) if k == "answers" else v) for k, v in fields.items()}) + return _copy_attempt(row) + + def attempts_of(self, user_id: str, kind: str, scope: str | None = None) -> list[dict]: + """A student's attempts of one kind (of one scope, when given), oldest first.""" + with self._lock: + rows = [r for r in self._attempts.values() if r["user_id"] == user_id and r["kind"] == kind and (scope is None or r["scope"] == scope)] + return [_copy_attempt(r) for r in sorted(rows, key=lambda r: r["started_at"])] + + def comets_of(self, user_id: str) -> set[str]: + with self._lock: + return set(self._comets.get(user_id, {})) + + def add_comet(self, user_id: str, comet_id: str) -> None: + with self._lock: + self._comets.setdefault(user_id, {}).setdefault(comet_id, datetime.now(timezone.utc).isoformat()) + + def reward_state(self, user_id: str) -> dict | None: + with self._lock: + row = self._reward.get(user_id) + return dict(row) if row else None + + def save_reward_state(self, user_id: str, **fields) -> dict: + """Set `last_comet_day` and/or `last_catch_day`; the other field stays as it was.""" + with self._lock: + row = self._reward.setdefault(user_id, {"user_id": user_id, "last_comet_day": None, "last_catch_day": None}) + row.update(fields) + return dict(row) + + def last_answered(self, user_id: str) -> dict[str, date]: + """The day of the student's newest answer on each skill (helped and wrong answers count): what fading reads.""" + with self._lock: + days: dict[str, date] = {} + for a in self._answers: + if a["user_id"] == user_id and (a["skill_id"] not in days or a["day"] > days[a["skill_id"]]): + days[a["skill_id"]] = a["day"] + return days + + def daily_correct(self, user_id: str) -> dict[date, int]: + """Correct practice answers per day (helped answers included): the daily goal and the streak.""" with self._lock: - row = self._members.get(email) - if row and not row["user_id"]: - row["user_id"] = user_id + counts: dict[date, int] = {} + for a in self._answers: + if a["user_id"] == user_id and a["correct"]: + counts[a["day"]] = counts.get(a["day"], 0) + 1 + return counts class SupabaseStore: @@ -93,20 +408,22 @@ class SupabaseStore: self.url, self.secret = url.rstrip("/"), secret def _request(self, method: str, table: str, params: dict[str, str] | None = None, body: dict | None = None, - returning: bool = False): + returning: bool = False, upsert: bool = False): query = "&".join(f"{k}={urllib.parse.quote(v, safe='(),.*:')}" for k, v in (params or {}).items()) headers = {"apikey": self.secret, "Authorization": f"Bearer {self.secret}", "User-Agent": "mathly2/1.0", "Content-Type": "application/json"} + prefer = [] + if upsert: + prefer.append("resolution=merge-duplicates") if returning: - headers["Prefer"] = "return=representation" + prefer.append("return=representation") + if prefer: + headers["Prefer"] = ",".join(prefer) data = json.dumps(body).encode() if body is not None else None - request = urllib.request.Request(f"{self.url}/rest/v1/{table}" + (f"?{query}" if query else ""), - data=data, method=method, headers=headers) try: - with urllib.request.urlopen(request, timeout=TIMEOUT) as response: - raw = response.read() + _, raw = pooled.request(method, f"{self.url}/rest/v1/{table}" + (f"?{query}" if query else ""), headers, data, TIMEOUT) except urllib.error.HTTPError as exc: - if exc.code == 409: + if exc.code in (400, 409): # a conflict, or one of the database's own refusals (see _why) raise raise StoreUnavailable(f"supabase answered {exc.code} for {method} {table}") from exc except (urllib.error.URLError, TimeoutError) as exc: @@ -117,40 +434,88 @@ class SupabaseStore: def _eq(value) -> str: return f"eq.{value}" - def create_class(self, teacher_email: str, name: str) -> dict: + @staticmethod + def _why(exc: urllib.error.HTTPError) -> str: + """The database's own message for a refusal, or empty if it sent none. The body can be read only once, so it is kept.""" + if not hasattr(exc, "_mathly_why"): + try: + exc._mathly_why = str(json.loads(exc.read() or b"{}").get("message", "")) + except (ValueError, AttributeError, OSError): + exc._mathly_why = "" + return exc._mathly_why + + def _refused(self, exc: urllib.error.HTTPError, conflict: Exception) -> Exception: + """A 409 is the conflict the caller expects (a name or an entry that already exists). Anything else the database refused + (a missing column because a migration was not applied, bad data) is a failure to report, not a name clash.""" + if exc.code == 409: + return conflict + return StoreUnavailable(f"supabase refused ({exc.code}): {self._why(exc) or exc.reason}") + + _CLASS = "id,name,created_by,teacher_email,lessons,ai_enabled,ai_daily_checks,created_at" + + def _class_row(self, row: dict) -> dict: + count = (row.get("m2_class_members") or [{"count": 0}])[0]["count"] + return {**{k: row[k] for k in self._CLASS.split(",")}, "students": count} + + # --- classes --- + + def create_class(self, created_by: str, name: str, *, lessons=(), teacher_email: str | None = None, + ai_enabled: bool = False, ai_daily_checks: int = 150) -> dict: + body = {"created_by": created_by, "name": name, "lessons": list(lessons), "teacher_email": teacher_email, + "ai_enabled": ai_enabled, "ai_daily_checks": ai_daily_checks} try: - rows = self._request("POST", "m2_classes", body={"teacher_email": teacher_email, "name": name}, returning=True) + rows = self._request("POST", "m2_classes", body=body, returning=True) except urllib.error.HTTPError as exc: - raise ClassExists(name) from exc - return rows[0] + raise self._refused(exc, ClassExists(name)) from exc + return {**rows[0], "students": 0} + + def update_class(self, class_id: int, **fields) -> dict: + unknown = set(fields) - {"name", "lessons", "teacher_email", "ai_enabled", "ai_daily_checks"} + if unknown: + raise ValueError(f"unknown class fields {sorted(unknown)}") + try: + rows = self._request("PATCH", "m2_classes", {"id": self._eq(class_id)}, fields, returning=True) + except urllib.error.HTTPError as exc: + if "teacher_is_student" in self._why(exc): + raise TeacherIsStudent(str(fields.get("teacher_email"))) from exc + raise self._refused(exc, ClassExists(str(fields.get("name")))) from exc + if not rows: + raise KeyError(class_id) + return self.get_class(class_id) - def classes_of(self, teacher_email: str) -> list[dict]: - rows = self._request("GET", "m2_classes", {"teacher_email": self._eq(teacher_email), - "select": "id,name,teacher_email,created_at,m2_class_members(count)", "order": "created_at"}) - return [{**{k: r[k] for k in ("id", "name", "teacher_email", "created_at")}, - "students": (r.get("m2_class_members") or [{"count": 0}])[0]["count"]} for r in rows] + def delete_class(self, class_id: int) -> bool: + return bool(self._request("DELETE", "m2_classes", {"id": self._eq(class_id)}, returning=True)) def get_class(self, class_id: int) -> dict | None: - rows = self._request("GET", "m2_classes", {"id": self._eq(class_id), "select": "id,name,teacher_email,created_at"}) - return rows[0] if rows else None + rows = self._request("GET", "m2_classes", {"id": self._eq(class_id), "select": f"{self._CLASS},m2_class_members(count)"}) + return self._class_row(rows[0]) if rows else None + + def classes(self) -> list[dict]: + rows = self._request("GET", "m2_classes", {"select": f"{self._CLASS},m2_class_members(count)", "order": "id"}) + return [self._class_row(r) for r in rows] + + def classes_taught(self, email: str) -> list[dict]: + rows = self._request("GET", "m2_classes", {"teacher_email": self._eq(email), + "select": f"{self._CLASS},m2_class_members(count)", "order": "id"}) + return [self._class_row(r) for r in rows] + + # --- students --- def members(self, class_id: int) -> list[dict]: return self._request("GET", "m2_class_members", {"class_id": self._eq(class_id), - "select": "email,user_id,added_at", "order": "added_at"}) + "select": "email,user_id,added_at", "order": "added_at,email"}) - def membership(self, email: str) -> dict | None: - rows = self._request("GET", "m2_class_members", {"email": self._eq(email), - "select": "class_id,email,user_id,added_at,m2_classes(name)"}) - if not rows: - return None - row = rows[0] - return {**{k: row[k] for k in ("class_id", "email", "user_id", "added_at")}, "class_name": row["m2_classes"]["name"]} + def classes_of_student(self, email: str) -> list[dict]: + rows = self._request("GET", "m2_class_members", {"email": self._eq(email), "select": "m2_classes(id,name,lessons)"}) + return [r["m2_classes"] for r in rows] def add_member(self, class_id: int, email: str) -> None: try: self._request("POST", "m2_class_members", body={"class_id": class_id, "email": email}) except urllib.error.HTTPError as exc: - raise MemberExists(email) from exc + if "teacher_is_student" in self._why(exc): + raise TeacherIsStudent(email) from exc + raise self._refused(exc, MemberExists(email)) from exc def remove_member(self, class_id: int, email: str) -> bool: rows = self._request("DELETE", "m2_class_members", {"class_id": self._eq(class_id), "email": self._eq(email)}, @@ -159,3 +524,194 @@ class SupabaseStore: def link_user(self, email: str, user_id: str) -> None: self._request("PATCH", "m2_class_members", {"email": self._eq(email), "user_id": "is.null"}, {"user_id": user_id}) + + def all_students(self) -> list[dict]: + rows = self._request("GET", "m2_class_members", {"select": "email,m2_classes(name)", "order": "email"}) + found: dict[str, list[str]] = {} + for r in rows: + found.setdefault(r["email"], []).append(r["m2_classes"]["name"]) + return [{"email": e, "classes": sorted(names)} for e, names in found.items()] + + # --- roles --- + + def roles_of(self, email: str) -> set[str]: + return {r["role"] for r in self._request("GET", "m2_roles", {"email": self._eq(email), "select": "role"})} + + def give_role(self, email: str, role: str, granted_by: str) -> None: + self._request("POST", "m2_roles", {"on_conflict": "email,role"}, + {"email": email, "role": role, "granted_by": granted_by}, upsert=True) + + def take_role(self, email: str, role: str, settings_admins: int = 0) -> str: + """One call in the database counts the admins and deletes together (function m2_take_role), so two admins + removing each other at once cannot leave none.""" + return self._request("POST", "rpc/m2_take_role", body={"p_email": email, "p_role": role, "p_settings_admins": settings_admins}) + + def accounts(self) -> list[dict]: + roles: dict[str, list[str]] = {} + for r in self._request("GET", "m2_roles", {"select": "email,role", "order": "email"}): + roles.setdefault(r["email"], []).append(r["role"]) + known = set(roles) + known |= {r["email"] for r in self._request("GET", "m2_class_members", {"select": "email"})} + known |= {r["teacher_email"] for r in self._request("GET", "m2_classes", {"select": "teacher_email", "teacher_email": "not.is.null"})} + return [{"email": e, "roles": sorted(roles.get(e, []))} for e in sorted(known)] + + # --- skill learning --- + + def get_progress(self, user_id: str, skill_id: str) -> dict | None: + rows = self._request("GET", "m2_skill_progress", {"user_id": self._eq(user_id), "skill_id": self._eq(skill_id), + "select": "*"}) + return rows[0] if rows else None + + def save_progress(self, user_id: str, skill_id: str, **fields) -> dict: + unknown = set(fields) - set(PROGRESS_FIELDS) + if unknown: + raise ValueError(f"unknown progress fields {sorted(unknown)}") + # merge-duplicates updates only the columns sent, so the other fields stay as they are + rows = self._request("POST", "m2_skill_progress", {"on_conflict": "user_id,skill_id"}, + {"user_id": user_id, "skill_id": skill_id, **fields}, returning=True, upsert=True) + return rows[0] + + def progress_of(self, user_id: str) -> list[dict]: + return self._request("GET", "m2_skill_progress", {"user_id": self._eq(user_id), "select": "*"}) + + def add_answer(self, user_id: str, skill_id: str, question_key: str, correct: bool, counted: bool, + mistake_id: str | None, day: date) -> None: + self._request("POST", "m2_answers", body={"user_id": user_id, "skill_id": skill_id, "question_key": question_key, + "correct": correct, "counted": counted, "mistake_id": mistake_id, + "day": day.isoformat()}) + + def last_counted_answers(self, user_id: str, skill_id: str, n: int) -> list[dict]: + rows = self._request("GET", "m2_answers", {"user_id": self._eq(user_id), "skill_id": self._eq(skill_id), + "counted": "eq.true", "select": "question_key,correct,day", "order": "id.desc", + "limit": str(n)}) + return [{**r, "day": date.fromisoformat(r["day"])} for r in reversed(rows)] + + def answer_counts(self, user_id: str, skill_id: str) -> dict[str, int]: + rows = self._request("GET", "m2_answers", {"user_id": self._eq(user_id), "skill_id": self._eq(skill_id), + "select": "question_key"}) + counts: dict[str, int] = {} + for r in rows: + counts[r["question_key"]] = counts.get(r["question_key"], 0) + 1 + return counts + + # --- real tests --- + + def create_test(self, class_id: int, test_day: date, lessons: list[str], created_by: str, *, note: str = "", questions: int = 12, + minutes: int = 45, created_at: datetime | None = None) -> dict: + fields = {"lessons": list(lessons), "questions": questions, "minutes": minutes} + _check_test(fields) + body = {"class_id": class_id, "date": test_day.isoformat(), **fields, "note": note, "created_by": created_by} + if created_at: + body["created_at"] = created_at.isoformat() + return _test_row(self._request("POST", "m2_tests", body=body, returning=True)[0]) + + def get_test(self, test_id: int) -> dict | None: + rows = self._request("GET", "m2_tests", {"id": self._eq(test_id), "select": "*"}) + return _test_row(rows[0]) if rows else None + + def update_test(self, test_id: int, **fields) -> dict: + unknown = set(fields) - TEST_FIELDS + if unknown: + raise ValueError(f"unknown test fields {sorted(unknown)}") + _check_test(fields) + body = {k: (v.isoformat() if isinstance(v, date) else v) for k, v in fields.items()} + rows = self._request("PATCH", "m2_tests", {"id": self._eq(test_id), "removed_at": "is.null"}, body, returning=True) + if not rows: + raise KeyError(test_id) + return _test_row(rows[0]) + + def remove_test(self, test_id: int, at: datetime | None = None) -> bool: + stamp = (at or datetime.now(timezone.utc)).isoformat() + return bool(self._request("PATCH", "m2_tests", {"id": self._eq(test_id), "removed_at": "is.null"}, {"removed_at": stamp}, returning=True)) + + def tests_of_classes(self, class_ids, include_removed: bool = False) -> list[dict]: + ids = sorted(set(class_ids)) + if not ids: + return [] + params = {"class_id": f"in.({','.join(str(i) for i in ids)})", "select": "*", "order": "date,id"} + if not include_removed: + params["removed_at"] = "is.null" + return [_test_row(r) for r in self._request("GET", "m2_tests", params)] + + # --- timed attempts --- + + def create_attempt(self, user_id: str, kind: str, scope: str, started_at: datetime, due_at: datetime, questions: list[dict]) -> dict: + rows = self._request("POST", "m2_attempts", body={"user_id": user_id, "kind": kind, "scope": scope, "started_at": started_at.isoformat(), + "due_at": due_at.isoformat(), "questions": questions}, returning=True) + return _attempt_row(rows[0]) + + def get_attempt(self, attempt_id: str) -> dict | None: + try: + rows = self._request("GET", "m2_attempts", {"id": self._eq(attempt_id), "select": "*"}) + except urllib.error.HTTPError as exc: + if exc.code == 400: # not a valid id + return None + raise + return _attempt_row(rows[0]) if rows else None + + def save_attempt(self, attempt_id: str, **fields) -> dict: + unknown = set(fields) - ATTEMPT_FIELDS + if unknown: + raise ValueError(f"unknown attempt fields {sorted(unknown)}") + body = {k: (v.isoformat() if isinstance(v, datetime) else v) for k, v in fields.items()} + rows = self._request("PATCH", "m2_attempts", {"id": self._eq(attempt_id)}, body, returning=True) + if not rows: + raise KeyError(attempt_id) + return _attempt_row(rows[0]) + + def attempts_of(self, user_id: str, kind: str, scope: str | None = None) -> list[dict]: + params = {"user_id": self._eq(user_id), "kind": self._eq(kind), "select": "*", "order": "started_at"} + if scope is not None: + params["scope"] = self._eq(scope) + return [_attempt_row(r) for r in self._request("GET", "m2_attempts", params)] + + def comets_of(self, user_id: str) -> set[str]: + rows = self._request("GET", "m2_comets", {"user_id": self._eq(user_id), "select": "comet_id"}) + return {r["comet_id"] for r in rows} + + def add_comet(self, user_id: str, comet_id: str) -> None: + self._request("POST", "m2_comets", {"on_conflict": "user_id,comet_id"}, {"user_id": user_id, "comet_id": comet_id}, upsert=True) + + def reward_state(self, user_id: str) -> dict | None: + rows = self._request("GET", "m2_reward_state", {"user_id": self._eq(user_id), "select": "*"}) + if not rows: + return None + return self.reward_state_row(rows[0]) + + def save_reward_state(self, user_id: str, **fields) -> dict: + body = {k: v.isoformat() if isinstance(v, date) else v for k, v in fields.items()} + rows = self._request("POST", "m2_reward_state", {"on_conflict": "user_id"}, {"user_id": user_id, **body}, returning=True, upsert=True) + return self.reward_state_row(rows[0]) + + @staticmethod + def reward_state_row(row: dict) -> dict: + return {**row, **{k: date.fromisoformat(row[k]) if row.get(k) else None for k in ("last_comet_day", "last_catch_day")}} + + def last_answered(self, user_id: str) -> dict[str, date]: + rows = self._request("GET", "m2_last_answered", {"user_id": self._eq(user_id), "select": "skill_id,day"}) + return {r["skill_id"]: date.fromisoformat(r["day"]) for r in rows} + + def daily_correct(self, user_id: str) -> dict[date, int]: + rows = self._request("GET", "m2_daily_correct", {"user_id": self._eq(user_id), "select": "day,correct"}) + return {date.fromisoformat(r["day"]): r["correct"] for r in rows} + + def answers_of(self, user_id: str, skill_id: str) -> list[dict]: + rows = self._request("GET", "m2_answers", {"user_id": self._eq(user_id), "skill_id": self._eq(skill_id), + "select": "question_key,correct,counted,day,mistake_id", "order": "id"}) + return [{**r, "day": date.fromisoformat(r["day"])} for r in rows] + + def recent_skills(self, user_id: str, n: int = 20) -> list[str]: + rows = self._request("GET", "m2_answers", {"user_id": self._eq(user_id), "select": "skill_id", "order": "id.desc", + "limit": str(max(200, n * 20))}) + found: list[str] = [] + for r in rows: + if r["skill_id"] not in found: + found.append(r["skill_id"]) + if len(found) == n: + break + return found + + def solved_keys(self, user_id: str, skill_id: str) -> set[str]: + rows = self._request("GET", "m2_answers", {"user_id": self._eq(user_id), "skill_id": self._eq(skill_id), + "correct": "eq.true", "select": "question_key"}) + return {r["question_key"] for r in rows} diff --git a/mathly2/supabase/migrations/20261107120000_m2_skill_learning.sql b/mathly2/supabase/migrations/20261107120000_m2_skill_learning.sql new file mode 100644 index 0000000000000000000000000000000000000000..d5557313c9f09819f15ead6c3dd3f26b45f40fbb --- /dev/null +++ b/mathly2/supabase/migrations/20261107120000_m2_skill_learning.sql @@ -0,0 +1,49 @@ +-- Mathly 2: skill learning. Additive (new objects only). Read and written only by the server with the secret key: +-- row-level security is on, there are no policies, and the browser roles get no grants (as in m2_classes). +-- Rollback: drop view m2_daily_correct; drop table m2_skill_progress, m2_answers; +begin; + +-- One row per practice answer. Append-only: it is the evidence for mastery and for later weak-skill picks. +-- `day` is the Israel calendar day decided by the server when it stored the answer; `counted` is false when the +-- student opened help for that question (such an answer is skipped by the mastery rule). +create table public.m2_answers ( + id bigint generated always as identity primary key, + user_id uuid not null, + skill_id text not null check (char_length(skill_id) between 1 and 80), + question_key text not null check (char_length(question_key) between 1 and 120), + correct boolean not null, + counted boolean not null default true, + mistake_id text, + day date not null, + answered_at timestamptz not null default now() +); +create index m2_answers_user_skill on public.m2_answers (user_id, skill_id, id); + +-- What the server must remember between requests about one student and one skill. +-- `mastered_at` is set once, when the mastery rule is first met, and never cleared. +create table public.m2_skill_progress ( + user_id uuid not null, + skill_id text not null check (char_length(skill_id) between 1 and 80), + stage text not null default 'example' check (stage in ('example', 'faded', 'practice')), + faded_done integer not null default 0 check (faded_done between 0 and 2), + current_key text, + current_helped boolean not null default false, + started_at timestamptz, + mastered_at timestamptz, + primary key (user_id, skill_id) +); +create index m2_skill_progress_user on public.m2_skill_progress (user_id); + +-- Correct practice answers per student and day: the daily goal and the streak. Helped answers count (effort). +create view public.m2_daily_correct as + select user_id, day, count(*)::integer as correct + from public.m2_answers + where correct + group by user_id, day; + +alter table public.m2_answers enable row level security; +alter table public.m2_skill_progress enable row level security; +revoke all on public.m2_answers, public.m2_skill_progress, public.m2_daily_correct from public, anon, authenticated; +grant all on public.m2_answers, public.m2_skill_progress, public.m2_daily_correct to service_role; +grant usage, select on sequence public.m2_answers_id_seq to service_role; +commit; diff --git a/mathly2/supabase/migrations/20261107130000_m2_roles_and_classes.sql b/mathly2/supabase/migrations/20261107130000_m2_roles_and_classes.sql new file mode 100644 index 0000000000000000000000000000000000000000..44f062184677bcfba2b78c2ee931592886c57eaa --- /dev/null +++ b/mathly2/supabase/migrations/20261107130000_m2_roles_and_classes.sql @@ -0,0 +1,75 @@ +-- Mathly 2: roles given by an admin, and classes made by a manager. Only m2_ objects change (mathly1's tables are never touched). +-- Rollback: drop function m2_take_role; drop table m2_roles; drop the two triggers and their functions; then restore the old +-- class key and the per-teacher name index (see the statements below, reversed) and drop the added m2_classes columns. +begin; + +-- Roles belong to an email (so they can be given before a first sign-in). The developer role comes only from the app's settings. +create table public.m2_roles ( + email text not null check (email = lower(email) and char_length(email) between 3 and 254), + role text not null check (role in ('student', 'teacher', 'manager', 'admin')), + granted_by text, + granted_at timestamptz not null default now(), + primary key (email, role) +); + +-- Classes: a manager creates them. teacher_email used to mean "who created it"; now it is the class's teacher (optional). +alter table public.m2_classes add column created_by text; +update public.m2_classes set created_by = teacher_email; +alter table public.m2_classes alter column teacher_email drop not null; +alter table public.m2_classes add column lessons text[] not null default '{}'; +alter table public.m2_classes add column ai_enabled boolean not null default false; +alter table public.m2_classes add column ai_daily_checks integer not null default 150 check (ai_daily_checks between 0 and 10000); +drop index public.m2_classes_teacher_name; +create unique index m2_classes_name on public.m2_classes (lower(name)); + +-- A student may be in several classes: the key is (class, email). +alter table public.m2_class_members drop constraint m2_class_members_pkey; +alter table public.m2_class_members add primary key (class_id, email); +create index m2_class_members_email on public.m2_class_members (email); + +-- A class's teacher is never also one of its students, whichever side is changed. +create function public.m2_teacher_is_not_student() returns trigger language plpgsql as $$ +begin + if tg_table_name = 'm2_class_members' then + if exists (select 1 from public.m2_classes where id = new.class_id and teacher_email = new.email) then + raise exception 'teacher_is_student' using errcode = '23514'; + end if; + else + if new.teacher_email is not null and exists (select 1 from public.m2_class_members where class_id = new.id and email = new.teacher_email) then + raise exception 'teacher_is_student' using errcode = '23514'; + end if; + end if; + return new; +end $$; +create trigger m2_members_teacher_check before insert or update on public.m2_class_members + for each row execute function public.m2_teacher_is_not_student(); +create trigger m2_classes_teacher_check before insert or update of teacher_email on public.m2_classes + for each row execute function public.m2_teacher_is_not_student(); + +-- Taking a role away. For 'admin' it counts the other admins and deletes in one step, so two admins removing each other at the +-- same moment cannot leave none. p_settings_admins is how many admins the app's settings name (they stay admins regardless). +-- Returns 'removed', 'absent' or 'last_admin' (nothing deleted). +create function public.m2_take_role(p_email text, p_role text, p_settings_admins integer default 0) returns text +language plpgsql as $$ +declare others integer; +begin + perform pg_advisory_xact_lock(hashtext('m2_roles_admin')); + if not exists (select 1 from public.m2_roles where email = p_email and role = p_role) then + return 'absent'; + end if; + if p_role = 'admin' then + select count(*) into others from public.m2_roles where role = 'admin' and email <> p_email; + if others + coalesce(p_settings_admins, 0) = 0 then + return 'last_admin'; + end if; + end if; + delete from public.m2_roles where email = p_email and role = p_role; + return 'removed'; +end $$; + +alter table public.m2_roles enable row level security; +revoke all on public.m2_roles from public, anon, authenticated; +grant all on public.m2_roles to service_role; +revoke all on function public.m2_take_role(text, text, integer) from public, anon, authenticated; +grant execute on function public.m2_take_role(text, text, integer) to service_role; +commit; diff --git a/mathly2/supabase/migrations/20261108090000_m2_progress_without_stages.sql b/mathly2/supabase/migrations/20261108090000_m2_progress_without_stages.sql new file mode 100644 index 0000000000000000000000000000000000000000..f80ef37e599530562e44bba4b842fc9db4f87f68 --- /dev/null +++ b/mathly2/supabase/migrations/20261108090000_m2_progress_without_stages.sql @@ -0,0 +1,9 @@ +-- Mathly 2: a skill no longer has teaching stages (worked and faded examples were dropped from the plan), so the progress table +-- loses the two columns that remembered them. Only an m2_ table changes. The data that matters (the question on screen, help, when +-- the skill was started and mastered) is untouched. +-- Rollback: alter table public.m2_skill_progress add column stage text not null default 'example' check (stage in ('example', 'faded', 'practice')), +-- add column faded_done integer not null default 0 check (faded_done between 0 and 2); +begin; +alter table public.m2_skill_progress drop column stage; +alter table public.m2_skill_progress drop column faded_done; +commit; diff --git a/mathly2/supabase/migrations/20261109090000_m2_rewards.sql b/mathly2/supabase/migrations/20261109090000_m2_rewards.sql new file mode 100644 index 0000000000000000000000000000000000000000..4c66e794110ee437d4470144a6e22a5f6b492876 --- /dev/null +++ b/mathly2/supabase/migrations/20261109090000_m2_rewards.sql @@ -0,0 +1,31 @@ +-- Mathly 2: rewards. Additive (new objects only). Read and written only by the server with the secret key: +-- row-level security is on, there are no policies, and the browser roles get no grants (as in m2_classes). +-- Rollback: drop view m2_last_answered; drop table m2_comets, m2_reward_state; +begin; + +-- The newest answer day per student and skill (helped and wrong answers count): fading stars read it. +create view public.m2_last_answered as + select user_id, skill_id, max(day) as day + from public.m2_answers + group by user_id, skill_id; + +-- The comets a student caught. +create table public.m2_comets ( + user_id uuid not null, + comet_id text not null, + caught_at timestamptz not null default now(), + primary key (user_id, comet_id) +); + +-- The day a comet last crossed for the student, and the day one was last caught (one catch per crossing). +create table public.m2_reward_state ( + user_id uuid primary key, + last_comet_day date, + last_catch_day date +); + +alter table public.m2_comets enable row level security; +alter table public.m2_reward_state enable row level security; +revoke all on public.m2_last_answered, public.m2_comets, public.m2_reward_state from public, anon, authenticated; +grant all on public.m2_last_answered, public.m2_comets, public.m2_reward_state to service_role; +commit; diff --git a/mathly2/supabase/migrations/20261110090000_m2_attempts.sql b/mathly2/supabase/migrations/20261110090000_m2_attempts.sql new file mode 100644 index 0000000000000000000000000000000000000000..a5b5b47a9740fe74a3e4bcf3225c79946a316a25 --- /dev/null +++ b/mathly2/supabase/migrations/20261110090000_m2_attempts.sql @@ -0,0 +1,29 @@ +-- Mathly 2: timed, graded attempts (lesson quizzes now; exercise tests and the simulation later). Additive (new objects only). +-- Read and written only by the server with the secret key: row-level security is on, there are no policies, and the browser roles +-- get no grants (as in m2_classes). +-- Rollback: drop table m2_attempts; +begin; + +-- One timed try. `questions` is the ordered list of bank references [{skill_id, key}], `answers` maps the question key (which starts with its skill id) to the chosen +-- choice position. An attempt with submitted_at null is open; the server settles it (grades it, sets timed_out) on the first read +-- after due_at. `grade` is a whole number 0-100, stored when the attempt is settled. +create table public.m2_attempts ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null, + kind text not null check (kind in ('quiz', 'exercise_test', 'simulation')), + scope text not null, + started_at timestamptz not null default now(), + due_at timestamptz not null, + submitted_at timestamptz, + timed_out boolean not null default false, + grade integer check (grade between 0 and 100), + questions jsonb not null default '[]'::jsonb, + answers jsonb not null default '{}'::jsonb, + check (due_at > started_at) +); +create index m2_attempts_user_kind_scope on public.m2_attempts (user_id, kind, scope); + +alter table public.m2_attempts enable row level security; +revoke all on public.m2_attempts from public, anon, authenticated; +grant all on public.m2_attempts to service_role; +commit; diff --git a/mathly2/supabase/migrations/20261111090000_m2_tests.sql b/mathly2/supabase/migrations/20261111090000_m2_tests.sql new file mode 100644 index 0000000000000000000000000000000000000000..ffa2e5fb915c34a0425d244becd175ed68b3723e --- /dev/null +++ b/mathly2/supabase/migrations/20261111090000_m2_tests.sql @@ -0,0 +1,27 @@ +-- Mathly 2: real tests a teacher sets for a class. Additive (new objects only). Read and written only by the server with the secret key: +-- row-level security is on, there are no policies, and the browser roles get no grants (as in m2_classes). +-- The two exercise tests and the simulation of a test are not rows: they exist because the test exists, and their tries are +-- m2_attempts rows (kind exercise_test / simulation, scope ":1", ":2" or ""). +-- Rollback: drop table m2_tests; +begin; + +create table public.m2_tests ( + id bigint generated always as identity primary key, + class_id bigint not null references public.m2_classes(id) on delete cascade, + date date not null, -- the test day (Israel calendar) + lessons text[] not null default '{}', + note text not null default '', + questions integer not null default 12 check (questions between 1 and 40), + minutes integer not null default 45 check (minutes between 5 and 180), + created_by text not null, + created_at timestamptz not null default now(), + removed_at timestamptz, -- soft delete: grades already earned keep their test's name + check (cardinality(lessons) > 0) +); +create index m2_tests_class on public.m2_tests (class_id) where removed_at is null; + +alter table public.m2_tests enable row level security; +revoke all on public.m2_tests from public, anon, authenticated; +grant all on public.m2_tests to service_role; +grant usage, select on sequence public.m2_tests_id_seq to service_role; +commit; diff --git a/mathly2/supabase/migrations/20261111100000_m2_rounds.sql b/mathly2/supabase/migrations/20261111100000_m2_rounds.sql new file mode 100644 index 0000000000000000000000000000000000000000..2f5954fbf374ab3626ec6baf2e7950d977200c90 --- /dev/null +++ b/mathly2/supabase/migrations/20261111100000_m2_rounds.sql @@ -0,0 +1,7 @@ +-- Mathly 2: practice is a round of a skill's questions, each shown once. The server must remember where the current round began. +-- `round_start` is how many answers the student had on the skill when the round began; the round is the answers after that. +-- It is null for a student who practised before this change: their earlier answers all count as past rounds. +-- Additive (one new column on an m2_ table). Rollback: alter table public.m2_skill_progress drop column round_start; +begin; +alter table public.m2_skill_progress add column round_start integer check (round_start is null or round_start >= 0); +commit; diff --git a/mathly2/tests/conftest.py b/mathly2/tests/conftest.py index 9f2a4d50fc6d7dcd46ed182c9a12026960218ccc..732e3bc98b1932f3d3ac2f4c088c6f693b1e4a47 100644 --- a/mathly2/tests/conftest.py +++ b/mathly2/tests/conftest.py @@ -1,5 +1,6 @@ """Tests run without Supabase regardless of the developer's local environment.""" import os -for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS"): +for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS", "DEVELOPER_EMAILS", + "ADMIN_EMAILS", "ANTHROPIC_API_KEY", "MATH_MODEL"): os.environ[name] = "" diff --git a/mathly2/tests/serve.py b/mathly2/tests/serve.py index 4cfe13831159f0a5df474c9b3a521fffa9ae2496..cd3eb9810d9369fbef98f4d832bfdb2a02b0c5dc 100644 --- a/mathly2/tests/serve.py +++ b/mathly2/tests/serve.py @@ -26,3 +26,9 @@ def running(app): finally: server.should_exit = True thread.join(timeout=5) + + +def offline_formulas(page): + """For tests that show no formulas: do not wait for the formula library from the network (a slow CDN made them time out).""" + page.route("**/mathjax@*/**", lambda route: route.abort()) + return page diff --git a/mathly2/tests/test_access.py b/mathly2/tests/test_access.py new file mode 100644 index 0000000000000000000000000000000000000000..594ccdcbde25f79b74912b0b9a83cdb67f9126a6 --- /dev/null +++ b/mathly2/tests/test_access.py @@ -0,0 +1,60 @@ +import pytest +from fastapi import Depends, FastAPI +from fastapi.testclient import TestClient + +from mathly2.access import GRANTABLE, PERMISSIONS, ROLES, allowed, need, permissions_of + +KNOWN = set().union(*PERMISSIONS.values()) - {"*"} + + +def test_there_are_five_roles_and_developer_is_never_grantable(): + assert ROLES == ("student", "teacher", "manager", "admin", "developer") + assert "developer" not in GRANTABLE and set(GRANTABLE) < set(ROLES) + + +@pytest.mark.parametrize("role,yes,no", [ + ("student", {"path.use"}, {"class.teach", "class.roster", "classes.manage", "students.list", "roles.manage"}), + ("teacher", {"path.use", "class.teach", "class.roster"}, {"classes.manage", "students.list", "roles.manage"}), + ("manager", {"classes.manage", "class.roster", "students.list"}, {"path.use", "class.teach", "roles.manage"}), + ("admin", {"roles.manage"}, {"path.use", "class.teach", "class.roster", "classes.manage", "students.list"}), +]) +def test_each_role_has_only_its_permissions(role, yes, no): + for permission in yes: + assert allowed([role], permission), (role, permission) + for permission in no: + assert not allowed([role], permission), (role, permission) + + +def test_developer_has_every_permission_even_ones_not_invented_yet(): + assert all(allowed(["developer"], p) for p in KNOWN | {"something.new"}) + + +def test_several_roles_add_up(): + assert permissions_of(["manager", "teacher"]) >= {"classes.manage", "class.teach", "path.use"} + assert not allowed([], "path.use") and permissions_of(["nonsense"]) == frozenset() + + +def test_manager_and_admin_see_no_learning_data(): + # learning data is the student's path and a teacher's view of their own classes: neither role has them + for role in ("manager", "admin"): + assert not allowed([role], "path.use") and not allowed([role], "class.teach") + + +def test_need_refuses_a_missing_permission_with_403_and_a_missing_sign_in_with_401(): + from mathly2.auth import DevAuthenticator + app = FastAPI() + app.state.authenticator = DevAuthenticator() + + class Roles: + def resolve(self, email, source=None): + return {"boss@x.test": frozenset({"manager"})}.get(email, frozenset({"student"})) + app.state.roles = Roles() + + @app.get("/manage") + def manage(user: dict = Depends(need("classes.manage"))): + return {"ok": user["email"]} + + client = TestClient(app) + assert client.get("/manage").status_code == 401 + assert client.get("/manage", headers={"Authorization": "Bearer dev:kid@x.test"}).status_code == 403 + assert client.get("/manage", headers={"Authorization": "Bearer dev:boss@x.test"}).json() == {"ok": "boss@x.test"} diff --git a/mathly2/tests/test_accounts.py b/mathly2/tests/test_accounts.py new file mode 100644 index 0000000000000000000000000000000000000000..e9903dea7cbb88b19c743394450499564f202835 --- /dev/null +++ b/mathly2/tests/test_accounts.py @@ -0,0 +1,81 @@ +import pytest +from fastapi.testclient import TestClient + +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore + +ADMIN, OTHER_ADMIN, HEAD = "admin@school.test", "admin2@school.test", "head@school.test" + + +def auth(email): + return {"Authorization": f"Bearer dev:{email}"} + + +def build(admins=frozenset()): + store = InMemoryStore() + store.give_role(ADMIN, "admin", "setup") + return TestClient(create_app(Settings(admins=admins, developers=frozenset({"dev@school.test"}), teachers=frozenset({"t@school.test"})), store=store)), store + + +@pytest.fixture +def client(): + return build()[0] + + +def test_only_an_admin_or_a_developer_reaches_the_accounts(client): + assert client.get("/api/accounts").status_code == 401 + for who in ("kid@school.test", "t@school.test"): + assert client.get("/api/accounts", headers=auth(who)).status_code == 403 + assert client.post("/api/accounts/x@school.test/roles/manager", headers=auth(who)).status_code == 403 + assert client.get("/api/accounts", headers=auth(ADMIN)).status_code == 200 + assert client.get("/api/accounts", headers=auth("dev@school.test")).status_code == 200 + + +def test_a_role_given_before_the_first_sign_in_applies_at_it(client): + assert client.post("/api/accounts/Rina@School.test/roles/manager", headers=auth(ADMIN)).status_code == 204 + assert client.get("/api/me", headers=auth("rina@school.test")).json()["roles"] == ["manager"] + assert client.post("/api/classes", json={"name": "ט'3", "lessons": ["t"]}, headers=auth("rina@school.test")).status_code == 201 + + +def test_the_accounts_list_shows_given_roles_and_roles_from_the_settings(): + client, store = build(admins=frozenset({HEAD})) + client.post("/api/accounts/new@school.test/roles/teacher", headers=auth(HEAD)) + listed = {a["email"]: a for a in client.get("/api/accounts", headers=auth(HEAD)).json()} + assert listed["new@school.test"]["roles"] == ["teacher"] and listed["new@school.test"]["from_settings"] == [] + assert listed[HEAD]["from_settings"] == ["admin"] and listed["dev@school.test"]["from_settings"] == ["developer"] + assert listed["t@school.test"]["from_settings"] == ["teacher"] and listed[ADMIN]["roles"] == ["admin"] + + +def test_an_admin_takes_a_role_away_and_it_stops_applying(client): + client.post("/api/accounts/rina@school.test/roles/manager", headers=auth(ADMIN)) + assert client.get("/api/me", headers=auth("rina@school.test")).json()["roles"] == ["manager"] + assert client.delete("/api/accounts/rina@school.test/roles/manager", headers=auth(ADMIN)).status_code == 204 + assert client.get("/api/me", headers=auth("rina@school.test")).json()["roles"] == ["student"] + assert client.delete("/api/accounts/rina@school.test/roles/manager", headers=auth(ADMIN)).status_code == 404 + + +def test_the_developer_role_cannot_be_given_and_bad_input_is_refused(client): + assert client.post("/api/accounts/x@school.test/roles/developer", headers=auth(ADMIN)).status_code == 422 + assert client.post("/api/accounts/x@school.test/roles/boss", headers=auth(ADMIN)).status_code == 422 + assert client.post("/api/accounts/not-an-email/roles/manager", headers=auth(ADMIN)).status_code == 422 + assert client.delete("/api/accounts/x@school.test/roles/developer", headers=auth(ADMIN)).status_code == 422 + + +def test_the_last_admin_cannot_remove_their_own_admin_role(client): + refused = client.delete(f"/api/accounts/{ADMIN}/roles/admin", headers=auth(ADMIN)) + assert refused.status_code == 409 and "האחרון" in refused.json()["detail"] + assert client.get("/api/me", headers=auth(ADMIN)).json()["roles"] == ["admin"] + + +def test_one_of_two_admins_can_step_down(client): + client.post(f"/api/accounts/{OTHER_ADMIN}/roles/admin", headers=auth(ADMIN)) + assert client.delete(f"/api/accounts/{ADMIN}/roles/admin", headers=auth(ADMIN)).status_code == 204 + assert client.get("/api/me", headers=auth(ADMIN)).json()["roles"] == ["student"] + assert client.delete(f"/api/accounts/{OTHER_ADMIN}/roles/admin", headers=auth(OTHER_ADMIN)).status_code == 409 + + +def test_an_admin_from_the_settings_lets_the_table_admin_step_down(): + client, _ = build(admins=frozenset({HEAD})) + assert client.delete(f"/api/accounts/{ADMIN}/roles/admin", headers=auth(HEAD)).status_code == 204 + assert client.get("/api/me", headers=auth(HEAD)).json()["roles"] == ["admin"] diff --git a/mathly2/tests/test_attempts.py b/mathly2/tests/test_attempts.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2e09d2fff782aab6390e9c41b086756d8aba46 --- /dev/null +++ b/mathly2/tests/test_attempts.py @@ -0,0 +1,118 @@ +"""The attempt engine (add-lesson-quizzes 1.2): grades, settling, and what a result reveals.""" +import copy +import json +from datetime import datetime, timedelta, timezone + +import pytest + +from mathly2 import attempts +from mathly2.bank import Bank, load_bank, question_key +from mathly2.store import InMemoryStore + +U = "11111111-1111-1111-1111-111111111111" +T0 = datetime(2026, 11, 10, 9, 0, tzinfo=timezone.utc) +DUE = T0 + timedelta(minutes=15) + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +def refs(bank, n=4): + """n questions from the first skills that have enough: [{skill_id, key}].""" + out = [] + for skill in bank.skills: + for q in skill.get("questions", [])[:2]: + out.append({"skill_id": skill["id"], "key": question_key(skill["id"], q)}) + return out[:n] + + +def choose(bank, ref, right=True): + question = bank._questions[ref["skill_id"]][ref["key"]] + picks = [i for i, c in enumerate(question["choices"]) if bool(c.get("correct")) == right] + if not right: + picks = [i for i in picks if question["choices"][i].get("mistake")] or picks + return picks[0] + + +def make(bank, n=4, **answers): + store = InMemoryStore() + questions = refs(bank, n) + row = store.create_attempt(U, "quiz", "t", T0, DUE, questions) + return store, row, questions + + +def test_the_grade_is_the_rounded_share_of_right_answers(): + assert attempts.percent(7, 10) == 70 and attempts.percent(8, 12) == 67 and attempts.percent(0, 10) == 0 and attempts.percent(10, 10) == 100 + assert attempts.percent(1, 8) == 13 and attempts.percent(1, 3) == 33 and attempts.percent(2, 3) == 67 and attempts.percent(0, 0) == 0 + + +def test_an_unanswered_or_unknown_answer_counts_as_wrong(bank): + store, row, questions = make(bank, 4) + answers = {questions[0]["key"]: choose(bank, questions[0]), questions[1]["key"]: 99, questions[2]["key"]: "x"} + assert attempts.grade(bank, questions, answers) == (25, 1) + assert attempts.grade(bank, questions, {}) == (0, 0) + + +def test_settling_grades_from_the_answers_saved_and_marks_timed_out(bank): + store, row, questions = make(bank, 4) + store.save_attempt(row["id"], answers={q["key"]: choose(bank, q) for q in questions[:3]}) + before = attempts.settle(store, bank, store.get_attempt(row["id"]), DUE - timedelta(seconds=1)) + assert before["submitted_at"] is None and before["grade"] is None # not overdue: untouched + settled = attempts.settle(store, bank, store.get_attempt(row["id"]), DUE + timedelta(minutes=20)) + assert settled["grade"] == 75 and settled["timed_out"] is True and settled["submitted_at"] == DUE + again = attempts.settle(store, bank, settled, DUE + timedelta(hours=5)) + assert again == settled == store.get_attempt(row["id"]) # settling twice changes nothing + + +def test_submitting_before_the_deadline_grades_at_once_and_is_idempotent(bank): + store, row, questions = make(bank, 4) + store.save_attempt(row["id"], answers={q["key"]: choose(bank, q) for q in questions[:2]}) + done = attempts.submit(store, bank, store.get_attempt(row["id"]), T0 + timedelta(minutes=5)) + assert done["grade"] == 50 and done["timed_out"] is False and done["submitted_at"] == T0 + timedelta(minutes=5) + store.save_attempt(row["id"], answers={q["key"]: choose(bank, q) for q in questions}) # even if answers changed afterwards... + assert attempts.submit(store, bank, store.get_attempt(row["id"]), T0 + timedelta(minutes=6))["grade"] == 50 # ...the grade stands + + +def test_submitting_after_the_deadline_is_a_timeout(bank): + store, row, questions = make(bank, 4) + done = attempts.submit(store, bank, row, DUE + timedelta(minutes=1)) + assert done["timed_out"] is True and done["grade"] == 0 + + +def test_the_result_lists_lost_skills_and_mistakes_but_never_the_right_answer(bank): + store, row, questions = make(bank, 4) + answers = {questions[0]["key"]: choose(bank, questions[0]), # right + questions[1]["key"]: choose(bank, questions[1], right=False), # wrong, with a named mistake + questions[2]["key"]: choose(bank, questions[2], right=False)} # wrong; the fourth is not answered + store.save_attempt(row["id"], answers=answers) + done = attempts.submit(store, bank, store.get_attempt(row["id"]), T0 + timedelta(minutes=3)) + out = attempts.result(bank, done) + assert out["grade"] == 25 and out["right"] == 1 and out["total"] == 4 and len(out["missed"]) == 3 + assert {s["id"] for s in out["lost_skills"]} == {q["skill_id"] for q in questions[1:]} + assert sum(s["missed"] for s in out["lost_skills"]) == 3 + unanswered = out["missed"][-1] + assert unanswered["picked"] is None and unanswered["mistake"] is None + wrong = out["missed"][0] + assert wrong["picked"] and wrong["question"] and wrong["skill_name"] + blob = json.dumps(out, ensure_ascii=False) + assert '"correct"' not in blob + for ref in questions[1:]: # no right choice's text appears + question = bank._questions[ref["skill_id"]][ref["key"]] + right_text = next(c["text"] for c in question["choices"] if c.get("correct")) + picked_texts = {m["picked"] for m in out["missed"]} + assert right_text not in picked_texts or right_text == wrong["picked"] + + +def test_a_question_the_bank_no_longer_has_is_skipped_in_the_result(bank): + store, row, questions = make(bank, 3) + data = copy.deepcopy(bank.data) + gone = questions[0] + for s in data["skills"]: + if s["id"] == gone["skill_id"]: + s["questions"] = [q for q in s["questions"] if question_key(s["id"], q) != gone["key"]] + smaller = Bank(data) + done = attempts.submit(store, smaller, store.get_attempt(row["id"]), T0 + timedelta(minutes=1)) + out = attempts.result(smaller, done) + assert out["total"] == 3 and len(out["missed"]) == 2 # the vanished question is not listed diff --git a/mathly2/tests/test_auth.py b/mathly2/tests/test_auth.py index 5418aabf2976162bd03018da93b088b45a71af8e..4e10599829cf411ec267186e5712fbc9a8644a71 100644 --- a/mathly2/tests/test_auth.py +++ b/mathly2/tests/test_auth.py @@ -28,13 +28,27 @@ def test_no_token_is_refused(client): assert client.get("/api/me", headers={"Authorization": "Bearer dev:not-an-email"}).status_code == 401 +def me(client, email): + return client.get("/api/me", headers=sign(email)).json() + + def test_a_listed_teacher_is_a_teacher(client): - assert client.get("/api/me", headers=sign(TEACHER)).json() == {"email": TEACHER, "role": "teacher", "class": None} - assert client.get("/api/me", headers=sign("Teacher@School.test")).json()["role"] == "teacher" # case does not matter + body = me(client, TEACHER) + assert body["email"] == TEACHER and body["roles"] == ["teacher"] and body["classes"] == [] and body["teaching"] == [] + assert "class.teach" in body["permissions"] and "classes.manage" not in body["permissions"] + assert me(client, "Teacher@School.test")["roles"] == ["teacher"] # case does not matter def test_everyone_else_is_a_student(client): - assert client.get("/api/me", headers=sign("kid@school.test")).json() == {"email": "kid@school.test", "role": "student", "class": None} + body = me(client, "kid@school.test") + assert body["roles"] == ["student"] and body["permissions"] == ["path.use"] and body["classes"] == [] + + +def test_developers_and_first_admins_come_from_the_settings(): + app = create_app(Settings(developers=frozenset({"dev@school.test"}), admins=frozenset({"head@school.test"}))) + client = TestClient(app) + assert me(client, "dev@school.test")["roles"] == ["developer"] and me(client, "dev@school.test")["permissions"] == ["*"] + assert me(client, "head@school.test")["roles"] == ["admin"] and me(client, "head@school.test")["permissions"] == ["roles.manage"] def test_page_carries_only_public_settings(): @@ -55,20 +69,16 @@ def test_dev_sign_in_is_off_when_supabase_is_on(): assert TestClient(app).get("/api/me", headers=sign("kid@school.test")).status_code in (401, 503) -class Reply(io.BytesIO): - def __enter__(self): return self - def __exit__(self, *a): return False - - def supabase_returns(monkeypatch, payload=None, error=None): + """Stand in for the HTTP call to Supabase's /auth/v1/user: the calls made are returned as (url, headers).""" calls = [] - def fake(request, timeout=0): - calls.append(request) + def fake(method, url, headers=None, body=None, timeout=0): + calls.append((url, headers or {})) if error: raise error - return Reply(json.dumps(payload).encode()) - monkeypatch.setattr(auth.urllib.request, "urlopen", fake) + return 200, json.dumps(payload).encode() + monkeypatch.setattr(auth.pooled, "request", fake) return calls @@ -77,7 +87,7 @@ def test_supabase_user_is_checked_with_the_token_and_cached(monkeypatch): a = SupabaseAuthenticator("https://p.test", "pub") assert a.user("tok") == {"id": "u1", "email": "kid@school.test"} assert a.user("tok")["id"] == "u1" - assert len(calls) == 1 and calls[0].headers["Authorization"] == "Bearer tok" + assert len(calls) == 1 and calls[0][1]["Authorization"] == "Bearer tok" and calls[0][0].endswith("/auth/v1/user") def test_an_unconfirmed_email_is_not_trusted(monkeypatch): diff --git a/mathly2/tests/test_bank.py b/mathly2/tests/test_bank.py index 55fb64e5ae8e64c62530462fc57d55f04ca341b2..5b40fc2af59842ca87b7ae8c63fdd72f6ab1a91b 100644 --- a/mathly2/tests/test_bank.py +++ b/mathly2/tests/test_bank.py @@ -74,3 +74,152 @@ def test_broken_bank_stops_loading(tmp_path, raw): path.write_text(json.dumps(raw), encoding="utf-8") with pytest.raises(BankError, match="unknown lesson"): load_bank(path) + + +# --- question keys (task 1.1) --- + +from mathly2.bank import question_key + + +def test_real_bank_has_a_distinct_key_for_every_question(): + bank = load_bank() + keys = [k for s in bank.skills for k in bank.question_keys(s["id"])] + assert len(keys) == 1050 and len(set(keys)) == 1050 + + +def test_question_key_is_stable_and_changes_with_the_content(raw): + question = raw["skills"][0]["questions"][0] + sid = raw["skills"][0]["id"] + assert question_key(sid, question) == question_key(sid, copy.deepcopy(question)) + edited = copy.deepcopy(question) + edited["question"] += " " + assert question_key(sid, edited) != question_key(sid, question) + + +def test_keys_survive_reordering_questions(raw): + data = copy.deepcopy(raw) + before = set(load_bank().question_keys(data["skills"][0]["id"])) + data["skills"][0]["questions"].reverse() + assert set(Bank(data).question_keys(data["skills"][0]["id"])) == before + + +def test_a_duplicated_question_in_a_skill_is_rejected(raw): + def change(d): + d["skills"][0]["questions"].append(copy.deepcopy(d["skills"][0]["questions"][0])) + assert any("identical to an earlier question" in p for p in broken(raw, change)) + + +# --- the solved example for the help button (add-learning-core 1.1) --- + +def _good_example(): + return {"question": "$x² + 5x + 6$", "answer": "$(x + 2)(x + 3)$", + "steps": [{"do": "מוצאים 2 ו־3", "why": "כי המכפלה 6 והסכום 5"}, {"do": "כותבים $(x + 2)(x + 3)$", "why": "כך מפרקים טרינום"}]} + + +def _with_example(raw, example): + data = copy.deepcopy(raw) + data["skills"][0]["worked_example"] = example + return data + + +def test_a_valid_solved_example_passes(raw): + assert check_bank(_with_example(raw, _good_example())) == [] + + +def test_the_real_bank_without_solved_examples_still_loads(): + load_bank() + + +def test_a_solved_example_needs_a_question_steps_and_an_answer(raw): + for broken_example in ({**_good_example(), "question": ""}, {**_good_example(), "steps": []}, {**_good_example(), "answer": ""}): + assert any("needs a question, steps and an answer" in p for p in check_bank(_with_example(raw, broken_example))) + + +def test_every_step_needs_what_is_done_and_why_as_text(raw): + example = _good_example() + example["steps"][0].pop("do") + assert any("step 1: no 'do'" in p for p in check_bank(_with_example(raw, example))) + example = _good_example() + example["steps"][1]["why"] = "" + assert any("step 2: 'why' must be text" in p for p in check_bank(_with_example(raw, example))) + example = _good_example() + example["steps"][0]["why"] = [{"text": "a", "correct": True}, {"text": "b"}] # the earlier plan's multiple choice + assert any("step 1: 'why' must be text" in p for p in check_bank(_with_example(raw, example))) + + +def test_faded_examples_from_the_earlier_plan_are_not_read_or_refused(raw): + data = _with_example(raw, _good_example()) + data["skills"][0]["faded_examples"] = [{"anything": 1}] + assert check_bank(data) == [] + + +# --- serving practice questions (task 1.3) --- + +from mathly2.bank import Bank + + +def _skill_with_figure(bank): + return next(s for s in bank.skills if any("figure" in q for q in s.get("questions", []))) + + +def test_a_served_question_never_carries_the_answer(): + bank = load_bank() + for skill in bank.skills: + for key in bank.question_keys(skill["id"]): + text = json.dumps(bank.practice_question(skill["id"], key), ensure_ascii=False) + assert '"correct"' not in text and '"mistake"' not in text + + +def test_served_choices_keep_their_bank_position(): + bank = load_bank() + skill = bank.skills[0] + key = bank.question_keys(skill["id"])[0] + served = bank.practice_question(skill["id"], key) + original = skill["questions"][0]["choices"] + assert [c["index"] for c in served["choices"]] == list(range(len(original))) + assert [c["text"] for c in served["choices"]] == [c["text"] for c in original] + + +def test_figures_and_graphs_are_served_with_the_question(): + bank = load_bank() + skill = _skill_with_figure(bank) + for key in bank.question_keys(skill["id"]): + question = next(q for q in skill["questions"] if question_key(skill["id"], q) == key) + served = bank.practice_question(skill["id"], key) + assert ("figure" in served) == ("figure" in question) + + +def test_grading_a_right_and_a_wrong_choice(): + bank = load_bank() + skill = bank.skills[0] + question = skill["questions"][0] + key = question_key(skill["id"], question) + right = next(i for i, c in enumerate(question["choices"]) if c.get("correct")) + wrong = next(i for i, c in enumerate(question["choices"]) if c.get("mistake")) + assert bank.grade(skill["id"], key, right) == {"correct": True, "mistake": None} + result = bank.grade(skill["id"], key, wrong) + assert result["correct"] is False + mistake = result["mistake"] + assert mistake["id"] == question["choices"][wrong]["mistake"] + assert mistake["name"] and mistake["tip"] + assert set(result) == {"correct", "mistake"} # no index or text of the right choice + assert set(mistake) == {"id", "name", "tip", "back"} + + +def test_grading_an_unknown_question_or_choice_gives_none(): + bank = load_bank() + sid = bank.skills[0]["id"] + key = bank.question_keys(sid)[0] + assert bank.grade(sid, "nope", 0) is None + assert bank.grade(sid, key, 99) is None + assert bank.grade(sid, key, -1) is None + assert bank.grade(sid, key, "0") is None + + +def test_mistake_back_is_none_when_the_bank_has_none(): + bank = load_bank() + without = next(m for m, v in bank.mistakes.items() if not v.get("back")) + with_back = next(m for m, v in bank.mistakes.items() if v.get("back")) + assert bank.mistake(without)["back"] is None + assert bank.mistake(with_back)["back"] == bank.mistakes[with_back]["back"] + assert bank.mistake(None) is None diff --git a/mathly2/tests/test_board_browser.py b/mathly2/tests/test_board_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..a0efb8eae57f90fdec305fb5b6d34db8daba33d3 --- /dev/null +++ b/mathly2/tests/test_board_browser.py @@ -0,0 +1,235 @@ +"""The smart board (copied from mathly1) in a real browser: its layout, tools, drawing, sketches and calculator. +The board is hosted in a small sheet built here, the same contract the exercise screen follows: +.mx-layer > .mx-sheet with a [data-board-toggle] button, and MathlyBoard.mount(layer, key, {question}).""" +import hashlib +import re +from pathlib import Path + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.main import create_app +from mathly2.tests.serve import offline_formulas, running + +STATIC = Path(__file__).parent.parent / "static" +COPIED = { + "math-board.js": "cd47807ae894e4298b5e3d7175e9ef12fd474f0035712d7fa40a2559edfa607f", + "board-math.js": "613e642f762a9ca8276c2192bf43d0a8cf7a606bf06f29f01b54b3a19747a579",} +PHONE, DESKTOP = {"width": 390, "height": 844}, {"width": 1280, "height": 800} +TOOLS = {"move": "הזזה", "pen": "עט", "line": "קו ישר", "circle": "עיגול", "angle": "זווית", "math": "נוסחה", "eraser": "מחק"} +HOST = """async (key) => { + const layer = document.createElement('div'); layer.className = 'mx-layer'; layer.id = 'host'; + layer.innerHTML = '
    '; + document.body.append(layer); + window.mountFor = (k, id) => MathlyBoard.mount(layer, k, { question: () => layer.querySelector('#' + id) }); + layer.querySelector('[data-board-toggle]').addEventListener('click', () => MathlyBoard.toggle()); + window.mountFor(key, 'q1'); +}""" + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def board_page(browser, url, viewport, scheme="light", requests=None): + page = offline_formulas(browser.new_page(viewport=viewport, color_scheme=scheme)) + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.on("console", lambda m: errors.append(m.text) if m.type == "error" and "mathjax" not in m.text.lower() and "ERR_FAILED" not in m.text else None) + if requests is not None: + page.on("request", lambda r: requests.append(r.url)) + page.goto(url) + page.wait_for_selector("#signin") + page.add_style_tag(url="/static/board.css") + page.add_script_tag(url="/static/board-math.js") + page.add_script_tag(url="/static/math-board.js") + page.evaluate(HOST, "skill:q1") + page.errors = errors + return page + + +def png(page): + return page.evaluate("document.querySelector('.mx-board canvas').toDataURL()") + + +def draw_line(page, dx=120, dy=60): + box = page.locator(".mx-board canvas").bounding_box() + x, y = box["x"] + 60, box["y"] + 120 + page.mouse.move(x, y) + page.mouse.down() + page.mouse.move(x + dx / 2, y + dy / 2, steps=5) + page.mouse.move(x + dx, y + dy, steps=5) + page.mouse.up() + + +# --- 3.1 the copied files --- + +def test_the_board_files_are_the_unedited_copies_from_mathly1(): + for name, digest in COPIED.items(): + assert hashlib.sha256((STATIC / name).read_bytes()).hexdigest() == digest, f"{name} was edited: copy it from mathly1 again" + assert (STATIC / "vendor" / "mathlive" / "mathlive.min.js").stat().st_size > 100_000 + + +@pytest.mark.parametrize("scheme", ["light", "dark"]) +def test_the_board_loads_and_opens_in_light_and_dark_with_no_error(browser, scheme): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP, scheme) + assert page.evaluate("Object.keys(window.MathlyBoard).sort()") == ["button", "closeFull", "desk", "isOn", "mount", "openFull", "show", "toggle"] + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board") + assert page.is_visible(".mx-board") and page.is_visible(".mx-board-bar") + background = page.evaluate("getComputedStyle(document.querySelector('.mx-board')).backgroundColor") + assert background not in ("", "rgba(0, 0, 0, 0)") + assert page.errors == [] + + +# --- 3.2 the board's behaviour --- + +def test_on_a_phone_the_board_covers_the_screen_and_closes_back_to_the_question(browser): + with running(create_app()) as url: + page = board_page(browser, url, PHONE) + assert page.evaluate("MathlyBoard.desk()") is False and page.locator(".mx-board").count() == 0 + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board.full") + box = page.locator(".mx-board").bounding_box() + assert box["width"] >= PHONE["width"] - 2 and box["height"] >= PHONE["height"] - 2 + assert page.get_attribute(".mx-board", "role") == "dialog" + page.click(".mx-board .mx-board-back") + page.wait_for_function("document.querySelector('.mx-board') === null") + assert page.is_visible("#q1") # the same question is still there + + +def test_on_a_desktop_the_board_sits_beside_the_sheet(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + assert page.evaluate("MathlyBoard.desk()") is True + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board") + board, sheet = page.locator(".mx-board").bounding_box(), page.locator(".mx-sheet").bounding_box() + assert board["x"] + board["width"] <= sheet["x"] + 2 # the board ends where the sheet starts + assert page.evaluate("document.querySelector('.mx-sheet').classList.contains('with-board')") + assert page.get_attribute(".mx-sheet", "aria-modal") is None # the board is outside the dialog: still reachable + page.click(".mx-board .mx-board-close") + page.wait_for_function("document.querySelector('.mx-board') === null") + assert page.get_attribute("[data-board-toggle]", "aria-pressed") == "false" + + +def test_every_tool_has_a_hebrew_label_and_an_icon(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board") + for tool, name in TOOLS.items(): + button = page.locator(f".mx-board [data-tool='{tool}']") + assert button.get_attribute("title") == name and button.locator("svg").count() == 1 + for action, name in {"calc": "מחשבון", "question": "השאלה", "undo": "ביטול", "clear": "ניקוי"}.items(): + assert name in page.inner_text(f".mx-board [data-do='{action}']") or page.get_attribute(f".mx-board [data-do='{action}']", "title") + assert page.get_attribute(".mx-board .mx-board-close", "aria-label") == "סגירת הלוח" + assert page.locator(".mx-board [data-ink]").count() == 3 # three ink colours + + +def test_a_pen_stroke_changes_the_canvas_and_undo_brings_it_back(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board canvas") + blank = png(page) + draw_line(page) + drawn = png(page) + assert drawn != blank + page.click(".mx-board [data-do='undo']") + assert png(page) == blank + draw_line(page) + page.click(".mx-board [data-do='clear']") + assert png(page) == blank + + +def test_the_eraser_removes_a_stroke_it_touches(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board canvas") + blank = png(page) + draw_line(page) + assert png(page) != blank + page.click(".mx-board [data-tool='eraser']") + box = page.locator(".mx-board canvas").bounding_box() + x, y = box["x"] + 60, box["y"] + 120 + page.mouse.move(x - 10, y - 10) + page.mouse.down() + page.mouse.move(x + 60, y + 30, steps=12) + page.mouse.move(x + 130, y + 70, steps=12) + page.mouse.up() + page.click(".mx-board [data-tool='pen']") + assert png(page) == blank # the stroke is gone + + +def test_the_questions_copy_stays_when_the_eraser_passes_over_it(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board canvas") + blank = png(page) + page.click(".mx-board [data-do='question']") + page.wait_for_function("(b) => document.querySelector('.mx-board canvas').toDataURL() !== b", arg=blank) + page.click(".mx-board [data-tool='pen']") # a new copy is selected; changing tool lets go of it + copied = png(page) + assert copied != blank + page.click(".mx-board [data-tool='eraser']") + box = page.locator(".mx-board canvas").bounding_box() + page.mouse.move(box["x"] + 10, box["y"] + 20) + page.mouse.down() + page.mouse.move(box["x"] + box["width"] - 10, box["y"] + 20, steps=10) + page.mouse.move(box["x"] + box["width"] - 10, box["y"] + 80, steps=10) + page.mouse.up() + page.click(".mx-board [data-tool='pen']") # the eraser's own cursor ring is not a mark + assert png(page) == copied # the eraser leaves the copy alone + + +def test_each_question_keeps_its_own_sketch_and_nothing_is_sent_anywhere(browser): + with running(create_app()) as url: + requests = [] + page = board_page(browser, url, DESKTOP, requests=requests) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board canvas") + blank = png(page) + draw_line(page) + first = png(page) + sent_before = len([r for r in requests if "/api/" in r]) + page.evaluate("window.mountFor('skill:q2', 'q2')") + page.wait_for_selector(".mx-board canvas") + assert png(page) == blank # question 2 starts empty + page.evaluate("window.mountFor('skill:q1', 'q1')") + page.wait_for_selector(".mx-board canvas") + assert png(page) == first # question 1's sketch is still there + assert len([r for r in requests if "/api/" in r]) == sent_before # the board sent nothing to the server + + +# --- 3.3 the calculator --- + +def calc_press(page, *labels): + """Press calculator keys by the label printed on them (each key holds its label in a ).""" + for label in labels: + page.locator(".mx-calc-keys button").filter(has=page.locator("b", has_text=re.compile(f"^{re.escape(label)}$"))).first.click() + + +def test_the_calculator_gives_sin_30_and_7_times_6(browser): + with running(create_app()) as url: + page = board_page(browser, url, DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board") + assert page.is_hidden(".mx-calc") + page.click(".mx-board [data-do='calc']") + page.wait_for_selector(".mx-calc", state="visible") + calc_press(page, "sin", "3", "0", ")", "=") + assert page.inner_text("[data-calc-out]").strip() == "0.5" # degrees + calc_press(page, "AC", "7", "×", "6", "=") + assert page.inner_text("[data-calc-out]").strip() == "42" + page.click(".mx-board [data-do='calc']") + assert page.is_hidden(".mx-calc") diff --git a/mathly2/tests/test_classes.py b/mathly2/tests/test_classes.py index 2fb2b0c19f2d5ca4efbd52d9ed0af3c5f70e1b41..478ecd201252daa59b03e74aa69df6403ef4dda7 100644 --- a/mathly2/tests/test_classes.py +++ b/mathly2/tests/test_classes.py @@ -4,21 +4,29 @@ from fastapi.testclient import TestClient from mathly2.classes import parse_emails from mathly2.config import Settings from mathly2.main import create_app +from mathly2.store import InMemoryStore -T1, T2 = "t1@school.test", "t2@school.test" +MGR, T1, T2, DEV = "mgr@school.test", "t1@school.test", "t2@school.test", "dev@school.test" + + +def auth(email): + return {"Authorization": f"Bearer dev:{email}"} @pytest.fixture -def client(): - return TestClient(create_app(Settings(teachers=frozenset({T1, T2})))) +def world(): + store = InMemoryStore() + store.give_role(MGR, "manager", "setup") + client = TestClient(create_app(Settings(teachers=frozenset({T1, T2}), developers=frozenset({DEV})), store=store)) + return client, store -def auth(email): - return {"Authorization": f"Bearer dev:{email}"} +def body(name="ט'3", **kw): + return {"name": name, "lessons": kw.pop("lessons", ["t", "t2"]), **kw} -def make_class(client, teacher=T1, name="ט'3"): - return client.post("/api/classes", json={"name": name}, headers=auth(teacher)) +def make(client, who=MGR, **kw): + return client.post("/api/classes", json=body(**kw), headers=auth(who)) def test_parse_emails_handles_pasted_lists(): @@ -26,63 +34,224 @@ def test_parse_emails_handles_pasted_lists(): assert valid == ["a@x.test", "b@x.test", "c@x.test"] and invalid == ["not-an-email"] -def test_teacher_creates_and_lists_classes(client): - created = make_class(client) - assert created.status_code == 201 and created.json()["name"] == "ט'3" - assert client.get("/api/classes", headers=auth(T1)).json() == [{"id": created.json()["id"], "name": "ט'3", "students": 0}] - assert client.get("/api/classes", headers=auth(T2)).json() == [] +# ---- the manager makes classes (spec: Manager creates classes) + +def test_a_manager_creates_a_class_with_lessons_teacher_and_students(world): + client, _ = world + created = make(client, teacher_email=T1, students="s1@school.test\ns2@school.test not-an-email") + assert created.status_code == 201 + row = created.json() + assert row["name"] == "ט'3" and row["lessons"] == ["t", "t2"] and row["teacher_email"] == T1 + assert row["ai_enabled"] is False and row["ai_daily_checks"] == 150 + assert row["students"] == 2 and row["student_emails"] == ["s1@school.test", "s2@school.test"] and row["invalid"] == ["not-an-email"] + assert [c["name"] for c in client.get("/api/classes", headers=auth(MGR)).json()] == ["ט'3"] + + +def test_a_developer_can_manage_classes_too(world): + client, _ = world + assert make(client, who=DEV).status_code == 201 + + +def test_a_teacher_a_student_and_a_stranger_cannot_create_classes(world): + client, _ = world + assert make(client, who=T1).status_code == 403 + assert make(client, who="kid@school.test").status_code == 403 + assert client.post("/api/classes", json=body()).status_code == 401 + assert client.get("/api/classes", headers=auth(T1)).status_code == 403 + + +def test_class_name_is_trimmed_checked_and_unique_ignoring_case(world): + client, _ = world + assert make(client, name=" ח' 1 ").json()["name"] == "ח' 1" + assert make(client, name="ח' 1").status_code == 409 + assert make(client, name=" ").status_code == 422 + assert make(client, name="x" * 81).status_code == 422 + assert make(client, name="x" * 80).status_code == 201 + + +def test_a_class_needs_at_least_one_known_lesson(world): + client, _ = world + assert make(client, lessons=[]).status_code == 422 + assert make(client, lessons=["nope"]).status_code == 422 + assert make(client, lessons=["t", "nope"]).status_code == 422 + assert make(client, name="B", lessons=["t", "t"]).json()["lessons"] == ["t"] # repeats collapse + + +def test_the_teacher_must_be_an_email_and_not_also_a_student(world): + client, _ = world + assert make(client, teacher_email="not-an-email").status_code == 422 + clash = make(client, teacher_email=T1, students=f"s@school.test {T1}") + assert clash.status_code == 422 and "תלמיד" in clash.json()["detail"] + assert client.get("/api/classes", headers=auth(MGR)).json() == [] # nothing was saved + + +def test_the_ai_budget_is_limited(world): + client, _ = world + assert make(client, ai_daily_checks=-1).status_code == 422 + assert make(client, name="B", ai_daily_checks=10001).status_code == 422 + assert make(client, name="C", ai_daily_checks=40, ai_enabled=True).json()["ai_enabled"] is True + + +def test_the_manager_can_list_the_lessons_to_choose_from(world): + client, _ = world + lessons = client.get("/api/classes/lessons", headers=auth(MGR)).json() + assert len(lessons) == 24 and set(lessons[0]) == {"id", "name", "skills"} and lessons[0]["skills"] > 0 + assert client.get("/api/classes/lessons", headers=auth(T1)).status_code == 403 + +# ---- editing and deleting (spec: Editing and deleting a class) -def test_class_name_is_trimmed_checked_and_unique(client): - assert make_class(client, name=" ח' 1 ").json()["name"] == "ח' 1" - assert make_class(client, name="ח' 1").status_code == 409 - assert make_class(client, name=" ").status_code == 422 - assert make_class(client, name="x" * 61).status_code == 422 +def test_a_manager_edits_everything_and_the_roster_follows(world): + client, store = world + cid = make(client, teacher_email=T1, students="a@school.test b@school.test").json()["id"] + edited = client.put(f"/api/classes/{cid}", json=body("ט'4", lessons=["k"], teacher_email=T2, students="b@school.test c@school.test", + ai_enabled=True, ai_daily_checks=60), headers=auth(MGR)).json() + assert (edited["name"], edited["lessons"], edited["teacher_email"], edited["ai_enabled"], edited["ai_daily_checks"]) == ("ט'4", ["k"], T2, True, 60) + assert edited["student_emails"] == ["b@school.test", "c@school.test"] -def test_students_cannot_use_class_endpoints(client): - kid = auth("kid@school.test") - assert client.get("/api/classes", headers=kid).status_code == 403 - assert client.post("/api/classes", json={"name": "A"}, headers=kid).status_code == 403 - assert client.get("/api/classes").status_code == 401 +def test_leaving_the_students_out_of_an_edit_keeps_the_roster(world): + client, _ = world + cid = make(client, students="a@school.test").json()["id"] + kept = client.put(f"/api/classes/{cid}", json=body("ט'3"), headers=auth(MGR)).json() + assert kept["student_emails"] == ["a@school.test"] -def test_add_a_list_of_students(client): - cid = make_class(client).json()["id"] - emails = "\n".join(f"s{i}@school.test" for i in range(25)) +def test_removing_a_student_through_an_edit_keeps_their_progress(world): + client, store = world + cid = make(client, students="a@school.test").json()["id"] + store.save_progress("u-a", "t_ext", started_at="then") + client.put(f"/api/classes/{cid}", json=body(students=""), headers=auth(MGR)) + assert client.get(f"/api/classes/{cid}", headers=auth(MGR)).json()["students"] == 0 + assert store.get_progress("u-a", "t_ext")["started_at"] == "then" + + +def test_editing_cannot_clash_with_another_class_or_make_a_student_the_teacher(world): + client, _ = world + make(client, name="A") + cid = make(client, name="B", students="s@school.test").json()["id"] + assert client.put(f"/api/classes/{cid}", json=body("a"), headers=auth(MGR)).status_code == 409 + assert client.put(f"/api/classes/{cid}", json=body("B", teacher_email="s@school.test"), headers=auth(MGR)).status_code == 422 + assert client.put("/api/classes/999", json=body("Z"), headers=auth(MGR)).status_code == 404 + + +def test_deleting_a_class_asks_nothing_of_the_students_progress(world): + client, store = world + cid = make(client, students="a@school.test").json()["id"] + store.save_progress("u-a", "t_ext", started_at="then") + assert client.delete(f"/api/classes/{cid}", headers=auth(MGR)).status_code == 204 + assert client.delete(f"/api/classes/{cid}", headers=auth(MGR)).status_code == 404 + assert client.get("/api/classes", headers=auth(MGR)).json() == [] + assert store.get_progress("u-a", "t_ext")["started_at"] == "then" + + +# ---- the roster (spec: Teacher adds students by email) + +def test_the_classes_teacher_adds_a_list_of_students(world): + client, _ = world + cid = make(client, teacher_email=T1).json()["id"] + emails = "\n".join(f"s{i}@school.test" for i in range(25)) + "\ndana@" result = client.post(f"/api/classes/{cid}/students", json={"emails": emails}, headers=auth(T1)).json() - assert len(result["added"]) == 25 and not result["elsewhere"] and not result["invalid"] - shown = client.get(f"/api/classes/{cid}", headers=auth(T1)).json() - assert len(shown["students"]) == 25 and shown["students"][0] == {"email": "s0@school.test", "signed_in": False} - assert client.get("/api/classes", headers=auth(T1)).json()[0]["students"] == 25 + assert len(result["added"]) == 25 and result["invalid"] == ["dana@"] + assert client.get(f"/api/classes/{cid}", headers=auth(MGR)).json()["students"] == 25 -def test_student_in_another_class_is_reported_not_added_twice(client): - a = make_class(client, name="A").json()["id"] - b = make_class(client, T2, "B").json()["id"] +def test_a_student_can_be_added_to_a_second_class(world): + client, store = world + a = make(client, name="A", teacher_email=T1).json()["id"] + b = make(client, name="B", teacher_email=T2).json()["id"] client.post(f"/api/classes/{a}/students", json={"emails": "s@school.test"}, headers=auth(T1)) - result = client.post(f"/api/classes/{b}/students", json={"emails": "s@school.test new@school.test"}, headers=auth(T2)).json() - assert result["elsewhere"] == [{"email": "s@school.test", "class_name": "A"}] and result["added"] == ["new@school.test"] - again = client.post(f"/api/classes/{a}/students", json={"emails": "s@school.test"}, headers=auth(T1)).json() - assert again["already_here"] == ["s@school.test"] and not again["added"] + again = client.post(f"/api/classes/{b}/students", json={"emails": "s@school.test"}, headers=auth(T2)).json() + assert again["added"] == ["s@school.test"] + assert [c["name"] for c in store.classes_of_student("s@school.test")] == ["A", "B"] + twice = client.post(f"/api/classes/{a}/students", json={"emails": "s@school.test"}, headers=auth(T1)).json() + assert twice["already_here"] == ["s@school.test"] and not twice["added"] + + +def test_a_teacher_cannot_add_themselves_as_a_student(world): + client, _ = world + cid = make(client, teacher_email=T1).json()["id"] + result = client.post(f"/api/classes/{cid}/students", json={"emails": f"{T1} kid@school.test"}, headers=auth(T1)).json() + assert result["teacher"] == [T1] and result["added"] == ["kid@school.test"] -def test_a_teacher_cannot_touch_another_teachers_class(client): - cid = make_class(client).json()["id"] - assert client.get(f"/api/classes/{cid}", headers=auth(T2)).status_code == 404 +def test_a_manager_can_use_any_roster_and_another_teacher_cannot(world): + client, _ = world + cid = make(client, teacher_email=T1).json()["id"] + assert client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth(MGR)).status_code == 200 assert client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth(T2)).status_code == 404 assert client.delete(f"/api/classes/{cid}/students/s@school.test", headers=auth(T2)).status_code == 404 + assert client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth("kid@school.test")).status_code == 403 -def test_remove_a_student(client): - cid = make_class(client).json()["id"] +def test_the_teacher_removes_a_student_and_the_progress_stays(world): + client, store = world + cid = make(client, teacher_email=T1).json()["id"] client.post(f"/api/classes/{cid}/students", json={"emails": "s@school.test"}, headers=auth(T1)) + store.save_progress("u-s", "t_ext", started_at="then") assert client.delete(f"/api/classes/{cid}/students/S@school.test", headers=auth(T1)).status_code == 204 assert client.delete(f"/api/classes/{cid}/students/s@school.test", headers=auth(T1)).status_code == 404 - assert client.get(f"/api/classes/{cid}", headers=auth(T1)).json()["students"] == [] + assert store.get_progress("u-s", "t_ext")["started_at"] == "then" + + +def test_a_teacher_cannot_change_the_class_itself(world): + client, _ = world + cid = make(client, teacher_email=T1).json()["id"] + assert client.put(f"/api/classes/{cid}", json=body("other"), headers=auth(T1)).status_code == 403 + assert client.delete(f"/api/classes/{cid}", headers=auth(T1)).status_code == 403 + assert client.get(f"/api/classes/{cid}", headers=auth(T1)).status_code == 403 -def test_too_many_emails_in_one_go(client): - cid = make_class(client).json()["id"] +def test_too_many_emails_in_one_go(world): + client, _ = world + cid = make(client, teacher_email=T1).json()["id"] emails = " ".join(f"s{i}@school.test" for i in range(201)) assert client.post(f"/api/classes/{cid}/students", json={"emails": emails}, headers=auth(T1)).status_code == 422 + + +# ---- the teacher's home and the manager's students (spec: Teacher home; Class and student lists) + +def test_a_teacher_sees_only_the_classes_they_teach_with_their_students(world): + client, _ = world + make(client, name="A", teacher_email=T1, students="a@school.test") + make(client, name="B", teacher_email=T1, students="b@school.test c@school.test") + make(client, name="C", teacher_email=T2) + mine = client.get("/api/teaching", headers=auth(T1)).json() + assert [c["name"] for c in mine] == ["A", "B"] and [len(c["students"]) for c in mine] == [1, 2] + assert mine[0]["students"][0] == {"email": "a@school.test", "signed_in": False} + assert client.get("/api/teaching", headers=auth("kid@school.test")).status_code == 403 + assert client.get("/api/teaching", headers=auth(MGR)).status_code == 403 # a manager does not teach + + +def test_a_class_teacher_who_is_in_no_setting_still_gets_the_teacher_home(world): + client, _ = world + make(client, teacher_email="newcomer@school.test", students="a@school.test") + assert [c["name"] for c in client.get("/api/teaching", headers=auth("newcomer@school.test")).json()] == ["ט'3"] + assert client.get("/api/me", headers=auth("newcomer@school.test")).json()["teaching"][0]["name"] == "ט'3" + + +def test_a_developer_sees_every_class_as_a_teacher(world): + client, _ = world + make(client, name="A", teacher_email=T1) + make(client, name="B", teacher_email=T2) + assert [c["name"] for c in client.get("/api/teaching", headers=auth(DEV)).json()] == ["A", "B"] + + +def test_the_manager_sees_every_student_with_their_classes(world): + client, _ = world + make(client, name="A", students="x@school.test y@school.test") + make(client, name="B", students="y@school.test") + assert client.get("/api/students", headers=auth(MGR)).json() == [ + {"email": "x@school.test", "classes": ["A"]}, {"email": "y@school.test", "classes": ["A", "B"]}] + assert client.get("/api/students", headers=auth(T1)).status_code == 403 + + +def test_a_database_that_refuses_a_save_gives_a_clear_503_not_a_name_clash(world): + from mathly2.store import StoreUnavailable + client, store = world + cid = make(client).json()["id"] + def refuse(*args, **kwargs): + raise StoreUnavailable("supabase refused (400): column lessons does not exist") + store.update_class = refuse + answer = client.put(f"/api/classes/{cid}", json=body("ט'3"), headers=auth(MGR)) + assert answer.status_code == 503 and "המיגרציות" in answer.json()["detail"] and "שם" not in answer.json()["detail"] diff --git a/mathly2/tests/test_collection_browser.py b/mathly2/tests/test_collection_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..96f5f252f1365371efac995e27049bd6501479b5 --- /dev/null +++ b/mathly2/tests/test_collection_browser.py @@ -0,0 +1,150 @@ +"""The collection screen in a real browser: what a student has mastered, and the empty start.""" +import uuid + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID = "kid@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) + + +@pytest.fixture +def world(): + bank = load_bank() + store = InMemoryStore() + store.add_member(store.create_class("setup", "A", lessons=[u["id"] for u in bank.lessons])["id"], KID) + return create_app(Settings(), bank=bank, store=store), store, bank + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def collection_page(browser, url): + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) + page.goto(url + "#/collection") + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector("#collection") + return page + + +def test_a_skill_mastered_through_the_server_appears_in_the_collection(browser, world): + app, store, bank = world + skill = bank.skills[0] + store.save_progress(KID_ID, skill["id"], started_at="then", mastered_at="then") + with running(app) as url: + page = collection_page(browser, url) + assert skill["name"] in page.inner_text("#done-skills") and "מיומנויות שנשלטו (1)" in page.inner_text("#collection") + assert "קבוצות כוכבים (0)" in page.inner_text("#collection") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + page.click("a[href='#/subject/math/path']") + page.wait_for_selector(".trail") + + +def test_the_collection_starts_empty_with_a_hint(browser, world): + app, _, _ = world + with running(app) as url: + page = collection_page(browser, url) + assert "מיומנויות שנשלטו (0)" in page.inner_text("#collection") and page.locator("#done-skills").count() == 0 + + +# --- add-rewards 4.2 / 5.1: constellations and comets --- + +PHONE = {"width": 360, "height": 800} + + +def master_lesson(store, bank, lesson_id): + ids = [s["id"] for s in bank.skills if s["unit"] == lesson_id] + for skill in ids: + store.save_progress(KID_ID, skill, started_at="then", mastered_at="then") + return ids + + +def lessons_of_size(bank, *sizes): + from collections import Counter + counts = Counter(s["unit"] for s in bank.skills) + return [next(l for l, n in counts.items() if n == size) for size in sizes] + + +def test_constellations_of_2_4_and_6_stars_and_the_fallback_fit_a_360px_screen(browser, world): + app, _, _ = world + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE)) + page.goto(url) + page.evaluate("""async () => { + const { constellationSvg } = await import('/static/sky.js'); + const host = document.createElement('div'); host.id = 'probe'; host.style.cssText = 'display:grid;grid-template-columns:repeat(2,130px);gap:8px;padding:8px'; + host.innerHTML = [['t', 2], ['k', 4], ['h', 6], ['zz', 4], ['zz', 7]].map(([id, n]) => constellationSvg(id, 'בדיקה', n)).join(''); + document.body.append(host); + const style = document.createElement('style'); style.textContent = '.con{width:100%;max-width:130px;height:110px;overflow:visible}'; document.head.append(style); + }""") + svgs = page.locator("#probe svg.con") + assert svgs.count() == 5 + for i, stars in enumerate([2, 4, 6, 4, 7]): + svg = svgs.nth(i) + assert svg.locator("path").count() == stars # one star per skill, fallback included + box = svg.bounding_box() + assert box["x"] >= 0 and box["x"] + box["width"] <= PHONE["width"] + assert "בדיקה" in svg.get_attribute("aria-label") and str(stars) in svg.get_attribute("aria-label") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +def test_mastering_a_lessons_last_skill_adds_its_constellation(browser, world): + app, store, bank = world + two, three = lessons_of_size(bank, 2, 3) + ids = [s["id"] for s in bank.skills if s["unit"] == two] + store.save_progress(KID_ID, ids[0], started_at="then", mastered_at="then") + with running(app) as url: + page = collection_page(browser, url) + assert "קבוצות כוכבים (0)" in page.inner_text("#collection") + store.save_progress(KID_ID, ids[1], started_at="then", mastered_at="then") # the lesson's last skill + page.reload(); page.wait_for_selector("#collection") + assert "קבוצות כוכבים (1)" in page.inner_text("#collection") + card = page.locator(f"#done-lessons .con-card[data-lesson='{two}']") + assert card.count() == 1 and card.locator("svg.con path").count() == 2 + + +def test_the_collection_shows_caught_comets_and_question_marks_for_the_rest(browser, world): + app, store, _ = world + for c in ("pi", "e", "zero"): + store.add_comet(KID_ID, c) + with running(app) as url: + page = collection_page(browser, url) + tiles = page.locator("#comets .comet-tile") + assert tiles.count() == 12 and page.locator("#comets .comet-tile.have").count() == 3 + assert page.locator("#comets .comet-tile:not(.have)").count() == 9 + assert "π" in page.inner_text("#comets .comet-tile.have >> nth=0") and "פאי" in page.inner_text("#comets") + assert page.locator("#comets .comet-tile:not(.have)", has_text="עוד לא נתפס").count() == 9 + assert "3 מתוך 12" in page.inner_text("#collection") + page.click("#comets [data-comet='pi']") # a caught comet opens its fact + assert "היחס בין ההיקף" in page.inner_text(".comet-dialog") + page.keyboard.press("Escape") + assert page.locator(".comet-dialog").count() == 0 + page.click("#comets .comet-tile:not(.have) >> nth=0") # a missing one opens a hint, no fact + assert "עוד לא נתפס" in page.inner_text(".comet-dialog") and "היחס בין" not in page.inner_text(".comet-dialog") + page.click(".comet-dialog button") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +def test_the_collection_dims_a_faded_skill_and_says_so(browser, world): + from datetime import timedelta + from mathly2 import clock + app, store, bank = world + skill = bank.skills[0]["id"] + store.save_progress(KID_ID, skill, started_at="then", mastered_at="then") + store.add_answer(KID_ID, skill, "k", True, True, None, clock.school_day() - timedelta(days=30)) + with running(app) as url: + page = collection_page(browser, url) + assert "דועך" in page.inner_text("#done-skills li.faded") diff --git a/mathly2/tests/test_comets.py b/mathly2/tests/test_comets.py new file mode 100644 index 0000000000000000000000000000000000000000..24fec313b45a66d4ad11255bb3e28fc59014d3b4 --- /dev/null +++ b/mathly2/tests/test_comets.py @@ -0,0 +1,66 @@ +"""The comets and the rule for when one is due (add-rewards 3.1).""" +from datetime import date + +from mathly2 import comets +from mathly2.store import InMemoryStore +from mathly2.tests.test_store import Recorder, U, V + +TODAY, YESTERDAY = date(2026, 11, 9), date(2026, 11, 8) + + +def test_there_are_twelve_comets_with_unique_ids_and_a_symbol_name_and_fact(): + assert len(comets.COMETS) == 12 and len(set(comets.IDS)) == 12 + assert all(c["sym"] and c["name"] and len(c["fact"]) > 20 for c in comets.COMETS) + assert [c["name"] for c in comets.COMETS][:3] == ["פאי", "פיבונאצ׳י", "יחס הזהב"] and comets.get("pi")["sym"] == "π" + assert comets.get("nope") is None + + +def test_all_caught_means_never_due(): + assert comets.due({"last_comet_day": YESTERDAY}, set(comets.IDS), TODAY, True, roll=0.0) is False + + +def test_at_most_one_comet_a_day(): + assert comets.due({"last_comet_day": TODAY}, set(), TODAY, True, roll=0.0) is False + + +def test_the_first_comet_comes_only_on_the_answer_that_reaches_the_goal(): + assert comets.due(None, set(), TODAY, goal_just_reached=False, roll=0.0) is False # no chance roll before the first comet + assert comets.due({"last_comet_day": None}, set(), TODAY, goal_just_reached=False, roll=0.0) is False + assert comets.due(None, set(), TODAY, goal_just_reached=True, roll=0.99) is True # certain, whatever the roll + + +def test_after_a_comet_was_offered_each_right_answer_has_a_12_percent_chance(): + state = {"last_comet_day": YESTERDAY} + assert comets.due(state, {"pi"}, TODAY, False, roll=0.11) is True + assert comets.due(state, {"pi"}, TODAY, False, roll=0.13) is False + + +def test_pick_gives_a_comet_the_student_does_not_have_and_none_when_all_are_held(): + held = set(comets.IDS[:11]) + assert comets.pick(held, roll=0.0)["id"] == comets.IDS[11] + assert comets.pick(set(comets.IDS)) is None + seen = {comets.pick({"pi"}, roll=i / 20)["id"] for i in range(20)} + assert "pi" not in seen and len(seen) == 11 + + +def test_store_remembers_caught_comets_and_the_reward_days_per_student(): + store = InMemoryStore() + assert store.comets_of(U) == set() and store.reward_state(U) is None + store.add_comet(U, "pi"); store.add_comet(U, "pi"); store.add_comet(V, "e") + assert store.comets_of(U) == {"pi"} and store.comets_of(V) == {"e"} + store.save_reward_state(U, last_comet_day=TODAY) + store.save_reward_state(U, last_catch_day=TODAY) # the other field stays + assert store.reward_state(U)["last_comet_day"] == TODAY and store.reward_state(U)["last_catch_day"] == TODAY + assert store.reward_state(V) is None + + +def test_supabase_comet_and_reward_requests(): + s = Recorder([[{"comet_id": "pi"}], None, [{"user_id": U, "last_comet_day": "2026-11-09", "last_catch_day": None}], + [{"user_id": U, "last_comet_day": "2026-11-09", "last_catch_day": None}], []]) + assert s.comets_of(U) == {"pi"} + s.add_comet(U, "e") + assert s.calls[1][:2] == ("POST", "m2_comets") and s.calls[1][3] == {"user_id": U, "comet_id": "e"} and s.calls[1][5] is True + assert s.reward_state(U) == {"user_id": U, "last_comet_day": TODAY, "last_catch_day": None} + saved = s.save_reward_state(U, last_comet_day=TODAY) + assert s.calls[3][3] == {"user_id": U, "last_comet_day": "2026-11-09"} and saved["last_comet_day"] == TODAY + assert s.reward_state(V) is None diff --git a/mathly2/tests/test_config.py b/mathly2/tests/test_config.py new file mode 100644 index 0000000000000000000000000000000000000000..409d6d7f2bd420c1803464423431e2a63cc7fea4 --- /dev/null +++ b/mathly2/tests/test_config.py @@ -0,0 +1,105 @@ +import pytest + +from mathly2 import config +from mathly2.config import load_settings + +NAMES = ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS", "DEVELOPER_EMAILS", "ADMIN_EMAILS", "ANTHROPIC_API_KEY") + + +@pytest.fixture(autouse=True) +def clean_environment(monkeypatch): + """Start with none of the settings in the environment; monkeypatch puts back whatever was there afterwards + (load_dotenv writes into os.environ, so this also stops one test leaking into the next).""" + for name in NAMES: + monkeypatch.setenv(name, "") + monkeypatch.delenv(name) + + +def write(tmp_path, text): + path = tmp_path / ".env" + path.write_text(text, encoding="utf-8") + return path + + +def test_the_env_file_fills_in_what_the_environment_does_not_set(tmp_path): + settings = load_settings(write(tmp_path, "TEACHER_EMAILS=A@School.test, b@school.test\n")) + assert settings.teachers == {"a@school.test", "b@school.test"} + assert settings.supabase_on is False # no Supabase values: local development + + +def test_a_real_environment_variable_wins_over_the_file(tmp_path, monkeypatch): + monkeypatch.setenv("TEACHER_EMAILS", "real@school.test") + settings = load_settings(write(tmp_path, "TEACHER_EMAILS=file@school.test\n")) + assert settings.teachers == {"real@school.test"} + + +def test_all_three_supabase_values_in_the_file_turn_supabase_on(tmp_path): + text = "SUPABASE_URL=https://p.supabase.test/\nSUPABASE_PUBLISHABLE_KEY=pub\nSUPABASE_SECRET_KEY=sec\n" + settings = load_settings(write(tmp_path, text)) + assert settings.supabase_on and settings.supabase_url == "https://p.supabase.test" + + +def test_a_half_configured_file_is_refused(tmp_path): + with pytest.raises(ValueError, match="all of SUPABASE_URL"): + load_settings(write(tmp_path, "SUPABASE_URL=https://p.supabase.test\n")) + + +def test_a_missing_env_file_is_fine(tmp_path): + assert load_settings(tmp_path / "nope.env").teachers == frozenset() + + +def test_the_two_default_files_are_this_apps_own_and_the_repository_root_one(): + assert config.ENV_FILE.parent.name == "mathly2" and config.ENV_FILE.name == ".env" + assert config.ROOT_ENV_FILE == config.ENV_FILE.parent.parent / ".env" and config.ROOT_ENV_FILE.parent.name == "mathly" + + +def test_the_repository_env_is_used_when_this_app_has_none(tmp_path, monkeypatch): + monkeypatch.setattr(config, "ENV_FILE", tmp_path / "missing.env") + monkeypatch.setattr(config, "ROOT_ENV_FILE", write(tmp_path, "ADMIN_EMAILS=root-admin@x.test\nTEACHER_EMAILS=root-teacher@x.test\n")) + settings = load_settings() + assert settings.admins == {"root-admin@x.test"} and settings.teachers == {"root-teacher@x.test"} + + +def test_order_is_environment_then_this_apps_file_then_the_repository_file(tmp_path, monkeypatch): + own = tmp_path / "own.env" + own.write_text("TEACHER_EMAILS=own@x.test\nADMIN_EMAILS=own-admin@x.test\n", encoding="utf-8") + root = tmp_path / "root.env" + root.write_text("TEACHER_EMAILS=root@x.test\nADMIN_EMAILS=root-admin@x.test\nDEVELOPER_EMAILS=root-dev@x.test\n", encoding="utf-8") + monkeypatch.setattr(config, "ENV_FILE", own) + monkeypatch.setattr(config, "ROOT_ENV_FILE", root) + monkeypatch.setenv("TEACHER_EMAILS", "env@x.test") + settings = load_settings() + assert settings.teachers == {"env@x.test"} # the environment wins over both files + assert settings.admins == {"own-admin@x.test"} # this app's file wins over the repository's + assert settings.developers == {"root-dev@x.test"} # the repository's file fills what is left + + +def test_passing_a_file_reads_only_that_file(tmp_path, monkeypatch): + monkeypatch.setattr(config, "ROOT_ENV_FILE", write(tmp_path, "ADMIN_EMAILS=root-admin@x.test\n")) + assert load_settings(tmp_path / "nope.env").admins == frozenset() + + +def test_the_example_file_lists_every_setting_with_empty_values(): + example = (config.ENV_FILE.parent / ".env.example").read_text(encoding="utf-8") + for name in ("SUPABASE_URL", "SUPABASE_PUBLISHABLE_KEY", "SUPABASE_SECRET_KEY", "TEACHER_EMAILS"): + assert f"\n{name}=\n" in example + + +def test_the_container_image_never_gets_the_env_file(): + ignore = (config.ENV_FILE.parent / "Dockerfile.dockerignore").read_text(encoding="utf-8").split() + assert "mathly2/.env" in ignore + + +def test_developers_and_admins_come_from_the_environment_and_the_file(tmp_path, monkeypatch): + monkeypatch.setenv("DEVELOPER_EMAILS", "Dev@School.test") + settings = load_settings(write(tmp_path, "ADMIN_EMAILS=head@school.test, deputy@school.test\nDEVELOPER_EMAILS=file-dev@school.test\n")) + assert settings.developers == {"dev@school.test"} # the environment wins over the file + assert settings.admins == {"head@school.test", "deputy@school.test"} # from the file + assert settings.teachers == frozenset() + + +def test_the_example_file_and_readme_name_the_new_settings(): + base = config.ENV_FILE.parent + for name in ("DEVELOPER_EMAILS", "ADMIN_EMAILS"): + assert f"\n{name}=\n" in (base / ".env.example").read_text(encoding="utf-8") + assert f"`{name}`" in (base / "README.md").read_text(encoding="utf-8") diff --git a/mathly2/tests/test_content_gaps.py b/mathly2/tests/test_content_gaps.py index e8916ff1b4e85416e2db0425750f79756f4cd34f..22ae44d2eca2ffa515824aa331edab8d2146ab32 100644 --- a/mathly2/tests/test_content_gaps.py +++ b/mathly2/tests/test_content_gaps.py @@ -1,25 +1,37 @@ from mathly2.bank import load_bank +from mathly2.scripts import content_gaps from mathly2.scripts.content_gaps import find_gaps def test_real_bank_gaps(): gaps = find_gaps(load_bank().data) - assert len(gaps["skills without a worked example"]) == 96 - assert len(gaps["skills without faded examples"]) == 96 - assert len(gaps["lessons without a quiz"]) == 20 - assert len(gaps["skills without questions"]) == 1 + assert len(gaps["skills without a solved example"]) == 96 + assert gaps["skills without questions"] == ["a_30_side"] assert len(gaps["mistakes without a skill to go back to"]) == 204 + assert gaps["skills with fewer than 10 questions"] == [] + assert set(gaps) == {"skills without a solved example", "skills without questions", "skills with fewer than 10 questions", + "mistakes without a skill to go back to"} -def test_a_skill_with_an_example_and_all_steps_explained_is_not_listed(): - data = {"units": [{"id": "u", "quiz": {"questions": []}}], - "skills": [{"id": "s", "unit": "u", "questions": [{}] * 10, - "worked_example": {"steps": [{"why": ["a", "b"]}]}, "faded_examples": [{}]}], - "mistakes": {}} +def test_a_complete_skill_is_not_listed(): + data = {"units": [], "skills": [{"id": "s", "unit": "u", "questions": [{}] * 10, "worked_example": {"steps": []}}], + "mistakes": {"m": {"back": "s"}}} assert all(not items for items in find_gaps(data).values()) -def test_step_without_why_is_listed(): - data = {"units": [], "skills": [{"id": "s", "unit": "u", "worked_example": {"steps": [{"why": ["a"]}, {}]}}], - "mistakes": {}} - assert find_gaps(data)["worked-example steps without 'why this step?' choices"] == ["s step 2"] +def test_few_questions_are_listed_with_their_count_and_the_threshold_can_change(): + data = {"units": [], "skills": [{"id": "a", "unit": "u", "questions": [{}] * 3, "worked_example": {}}, + {"id": "b", "unit": "u", "questions": [{}] * 9, "worked_example": {}}], "mistakes": {}} + assert find_gaps(data)["skills with fewer than 10 questions"] == ["a (3)", "b (9)"] + assert find_gaps(data, min_questions=5)["skills with fewer than 5 questions"] == ["a (3)"] + + +def test_a_mistake_with_an_empty_back_is_a_gap(): + data = {"units": [], "skills": [], "mistakes": {"x": {"back": ""}, "y": {}, "z": {"back": "s"}}} + assert find_gaps(data)["mistakes without a skill to go back to"] == ["x", "y"] + + +def test_the_command_prints_each_gap_with_its_count(capsys): + assert content_gaps.main([]) == 0 + out = capsys.readouterr().out + assert "skills without a solved example: 96" in out and "skills without questions: 1" in out and "a_30_side" in out diff --git a/mathly2/tests/test_countdown.py b/mathly2/tests/test_countdown.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf27cfe5c0e406959dd2f88a1bec5f9ca219e33 --- /dev/null +++ b/mathly2/tests/test_countdown.py @@ -0,0 +1,95 @@ +"""The countdown plan and today's task (add-test-readiness 1.2).""" +from datetime import date, timedelta + +from mathly2 import countdown as c + +TEST = date(2026, 11, 30) +SET_LONG = TEST - timedelta(days=14) + + +def facts(**kw): + base = {"path_done": False, "next_path_skill": "s1", "ex1_done": False, "ex2_done": False, "sim_taken": False, + "review_left": [], "stale": ["old", "older"]} + return {**base, **kw} + + +def on(days_left, plan_for=SET_LONG, **kw): + return c.task(days_left, c.plan(TEST, plan_for), facts(**kw)) + + +def test_the_plan_for_two_weeks_has_the_prds_days(): + assert c.plan(TEST, SET_LONG) == {"n": 14, "ex1": 9, "ex2": 7, "sim": 5, "review_from": 4} + assert c.plan(TEST, TEST - timedelta(days=9))["ex1"] == 9 + + +def test_twelve_days_ahead_the_plan_asks_to_finish_the_path(): + assert on(12) == {"kind": "path", "skill": "s1"} + assert on(10) == {"kind": "path", "skill": "s1"} + + +def test_nine_seven_and_five_days_ahead_are_exercise_test_1_2_and_the_simulation(): + assert on(9, path_done=True) == {"kind": "ex1"} + assert on(8, path_done=True) == {"kind": "ex1"} + assert on(7, path_done=True, ex1_done=True) == {"kind": "ex2"} + assert on(5, path_done=True, ex1_done=True, ex2_done=True) == {"kind": "sim"} + + +def test_the_recommended_step_comes_first_even_when_an_earlier_one_was_missed(): + assert on(5) == {"kind": "sim"} # exercise tests missed: the required simulation still comes first + assert on(7) == {"kind": "ex2"} + + +def test_a_done_step_moves_to_the_next_one_early_but_never_to_a_closed_simulation(): + assert on(12, path_done=True) == {"kind": "ex1"} # the path is done: exercise test 1 early + assert on(12, path_done=True, ex1_done=True) == {"kind": "ex2"} + assert on(10, path_done=True, ex1_done=True, ex2_done=True) == {"kind": "continue"} # the simulation is not open yet + assert on(9, path_done=False, ex1_done=True) == {"kind": "ex2"} + + +def test_after_the_simulation_the_last_days_review_a_failed_skill_and_the_day_before_is_mixed(): + done = dict(path_done=True, ex1_done=True, ex2_done=True, sim_taken=True) + assert on(3, review_left=["f1", "f2"], **done) == {"kind": "review", "skill": "f1"} + assert on(2, review_left=["f2"], **done) == {"kind": "review", "skill": "f2"} + assert on(4, review_left=[], **done) == {"kind": "mixed_review", "skill": "old"} # nothing failed is left: mixed review + assert on(1, review_left=["f2"], **done) == {"kind": "mixed_review", "skill": "old"} # the day before is always the light mixed review + assert on(0, review_left=["f2"], **done) == {"kind": "continue"} + + +def test_the_simulation_is_asked_for_in_the_last_days_if_it_was_not_taken(): + assert on(4, path_done=True, ex1_done=True, ex2_done=True) == {"kind": "sim"} + assert on(0) == {"kind": "sim"} # open until the test day + + +def test_a_test_set_six_days_ahead_keeps_the_order_within_six_days(): + p = c.plan(TEST, TEST - timedelta(days=6)) + assert p == {"n": 6, "ex1": 6, "ex2": 5, "sim": 3, "review_from": 3} + days = [p["ex1"], p["ex2"], p["sim"]] + assert days == sorted(days, reverse=True) and p["ex1"] <= 6 + sequence = [c.step_for(d, p) for d in range(6, 0, -1)] + assert sequence == ["ex1", "ex2", "ex2", "sim", "sim", "sim"] # path, then ex1, ex2, simulation, then review (after the simulation) + after = {**facts(path_done=True, ex1_done=True, ex2_done=True, sim_taken=True, review_left=["f"])} + assert c.task(2, p, after) == {"kind": "review", "skill": "f"} + + +def test_a_very_short_notice_keeps_every_step_startable_in_order(): + p = c.plan(TEST, TEST - timedelta(days=2)) + assert p["ex1"] >= p["ex2"] >= p["sim"] >= p["review_from"] >= 1 + assert c.task(2, p, facts(path_done=True)) == {"kind": "ex1"} + assert c.task(2, p, facts(path_done=True, ex1_done=True)) == {"kind": "ex2"} + + +def test_the_closest_test_gives_the_task(): + soon = {"id": 1, "date": date(2026, 11, 14)} + later = {"id": 2, "date": date(2026, 11, 20)} + today = date(2026, 11, 10) + assert c.closest([later, soon], today)["id"] == 1 # tests in 4 and in 10 days: the one in 4 + assert c.closest([{"id": 3, "date": date(2026, 11, 9)}], today) is None + assert c.closest([{"id": 4, "date": today}], today)["id"] == 4 # the test day itself is still upcoming + assert c.closest([], today) is None + + +def test_the_outline_lists_the_steps_with_their_days_and_done_marks(): + p = c.plan(TEST, SET_LONG) + steps = c.outline(p, facts(path_done=True, ex1_done=True, sim_taken=True, review_left=["x"])) + assert [(s["id"], s["done"]) for s in steps] == [("path", True), ("ex1", True), ("ex2", False), ("sim", True), ("review", False)] + assert [s["day"] for s in steps[1:]] == [9, 7, 5, 4] diff --git a/mathly2/tests/test_database_waits.py b/mathly2/tests/test_database_waits.py new file mode 100644 index 0000000000000000000000000000000000000000..846908fac29d781b008b717f537ae1db9befafa7 --- /dev/null +++ b/mathly2/tests/test_database_waits.py @@ -0,0 +1,80 @@ +"""Few database round trips (fewer-database-calls 1.1): with every store call made to wait, a screen and an answer must still be quick, +because independent reads run at the same time and repeated reads happen once.""" +import time +import uuid + +import pytest +from fastapi.testclient import TestClient + +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore + +DELAY = 0.1 +KID = "kid@school.test" +H = {"Authorization": f"Bearer dev:{KID}"} + + +class SlowStore(InMemoryStore): + """Every public call takes DELAY seconds, like a remote database.""" + slow = False + + def __getattribute__(self, name): + attr = super().__getattribute__(name) + if callable(attr) and not name.startswith("_") and name != "calls" and super().__getattribute__("slow"): + def waiting(*a, **k): + time.sleep(DELAY) + return attr(*a, **k) + return waiting + return attr + + +@pytest.fixture(scope="module") +def world(): + bank = load_bank() + store = SlowStore() + lessons = [l["id"] for l in bank.lessons][:6] + klass = store.create_class("setup", "A", lessons=lessons, teacher_email="t@school.test") + store.add_member(klass["id"], KID) + from datetime import timedelta + from mathly2 import clock + store.create_test(klass["id"], clock.school_day() + timedelta(days=9), lessons[:2], "t@school.test", created_at=clock.now() - timedelta(days=20)) + client = TestClient(create_app(Settings(), bank=bank, store=store)) + skill = next(s["id"] for s in bank.skills if s["unit"] in lessons and bank.question_keys(s["id"])) + client.get("/api/me", headers=H) # warm the roles cache, as a signed-in student's later requests are + client.get(f"/api/skills/{skill}", headers=H) # the question is chosen and remembered on the first open + store.slow = True + yield client, bank, skill, store + store.slow = False + + +def timed(client, method, path, **kw): + start = time.perf_counter() + response = client.request(method, path, headers=H, **kw) + assert response.status_code == 200, response.text + return time.perf_counter() - start + + +@pytest.mark.parametrize("path", ["/api/home", "/api/path", "/api/grades", "/api/collection"]) +def test_a_screen_waits_for_the_database_at_most_three_times_in_a_row(world, path): + client, _, _, _ = world + assert timed(client, "GET", path) < 0.55 + + +def test_opening_a_skill_waits_at_most_three_times_in_a_row(world): + client, _, skill, _ = world + assert timed(client, "GET", f"/api/skills/{skill}") < 0.55 + + +def test_an_answer_waits_at_most_four_times_in_a_row(world): + client, bank, skill, store = world + store.slow = False + key = client.get(f"/api/skills/{skill}", headers=H).json()["question"]["key"] + store.slow = True + assert timed(client, "POST", f"/api/skills/{skill}/answer", json={"question_key": key, "choice": 0}) < 0.75 + + +def test_me_waits_at_most_two_or_three_times(world): + client, _, _, _ = world + assert timed(client, "GET", "/api/me") < 0.55 diff --git a/mathly2/tests/test_draft_examples.py b/mathly2/tests/test_draft_examples.py new file mode 100644 index 0000000000000000000000000000000000000000..251ca7bae42da7eaae5791bbe6f1520f516917d5 --- /dev/null +++ b/mathly2/tests/test_draft_examples.py @@ -0,0 +1,212 @@ +"""The drafting tool, with a fake AI client: nothing here calls the network or spends money.""" +import copy +import json + +import anthropic +import httpx +import pytest + +from mathly2.bank import BANK_PATH, check_bank, load_bank +from mathly2.scripts import draft_examples as tool + + +@pytest.fixture(autouse=True) +def the_real_bank_is_never_touched(): + """A test that writes to the real bank would add fake examples to the app's content: fail loudly.""" + before = BANK_PATH.read_bytes() + yield + assert BANK_PATH.read_bytes() == before, "a test changed the real exercise bank" + + +@pytest.fixture +def data(): + return copy.deepcopy(load_bank().data) + + +def good_model_answer(): + return {"worked_example": {"question": "$x² + 5x + 6$", "answer": "$(x + 2)(x + 3)$", "steps": [ + {"do": "מוצאים 2 ו־3", "why": "כי המכפלה 6 והסכום 5"}, + {"do": "כותבים $(x + 2)(x + 3)$", "why": "כך מפרקים טרינום לגורמים"}]}} + + +class Block: + type = "text" + + def __init__(self, text): + self.text = text + + +class Response: + def __init__(self, text, stop="end_turn"): + self.content, self.stop_reason = [Block(text)], stop + + +class FakeClient: + def __init__(self, *answers): + self.answers, self.requests = list(answers), [] + self.messages = self + + def create(self, **kwargs): + self.requests.append(kwargs) + answer = self.answers.pop(0) + if isinstance(answer, Exception): + raise answer + return answer if isinstance(answer, Response) else Response(json.dumps(answer, ensure_ascii=False)) + + +def first_without_example(data, lesson="t"): + return tool.skills_without_examples(data, lesson)[0] + + +# --- draft --- + +def test_a_good_draft_is_in_the_bank_shape_and_has_no_problems(data): + skill = first_without_example(data) + client = FakeClient(good_model_answer()) + review = tool.draft_lesson(client, "m", data, "t", only=[skill["id"]]) + entry = review["drafts"][skill["id"]] + assert entry["problems"] == [] and entry["approved"] is False and entry["reviewed_by"] == "" + assert set(entry["example"]) == {"worked_example"} and entry["example"]["worked_example"]["steps"][0]["why"] == "כי המכפלה 6 והסכום 5" + assert client.requests[0]["system"] == tool.SYSTEM + + +def test_the_schema_asks_for_one_plain_text_example_and_no_faded_ones(): + schema = tool.EXAMPLE_SCHEMA + assert schema["required"] == ["worked_example"] + step = schema["properties"]["worked_example"]["properties"]["steps"]["items"]["properties"] + assert step["why"] == {"type": "string"} and "faded_examples" not in json.dumps(schema) + + +def test_the_request_shows_the_skill_and_its_common_mistakes(data): + skill = first_without_example(data) + client = FakeClient(good_model_answer()) + tool.draft_lesson(client, "m", data, "t", only=[skill["id"]]) + sent = json.loads(client.requests[0]["messages"][0]["content"]) + assert sent["skill"] == skill["name"] and 0 < len(sent["practice_questions"]) <= tool.SAMPLE_QUESTIONS + assert sent["common_mistakes"] and all({"name", "tip"} <= set(m) for m in sent["common_mistakes"]) + + +def test_a_draft_that_breaks_the_bank_rules_is_flagged(data): + skill = first_without_example(data) + answer = good_model_answer() + answer["worked_example"]["steps"][0]["why"] = "" + answer["worked_example"]["answer"] = "" + entry = tool.draft_lesson(FakeClient(answer), "m", data, "t", only=[skill["id"]])["drafts"][skill["id"]] + assert any("needs a question, steps and an answer" in p for p in entry["problems"]) + assert any("step 1: 'why' must be text" in p for p in entry["problems"]) + + +def test_a_failed_request_becomes_a_problem_not_a_crash(data): + skills = tool.skills_without_examples(data, "t")[:3] + error = anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.test")) + client = FakeClient(error, Response("{}", stop="refusal"), Response("not json")) + review = tool.draft_lesson(client, "m", data, "t", only=[s["id"] for s in skills]) + problems = [review["drafts"][s["id"]]["problems"][0] for s in skills] + assert all(p.startswith("no draft:") for p in problems) + assert "stop_reason=refusal" in problems[1] and "not the expected JSON" in problems[2] + assert all(review["drafts"][s["id"]]["example"] is None for s in skills) + + +def test_limit_and_only_choose_the_skills(data): + ids = [s["id"] for s in tool.skills_without_examples(data, "t")] + assert len(tool.draft_lesson(FakeClient(*[good_model_answer()] * 2), "m", data, "t", limit=2)["drafts"]) == 2 + only = tool.draft_lesson(FakeClient(good_model_answer()), "m", data, "t", only=[ids[1]]) + assert list(only["drafts"]) == [ids[1]] + + +def test_a_skill_that_already_has_a_solved_example_is_not_drafted(data): + skill = first_without_example(data) + skill["worked_example"] = good_model_answer()["worked_example"] + assert skill["id"] not in [s["id"] for s in tool.skills_without_examples(data, "t")] + + +# --- merge --- + +@pytest.fixture +def bank_copy(tmp_path, monkeypatch): + path = tmp_path / "bank.json" + path.write_text(BANK_PATH.read_text(encoding="utf-8"), encoding="utf-8") + monkeypatch.setattr(tool, "BANK_PATH", path) + return path + + +def three(data): + return [s["id"] for s in tool.skills_without_examples(data, "t")[:3]] + + +def review_file(tmp_path, data, approve, reviewer="מורה"): + drafts = {sid: {"approved": sid in approve, "reviewed_by": reviewer if sid in approve else "", + "example": tool.clean(good_model_answer()), "problems": []} for sid in three(data)} + path = tmp_path / "review.json" + path.write_text(json.dumps({"drafts": drafts}, ensure_ascii=False), encoding="utf-8") + return path + + +def test_merge_adds_only_the_approved_drafts_and_the_bank_still_loads(tmp_path, data, bank_copy, capsys): + ids = three(data) + assert tool.main(["merge", str(review_file(tmp_path, data, {ids[0]}))]) == 0 + merged = json.loads(bank_copy.read_text(encoding="utf-8")) + by_id = {s["id"]: s for s in merged["skills"]} + assert by_id[ids[0]]["worked_example"]["steps"][0]["why"] == "כי המכפלה 6 והסכום 5" + assert "worked_example" not in by_id[ids[1]] and "worked_example" not in by_id[ids[2]] + assert check_bank(merged) == [] and load_bank(bank_copy) + out = capsys.readouterr().out + assert f"added solved examples to bank.json: {ids[0]}" in out and f"{ids[1]}: not approved" in out + + +def test_merge_leaves_out_an_approval_without_a_reviewer_name(tmp_path, data, bank_copy, capsys): + before = bank_copy.read_text(encoding="utf-8") + assert tool.main(["merge", str(review_file(tmp_path, data, {three(data)[0]}, reviewer=" "))]) == 1 + assert "approved without the reviewer's name" in capsys.readouterr().out + assert bank_copy.read_text(encoding="utf-8") == before + + +def test_merge_refuses_a_draft_that_breaks_the_rules_even_if_approved(tmp_path, data, bank_copy, capsys): + ids = three(data) + path = review_file(tmp_path, data, {ids[0]}) + review = json.loads(path.read_text(encoding="utf-8")) + review["drafts"][ids[0]]["example"]["worked_example"]["steps"][0]["why"] = "" + path.write_text(json.dumps(review, ensure_ascii=False), encoding="utf-8") + before = bank_copy.read_text(encoding="utf-8") + assert tool.main(["merge", str(path)]) == 1 + assert "'why' must be text" in capsys.readouterr().out + assert bank_copy.read_text(encoding="utf-8") == before + + +def test_merge_never_overwrites_a_skill_that_already_has_a_solved_example(tmp_path, data, bank_copy, capsys): + path = review_file(tmp_path, data, {three(data)[0]}) + assert tool.main(["merge", str(path)]) == 0 + assert tool.main(["merge", str(path)]) == 1 # the same review again + assert "already has a solved example" in capsys.readouterr().out + + +def test_writing_the_bank_keeps_the_files_own_format(): + assert BANK_PATH.read_text(encoding="utf-8") == json.dumps(load_bank().data, ensure_ascii=False, indent=1) + "\n" + + +# --- the command line --- + +def test_dry_run_sends_nothing_and_needs_no_key(monkeypatch, capsys): + def boom(*args, **kwargs): + raise AssertionError("the dry run must not create a client") + monkeypatch.setattr(anthropic, "Anthropic", boom) + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_API_KEY", raising=False) + before = BANK_PATH.read_bytes() + assert tool.main(["draft", "--lesson", "t", "--dry-run"]) == 0 + out = capsys.readouterr().out + assert "5 skills without a solved example" in out and "nothing was sent" in out and "system prompt" in out + assert BANK_PATH.read_bytes() == before + + +def test_draft_without_a_key_or_with_a_bad_lesson_or_over_a_review_stops(monkeypatch, capsys, tmp_path): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_API_KEY", raising=False) + assert tool.main(["draft", "--lesson", "nope"]) == 2 + assert tool.main(["draft", "--lesson", "t"]) == 2 + assert "ANTHROPIC_API_KEY" in capsys.readouterr().err + monkeypatch.setenv("ANTHROPIC_API_KEY", "k") + existing = tmp_path / "review.json" + existing.write_text("{}", encoding="utf-8") + assert tool.main(["draft", "--lesson", "t", "--out", str(existing)]) == 2 # may hold a teacher's review + assert existing.read_text(encoding="utf-8") == "{}" diff --git a/mathly2/tests/test_exam.py b/mathly2/tests/test_exam.py new file mode 100644 index 0000000000000000000000000000000000000000..8d33c2b7bb0d69b5d54e0465e00ea00fd008b5f7 --- /dev/null +++ b/mathly2/tests/test_exam.py @@ -0,0 +1,103 @@ +"""Drawing exercise tests and simulations (add-test-readiness 1.4).""" +import random +from collections import Counter + +import pytest + +from mathly2 import exam +from mathly2.bank import load_bank + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +def lessons_and_skills(bank, count=2, per=4): + """Lessons whose skills all have questions, enough skills in total: (lessons, skill ids).""" + sizes = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + lessons = [l for l, c in sizes.items() if c == per][:count] + return lessons, [s["id"] for s in bank.skills if s["unit"] in lessons] + + +def states(skills, learning=(), mastered=(), **kw): + out = {i: "not_started" for i in skills} + out.update({i: "learning" for i in learning}) + out.update({i: "mastered" for i in mastered}) + return out + + +def per_skill(drawn): + return Counter(q["skill_id"] for q in drawn["questions"]) + + +def test_few_weak_skills_give_one_question_each_and_the_rest_comes_from_other_skills(bank): + lessons, skills = lessons_and_skills(bank) # 8 skills + weak = skills[:3] + got = exam.draw(bank, lessons, states(skills, learning=weak, mastered=skills[3:]), 12, share=0.6, rng=random.Random(1)) + assert len(got["questions"]) == 12 and got["weak"] == weak + counts = per_skill(got) + assert sum(counts[i] for i in weak) == 3 # 7 weak needed, only 3 weak skills: 3 weak questions + assert sum(counts[i] for i in skills[3:]) == 9 # the other 9 from other covered skills + + +def test_enough_weak_skills_give_60_percent_in_test_1_and_30_in_test_2(bank): + lessons, skills = lessons_and_skills(bank, count=3) # 12 skills + weak, others = skills[:9], skills[9:] + st = states(skills, learning=weak, mastered=others) + one = exam.draw(bank, lessons, st, 10, share=exam.EXERCISE_SHARE[1], rng=random.Random(2)) + two = exam.draw(bank, lessons, st, 10, share=exam.EXERCISE_SHARE[2], rng=random.Random(3)) + # the other skills are then drawn from round after round; the weak ones come first, one per skill + assert sum(per_skill(one)[i] for i in weak) >= 6 and sum(per_skill(two)[i] for i in weak) >= 3 + assert len(one["questions"]) == len(two["questions"]) == 10 + + +def test_a_not_started_skill_is_never_drawn_and_is_listed_to_practise_first(bank): + lessons, skills = lessons_and_skills(bank) + st = states(skills, learning=skills[:2], mastered=skills[2:5]) # skills[5:] are not started + got = exam.draw(bank, lessons, st, 12, share=0.6, rng=random.Random(4)) + assert got["practice_first"] == skills[5:] + assert not set(per_skill(got)) & set(skills[5:]) + + +def test_a_skill_answered_wrong_in_an_earlier_exercise_test_counts_as_weak(bank): + lessons, skills = lessons_and_skills(bank) + st = states(skills, mastered=skills) # everything mastered: nothing weak by state + got = exam.draw(bank, lessons, st, 12, share=0.6, weak_before={skills[0], skills[1]}, rng=random.Random(5)) + assert set(got["weak"]) == {skills[0], skills[1]} + assert per_skill(got)[skills[0]] >= 1 and per_skill(got)[skills[1]] >= 1 + + +def test_a_retake_takes_new_questions_while_enough_remain(bank): + lessons, skills = lessons_and_skills(bank) + st = states(skills, learning=skills) + used: Counter = Counter() + first = exam.draw(bank, lessons, st, 12, share=0.6, used=used, rng=random.Random(6)) + used.update(q["key"] for q in first["questions"]) + second = exam.draw(bank, lessons, st, 12, share=0.6, used=used, rng=random.Random(7)) + assert not {q["key"] for q in first["questions"]} & {q["key"] for q in second["questions"]} + + +def test_the_simulation_spreads_one_question_per_skill_round_after_round(bank): + lessons, skills = lessons_and_skills(bank) # 8 skills + st = states(skills, learning=skills[:2], mastered=skills[2:]) + got = exam.draw(bank, lessons, st, 12, share=0.0, rng=random.Random(8)) + counts = per_skill(got) + assert len(got["questions"]) == 12 and set(counts) == set(skills) and sorted(counts.values()) == [1, 1, 1, 1, 2, 2, 2, 2] + assert len({q["key"] for q in got["questions"]}) == 12 + + +def test_nothing_started_gives_no_questions_and_everything_is_listed(bank): + lessons, skills = lessons_and_skills(bank) + got = exam.draw(bank, lessons, states(skills), 12, share=0.6, rng=random.Random(9)) + assert got["questions"] == [] and got["practice_first"] == skills and got["weak"] == [] + + +def test_a_small_pool_gives_what_there_is_and_the_draw_is_repeatable(bank): + lessons, skills = lessons_and_skills(bank, count=1) + st = states(skills, learning=skills[:1]) + few = exam.draw(bank, lessons, st, 40, share=0.6, rng=random.Random(10)) + assert len(few["questions"]) == len(bank.question_keys(skills[0])) # one started skill: its own questions only + a = exam.draw(bank, lessons, states(skills, learning=skills), 12, share=0.6, rng=random.Random(11)) + b = exam.draw(bank, lessons, states(skills, learning=skills), 12, share=0.6, rng=random.Random(11)) + assert a == b diff --git a/mathly2/tests/test_exercise_browser.py b/mathly2/tests/test_exercise_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..bc524f50b5ffa997b27a764da0cb1bd933d0401f --- /dev/null +++ b/mathly2/tests/test_exercise_browser.py @@ -0,0 +1,501 @@ +"""The exercise screen in a real browser: the sheet over the path, tap to answer, help, chips, resuming, closing, and the board.""" +import copy +import uuid +from datetime import date + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.bank import Bank, load_bank, question_key +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID, MGR, DEV = "kid@school.test", "mgr@school.test", "dev@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) +PHONE, DESKTOP = {"width": 390, "height": 844}, {"width": 1280, "height": 800} +SOLVED = {"question": "$x² + 5x + 6$", "answer": "$(x + 2)(x + 3)$", + "steps": [{"do": "מוצאים 2 ו־3", "why": "המכפלה 6 והסכום 5"}, {"do": "כותבים $(x + 2)(x + 3)$", "why": "כך מפרקים"}]} +LONG_AGO = date(2020, 1, 1) + + +@pytest.fixture(scope="module") +def raw(): + return copy.deepcopy(load_bank().data) + + +@pytest.fixture +def world(raw): + data = copy.deepcopy(raw) + plain = [s for s in data["skills"] if len(s.get("questions", [])) >= 4 and not s.get("prereqs")] + bare, solved = plain[0]["id"], plain[1]["id"] + for s in data["skills"]: + if s["id"] == solved: + s["worked_example"] = copy.deepcopy(SOLVED) + bank = Bank(data) + chained = next(s["id"] for s in bank.skills if s.get("prereqs") and s.get("questions")) + store = InMemoryStore() + store.give_role(MGR, "manager", "setup") + store.add_member(store.create_class("setup", "A", lessons=[u["id"] for u in data["units"]])["id"], KID) + app = create_app(Settings(developers=frozenset({DEV})), bank=bank, store=store) + return app, store, bank, {"bare": bare, "solved": solved, "chained": chained} + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def sign_in(browser, url, where="", viewport=PHONE, email=KID): + page = offline_formulas(browser.new_page(viewport=viewport)) + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(url + where) + page.fill("#email", email) + page.click("#dev button") + if not where: # the first screen is the subjects: open math + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + page.errors = errors + return page + + +def open_skill(browser, url, skill, **kw): + page = sign_in(browser, url, f"#/skill/{skill}", **kw) + page.wait_for_selector(".mx-sheet #ex-q") + return page + + +def key_on_screen(page): + return page.get_attribute("#ex-q", "data-key") + + +def choose(page, bank, skill, right=True): + """Tap the right (or a wrong) choice of the question on screen; returns its bank position.""" + key = key_on_screen(page) + question = next(q for q in bank.skill(skill)["questions"] if question_key(skill, q) == key) + wanted = [i for i, c in enumerate(question["choices"]) if bool(c.get("correct")) == right] + if not right: + wanted = [i for i in wanted if question["choices"][i].get("mistake")] or wanted + page.click(f"#ex-choices .ex-choice[data-i='{wanted[0]}']") + return wanted[0] + + +# --- 5.1 the sheet --- + +def test_opening_a_skill_shows_the_sheet_over_the_path_with_its_parts(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + skill = bank.skill(ids["bare"]) + assert page.locator("#path").count() == 1 # the path is still there under the sheet + assert page.get_attribute(".mx-sheet", "role") == "dialog" and page.get_attribute(".mx-sheet", "aria-modal") == "true" + lesson = next(l for l in bank.lessons if l["id"] == skill["unit"]) + head = page.inner_text(".mx-shtop") + assert lesson["name"] in head and skill["name"] in head + assert page.locator("[data-board-toggle]").count() == 1 and page.locator("[data-help]").count() == 1 and page.locator(".mx-x").count() == 1 + assert skill["description"] in page.inner_text(".ex-explain") + total = len(bank.practice_keys(skill["id"])) # practice uses at most 10 questions per skill + assert page.inner_text("#ex-count") == f"שאלה 1 מתוך {total}" and page.locator("#ex-dots i").count() == total + assert page.locator("#ex-q .ex-text").count() == 1 and page.locator("#ex-choices .ex-choice").count() >= 2 + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") and page.errors == [] + + +def test_choices_come_in_a_new_order_and_the_server_grades_by_their_bank_position(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + shuffles = page.evaluate("import('/static/ui.js').then(m => Array.from({length: 12}, () => m.shuffled([0, 1, 2, 3]).join()))") + assert len(set(shuffles)) > 1 # not always the same order + shown = page.eval_on_selector_all("#ex-choices .ex-choice", "els => els.map(e => Number(e.dataset.i))") + assert sorted(shown) == list(range(len(shown))) # every bank position, once + choose(page, bank, ids["bare"], right=True) + page.wait_for_selector("#ex-fb .ex-ok") # graded right whatever the order on screen + + +# --- 5.2 right and wrong answers --- + +def test_a_right_answer_celebrates_counts_and_goes_on_after_a_countdown_that_can_be_skipped(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + first = key_on_screen(page) + choose(page, bank, ids["bare"], right=True) + page.wait_for_selector("#ex-fb .ex-ok") + assert "נכון ✓" in page.inner_text("#ex-fb") and "1 תשובה נכונה ברצף" in page.inner_text("#ex-fb") + assert page.locator(".ex-choice.right").count() == 1 and page.locator(".ex-choice .burst").count() == 1 + assert "בעוד" in page.inner_text("#ex-countdown") + assert page.locator("#ex-dots i.ok").count() == 1 and "שאלה 2 מתוך" in page.inner_text("#ex-count") + page.click("#ex-skip") + page.wait_for_function("(k) => document.getElementById('ex-q').dataset.key !== k", arg=first) + assert page.locator(".ex-choice.right").count() == 0 and page.locator("#ex-fb").inner_text().strip() == "" + + +def test_the_countdown_moves_on_by_itself_and_can_be_stopped(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + first = key_on_screen(page) + choose(page, bank, ids["bare"]) + page.wait_for_function("(k) => document.getElementById('ex-q').dataset.key !== k", arg=first, timeout=8000) # by itself + second = key_on_screen(page) + choose(page, bank, ids["bare"]) + page.click("#ex-pause") + page.wait_for_timeout(3600) + assert key_on_screen(page) == second and page.locator("#ex-fb .ex-ok").count() == 1 # stopped: it stays + + +def test_a_wrong_answer_is_quiet_names_the_mistake_never_marks_the_right_choice_and_gives_another_question(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + first = key_on_screen(page) + question = next(q for q in bank.skill(ids["bare"])["questions"] if question_key(ids["bare"], q) == first) + wrong = choose(page, bank, ids["bare"], right=False) + page.wait_for_selector("#ex-fb .ex-bad") + mistake = bank.mistakes[question["choices"][wrong]["mistake"]] + assert mistake["name"] in page.inner_text("#ex-fb .ex-bad") + assert page.locator(".ex-choice.wrong").count() == 1 and page.locator(".ex-choice.right").count() == 0 # the right one is not shown + assert page.locator("#ex-countdown").count() == 0 and page.locator(".ex-choice .burst").count() == 0 + assert page.locator("#ex-returns").count() == 0 and page.inner_text("#ex-other") == "לשאלה הבאה" # a wrong question does not come back + page.click("#ex-other") + page.wait_for_function("(k) => document.getElementById('ex-q').dataset.key !== k", arg=first) + + +def test_a_mistake_that_names_a_skill_to_go_back_to_links_to_it(browser, world): + app, store, bank, _ = world + skill_id, question, index = next((s["id"], q, i) for s in bank.skills for q in s.get("questions", []) + for i, c in enumerate(q["choices"]) if c.get("mistake") and bank.mistakes[c["mistake"]].get("back")) + store.save_progress(KID_ID, skill_id, current_key=question_key(skill_id, question)) + back = bank.mistakes[question["choices"][index]["mistake"]]["back"] + with running(app) as url: + page = open_skill(browser, url, skill_id) + page.click(f"#ex-choices .ex-choice[data-i='{index}']") + page.wait_for_selector("#ex-fb .ex-bad a") + assert page.get_attribute("#ex-fb .ex-bad a", "href") == f"#/skill/{back}" + page.click("#ex-fb .ex-bad a") + page.wait_for_function("(t) => document.getElementById('ex-title').innerText.includes(t)", arg=bank.skill(back)["name"]) + + +def test_mastering_a_skill_is_announced_and_marked(browser, world): + app, store, bank, ids = world + skill = ids["bare"] + key = bank.question_keys(skill)[0] + store.save_progress(KID_ID, skill, started_at="then", current_key=key) + for n in (1, 2): + store.add_answer(KID_ID, skill, f"old{n}", True, True, None, LONG_AGO) # two right answers long ago, today the third + with running(app) as url: + page = open_skill(browser, url, skill) + choose(page, bank, skill) + page.wait_for_selector("#ex-mastered") + assert "המיומנות נשלטה" in page.inner_text("#ex-mastered") and page.locator(".ex-done").count() == 1 + + +# --- 5.3 help and related skills --- + +def test_help_shows_the_explanation_and_a_solved_example_only_when_there_is_one_and_the_answer_does_not_count(browser, world): + app, store, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + assert page.is_hidden("#ex-helpbox") + page.click("[data-help]") + page.wait_for_selector("#ex-helpbox", state="visible") + assert bank.skill(ids["bare"])["description"] in page.inner_text("#ex-helpbox") and "דוגמה פתורה" not in page.inner_text("#ex-helpbox") + assert "לא תיספר לשליטה" in page.inner_text("#ex-helpbox") + choose(page, bank, ids["bare"]) + page.wait_for_selector("#ex-fb .ex-ok") + assert store.last_counted_answers(KID_ID, ids["bare"], 5) == [] # stored, but not counted toward mastery + assert store.answer_counts(KID_ID, ids["bare"]) # it was stored + page2 = open_skill(browser, url, ids["solved"]) + page2.click("[data-help]") + text = page2.inner_text("#ex-helpbox") + assert "דוגמה פתורה" in text and "מוצאים 2 ו־3" in text and "המכפלה 6 והסכום 5" in text and "תשובה:" in text + + +def test_related_skills_are_chips_that_open_that_skill(browser, world): + app, _, bank, ids = world + skill = bank.skill(ids["chained"]) + needed = bank.skill(skill["prereqs"][0]) + with running(app) as url: + page = open_skill(browser, url, ids["chained"]) + assert needed["name"] in page.inner_text(".ex-related") + page.click(f".ex-related a[href='#/skill/{needed['id']}']") + page.wait_for_function("(t) => document.getElementById('ex-title').innerText.includes(t)", arg=needed["name"]) + assert page.locator("#path").count() == 1 and page.locator(".mx-sheet").count() == 1 # still one sheet over the path + + +# --- 5.4 resuming and stale answers --- + +def test_reopening_a_skill_continues_with_the_question_that_was_on_screen(browser, world): + app, _, _, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + key = key_on_screen(page) + page.click(".mx-x") + page.wait_for_selector(".mx-layer", state="detached") + page.click(f".star[data-skill='{ids['bare']}']") + page.wait_for_selector("#ex-q") + assert key_on_screen(page) == key + + +def test_an_answer_for_a_question_another_tab_replaced_shows_the_current_question(browser, world): + app, store, bank, ids = world + with running(app) as url: + first = open_skill(browser, url, ids["bare"]) + stale = key_on_screen(first) + store.save_progress(KID_ID, ids["bare"], current_key=next(k for k in bank.question_keys(ids["bare"]) if k != stale)) # another tab moved on + choose(first, bank, ids["bare"], right=True) + first.wait_for_selector(".ex-note") + assert "התחלפה" in first.inner_text(".ex-note") and key_on_screen(first) == store.get_progress(KID_ID, ids["bare"])["current_key"] + assert store.answer_counts(KID_ID, ids["bare"]) == {} # the stale answer was not stored + + +def test_a_skill_with_no_questions_says_so(browser, world): + app, _, _, _ = world + with running(app) as url: + page = sign_in(browser, url, "#/skill/a_30_side") + page.wait_for_selector("#no-practice") + assert "אין עדיין שאלות תרגול" in page.inner_text(".mx-sheet") and page.locator("#ex-choices").count() == 0 + + +# --- 5.5 closing, links, the board --- + +def test_closing_the_sheet_shows_the_updated_star_and_escape_and_the_scrim_close_it_too(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = sign_in(browser, url) + page.wait_for_selector(".star") + page.click(f".star[data-skill='{ids['bare']}']") + page.wait_for_selector("#ex-q") + assert page.evaluate("location.hash") == f"#/skill/{ids['bare']}" + choose(page, bank, ids["bare"]) + page.wait_for_selector("#ex-fb .ex-ok") + page.click(".mx-x") + page.wait_for_selector(".mx-layer", state="detached") + assert page.evaluate("location.hash") == "#/subject/math/path" + page.wait_for_function("(id) => document.querySelector(`.star[data-skill='${id}'] .lbl`).innerText.includes('בלמידה')", arg=ids["bare"]) # the star shows its new state + assert page.get_attribute(".star.next", "data-skill") == ids["bare"] # and the owl is on it + page.click(f".star[data-skill='{ids['bare']}']") + page.wait_for_selector("#ex-q") + page.keyboard.press("Escape") + page.wait_for_selector(".mx-layer", state="detached") + page.click(f".star[data-skill='{ids['bare']}']") + page.wait_for_selector("#ex-q") + page.mouse.click(2, 2) # the scrim + page.wait_for_selector(".mx-layer", state="detached") + + +def test_a_link_and_a_reload_open_the_sheet_over_the_path(browser, world): + app, _, _, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + page.reload() + page.wait_for_selector(".mx-sheet #ex-q") + assert page.locator(".trail .star").count() > 0 + + +def test_switching_role_or_signing_out_takes_the_sheet_away(browser, world): + """A modal sheet covers the header, so a person cannot reach these buttons with the mouse while it is open; the shell still + closes it if the role changes or the person signs out some other way (a script click stands in for that).""" + app, _, _, ids = world + with running(app) as url: + page = sign_in(browser, url, f"#/skill/{ids['bare']}", email=DEV) + page.wait_for_selector(".mx-sheet #ex-q") + page.evaluate("document.querySelector('#nav [data-role=manager]').click()") + page.wait_for_selector("#mgr") + assert page.locator(".mx-layer").count() == 0 + page.click("#nav [data-role='student']") + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector("#path") + page.click(".star >> nth=0") + page.wait_for_selector(".mx-sheet") + page.evaluate("document.getElementById('out').click()") + page.wait_for_selector("#signin") + assert page.locator(".mx-layer").count() == 0 + + +def test_the_board_opens_from_the_sheet_beside_it_on_a_desktop_with_a_sketch_per_question(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"], viewport=DESKTOP) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board canvas") + board, sheet = page.locator(".mx-board").bounding_box(), page.locator(".mx-sheet").bounding_box() + assert board["x"] + board["width"] <= sheet["x"] + 2 + blank = page.evaluate("document.querySelector('.mx-board canvas').toDataURL()") + box = page.locator(".mx-board canvas").bounding_box() + page.mouse.move(box["x"] + 60, box["y"] + 150) + page.mouse.down() + page.mouse.move(box["x"] + 200, box["y"] + 220, steps=8) + page.mouse.up() + drawn = page.evaluate("document.querySelector('.mx-board canvas').toDataURL()") + assert drawn != blank + choose(page, bank, ids["bare"]) + page.click("#ex-skip") + page.wait_for_function("(b) => document.querySelector('.mx-board canvas').toDataURL() === b", arg=blank) # the next question starts clean + assert page.locator(".mx-board").count() == 1 and page.get_attribute("[data-board-toggle]", "aria-pressed") == "true" + + +def test_on_a_phone_the_board_covers_the_screen_and_returns_to_the_same_question(browser, world): + app, _, _, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"], viewport=PHONE) + key = key_on_screen(page) + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board.full") + page.click(".mx-board-back") + page.wait_for_function("document.querySelector('.mx-board') === null") + assert key_on_screen(page) == key and page.locator(".mx-sheet").count() == 1 + + +def test_a_skill_with_thirty_questions_says_question_n_of_ten_in_the_browser(browser, world): + app, _, bank, _ = world + big = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 30) + with running(app) as url: + page = open_skill(browser, url, big) + assert page.inner_text("#ex-count") == "שאלה 1 מתוך 10" and page.locator("#ex-dots i").count() == 10 + + +# --- show-answer-pending: the thinking indicator --- + +def test_a_tapped_choice_shows_it_is_being_checked_until_the_slow_answer_arrives(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + held = [] + page.route("**/api/skills/*/answer", lambda route: held.append(route)) # the answer request is held back until the test lets it go + key = key_on_screen(page) + question = next(q for q in bank.skill(ids["bare"])["questions"] if question_key(ids["bare"], q) == key) + right = next(i for i, c in enumerate(question["choices"]) if c.get("correct")) + other = next(i for i, c in enumerate(question["choices"]) if not c.get("correct")) + page.click(f"#ex-choices .ex-choice[data-i='{right}']") + page.wait_for_selector("#ex-thinking") + assert "בודקים" in page.inner_text("#ex-fb") # the line, and the tapped choice spins + tapped = page.locator(f"#ex-choices .ex-choice[data-i='{right}']") + assert "pending" in tapped.get_attribute("class") and tapped.get_attribute("aria-busy") == "true" + assert page.evaluate("(i) => getComputedStyle(document.querySelector(`.ex-choice[data-i='${i}']`), '::after').animationName", right) == "ex-spin" + faded = page.locator(f"#ex-choices .ex-choice[data-i='{other}']") + assert faded.is_disabled() and "dim" in faded.get_attribute("class") # the others step back and cannot be tapped + held[0].continue_() # the answer arrives + page.wait_for_selector("#ex-fb .ex-ok") + assert page.locator("#ex-thinking").count() == 0 and page.locator(".ex-choice.pending, .ex-choice.dim").count() == 0 + assert "right" in page.locator(f"#ex-choices .ex-choice[data-i='{right}']").get_attribute("class") + + +def test_the_indicator_has_words_and_a_still_spinner_with_reduced_motion(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE, reduced_motion="reduce")) + page.goto(f"{url}#/skill/{ids['bare']}") + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector(".mx-sheet #ex-q") + held = [] + page.route("**/api/skills/*/answer", lambda route: held.append(route)) + page.click("#ex-choices .ex-choice >> nth=0") + page.wait_for_selector("#ex-thinking") + assert "בודקים" in page.inner_text("#ex-fb") + assert page.evaluate("document.getAnimations().filter(a => a.animationName === 'ex-spin').length") == 0 # words, but no turning + held[0].continue_() + page.wait_for_selector("#ex-fb .ex-ok, #ex-fb .ex-bad") + + +def test_after_an_error_the_indicator_goes_and_the_choices_work_again(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + page.route("**/api/skills/*/answer", lambda route: route.fulfill(status=500, body='{"detail": "x"}', content_type="application/json")) + page.click("#ex-choices .ex-choice >> nth=0") + page.wait_for_selector("#ex-fb [role=alert]") + assert page.locator("#ex-thinking").count() == 0 and page.locator(".ex-choice.pending, .ex-choice.dim").count() == 0 + assert page.locator("#ex-choices .ex-choice:disabled").count() == 0 + + +# --- mark-wrong-choice --- + +def test_a_wrong_answer_marks_only_the_chosen_choice_with_a_word_and_a_symbol(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + wrong = choose(page, bank, ids["bare"], right=False) + page.wait_for_selector("#ex-fb .ex-bad") + chosen = page.locator(f"#ex-choices .ex-choice[data-i='{wrong}']") + assert "wrong" in chosen.get_attribute("class") and "✗ לא נכון" in chosen.inner_text() # the word is part of the choice, so a screen reader reads it + assert page.locator("#ex-choices .verdict").count() == 1 # nothing else carries a label + assert page.locator("#ex-choices .ex-choice.wrong").count() == 1 and page.locator("#ex-choices .ex-choice.right").count() == 0 + width = page.evaluate("(i) => getComputedStyle(document.querySelector(`.ex-choice[data-i='${i}']`)).borderTopWidth", wrong) + assert width == "3px" # a stronger border than the 2px of the others + assert page.locator("#ex-choices .ex-choice:not(.wrong)").first.evaluate("e => getComputedStyle(e).borderTopWidth") == "2px" + + +# --- ten-question-rounds --- + +def next_after(page): + """Move on after an answer: the right answer's "next" or the wrong answer's "next" (or the result after the last).""" + page.click("#ex-skip, #ex-other, #ex-results") + + +def play(page, bank, skill, rights): + for n, ok in enumerate(rights): + choose(page, bank, skill, right=ok) + page.wait_for_selector("#ex-fb .ex-ok, #ex-fb .ex-bad") + key = key_on_screen(page) + next_after(page) + if n < len(rights) - 1: + page.wait_for_function("(k) => document.querySelector('#ex-q')?.dataset.key !== k", arg=key) + + +def test_the_dots_fill_for_right_and_are_marked_for_wrong_and_the_counter_follows_the_round(browser, world): + app, _, bank, ids = world + with running(app) as url: + page = open_skill(browser, url, ids["bare"]) + assert page.inner_text("#ex-count") == "שאלה 1 מתוך 10" and page.locator("#ex-dots i").count() == 10 + play(page, bank, ids["bare"], [True, False]) + page.wait_for_selector("#ex-q") + assert page.inner_text("#ex-count") == "שאלה 3 מתוך 10" + assert page.locator("#ex-dots i.ok").count() == 1 and page.locator("#ex-dots i.bad").count() == 1 + assert page.locator("#ex-dots i.bad").inner_text() == "✗" + assert "1 נכונות" in page.get_attribute("#ex-dots", "aria-label") or "נענו 2 מתוך 10" in page.get_attribute("#ex-dots", "aria-label") + + +def test_ten_answers_end_the_round_with_a_result_that_survives_a_reload_and_a_new_round_starts_again(browser, world): + app, _, bank, ids = world + skill = ids["bare"] + rights = [True, True, False, True, False, True, True, True, False, True] # 7 right, 3 wrong + with running(app) as url: + page = open_skill(browser, url, skill) + play(page, bank, skill, rights) + page.wait_for_selector("#ex-round") + assert page.inner_text("#ex-score").replace("\n", " ").split()[:3] == ["7", "מתוך", "10"] and page.locator("#ex-q").count() == 0 + assert page.locator("#ex-missed li").count() == 3 and page.inner_text("#ex-count") == "הסבב הסתיים" + assert page.locator("#ex-dots i.ok").count() == 7 and page.locator("#ex-dots i.bad").count() == 3 + assert page.locator("#ex-round .right, #ex-round [data-correct]").count() == 0 # no right answer is shown + page.reload() # the result is still there + page.wait_for_selector("#ex-round") + assert page.locator("#ex-score b").inner_text() == "7" + page.click("#ex-newround") # a new round: ten again, empty dots + page.wait_for_selector("#ex-q") + assert page.inner_text("#ex-count") == "שאלה 1 מתוך 10" and page.locator("#ex-dots i.ok, #ex-dots i.bad").count() == 0 + + +def test_a_wrong_question_is_not_shown_again_in_the_round_in_the_browser(browser, world): + app, _, bank, ids = world + skill = ids["bare"] + with running(app) as url: + page = open_skill(browser, url, skill) + shown = [] + for n in range(10): + shown.append(key_on_screen(page)) + choose(page, bank, skill, right=(n % 2 == 0)) + page.wait_for_selector("#ex-fb .ex-ok, #ex-fb .ex-bad") + next_after(page) + if n < 9: + page.wait_for_function("(k) => document.querySelector('#ex-q')?.dataset.key !== k", arg=shown[-1]) + assert len(set(shown)) == 10 # each question once, none came back + page.wait_for_selector("#ex-round") diff --git a/mathly2/tests/test_figures_browser.py b/mathly2/tests/test_figures_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..f8016870cc10de30e8ddde5eb530d478ebb16001 --- /dev/null +++ b/mathly2/tests/test_figures_browser.py @@ -0,0 +1,58 @@ +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.bank import load_bank +from mathly2.main import create_app +from mathly2.tests.serve import offline_formulas, running + + +def bank_questions(): + return [q for s in load_bank().skills for q in s.get("questions", [])] + + +def test_a_geometry_figure_and_a_graph_are_drawn(): + figure = next(q for q in bank_questions() if "figure" in q) + graph = next(q for q in bank_questions() if "graph" in q) + with running(create_app()) as url, playwright.sync_playwright() as p: + browser = p.chromium.launch() + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) + page.goto(url) + page.evaluate("""async ([figure, graph]) => { + const { figures } = await import('/static/figures.js'); + const box = document.createElement('div'); + box.id = 'probe'; + box.innerHTML = figures(figure) + figures(graph); + document.body.append(box); + }""", [figure, graph]) + assert page.locator("#probe .mx-figure svg").count() == 1 + assert page.locator("#probe .mx-figure svg .s, #probe .mx-figure svg .d").count() >= 1 # a shape was drawn + assert page.locator("#probe .mx-figure text.v").count() >= 1 # with its point names + assert page.locator("#probe .mx-plot svg path.c").count() == 1 + assert page.locator("#probe .mx-plot svg circle").count() == len(graph["graph"]["points"]) + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + browser.close() + + +def test_every_figure_and_graph_in_the_bank_can_be_drawn(): + drawn = [q for q in bank_questions() if "figure" in q or "graph" in q] + assert len(drawn) == 463 + with running(create_app()) as url, playwright.sync_playwright() as p: + browser = p.chromium.launch() + page = offline_formulas(browser.new_page()) + page.goto(url) + failures = page.evaluate("""async (questions) => { + const { figures } = await import('/static/figures.js'); + const bad = []; + questions.forEach((q, i) => { + try { + const holder = document.createElement('div'); + holder.innerHTML = figures(q); + if (!holder.querySelector('svg')) bad.push(i + ': no svg'); + if (/NaN|undefined|Infinity/.test(holder.innerHTML)) bad.push(i + ': bad number'); + } catch (error) { bad.push(i + ': ' + error.message); } + }); + return bad; + }""", drawn) + browser.close() + assert failures == [] diff --git a/mathly2/tests/test_foundation_screens_browser.py b/mathly2/tests/test_foundation_screens_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..db7393f0a3ab5c4b592e3a8778d57b1851efe449 --- /dev/null +++ b/mathly2/tests/test_foundation_screens_browser.py @@ -0,0 +1,364 @@ +"""The foundation's screens in a real browser: the look, the sign-in page, the role switcher and each role's home.""" +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import running + +ADMIN, MGR, TEACHER, KID, DEV, BOTH = ("adm@school.test", "mgr@school.test", "t@school.test", "kid@school.test", + "dev@school.test", "both@school.test") +PHONE, DESKTOP = {"width": 390, "height": 844}, {"width": 1280, "height": 800} + + +def seeded(**settings): + store = InMemoryStore() + store.give_role(ADMIN, "admin", "setup") + store.give_role(MGR, "manager", "setup") + store.give_role(BOTH, "manager", "setup") + app = create_app(Settings(teachers=frozenset({TEACHER}), developers=frozenset({DEV}), **settings), store=store) + return app, store + + +def sign_in(page, url, email): + page.goto(url) + page.fill("#email", email) + page.click("#dev button") + + +def sign_out_and_in(page, email): + page.click("#out") + page.wait_for_selector("form#dev") + page.fill("#email", email) + page.click("#dev button") + + +def no_sideways_scroll(page): + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +def page_for(browser, viewport): + """A page that does not wait for the formula library from the network: these screens show no formulas.""" + page = browser.new_page(viewport=viewport) + page.route("**/mathjax@*/**", lambda route: route.abort()) + return page + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +# --- 4.1 the sky look --- + +def test_the_app_is_always_dark_with_stars_and_the_owl_stops_moving_under_reduced_motion(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + page.goto(url) + page.wait_for_selector(".sky-owl") + colors = {} + for scheme in ("light", "dark"): # a light device still gets the dark sky + page.emulate_media(color_scheme=scheme) + colors[scheme] = page.evaluate("getComputedStyle(document.body).backgroundColor") + assert colors["light"] == colors["dark"] == "rgb(6, 10, 25)" + image = page.evaluate("getComputedStyle(document.body).backgroundImage") + assert image.count("radial-gradient") >= 10 # two glows and the small stars + page.emulate_media(reduced_motion="no-preference") + assert page.evaluate("document.getAnimations().length") > 0 # the owl blinks: the test can see motion + page.emulate_media(reduced_motion="reduce") + assert page.evaluate("document.getAnimations().length") == 0 + + +# --- 4.2 the sign-in page --- + +def test_the_sign_in_page_has_the_logo_the_owl_a_status_line_and_the_dev_form(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + page.goto(url) + page.wait_for_selector("#signin") + assert page.get_attribute("#signin img.logo", "alt") == "לומדים בכיף" and page.locator("#signin .sky-owl").count() == 1 + assert page.evaluate("document.querySelector('#signin img.logo').complete && document.querySelector('#signin img.logo').naturalWidth") > 0 + assert "יש להיכנס" in page.inner_text("#signin .status") and "dev only" in page.inner_text("#signin") + assert page.locator("#google").count() == 0 + no_sideways_scroll(page) + + +STUB = "window.supabase={createClient:()=>({auth:{getSession:async()=>({data:{session:null}}),signInWithOAuth:async()=>({}),signOut:async()=>({})}})}" + + +def with_supabase(): + store = InMemoryStore() + settings = Settings(supabase_url="https://p.supabase.test", supabase_key="pub", supabase_secret="sec") + return create_app(settings, store=store, authenticator=type("A", (), {"user": lambda self, t: None})()) + + +def test_the_real_sign_in_page_has_one_google_button(browser): + with running(with_supabase()) as url: + page = page_for(browser, PHONE) + page.route("**/supabase.js", lambda route: route.fulfill(content_type="text/javascript", body=STUB)) + page.goto(url) + page.wait_for_selector("#google") + assert page.inner_text("#google") == "כניסה עם Google" and page.locator("#signin button").count() == 1 + assert page.locator("form#dev").count() == 0 + + +def test_when_the_sign_in_service_is_down_the_page_says_so_and_offers_to_try_again(browser): + with running(with_supabase()) as url: + page = page_for(browser, PHONE) + page.route("**/supabase.js", lambda route: route.abort()) + page.goto(url) + page.wait_for_selector("#retry") + assert "לא הצלחנו להתחבר" in page.inner_text("#signin .status") + page.unroute("**/supabase.js") + page.route("**/supabase.js", lambda route: route.fulfill(content_type="text/javascript", body=STUB)) + page.click("#retry") + page.wait_for_selector("#google") # the retry worked + + +# --- 4.3 the role switcher --- + +def test_a_manager_who_is_also_a_teacher_gets_two_chips_and_the_last_choice_is_remembered(browser): + app, store = seeded() + store.create_class("setup", "ט'3", lessons=["t"], teacher_email=BOTH) + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, BOTH) + page.wait_for_selector("#nav .roles") + assert [b.inner_text() for b in page.locator("#nav .roles button").all()] == ["מורה", "מנהל כיתות"] + page.wait_for_selector("#teaching") # the first role is the first one shown + page.click("#nav [data-role='manager']") + page.wait_for_selector("#mgr") + assert page.get_attribute("#nav [data-role='manager']", "aria-pressed") == "true" + page.reload() + page.wait_for_selector("#mgr") # remembered on this device + page.click("#nav [data-role='teacher']") + page.wait_for_selector("#teaching") + + +def test_a_person_with_one_role_sees_no_chips_and_a_developer_sees_all_five(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, TEACHER) + page.wait_for_selector("#teaching") + assert page.locator("#nav .roles").count() == 0 + sign_out_and_in(page, DEV) + page.wait_for_selector("#nav .roles") + assert page.locator("#nav .roles button").count() == 5 + + +# --- 4.4 the manager's screens --- + +def fill_class(page, name, lessons, teacher, students): + page.fill("#c-name", name) + for lesson in lessons: + page.check(f"#c-lessons input[value='{lesson}']") + page.fill("#c-teacher", teacher) + page.fill("#c-students", students) + + +@pytest.mark.parametrize("viewport", [PHONE, DESKTOP], ids=["390px", "1280px"]) +def test_a_manager_creates_edits_and_deletes_classes_without_scrolling_sideways(browser, viewport): + app, store = seeded() + with running(app) as url: + page = page_for(browser, viewport) + page.on("dialog", lambda d: d.accept()) + sign_in(page, url, MGR) + page.wait_for_selector("#mgr") + page.click("#new-class") + page.wait_for_selector("#class-form") + assert not page.is_checked("#c-ai") and page.input_value("#c-budget") == "150" # the AI starts off + fill_class(page, "ט'3", ["t", "t2"], "rina@school.test", "a@school.test\nb@school.test") + page.click("#c-save") + page.wait_for_selector("#classes article") + assert "ט'3" in page.inner_text("#classes") and "rina@school.test" in page.inner_text("#classes") and "2 תלמידים" in page.inner_text("#classes") + no_sideways_scroll(page) + page.click("#new-class") + fill_class(page, "ט'4", ["k"], "avi@school.test", "c@school.test") + page.click("#c-save") + page.wait_for_function("document.querySelectorAll('#classes article').length === 2") + if viewport["width"] > 800: + columns = page.evaluate("getComputedStyle(document.getElementById('classes')).gridTemplateColumns.split(' ').length") + assert columns >= 2 # the wide screen is used + page.click("#classes article >> nth=0 >> [data-edit]") + page.wait_for_selector("#class-form") + assert page.input_value("#c-name") == "ט'3" and page.is_checked("#c-lessons input[value='t2']") + page.fill("#c-name", "ט'3 חדשה") + page.uncheck("#c-lessons input[value='t2']") + page.check("#c-ai") + page.click("#c-save") + page.wait_for_selector("#classes article") + assert "ט'3 חדשה" in page.inner_text("#classes") and "AI: פועל" in page.inner_text("#classes") + page.click("#classes article >> nth=0 >> [data-delete]") + page.wait_for_function("document.querySelectorAll('#classes article').length === 1") + assert [c["name"] for c in store.classes()] == ["ט'4"] + page.click("[data-tab='students']") + page.wait_for_selector("#students-list") + assert "c@school.test" in page.inner_text("#students-list") and "ט'4" in page.inner_text("#students-list") + no_sideways_scroll(page) + + +def test_the_editor_shows_why_a_class_was_not_saved(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, MGR) + page.click("#new-class") + fill_class(page, "ט'3", ["t"], "x@school.test", "x@school.test") + page.click("#c-save") + page.wait_for_selector("#mgr .error") + assert "לא יכול להיות גם תלמיד" in page.inner_text("#mgr .error") + + +def test_a_refused_save_shows_the_reason_in_view_keeps_what_was_typed_and_can_then_be_fixed(browser): + app, store = seeded() + cid = store.create_class("setup", "ט'3", lessons=["t", "t2"], teacher_email="old@school.test")["id"] + for email in ("a@school.test", "b@school.test"): + store.add_member(cid, email) + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, DEV) # a developer manages classes too + page.wait_for_selector("#nav .roles") + page.click("#nav [data-role='manager']") + page.click("[data-edit]") + page.wait_for_selector("#class-form") + page.fill("#c-name", "ט'3 חדשה") + page.fill("#c-teacher", "a@school.test") # a student of the class: not allowed + page.evaluate("window.scrollTo(0, document.body.scrollHeight)") # the save button is at the bottom of a long form + page.click("#c-save") + page.wait_for_selector("#form-error") + assert "לא נשמר" in page.inner_text("#form-error") and "לא יכול להיות גם תלמיד" in page.inner_text("#form-error") + assert page.evaluate("(() => { const r = document.getElementById('form-error').getBoundingClientRect(); return r.top >= 0 && r.bottom <= innerHeight; })()") + assert page.input_value("#c-teacher") == "a@school.test" and page.input_value("#c-name") == "ט'3 חדשה" # typed values stay + assert store.get_class(cid)["teacher_email"] == "old@school.test" # nothing was saved + page.fill("#c-teacher", "newteacher@school.test") # fix the one thing + page.click("#c-save") + page.wait_for_selector("#classes article") + saved = store.get_class(cid) + assert (saved["teacher_email"], saved["name"]) == ("newteacher@school.test", "ט'3 חדשה") + assert [m["email"] for m in store.members(cid)] == ["a@school.test", "b@school.test"] + + +# --- 4.5 the teacher's home --- + +def test_a_teacher_adds_three_students_and_removes_one_and_has_no_class_editor(browser): + app, store = seeded() + store.create_class("setup", "ט'3", lessons=["t"], teacher_email=TEACHER) + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, TEACHER) + page.wait_for_selector(".class-card") + page.fill(".emails", "a@school.test, b@school.test\nc@school.test") + page.click(".add-students button") + page.wait_for_function("document.querySelectorAll('.students li').length === 3") + assert "נוספו 3 תלמידים" in page.inner_text(".report") + page.click("[data-remove='a@school.test']") + page.wait_for_function("document.querySelectorAll('.students li').length === 2") + page.fill(".emails", "t@school.test b@school.test") + page.click(".add-students button") + page.wait_for_function("document.querySelector('.report').innerText.includes('כבר היו בכיתה')") + assert "מורה הכיתה לא יכול להיות גם תלמיד בה" in page.inner_text(".report") # the teacher cannot add themselves + assert page.locator("#mgr, #new-class, [data-edit], [data-delete]").count() == 0 + no_sideways_scroll(page) + + +def test_a_teacher_with_no_class_is_told_a_manager_chooses_the_teacher(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, TEACHER) + page.wait_for_selector("#teaching") + assert "מנהל הכיתות קובע" in page.inner_text("#teaching") + + +# --- 4.6 the admin's screen and the access page --- + +def test_an_admin_gives_the_manager_role_to_a_new_email_and_the_last_admin_cannot_step_down(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, ADMIN) + page.wait_for_selector("#accounts") + page.fill("#g-email", "rina@school.test") + page.select_option("#g-role", "manager") + page.click("#give button") + page.wait_for_selector("tr[data-email='rina@school.test']") + assert "מנהל כיתות" in page.inner_text("tr[data-email='rina@school.test']") + page.click(f"tr[data-email='{ADMIN}'] [data-take='admin']") + page.wait_for_selector("#accounts .error") + assert "האחרון" in page.inner_text("#accounts .error") + no_sideways_scroll(page) + + +def test_every_account_can_see_its_own_roles_and_what_they_allow(browser): + app, _ = seeded() + with running(app) as url: + page = page_for(browser, PHONE) + sign_in(page, url, MGR) + page.wait_for_selector("#mgr") + page.click("#access") + page.wait_for_selector("#my-access") + text = page.inner_text("#my-access") + assert MGR in text and "מנהל כיתות" in text and "ליצור, לערוך ולמחוק כיתות" in text and "בלי גישה לנתוני למידה" in text + + +# --- a link lands where it points, and changing role clears it --- + +def test_a_link_and_a_reload_land_where_they_point_and_switching_role_clears_the_address(browser): + app, store = seeded() + store.add_member(store.create_class("setup", "ט'3", lessons=["t"], teacher_email=BOTH)["id"], KID) + store.give_role(KID, "manager", "setup") # two roles, so there is a switcher + with running(app) as url: + page = page_for(browser, PHONE) + page.goto(url + "#/collection") + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector("#collection") # the first screen honours the link + page.reload() + page.wait_for_selector("#collection") + page.click("#nav [data-role='manager']") + page.wait_for_selector("#mgr") + assert page.evaluate("location.hash") == "" # switching role forgets the old address + + +# --- 6.1 the roles end to end --- + +def test_an_admin_a_manager_a_teacher_and_a_student_each_do_their_part(browser): + app, store = seeded() + with running(app) as url: + page = page_for(browser, DESKTOP) + page.on("dialog", lambda d: d.accept()) + sign_in(page, url, ADMIN) + page.wait_for_selector("#accounts") + page.fill("#g-email", "newmgr@school.test") + page.select_option("#g-role", "manager") + page.click("#give button") + page.wait_for_selector("tr[data-email='newmgr@school.test']") + + sign_out_and_in(page, "newmgr@school.test") + page.wait_for_selector("#mgr") # the role given before the first sign-in applies + page.click("#new-class") + fill_class(page, "ט'3", ["t", "t2"], TEACHER, "s1@school.test\ns2@school.test") + page.click("#c-save") + page.wait_for_selector("#classes article") + + sign_out_and_in(page, TEACHER) + page.wait_for_selector(".class-card") + assert page.locator(".students li").count() == 2 + page.fill(".emails", "s3@school.test") + page.click(".add-students button") + page.wait_for_function("document.querySelectorAll('.students li').length === 3") + + sign_out_and_in(page, "s3@school.test") + page.click(".subject-card") # a student of the class sees the subjects, then the home, then the path + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector("#path") + assert [m["user_id"] is not None for m in store.members(store.classes()[0]["id"]) if m["email"] == "s3@school.test"] == [True] + no_sideways_scroll(page) diff --git a/mathly2/tests/test_fresh_files.py b/mathly2/tests/test_fresh_files.py new file mode 100644 index 0000000000000000000000000000000000000000..946f638a95b7cf7afe088be50b0a3ba76e111fce --- /dev/null +++ b/mathly2/tests/test_fresh_files.py @@ -0,0 +1,56 @@ +"""Updates reach every device (serve-fresh-files): the page and its files are revalidated, unchanged files are a 304.""" +from fastapi.testclient import TestClient + +from mathly2.config import Settings +from mathly2.main import create_app + + +def client(): + return TestClient(create_app(Settings())) + + +def test_the_page_and_static_files_must_be_checked_before_reuse(): + c = client() + assert c.get("/").headers["cache-control"] == "no-cache" + for path in ("/static/app.css", "/static/app.js", "/static/logo.svg"): + response = c.get(path) + assert response.status_code == 200 and response.headers["cache-control"] == "no-cache" and response.headers["etag"] + + +def test_an_unchanged_file_is_not_sent_again(): + c = client() + etag = c.get("/static/app.css").headers["etag"] + again = c.get("/static/app.css", headers={"If-None-Match": etag}) + assert again.status_code == 304 and again.content == b"" + + +def test_api_routes_are_unchanged(): + assert "no-cache" not in client().get("/api/health").headers.get("cache-control", "") + + +def test_the_icon_is_served_unchanged_from_mathly1(): + from pathlib import Path + root = Path(__file__).resolve().parents[2] + response = client().get("/static/icons/icon-192.png") + assert response.status_code == 200 and response.headers["content-type"] == "image/png" + assert response.content == (root / "static" / "icons" / "icon-192.png").read_bytes() + + +def test_the_page_loads_with_its_icon_and_no_failed_request_or_console_error(): + import pytest + playwright = pytest.importorskip("playwright.sync_api") + from mathly2.tests.serve import offline_formulas, running + with running(create_app(Settings())) as url, playwright.sync_playwright() as p: + browser = p.chromium.launch() + page = offline_formulas(browser.new_page()) + failed, errors = [], [] + page.on("response", lambda r: failed.append(r.url) if r.status >= 400 else None) + page.on("requestfailed", lambda r: errors.append(r.url) if "mathjax" not in r.url else None) # the test blocks MathJax on purpose + page.on("console", lambda m: errors.append(m.text) if m.type == "error" and "ERR_FAILED" not in m.text else None) + page.goto(url) + page.wait_for_selector("#signin") + page.wait_for_timeout(500) + assert page.get_attribute("link[rel=icon]", "href") == "/static/icons/icon-192.png" + assert page.evaluate("fetch('/static/icons/icon-192.png').then(r => r.status)") == 200 + assert failed == [] and errors == [] + browser.close() diff --git a/mathly2/tests/test_home_browser.py b/mathly2/tests/test_home_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..59c0b09ea3b35a993ad56a6c313f8923c668783b --- /dev/null +++ b/mathly2/tests/test_home_browser.py @@ -0,0 +1,515 @@ +"""The student's home, the bottom tab bar and a test's card in a real browser (add-test-readiness 3.1-3.3, 3.5).""" +import uuid +from collections import Counter +from datetime import timedelta + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2 import clock +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID, TEACHER = "kid@school.test", "t@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) +PHONE = {"width": 360, "height": 800} +PATH_TAB = ".tabs a[href='#/subject/math/path']" + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def world(bank): + sizes = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + lessons = [l for l, c in sizes.items() if c == 4][:2] + store = InMemoryStore() + klass = store.create_class("setup", "A", lessons=lessons, teacher_email=TEACHER) + store.add_member(klass["id"], KID) + return create_app(Settings(), bank=bank, store=store), store, klass, lessons + + +def add_test(store, klass, lessons, days_ahead, set_days_ago=20, **kw): + """A test `days_ahead` days from today that was set `set_days_ago` days ago (so the full plan applies).""" + now = clock.now() + return store.create_test(klass["id"], clock.school_day() + timedelta(days=days_ahead), lessons, TEACHER, + created_at=now - timedelta(days=set_days_ago), **kw) + + +def covered(bank, lessons): + return [s["id"] for s in bank.skills if s["unit"] in lessons and bank.question_keys(s["id"])] + + +def sign_in(browser, url, where="", viewport=PHONE): + page = offline_formulas(browser.new_page(viewport=viewport)) + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(url + where) + page.fill("#email", KID) + page.click("#dev button") + page.errors = errors + return page + + +def to_home(page): + page.click(".subject-card") + page.wait_for_selector(".tabs") + + +def no_sideways_scroll(page): + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +# --- 3.1 the card opens home and the tab bar is at the bottom --- + +def test_the_card_opens_home_and_each_tab_opens_its_screen(browser, bank): + app, _, _, _ = world(bank) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + assert page.evaluate("location.hash") == "#/subject/math" and page.locator(".tabs a[aria-current='page']").inner_text() == "בית" + assert page.locator(".tabs a").all_inner_texts() == ["בית", "מסלול", "ציונים", "האוסף"] + for href, marker in (("#/subject/math/path", ".orbit"), ("#/grades", "#grades"), ("#/collection", "#collection"), ("#/subject/math", "#no-test")): + page.click(f".tabs a[href='{href}']") + page.wait_for_selector(marker) + assert page.errors == [] + + +def test_the_tab_bar_stays_at_the_bottom_with_big_targets_and_covers_nothing(browser, bank): + app, _, _, _ = world(bank) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + page.click(PATH_TAB) + page.wait_for_selector(".orbit") + bar = page.locator(".tabs").bounding_box() + assert abs(bar["y"] + bar["height"] - PHONE["height"]) <= 1 and bar["width"] == PHONE["width"] + for box in [t.bounding_box() for t in page.locator(".tabs a").all()]: + assert box["height"] >= 44 and box["width"] >= 44 + page.evaluate("window.scrollTo(0, document.body.scrollHeight)") + last = page.evaluate("document.querySelector('.trail').lastElementChild.getBoundingClientRect().bottom") + assert last <= page.locator(".tabs").bounding_box()["y"] + 1 # the end of the page is above the bar + no_sideways_scroll(page) + + +def test_a_link_to_a_skill_still_opens_the_path_with_its_sheet(browser, bank): + app, _, _, lessons = world(bank) + skill = covered(bank, lessons)[0] + with running(app) as url: + page = sign_in(browser, url, f"#/skill/{skill}") + page.wait_for_selector(".mx-sheet #ex-q") + assert page.locator("#path").count() == 1 and page.locator(".tabs").count() == 1 + page.click(".mx-x") + page.wait_for_selector(".orbit") + assert page.evaluate("location.hash") == "#/subject/math/path" + + +# --- 3.2 home --- + +def test_with_no_test_home_says_so_and_continues_the_path(browser, bank): + app, _, _, lessons = world(bank) + first = covered(bank, lessons)[0] + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + assert "עוד לא קבע מבחן" in page.inner_text("#no-test") and page.locator("#nearest-test").count() == 0 + assert page.get_attribute("#continue-path", "href") == f"#/skill/{first}" + no_sideways_scroll(page) + + +def test_nine_days_before_the_test_the_button_opens_exercise_test_1_with_the_readiness_bar(browser, bank): + app, store, klass, lessons = world(bank) + skills = covered(bank, lessons) + for i in skills[:6]: + store.save_progress(KID_ID, i, started_at="then", mastered_at="then") # M = 6 of 8 + test = add_test(store, klass, lessons, 9) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + assert "בעוד 9 ימים" in page.inner_text("#nearest-test h2") + assert page.get_attribute("#today-task", "href") == f"#/exam/{test['id']}/1" and "מבחן תרגול 1" in page.inner_text("#today-task") + bar = page.locator("#nearest-test [role=progressbar]") + assert bar.get_attribute("aria-valuenow") == "75" and "75" in bar.get_attribute("aria-label") + parts = page.inner_text(".rd-parts") + assert "M שליטה 75" in parts and "E מבחני תרגול —" in parts and "S סימולציה —" in parts + assert "עוד לא עשיתם מבחן סימולציה" in page.inner_text(".rd-note") + no_sideways_scroll(page) + + +def test_four_days_before_the_test_the_simulation_is_required_on_home(browser, bank): + app, store, klass, lessons = world(bank) + test = add_test(store, klass, lessons, 4) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + required = page.locator(f".required[data-required='{test['id']}']") + assert required.count() == 1 and "חובה" in required.inner_text() and required.get_attribute("href") == f"#/sim/{test['id']}" + assert page.get_attribute("#today-task", "href") == f"#/sim/{test['id']}" + + +def test_the_readiness_bar_shows_every_part_and_loses_the_cap_after_the_simulation(browser, bank): + app, store, klass, lessons = world(bank) + for i in covered(bank, lessons): + store.save_progress(KID_ID, i, started_at="then", mastered_at="then") + test = add_test(store, klass, lessons, 3) + now = clock.now() + for scope, kind, grade in ((f"{test['id']}:1", "exercise_test", 60), (f"{test['id']}:2", "exercise_test", 80), (str(test["id"]), "simulation", 90)): + row = store.create_attempt(KID_ID, kind, scope, now - timedelta(days=1), now - timedelta(days=1) + timedelta(minutes=45), []) + store.save_attempt(row["id"], submitted_at=now - timedelta(days=1) + timedelta(minutes=5), grade=grade) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + parts = page.inner_text(".rd-parts") + assert "M שליטה 100" in parts and "E מבחני תרגול 70" in parts and "S סימולציה 90" in parts + assert page.locator(".rd-note").count() == 0 and "מוכנים" in page.inner_text(".rd-label") + assert page.locator(".required").count() == 0 # the simulation is taken + + +def test_other_tests_are_listed_small_and_the_closest_one_gives_the_task(browser, bank): + app, store, klass, lessons = world(bank) + far = add_test(store, klass, lessons, 20) + near = add_test(store, klass, lessons, 9) + with running(app) as url: + page = sign_in(browser, url) + to_home(page) + assert page.get_attribute("#nearest-test", "data-test") == str(near["id"]) + assert page.locator("#other-tests li").count() == 1 and page.get_attribute("#other-tests a", "href") == f"#/test/{far['id']}" + + +# --- 3.3 a test's card --- + +def card_page(browser, url, test_id): + page = sign_in(browser, url, f"#/test/{test_id}") + page.wait_for_selector("#test-card") + return page + + +def finished(store, scope, kind, grade, questions=None, answers=None): + now = clock.now() + row = store.create_attempt(KID_ID, kind, scope, now - timedelta(days=1), now - timedelta(days=1) + timedelta(minutes=45), questions or []) + return store.save_attempt(row["id"], submitted_at=now - timedelta(days=1) + timedelta(minutes=9), grade=grade, answers=answers or {}) + + +def test_a_fresh_card_shows_the_plan_the_exercise_tests_what_to_practise_first_and_when_the_simulation_opens(browser, bank): + app, store, klass, lessons = world(bank) + skills = covered(bank, lessons) + store.save_progress(KID_ID, skills[0], started_at="then", mastered_at="then") + test = add_test(store, klass, lessons, 14, questions=10, minutes=30) + with running(app) as url: + page = card_page(browser, url, test["id"]) + assert "10 שאלות · 30 דקות" in page.inner_text("#test-card") and "בעוד 14 ימים" in page.inner_text("#test-card h2") + steps = page.locator("#plan li") + assert steps.count() == 5 and [steps.nth(i).get_attribute("data-step") for i in range(5)] == ["path", "ex1", "ex2", "sim", "review"] + assert "עד 9 ימים לפני" in steps.nth(0).inner_text() and "בערך 9 ימים לפני" in steps.nth(1).inner_text() and "בערך 5 ימים לפני" in steps.nth(3).inner_text() + assert page.locator("#plan li.done").count() == 0 + assert page.locator("#exercises li").count() == 2 and "עוד לא נעשה" in page.inner_text("#exercises li >> nth=0") + assert page.get_attribute("#exercises li[data-exercise='2'] a", "href") == f"#/exam/{test['id']}/2" and "התחלה" in page.inner_text("#exercises li >> nth=1") + assert page.locator("#practice-first a").count() == 7 # eight covered skills, one started + assert "ייפתח ב־" in page.inner_text("#sim-closed") and page.locator("#sim-start").count() == 0 + no_sideways_scroll(page) + + +def test_exercise_tests_show_their_best_grade_and_offer_a_retake_or_to_continue(browser, bank): + app, store, klass, lessons = world(bank) + test = add_test(store, klass, lessons, 10) + finished(store, f"{test['id']}:1", "exercise_test", 55) + finished(store, f"{test['id']}:1", "exercise_test", 80) + now = clock.now() + store.create_attempt(KID_ID, "exercise_test", f"{test['id']}:2", now, now + timedelta(minutes=45), []) # exercise test 2 is open + with running(app) as url: + page = card_page(browser, url, test["id"]) + one, two = page.locator("#exercises li[data-exercise='1']"), page.locator("#exercises li[data-exercise='2']") + assert "הציון הטוב: 80" in one.inner_text() and "2 ניסיונות" in one.inner_text() and "שוב" in one.locator("a").inner_text() + assert "להמשיך" in two.locator("a").inner_text() + assert page.locator("#plan li[data-step='ex1'].done").count() == 1 and page.locator("#plan li[data-step='ex2'].done").count() == 0 + + +def test_an_open_simulation_is_required_and_a_taken_one_shows_its_grade_and_review_skills(browser, bank): + app, store, klass, lessons = world(bank) + skills = covered(bank, lessons) + test = add_test(store, klass, lessons, 4) + with running(app) as url: + page = card_page(browser, url, test["id"]) + assert page.locator("#simulation .req").count() == 1 and page.get_attribute("#sim-start", "href") == f"#/sim/{test['id']}" + assert "התחלה" in page.inner_text("#sim-start") + questions = [{"skill_id": skills[0], "key": bank.question_keys(skills[0])[0]}, {"skill_id": skills[1], "key": bank.question_keys(skills[1])[0]}] + finished(store, str(test["id"]), "simulation", 0, questions=questions) # nothing answered: both skills failed + page.reload() + page.wait_for_selector("#simulation[data-taken='true']") + assert page.inner_text("#sim-grade") == "0" and page.locator("#sim-start").count() == 0 + assert [a.get_attribute("href") for a in page.locator("#sim-review a").all()] == [f"#/skill/{skills[0]}", f"#/skill/{skills[1]}"] + assert page.locator("#plan li[data-step='sim'].done").count() == 1 + + +def test_a_test_of_another_class_or_a_missing_one_shows_an_error(browser, bank): + app, _, _, _ = world(bank) + with running(app) as url: + page = sign_in(browser, url, "#/test/999") + page.wait_for_selector("[role=alert]") + assert "לא נמצא" in page.inner_text("[role=alert]") + + +# --- 3.4 the same sheet runs exercise tests and the simulation --- + +def started_skills(store, bank, lessons, n=5): + skills = covered(bank, lessons) + for i in skills[:n]: + store.save_progress(KID_ID, i, started_at="then") + return skills + + +def test_an_exercise_test_runs_with_the_tests_length_and_timer_and_links_its_weak_skills_at_the_end(browser, bank): + app, store, klass, lessons = world(bank) + skills = started_skills(store, bank, lessons) + test = add_test(store, klass, lessons, 10, questions=6, minutes=30) + with running(app) as url: + page = sign_in(browser, url, f"#/exam/{test['id']}/1") + page.wait_for_selector("#qz-q") + assert page.evaluate("location.hash").startswith(f"#/exam/{test['id']}/1/") # the address names the attempt + assert "מבחן תרגול 1" in page.inner_text(".mx-sheet") and page.locator(".qz-dot").count() == 6 + assert page.inner_text("#qz-timer").startswith("29:") or page.inner_text("#qz-timer") == "30:00" + sheet = page.inner_text(".mx-sheet") + assert not any(bank.skill(i)["name"] in sheet for i in skills) # no skill names, no feedback + page.click("#qz-submit") + page.click("#qz-yes") + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "0" and "תוצאת מבחן תרגול 1" in page.inner_text(".mx-sheet") + links = [a.get_attribute("href") for a in page.locator("#qz-lost a").all()] + assert links and all(h.startswith("#/skill/") and h[8:] in skills for h in links) # weak skills link to their stars + assert page.locator("#qz-retake").inner_text() == "מבחן חוזר" + page.click("#qz-retake") # a retake is a new attempt + page.wait_for_selector("#qz-q") + assert len(store.attempts_of(KID_ID, "exercise_test", f"{test['id']}:1")) == 2 + page.click(".mx-x") + page.wait_for_selector("#test-card") # closing leads back to the test's card + assert page.evaluate("location.hash") == f"#/test/{test['id']}" + + +def test_the_simulation_can_be_taken_once_and_a_second_visit_shows_the_result(browser, bank): + app, store, klass, lessons = world(bank) + started_skills(store, bank, lessons) + test = add_test(store, klass, lessons, 4, questions=6, minutes=45) + with running(app) as url: + page = sign_in(browser, url, f"#/sim/{test['id']}") + page.wait_for_selector("#qz-q") + assert "מבחן סימולציה" in page.inner_text(".mx-sheet") and page.locator(".qz-dot").count() == 6 + page.click("#qz-submit") + page.click("#qz-yes") + page.wait_for_selector("#qz-grade") + assert page.locator("#qz-retake").count() == 0 and "פעם אחת" in page.inner_text(".qz-result") + page.goto(url + f"#/sim/{test['id']}") # opening it again + page.reload() + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "0" and page.locator("#qz-q").count() == 0 + assert len(store.attempts_of(KID_ID, "simulation")) == 1 + page.click(".qz-actions [data-close]") + page.wait_for_selector("#test-card") + assert page.inner_text("#sim-grade") == "0" + + +def test_the_simulation_before_its_window_says_when_it_opens_and_does_not_start(browser, bank): + app, store, klass, lessons = world(bank) + started_skills(store, bank, lessons) + test = add_test(store, klass, lessons, 14) + with running(app) as url: + page = sign_in(browser, url, f"#/sim/{test['id']}") + page.wait_for_selector("[role=alert]") + assert "ייפתח" in page.inner_text("[role=alert]") and page.locator("#qz-q").count() == 0 + assert store.attempts_of(KID_ID, "simulation") == [] + + +# --- 3.5 the grades screen has exercise tests and simulations --- + +def test_exercise_tests_and_the_simulation_appear_on_the_grades_screen(browser, bank): + app, store, klass, lessons = world(bank) + test = add_test(store, klass, lessons, 6) + removed = add_test(store, klass, lessons, 12) + finished(store, f"{test['id']}:1", "exercise_test", 55) + finished(store, f"{test['id']}:1", "exercise_test", 80) + finished(store, f"{test['id']}:2", "exercise_test", 70) + finished(store, str(test["id"]), "simulation", 65) + finished(store, f"{removed['id']}:1", "exercise_test", 90) + store.remove_test(removed["id"]) + with running(app) as url: + page = sign_in(browser, url, "#/grades") + page.wait_for_selector("#exercise-grades") + one = page.locator(f"#exercise-grades li[data-test='{test['id']}'][data-number='1']") + assert one.locator(".gr-num").inner_text() == "80" and "2 ניסיונות" in one.inner_text() and "מבחן תרגול 1" in one.inner_text() + assert page.locator(f"#exercise-grades li[data-test='{test['id']}'][data-number='2'] .gr-num").inner_text() == "70" + assert page.locator(f"#simulation-grades li[data-test='{test['id']}'] .gr-num").inner_text() == "65" + gone = page.locator(f"#exercise-grades li[data-test='{removed['id']}']") + assert gone.locator(".gr-num").inner_text() == "90" and "הוסר" in gone.inner_text() # a removed test keeps its grade and name + assert page.locator("#no-grades").count() == 0 and page.locator("#quiz-grades").count() == 0 + no_sideways_scroll(page) + page.click(f"#simulation-grades li[data-test='{test['id']}'] a") + page.wait_for_selector("#test-card") + + +# --- 4.1 the teacher's tests tab --- + +DESKTOP = {"width": 1280, "height": 800} + + +def teacher_page(browser, url, viewport=PHONE): + page = offline_formulas(browser.new_page(viewport=viewport)) + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(url) + page.fill("#email", TEACHER) + page.click("#dev button") + page.wait_for_selector("#teaching") + page.click("#teacher-tabs [data-tab='tests']") + page.wait_for_selector("#tests") + page.errors = errors + return page + + +def iso(days): + return (clock.school_day() + timedelta(days=days)).isoformat() + + +@pytest.mark.parametrize("viewport", [PHONE, DESKTOP]) +def test_a_teacher_sets_a_test_with_the_defaults_moves_its_date_and_removes_it(browser, bank, viewport): + app, store, klass, lessons = world(bank) + with running(app) as url: + page = teacher_page(browser, url, viewport) + assert "עוד לא נקבע מבחן" in page.inner_text(".class-tests") + page.click(".set-test summary") + assert page.input_value("[name=questions]") == "12" and page.input_value("[name=minutes]") == "45" # the defaults + page.fill("[name=date]", iso(10)) + page.fill("[name=note]", "פרק 3") + page.click(".set-test button[type=submit]") + page.wait_for_selector(".test-row") + row = page.locator(".test-row") + assert "12 שאלות" in row.inner_text() and "45 דקות" in row.inner_text() and "בעוד 10 ימים" in row.inner_text() and "פרק 3" in row.inner_text() + assert [t["questions"] for t in store.tests_of_classes([klass["id"]])] == [12] + page.click("[data-edit]") # move the date two days later + page.fill(".edit-slot [name=date]", iso(12)) + page.click(".edit-slot button[type=submit]") + page.wait_for_function("document.querySelector('.test-row h4').innerText.includes('בעוד 12 ימים')") + page.click("[data-remove-test]") # removing takes two steps + page.click("[data-confirm-remove]") + page.wait_for_selector(".test-row", state="detached") + assert store.tests_of_classes([klass["id"]]) == [] and len(store.tests_of_classes([klass["id"]], include_removed=True)) == 1 + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + assert page.errors == [] + + +def test_the_tab_shows_who_has_not_taken_the_simulation_and_each_students_readiness(browser, bank): + app, store, klass, lessons = world(bank) + others = ["a@school.test", "b@school.test"] + for email in others: + store.add_member(klass["id"], email) + test = add_test(store, klass, lessons, 5) + now = clock.now() + row = store.create_attempt(KID_ID, "simulation", str(test["id"]), now - timedelta(days=1), now - timedelta(days=1) + timedelta(minutes=45), []) + store.save_attempt(row["id"], submitted_at=now - timedelta(days=1) + timedelta(minutes=5), grade=75) + store.link_user(KID, KID_ID) + with running(app) as url: + page = teacher_page(browser, url) + assert "1 מתוך 3 עשו סימולציה" in page.inner_text(".sim-count") + missing = page.inner_text(".sim-missing") + assert "a@school.test" in missing and "b@school.test" in missing and KID not in missing + assert page.locator(".readiness-table tbody tr").count() == 3 + mine = page.locator(f".readiness-table tr:has-text('{KID}')") + assert "28" in mine.inner_text() and "75" in mine.inner_text() and "0%" in mine.inner_text() # M 0 and S 75: (30*75) / 80 + + +def test_a_refused_test_shows_why_and_keeps_what_was_typed(browser, bank): + app, store, klass, lessons = world(bank) + with running(app) as url: + page = teacher_page(browser, url) + page.click(".set-test summary") + page.fill("[name=date]", iso(10)) + page.fill("[name=note]", "לא לאבד") + for box in page.locator(".set-test [name=lessons]").all(): + box.uncheck() # no lesson: the server refuses + page.click(".set-test button[type=submit]") + page.wait_for_selector(".set-test .form-error:not([hidden])") + assert page.input_value(".set-test [name=note]") == "לא לאבד" and page.input_value(".set-test [name=date]") == iso(10) + assert store.tests_of_classes([klass["id"]]) == [] + + +# --- 5.1 the whole countdown --- + +def answer_in_browser(page, bank, store, kind, scope, rights): + """Answer the open attempt on screen right or wrong, one flag per question, moving with "next"; then submit.""" + page.wait_for_selector("#qz-q") + refs = store.attempts_of(KID_ID, kind, scope)[-1]["questions"] + for n, ok in enumerate(rights): + key = page.get_attribute("#qz-q", "data-key") + question = bank._questions[key.split(":")[0]][key] + picks = [i for i, c in enumerate(question["choices"]) if bool(c.get("correct")) == ok] + page.click(f"#qz-choices .qz-choice[data-i='{picks[0]}']") + if n < len(rights) - 1: + page.click(".qz-nav button >> nth=1") + page.wait_for_function("(k) => document.querySelector('#qz-q').dataset.key !== k", arg=key) + page.click("#qz-submit") + page.wait_for_selector("#qz-grade") + return refs + + +def test_the_whole_countdown_from_setting_a_test_to_the_review(browser, bank, monkeypatch): + app, store, klass, lessons = world(bank) + moment = {"now": clock.now()} + monkeypatch.setattr(clock, "now", lambda: moment["now"]) + advance = lambda days: moment.update(now=moment["now"] + timedelta(days=days)) + skills = covered(bank, lessons) + with running(app) as url: + teacher = teacher_page(browser, url) # the teacher sets a test 12 days ahead, 6 questions + teacher.click(".set-test summary") + teacher.fill("[name=date]", iso(12)) + teacher.fill("[name=questions]", "6") + teacher.click(".set-test button[type=submit]") + teacher.wait_for_selector(".test-row") + test = store.tests_of_classes([klass["id"]])[0] + student = sign_in(browser, url) + to_home(student) + task = lambda: student.get_attribute("#today-task", "href") + reload_home = lambda: (student.goto(url + "#/subject/math"), student.reload(), student.wait_for_selector(".tabs"), student.wait_for_selector("#today-task")) + + assert task() == f"#/skill/{skills[0]}" and "לסיים את המסלול" in student.inner_text("#today-task") # 12 days: finish the path + assert "סימולציה" in student.inner_text(".rd-note") # the bar says it is capped until the simulation + for i in skills: # the path is finished + store.save_progress(KID_ID, i, started_at="then", mastered_at="then") + reload_home() + assert task() == f"#/exam/{test['id']}/1" # next: exercise test 1, early + student.click("#today-task") + answer_in_browser(student, bank, store, "exercise_test", f"{test['id']}:1", [True] * 6) + assert student.inner_text("#qz-grade b") == "100" + advance(3) # 9 days left + reload_home() + assert task() == f"#/exam/{test['id']}/2" # exercise test 2 + student.click("#today-task") + answer_in_browser(student, bank, store, "exercise_test", f"{test['id']}:2", [True] * 6) + advance(4) # 5 days left: the simulation opens + reload_home() + assert task() == f"#/sim/{test['id']}" and student.locator(f".required[data-required='{test['id']}']").count() == 1 + before = student.inner_text(".rd-parts") + assert "E מבחני תרגול 100" in before and "S סימולציה —" in before + student.click("#today-task") + answer_in_browser(student, bank, store, "simulation", str(test["id"]), [True, True, True, True, False, False]) + assert student.inner_text("#qz-grade b") == "67" + failed = [a.get_attribute("href") for a in student.locator("#qz-lost a").all()] + assert failed + advance(2) # 3 days left: review what failed + reload_home() + assert task() in failed and student.locator(".required").count() == 0 # a failed skill is today's review + assert "S סימולציה 67" in student.inner_text(".rd-parts") and student.locator(".rd-note").count() == 0 # the cap is gone after the simulation + teacher.reload() + teacher.click("#teacher-tabs [data-tab='tests']") + teacher.wait_for_selector(".test-row") + assert "1 מתוך 1 עשו סימולציה" in teacher.inner_text(".sim-count") diff --git a/mathly2/tests/test_learning.py b/mathly2/tests/test_learning.py new file mode 100644 index 0000000000000000000000000000000000000000..82932d958b08acc2dc3e2639c7a8751a5f52842e --- /dev/null +++ b/mathly2/tests/test_learning.py @@ -0,0 +1,223 @@ +import random +from datetime import date, timedelta + +import pytest + +from mathly2.learning import (LEARNING, MASTERED, NOT_STARTED, current_round, is_mastered, mark_started, next_in_round, next_skill, + record_practice_answer, skill_state, streak, today_progress) +from mathly2.store import InMemoryStore + +U, S = "u-1", "skill-1" +MON, TUE = date(2026, 11, 2), date(2026, 11, 3) +NOW = "2026-11-02T10:00:00+00:00" + + +@pytest.fixture +def store(): + return InMemoryStore() + + +def answer(store, n, correct, day, counted=True): + return record_practice_answer(store, U, S, f"{S}:q{n}", correct, counted, None if correct else "m1", day, NOW) + + +def state(store): + return skill_state(store.get_progress(U, S)) + + +# --- the mastery rule (spec: skill-mastery) --- + +def test_mastered_over_two_days(store): + answer(store, 1, True, MON) + answer(store, 2, True, MON) + assert state(store) == LEARNING + answer(store, 3, True, TUE) + assert state(store) == MASTERED + + +def test_three_in_a_row_on_one_day_is_not_yet_mastered(store): + for n in (1, 2, 3): + answer(store, n, True, MON) + assert state(store) == LEARNING + answer(store, 4, True, TUE) # the last 3 are now Mon, Mon, Tue + assert state(store) == MASTERED + + +def test_help_opened_skips_the_answer_without_breaking_the_run(store): + answer(store, 1, True, MON) + answer(store, 2, True, MON) + answer(store, 3, True, MON, counted=False) # helped: ignored for mastery + assert state(store) == LEARNING # a helped answer cannot be the third + answer(store, 4, True, TUE) + assert state(store) == MASTERED # Mon, Mon, Tue: the run survived the helped answer + + +def test_a_wrong_answer_restarts_the_run(store): + answer(store, 1, True, MON) + answer(store, 2, True, MON) + answer(store, 3, False, MON) + answer(store, 4, True, TUE) + assert state(store) == LEARNING # the last 3 are correct, wrong, correct + answer(store, 5, True, TUE) + answer(store, 6, True, TUE + timedelta(days=1)) + assert state(store) == MASTERED + + +def test_a_wrong_answer_months_later_does_not_undo_mastery(store): + answer(store, 1, True, MON) + answer(store, 2, True, MON) + answer(store, 3, True, TUE) + first = store.get_progress(U, S)["mastered_at"] + answer(store, 4, False, date(2027, 3, 8)) + assert state(store) == MASTERED + assert store.get_progress(U, S)["mastered_at"] == first + + +def test_mastered_at_is_set_once(store): + answer(store, 1, True, MON) + answer(store, 2, True, MON) + record_practice_answer(store, U, S, "k3", True, True, None, TUE, "2026-11-03T08:00:00+00:00") + record_practice_answer(store, U, S, "k4", True, True, None, TUE, "2026-11-09T08:00:00+00:00") + assert store.get_progress(U, S)["mastered_at"] == "2026-11-03T08:00:00+00:00" + + +def test_is_mastered_needs_exactly_the_last_three(): + a = lambda correct, day: {"correct": correct, "day": day} + assert not is_mastered([]) + assert not is_mastered([a(True, MON), a(True, TUE)]) + assert is_mastered([a(False, MON), a(True, MON), a(True, MON), a(True, TUE)]) + + +# --- skill states --- + +def test_skill_states(store): + assert skill_state(None) == NOT_STARTED + assert state(store) == NOT_STARTED + store.save_progress(U, S, current_key="k") # a row without started_at is still not started + assert state(store) == NOT_STARTED + + +def test_a_why_answer_moves_a_skill_to_learning_but_cannot_master_it(store): + mark_started(store, U, S, NOW) + assert state(store) == LEARNING + for _ in range(5): + mark_started(store, U, S, NOW) + assert state(store) == LEARNING # only practice answers can master + assert store.get_progress(U, S)["started_at"] == NOW + + +def test_first_practice_answer_moves_not_started_to_learning(store): + answer(store, 1, False, MON) + assert state(store) == LEARNING + + +# --- the round: each question of a skill once --- + +KEYS = [f"k{i}" for i in range(10)] + + +def rows(*pairs): + return [{"question_key": k, "correct": ok, "counted": True, "day": MON, "mistake_id": None} for k, ok in pairs] + + +def test_a_round_asks_every_question_once_and_ends_when_all_are_answered(): + rng, answered, last, shown = random.Random(1), [], None, [] + left = list(KEYS) + while True: + nxt = next_in_round(left, last, rng) + if nxt is None: + break + shown.append(nxt) + answered.append((nxt, len(shown) % 3 != 0)) # every third answer wrong + last = nxt + left = current_round(KEYS, rows(*answered), 0)["left"] + assert sorted(shown) == sorted(KEYS) and len(set(shown)) == 10 # each once, a wrong one does not come back + assert current_round(KEYS, rows(*answered), 0)["done"] is True + + +def test_the_round_is_the_answers_since_its_start_and_no_start_means_a_new_round_begins(): + old = rows(("k0", True), ("k1", False), ("k2", True)) + assert current_round(KEYS, old, None) == {"answers": [], "left": KEYS, "done": False} # an old student: everything so far is past + now = old + rows(("k5", True), ("k6", False)) + got = current_round(KEYS, now, 3) + assert [a["question_key"] for a in got["answers"]] == ["k5", "k6"] and got["left"] == [k for k in KEYS if k not in ("k5", "k6")] and not got["done"] + + +def test_a_question_not_in_the_round_or_repeated_is_ignored_and_a_skill_with_no_questions_is_never_done(): + got = current_round(["a", "b"], rows(("a", True), ("a", False), ("zzz", True)), 0) + assert [a["question_key"] for a in got["answers"]] == ["a"] and got["left"] == ["b"] and not got["done"] + assert current_round([], [], 0)["done"] is False + + +def test_next_in_round_is_never_the_one_just_answered_and_none_when_nothing_is_left(): + rng = random.Random(2) + for _ in range(50): + assert next_in_round(["k1", "k2", "k3"], "k2", rng) != "k2" + assert next_in_round([]) is None and next_in_round(["k1"], "k1") is None + assert next_in_round(["only"]) == "only" # a skill with one question: a round of one + + +# --- daily goal and streak --- + +TODAY = date(2026, 11, 10) + + +def test_goal_missed_and_reached(): + assert today_progress({TODAY: 3}, TODAY) == {"done": 3, "goal": 5, "reached": False} + assert today_progress({TODAY: 5}, TODAY)["reached"] is True + assert today_progress({}, TODAY)["done"] == 0 + + +def test_streak_counts_today_once_it_reaches_five(): + assert streak({TODAY: 5, TODAY - timedelta(days=1): 6}, TODAY) == 2 + + +def test_streak_is_kept_before_todays_five(): + daily = {TODAY: 3, TODAY - timedelta(days=1): 5, TODAY - timedelta(days=2): 7} + assert streak(daily, TODAY) == 2 + + +def test_streak_breaks_after_a_missed_day(): + daily = {TODAY: 5, TODAY - timedelta(days=1): 4, TODAY - timedelta(days=2): 9} + assert streak(daily, TODAY) == 1 + assert streak({TODAY - timedelta(days=2): 9}, TODAY) == 0 + assert streak({}, TODAY) == 0 + + +# --- the next skill (add-learning-core 1.4; spec: Next skill) --- + +ORDER = ["a", "b", "c", "d"] + + +def test_a_new_student_gets_the_first_skill(): + assert next_skill(ORDER, {}, []) == "a" + + +def test_the_marker_stays_on_the_skill_answered_last_while_it_is_not_mastered(): + states = {"a": MASTERED, "b": LEARNING, "c": LEARNING} + assert next_skill(ORDER, states, ["c", "b", "a"]) == "c" # c was answered most recently + + +def test_when_the_last_answer_mastered_a_skill_it_goes_to_the_most_recent_unmastered_one(): + states = {"a": MASTERED, "b": LEARNING, "c": MASTERED} + assert next_skill(ORDER, states, ["c", "b", "a"]) == "b" + + +def test_when_every_recent_skill_is_mastered_it_goes_to_the_first_unmastered_in_order(): + states = {"c": MASTERED, "d": MASTERED} + assert next_skill(ORDER, states, ["d", "c"]) == "a" + + +def test_when_everything_is_mastered_nothing_is_marked(): + assert next_skill(ORDER, {k: MASTERED for k in ORDER}, ["a", "b"]) is None + + +def test_skills_outside_the_students_lessons_never_carry_the_marker(): + assert next_skill(ORDER, {}, ["elsewhere", "b"]) == "b" + assert next_skill([], {}, ["a"]) is None + + +def test_the_marker_never_changes_the_states_or_the_order(): + states, order = {"a": LEARNING}, list(ORDER) + next_skill(order, states, ["a"]) + assert states == {"a": LEARNING} and order == ORDER diff --git a/mathly2/tests/test_migrations.py b/mathly2/tests/test_migrations.py index d3c25e19097c70e9f2cb1be6ac8ac87c0ebbcb4d..04a55c5d04dd26128f2751115280500b32d35e8c 100644 --- a/mathly2/tests/test_migrations.py +++ b/mathly2/tests/test_migrations.py @@ -49,12 +49,250 @@ def test_row_level_security_is_on_and_has_no_policies(db): assert policies == 0 -def test_a_student_email_can_belong_to_only_one_class(db): +def _class(c, name, teacher=None, lessons="{t}"): + return c.execute("insert into public.m2_classes(name, teacher_email, created_by, lessons) values (%s, %s, 'mgr@school.test', %s) returning id", + (name, teacher, lessons)).fetchone()[0] + + +def test_a_student_can_be_in_several_classes_but_only_once_in_each(db): + with psycopg.connect(db, autocommit=True) as c: + a, b = _class(c, "ו'1"), _class(c, "ו'2") + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'multi@school.test')", (a,)) + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'multi@school.test')", (b,)) + with pytest.raises(psycopg.errors.UniqueViolation): + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'multi@school.test')", (a,)) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'UPPER@school.test')", (a,)) + + +def test_class_names_are_unique_ignoring_case_across_creators(db): + with psycopg.connect(db, autocommit=True) as c: + _class(c, "Dalet") + with pytest.raises(psycopg.errors.UniqueViolation): + _class(c, "dALET", teacher="someone@school.test") + + +def test_a_class_can_have_no_teacher_and_has_the_ai_off_with_150_checks(db): + with psycopg.connect(db, autocommit=True) as c: + cid = _class(c, "ז'1") + assert c.execute("select teacher_email, ai_enabled, ai_daily_checks, lessons from public.m2_classes where id = %s", (cid,)).fetchone() == (None, False, 150, ["t"]) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("update public.m2_classes set ai_daily_checks = -1 where id = %s", (cid,)) + + +def test_a_teacher_cannot_also_be_a_student_of_the_same_class(db): + with psycopg.connect(db, autocommit=True) as c: + cid = _class(c, "ח'7", teacher="teach@school.test") + with pytest.raises(psycopg.errors.CheckViolation, match="teacher_is_student"): + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'teach@school.test')", (cid,)) + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'kid7@school.test')", (cid,)) + with pytest.raises(psycopg.errors.CheckViolation, match="teacher_is_student"): + c.execute("update public.m2_classes set teacher_email = 'kid7@school.test' where id = %s", (cid,)) + other = _class(c, "ח'8") + c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'teach@school.test')", (other,)) # a student elsewhere is fine + + +def test_roles_accept_only_the_four_grantable_ones_in_lower_case(db): + with psycopg.connect(db, autocommit=True) as c: + for role in ("student", "teacher", "manager", "admin"): + c.execute("insert into public.m2_roles(email, role, granted_by) values ('grant@school.test', %s, 'a@school.test')", (role,)) + for bad in (("grant@school.test", "developer"), ("grant@school.test", "boss"), ("Grant@school.test", "admin")): + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_roles(email, role) values (%s, %s)", bad) + with pytest.raises(psycopg.errors.UniqueViolation): + c.execute("insert into public.m2_roles(email, role) values ('grant@school.test', 'admin')") + + +def test_take_role_in_one_step_keeps_the_last_admin(db): + take = lambda email, role, settings=0: as_role(db, "service_role", "select public.m2_take_role(%s, %s, %s)", email, role, settings)[0][0] + with psycopg.connect(db, autocommit=True) as c: + c.execute("delete from public.m2_roles where role = 'admin'") + c.execute("insert into public.m2_roles(email, role) values ('adm1@school.test', 'admin'), ('adm2@school.test', 'admin'), ('mgr@school.test', 'manager')") + assert take("nobody@school.test", "admin") == "absent" + assert take("mgr@school.test", "manager") == "removed" + assert take("adm1@school.test", "admin") == "removed" + assert take("adm2@school.test", "admin") == "last_admin" # the only one left stays + assert take("adm2@school.test", "admin", 1) == "removed" # unless the settings name another admin + with psycopg.connect(db, autocommit=True) as c: + assert c.execute("select count(*) from public.m2_roles where role = 'admin'").fetchone()[0] == 0 + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +def test_browser_roles_cannot_read_roles_or_take_one_away(db, role): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "select * from public.m2_roles") + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "select public.m2_take_role('a@school.test', 'admin', 0)") + + +def test_row_level_security_is_on_for_roles(db): with psycopg.connect(db, autocommit=True) as c: - c.execute("insert into public.m2_classes(name, teacher_email) values ('ח''1', 't@school.test')") - ids = [r[0] for r in c.execute("select id from public.m2_classes order by id").fetchall()] - c.execute("insert into public.m2_class_members(class_id, email) values (%s, 's@school.test')", (ids[0],)) + assert c.execute("select relrowsecurity from pg_class where relname = 'm2_roles'").fetchone()[0] is True + assert c.execute("select count(*) from pg_policies where tablename like 'm2_%'").fetchone()[0] == 0 + + +# --- skill learning (task 2.1) --- + +USER = "11111111-1111-1111-1111-111111111111" +OTHER = "22222222-2222-2222-2222-222222222222" + + +def test_daily_correct_counts_only_correct_answers_per_student_and_day(db): + with psycopg.connect(db, autocommit=True) as c: + c.execute("delete from public.m2_answers") + rows = [(USER, "s", "q1", True, True, "2026-11-02"), (USER, "s", "q2", True, False, "2026-11-02"), + (USER, "s", "q3", False, True, "2026-11-02"), (USER, "s", "q4", True, True, "2026-11-03"), + (OTHER, "s", "q1", True, True, "2026-11-02")] + for user, skill, key, correct, counted, day in rows: + c.execute("insert into public.m2_answers(user_id, skill_id, question_key, correct, counted, day) " + "values (%s, %s, %s, %s, %s, %s)", (user, skill, key, correct, counted, day)) + got = as_role(db, "service_role", "select to_char(day, 'YYYY-MM-DD'), correct from public.m2_daily_correct " + "where user_id = %s order by day", USER) + assert got == [("2026-11-02", 2), ("2026-11-03", 1)] # the helped answer counts; the wrong one does not + + +def test_progress_row_is_unique_per_student_and_skill_with_defaults(db): + with psycopg.connect(db, autocommit=True) as c: + c.execute("insert into public.m2_skill_progress(user_id, skill_id) values (%s, 'a')", (USER,)) + row = c.execute("select current_key, current_helped, started_at, mastered_at from public.m2_skill_progress " + "where user_id = %s and skill_id = 'a'", (USER,)).fetchone() + assert row == (None, False, None, None) with pytest.raises(psycopg.errors.UniqueViolation): - c.execute("insert into public.m2_class_members(class_id, email) values (%s, 's@school.test')", (ids[1],)) + c.execute("insert into public.m2_skill_progress(user_id, skill_id) values (%s, 'a')", (USER,)) + + +def test_progress_no_longer_has_the_stage_columns_and_keeps_the_rest(db): + with psycopg.connect(db, autocommit=True) as c: + columns = {r[0] for r in c.execute("select column_name from information_schema.columns " + "where table_schema = 'public' and table_name = 'm2_skill_progress'").fetchall()} + assert columns == {"user_id", "skill_id", "current_key", "current_helped", "started_at", "mastered_at", "round_start"} + + +def test_round_start_is_empty_for_old_rows_and_cannot_be_negative(db): + with psycopg.connect(db, autocommit=True) as c: + c.execute("insert into public.m2_skill_progress(user_id, skill_id) values ('33333333-3333-3333-3333-333333333333', 'r')") + assert c.execute("select round_start from public.m2_skill_progress where skill_id = 'r'").fetchone() == (None,) + c.execute("update public.m2_skill_progress set round_start = 10 where skill_id = 'r'") with pytest.raises(psycopg.errors.CheckViolation): - c.execute("insert into public.m2_class_members(class_id, email) values (%s, 'UPPER@school.test')", (ids[0],)) + c.execute("update public.m2_skill_progress set round_start = -1 where skill_id = 'r'") + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +@pytest.mark.parametrize("table", ["m2_answers", "m2_skill_progress", "m2_daily_correct"]) +def test_browser_roles_cannot_read_skill_learning_objects(db, role, table): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, f"select * from public.{table}") + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +def test_browser_roles_cannot_write_answers(db, role): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "insert into public.m2_answers(user_id, skill_id, question_key, correct, day) " + "values (%s, 's', 'q', true, '2026-11-02')", USER) + + +def test_row_level_security_is_on_for_the_new_tables(db): + with psycopg.connect(db, autocommit=True) as c: + on = dict(c.execute("select relname, relrowsecurity from pg_class " + "where relname in ('m2_answers','m2_skill_progress')").fetchall()) + policies = c.execute("select count(*) from pg_policies where tablename like 'm2_%'").fetchone()[0] + assert on == {"m2_answers": True, "m2_skill_progress": True} + assert policies == 0 + + +def test_server_role_can_insert_answers_and_progress(db): + as_role(db, "service_role", "insert into public.m2_answers(user_id, skill_id, question_key, correct, day) " + "values (%s, 'svc', 'q', true, '2026-11-04')", USER) + as_role(db, "service_role", "insert into public.m2_skill_progress(user_id, skill_id) values (%s, 'svc')", USER) + + +def test_last_answered_gives_the_newest_day_per_student_and_skill(db): + with psycopg.connect(db, autocommit=True) as c: + c.execute("delete from public.m2_answers") + for user, skill, key, day in ((USER, "s", "q1", "2026-11-02"), (USER, "s", "q2", "2026-11-09"), (USER, "t", "q1", "2026-11-03"), + (OTHER, "s", "q1", "2026-11-20")): + c.execute("insert into public.m2_answers(user_id, skill_id, question_key, correct, counted, day) values (%s, %s, %s, false, false, %s)", + (user, skill, key, day)) + got = as_role(db, "service_role", "select skill_id, to_char(day, 'YYYY-MM-DD') from public.m2_last_answered where user_id = %s order by skill_id", USER) + assert got == [("s", "2026-11-09"), ("t", "2026-11-03")] + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +def test_browser_roles_cannot_read_the_reward_tables(db, role): + for table in ("m2_comets", "m2_reward_state", "m2_last_answered"): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, f"select * from public.{table}") + + +def test_a_student_catches_each_comet_once_and_has_one_state_row(db): + with psycopg.connect(db, autocommit=True) as c: + c.execute("insert into public.m2_comets(user_id, comet_id) values (%s, 'pi')", (USER,)) + c.execute("insert into public.m2_comets(user_id, comet_id) values (%s, 'pi')", (OTHER,)) # another student may have it too + with pytest.raises(psycopg.errors.UniqueViolation): + c.execute("insert into public.m2_comets(user_id, comet_id) values (%s, 'pi')", (USER,)) + c.execute("insert into public.m2_reward_state(user_id) values (%s)", (USER,)) + with pytest.raises(psycopg.errors.UniqueViolation): + c.execute("insert into public.m2_reward_state(user_id) values (%s)", (USER,)) + assert c.execute("select last_comet_day, last_catch_day from public.m2_reward_state where user_id = %s", (USER,)).fetchone() == (None, None) + + +def test_attempts_have_defaults_and_refuse_bad_values(db): + with psycopg.connect(db, autocommit=True) as c: + row = c.execute("insert into public.m2_attempts(user_id, kind, scope, due_at) values (%s, 'quiz', 't', now() + interval '15 minutes') " + "returning submitted_at, timed_out, grade, questions, answers", (USER,)).fetchone() + assert row == (None, False, None, [], {}) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_attempts(user_id, kind, scope, due_at) values (%s, 'oral', 't', now() + interval '1 minute')", (USER,)) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_attempts(user_id, kind, scope, due_at, grade) values (%s, 'quiz', 't', now() + interval '1 minute', 101)", (USER,)) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_attempts(user_id, kind, scope, due_at) values (%s, 'quiz', 't', now() - interval '1 minute')", (USER,)) + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +def test_browser_roles_cannot_touch_attempts(db, role): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "select * from public.m2_attempts") + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "insert into public.m2_attempts(user_id, kind, scope, due_at) values ('11111111-1111-1111-1111-111111111111', 'quiz', 't', now() + interval '1 minute')") + + +def test_the_server_role_can_use_attempts_and_rls_has_no_policies(db): + as_role(db, "service_role", "insert into public.m2_attempts(user_id, kind, scope, due_at) values (%s, 'quiz', 'u', now() + interval '1 minute')", OTHER) + assert as_role(db, "service_role", "select count(*) from public.m2_attempts where user_id = %s", OTHER) == [(1,)] + with psycopg.connect(db, autocommit=True) as c: + assert c.execute("select relrowsecurity from pg_class where relname = 'm2_attempts'").fetchone() == (True,) + assert c.execute("select count(*) from pg_policies where tablename = 'm2_attempts'").fetchone() == (0,) + + +def test_a_test_has_defaults_limits_and_cascades_with_its_class(db): + with psycopg.connect(db, autocommit=True) as c: + cid = _class(c, "מבחן-1") + row = c.execute("insert into public.m2_tests(class_id, date, lessons, created_by) values (%s, '2026-11-20', '{t,t2}', 't@school.test') " + "returning questions, minutes, note, removed_at", (cid,)).fetchone() + assert row == (12, 45, "", None) + for column, value in (("questions", 0), ("questions", 41), ("minutes", 4), ("minutes", 181)): + with pytest.raises(psycopg.errors.CheckViolation): + c.execute(f"insert into public.m2_tests(class_id, date, lessons, created_by, {column}) values (%s, '2026-11-20', '{{t}}', 't@s', {value})", (cid,)) + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into public.m2_tests(class_id, date, lessons, created_by) values (%s, '2026-11-20', '{}', 't@s')", (cid,)) + c.execute("delete from public.m2_classes where id = %s", (cid,)) + assert c.execute("select count(*) from public.m2_tests where class_id = %s", (cid,)).fetchone() == (0,) + + +@pytest.mark.parametrize("role", ["authenticated", "anon"]) +def test_browser_roles_cannot_touch_tests(db, role): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "select * from public.m2_tests") + with pytest.raises(psycopg.errors.InsufficientPrivilege): + as_role(db, role, "insert into public.m2_tests(class_id, date, lessons, created_by) values (1, '2026-11-20', '{t}', 'x')") + + +def test_the_server_role_can_use_tests_and_rls_has_no_policies(db): + with psycopg.connect(db, autocommit=True) as c: + cid = _class(c, "מבחן-2") + as_role(db, "service_role", "insert into public.m2_tests(class_id, date, lessons, created_by) values (%s, '2026-11-21', '{t}', 'x')", cid) + assert as_role(db, "service_role", "select count(*) from public.m2_tests where class_id = %s", cid) == [(1,)] + with psycopg.connect(db, autocommit=True) as c: + assert c.execute("select relrowsecurity from pg_class where relname = 'm2_tests'").fetchone() == (True,) + assert c.execute("select count(*) from pg_policies where tablename = 'm2_tests'").fetchone() == (0,) diff --git a/mathly2/tests/test_no_content_before_sign_in.py b/mathly2/tests/test_no_content_before_sign_in.py index 1f387b8100f9431983498aaf2d065070fbf5194d..b1c104ccadd7a1e066eaedd5f8a57b4f02b1f60b 100644 --- a/mathly2/tests/test_no_content_before_sign_in.py +++ b/mathly2/tests/test_no_content_before_sign_in.py @@ -29,6 +29,13 @@ def test_there_are_routes_to_check(app): assert ('DELETE', '/api/classes/{class_id}/students/{email}') in set(api_routes(app)) +def test_the_skill_learning_routes_are_among_those_checked(app): + routes = set(api_routes(app)) + for route in (("GET", "/api/skills/{skill_id}"), ("POST", "/api/skills/{skill_id}/help"), ("POST", "/api/skills/{skill_id}/answer"), + ("GET", "/api/path"), ("GET", "/api/collection")): + assert route in routes + + @pytest.mark.parametrize("headers", [{}, {"Authorization": "Bearer "}, {"Authorization": "Bearer dev:nobody"}, {"Authorization": "Basic abc"}]) def test_every_api_route_refuses_a_caller_without_a_valid_token(app, headers): client = TestClient(app) diff --git a/mathly2/tests/test_path_browser.py b/mathly2/tests/test_path_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..6711043513bf7993def6955d82c88302771e9a27 --- /dev/null +++ b/mathly2/tests/test_path_browser.py @@ -0,0 +1,277 @@ +"""The path in a real browser at phone width: orbits of every size, the states in words, the owl, keyboard use, reduced motion.""" +import uuid +from collections import Counter + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID = "kid@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) +NOW = "2026-11-02T10:00:00+00:00" +PHONE = {"width": 360, "height": 800} +WORDS = {"not_started": "לא התחלת", "learning": "בלמידה", "mastered": "נשלטה"} + + +def lessons_by_size(bank): + sizes = Counter(s["unit"] for s in bank.skills) + pick = lambda n: next(lesson for lesson, count in sizes.items() if count == n) + return pick(2), pick(3), pick(6) + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +def world(bank, lessons): + store = InMemoryStore() + store.add_member(store.create_class("setup", "A", lessons=list(lessons))["id"], KID) + return create_app(Settings(), bank=bank, store=store), store + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def path_page(browser, url, scheme="light", **options): + page = offline_formulas(browser.new_page(viewport=PHONE, color_scheme=scheme, **options)) + page.goto(url) + page.fill("#email", KID) + page.click("#dev button") + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector(".orbit") + return page + + +# --- 4.1 the rings --- + +def test_rings_of_2_3_and_6_skills_fit_a_360px_screen_and_keep_clear_of_the_hub(browser, bank): + two, three, six = lessons_by_size(bank) + app, _ = world(bank, [two, three, six]) + with running(app) as url: + page = path_page(browser, url) + assert page.locator(".orbit").count() == 3 + for lesson, n in ((two, 2), (three, 3), (six, 6)): + orbit = page.locator(f"#lesson-{lesson}") + hub = orbit.locator(".hub").bounding_box() + stars = orbit.locator(".star .node") + assert stars.count() == n + for i in range(n): + node = stars.nth(i).bounding_box() + assert node["x"] >= 0 and node["x"] + node["width"] <= PHONE["width"], f"star {i + 1} of {lesson} leaves the screen" + apart = (node["x"] + node["width"] <= hub["x"] or hub["x"] + hub["width"] <= node["x"] + or node["y"] + node["height"] <= hub["y"] or hub["y"] + hub["height"] <= node["y"]) + assert apart, f"star {i + 1} of {lesson} is over the hub" + labels = orbit.locator(".star .lbl") + for i in range(n): + box = labels.nth(i).bounding_box() + assert box["x"] >= 0 and box["x"] + box["width"] <= PHONE["width"] + assert orbit.locator(".ring path").count() == (n - 1) + (1 if n > 2 else 0) # the arcs between neighbours, and the faint closing one + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +def test_stars_are_numbered_clockwise_from_the_top(browser, bank): + _, _, six = lessons_by_size(bank) + app, _ = world(bank, [six]) + with running(app) as url: + page = path_page(browser, url) + hub = page.locator(".hub").bounding_box() + centre = (hub["x"] + hub["width"] / 2, hub["y"] + hub["height"] / 2) + found = [] + for i in range(6): + node = page.locator(".star .node").nth(i).bounding_box() + found.append((node["x"] + node["width"] / 2 - centre[0], node["y"] + node["height"] / 2 - centre[1])) + assert found[0][1] < 0 and abs(found[0][0]) < 5 # 1 is at the top + assert found[1][0] > 0 and found[2][0] > 0 and found[3][1] > 0 # then right, down, and round to the left + assert found[4][0] < 0 and found[5][0] < 0 + + +# --- 4.2 the states, the owl, the lessons shown --- + +@pytest.mark.parametrize("scheme", ["light", "dark"]) +def test_each_state_says_its_word_the_mastered_star_differs_and_the_owl_is_on_the_next_one(browser, bank, scheme): + two, three, _ = lessons_by_size(bank) + app, store = world(bank, [two, three]) + first, second = (s["id"] for s in bank.skills if s["unit"] == two) + store.save_progress(KID_ID, first, started_at=NOW, mastered_at=NOW) # mastered + store.save_progress(KID_ID, second, started_at=NOW) # learning + store.add_answer(KID_ID, second, "k", False, True, None, __import__("datetime").date(2026, 11, 2)) # answered last: the owl goes here + with running(app) as url: + page = path_page(browser, url, scheme) + assert page.locator(".orbit").count() == 2 and page.locator(f"#lesson-{two}, #lesson-{three}").count() == 2 + for skill, state in ((first, "mastered"), (second, "learning")): + text = page.inner_text(f".star[data-skill='{skill}'] .lbl") + assert WORDS[state] in text and {"mastered": "✓", "learning": "◐"}[state] in text + third = next(s["id"] for s in bank.skills if s["unit"] == three) + assert WORDS["not_started"] in page.inner_text(f".star[data-skill='{third}'] .lbl") and "○" in page.inner_text(f".star[data-skill='{third}'] .lbl") + look = lambda skill: page.evaluate("(id) => { const n = document.querySelector(`.star[data-skill='${id}'] .node`); const s = getComputedStyle(n);" + " return [s.borderTopColor, s.backgroundImage + s.backgroundColor]; }", skill) + assert look(first) != look(second) != look(third) and look(first) != look(third) # three different looks + assert page.locator(".star.next").count() == 1 and page.get_attribute(".star.next", "data-skill") == second + assert page.locator(".star.next .perch .sky-owl").count() == 1 + assert "ממשיכים כאן" in page.inner_text(".star.next .lbl") + assert "1 מתוך 2 נשלטו" in page.inner_text(f"#lesson-{two} .hub") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + + +def test_a_new_student_gets_the_owl_on_the_first_skill_and_everything_stays_open(browser, bank): + two, three, _ = lessons_by_size(bank) + app, _ = world(bank, [two, three]) + with running(app) as url: + page = path_page(browser, url) + first = page.locator(".star").first.get_attribute("data-skill") + assert page.get_attribute(".star.next", "data-skill") == first + assert page.locator(".star[href]").count() == page.locator(".star").count() # every star is a link: nothing is locked + + +def test_a_student_sees_only_the_lessons_of_their_class(browser, bank): + two, _, _ = lessons_by_size(bank) + app, _ = world(bank, [two]) + with running(app) as url: + page = path_page(browser, url) + assert page.locator(".orbit").count() == 1 and page.locator(f"#lesson-{two}").count() == 1 + + +# --- 4.3 access --- + +def test_every_star_is_reached_with_tab_and_opened_with_enter_and_names_its_number_name_and_state(browser, bank): + two, _, _ = lessons_by_size(bank) + app, _ = world(bank, [two]) + with running(app) as url: + page = path_page(browser, url) + skills = [s for s in bank.skills if s["unit"] == two] + for i, skill in enumerate(skills, 1): + assert page.get_attribute(f".star[data-skill='{skill['id']}']", "aria-label").startswith(f"{i}. {skill['name']}: ") + page.focus("#out") # start before the path, then Tab onwards + reached = [] + for _ in range(40): + page.keyboard.press("Tab") + on = page.evaluate("document.activeElement.classList.contains('star') ? document.activeElement.dataset.skill : null") + if on and on not in reached: + reached.append(on) + if len(reached) == len(skills): + break + assert reached == [s["id"] for s in skills] # in order, by keyboard + page.keyboard.press("Enter") + assert page.evaluate("location.hash") == f"#/skill/{skills[-1]['id']}" + + +def test_nothing_on_the_path_animates_when_the_device_asks_for_less_motion(browser, bank): + two, _, _ = lessons_by_size(bank) + app, _ = world(bank, [two]) + with running(app) as url: + page = path_page(browser, url) + assert page.evaluate("document.getAnimations().length") > 0 # the owl blinks and the next star pulses + page.emulate_media(reduced_motion="reduce") + assert page.evaluate("document.getAnimations().length") == 0 + + +# --- 7.3 choosing a subject --- + +def test_after_sign_in_the_student_sees_the_math_card_then_the_path_and_can_go_back(browser, bank): + two, three, _ = lessons_by_size(bank) + app, store = world(bank, [two, three]) + first = next(s["id"] for s in bank.skills if s["unit"] == two) + store.save_progress(KID_ID, first, started_at=NOW, mastered_at=NOW) + total = sum(1 for s in bank.skills if s["unit"] in (two, three)) + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE)) + page.goto(url) + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector(".subject-card") + assert page.locator(".orbit").count() == 0 and page.locator(".subject-card").count() == 1 # the subjects first, no path yet + assert "מתמטיקה" in page.inner_text(".subject-card") and f"1 מתוך {total} מיומנויות" in page.inner_text(".subject-card") + assert page.get_attribute(".subject-card [role=progressbar]", "aria-valuenow") == "1" + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + page.click(".subject-card") + page.wait_for_selector(".tabs") # the card opens the subject's home + assert page.evaluate("location.hash") == "#/subject/math" and page.locator(".orbit").count() == 0 + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector(".orbit") + assert page.evaluate("location.hash") == "#/subject/math/path" + page.click("#to-subjects") # a way back to the subjects + page.wait_for_selector(".subject-card") + assert page.locator(".orbit").count() == 0 + + +def test_a_link_to_a_skill_opens_the_math_path_with_its_sheet(browser, bank): + two, _, _ = lessons_by_size(bank) + app, _ = world(bank, [two]) + skill = next(s["id"] for s in bank.skills if s["unit"] == two) + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE)) + page.goto(f"{url}#/skill/{skill}") + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector(".mx-sheet #ex-q") + assert page.locator("#path").count() == 1 and page.locator(".subject-card").count() == 0 + + +# --- add-rewards 1.1: the goal and the streak are on the path --- + +def test_the_path_shows_todays_goal_and_the_streak(browser, bank): + two, _, _ = lessons_by_size(bank) + app, store = world(bank, [two]) + skill = next(s["id"] for s in bank.skills if s["unit"] == two) + from mathly2 import clock + for i in range(3): + store.add_answer(KID_ID, skill, f"k{i}", True, True, None, clock.school_day()) + with running(app) as url: + page = path_page(browser, url) + assert "יעד יומי: 3 מתוך 5" in page.inner_text("#goal-text") and "רצף: 0" in page.inner_text("#streak") + assert page.get_attribute("#goal [role=progressbar]", "aria-valuenow") == "3" + + +# --- add-rewards 2.3: a faded star --- + +def test_a_faded_star_is_dimmed_says_fading_and_still_counts_as_mastered(browser, bank): + from datetime import timedelta + from mathly2 import clock + two, _, _ = lessons_by_size(bank) + app, store = world(bank, [two]) + first, second = [s["id"] for s in bank.skills if s["unit"] == two][:2] + for skill in (first, second): + store.save_progress(KID_ID, skill, started_at=NOW, mastered_at=NOW) + store.add_answer(KID_ID, first, "k", True, True, None, clock.school_day() - timedelta(days=20)) # faded + store.add_answer(KID_ID, second, "k", True, True, None, clock.school_day() - timedelta(days=1)) # bright + with running(app) as url: + page = path_page(browser, url) + faded, bright = f".star[data-skill='{first}']", f".star[data-skill='{second}']" + assert "דועך" in page.inner_text(faded + " .lbl") and "◌" in page.inner_text(faded + " .lbl") + assert "דועך" in page.get_attribute(faded, "aria-label") and "נשלטה" in page.get_attribute(faded, "aria-label") + assert "דועך" not in page.inner_text(bright + " .lbl") + look = lambda sel: page.evaluate("(s) => getComputedStyle(document.querySelector(s + ' .node')).opacity", sel) + assert look(faded) != look(bright) + assert "2 מתוך" in page.inner_text(f"#lesson-{two} .hub") # fading does not change what counts + # one answer on it relights the star + store.add_answer(KID_ID, first, "k2", False, True, None, clock.school_day()) + page.reload() + page.wait_for_selector(".orbit") + assert "דועך" not in page.inner_text(faded + " .lbl") + + +# --- after Google sign-in the address holds the token: the student still lands on the subjects --- + +def test_an_oauth_fragment_in_the_address_does_not_skip_the_subject_cards(browser, bank): + two, _, _ = lessons_by_size(bank) + app, _ = world(bank, [two]) + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE)) + page.goto(url + "#access_token=abc.def.ghi&expires_in=3600&token_type=bearer") # what the sign-in service sends the browser back with + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector(".subject-card") + assert page.locator(".orbit").count() == 0 diff --git a/mathly2/tests/test_permissions.py b/mathly2/tests/test_permissions.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa174c8c05efbd7cf473637001b9a8520a9e66a --- /dev/null +++ b/mathly2/tests/test_permissions.py @@ -0,0 +1,121 @@ +"""The permission matrix, checked against the real routes: every /api route says which permission it needs, and a caller whose +roles lack it is refused with 403, whatever the route does. Routes are read from the app itself, so a new route that is not +listed here fails the test and must be given a permission.""" +import re + +import pytest +from fastapi.testclient import TestClient + +from mathly2.access import ROLES, allowed +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore + +PUBLIC = {("GET", "/api/health")} +ANY_SIGNED_IN = {("GET", "/api/me")} +NEEDS = { # (method, path) -> permission + ("GET", "/api/lessons"): "path.use", + ("GET", "/api/path"): "path.use", + ("GET", "/api/collection"): "path.use", + ("GET", "/api/teaching/tests"): "class.teach", + ("POST", "/api/classes/{class_id}/tests"): "class.teach", + ("PUT", "/api/tests/{test_id}"): "class.teach", + ("DELETE", "/api/tests/{test_id}"): "class.teach", + ("GET", "/api/home"): "path.use", + ("POST", "/api/tests/{test_id}/exercise/{number}/start"): "path.use", + ("POST", "/api/tests/{test_id}/simulation/start"): "path.use", + ("GET", "/api/tests/{test_id}"): "path.use", + ("GET", "/api/lessons/{lesson_id}/quiz"): "path.use", + ("POST", "/api/lessons/{lesson_id}/quiz/start"): "path.use", + ("GET", "/api/attempts/{attempt_id}"): "path.use", + ("PUT", "/api/attempts/{attempt_id}/answers"): "path.use", + ("POST", "/api/attempts/{attempt_id}/submit"): "path.use", + ("GET", "/api/grades"): "path.use", + ("GET", "/api/comets"): "path.use", + ("POST", "/api/comets/catch"): "path.use", + ("GET", "/api/skills/{skill_id}"): "path.use", + ("POST", "/api/skills/{skill_id}/help"): "path.use", + ("POST", "/api/skills/{skill_id}/answer"): "path.use", + ("POST", "/api/skills/{skill_id}/round"): "path.use", + ("GET", "/api/classes"): "classes.manage", + ("GET", "/api/classes/lessons"): "classes.manage", + ("POST", "/api/classes"): "classes.manage", + ("GET", "/api/classes/{class_id}"): "classes.manage", + ("PUT", "/api/classes/{class_id}"): "classes.manage", + ("DELETE", "/api/classes/{class_id}"): "classes.manage", + ("POST", "/api/classes/{class_id}/students"): "class.roster", + ("DELETE", "/api/classes/{class_id}/students/{email}"): "class.roster", + ("GET", "/api/teaching"): "class.teach", + ("GET", "/api/students"): "students.list", + ("GET", "/api/accounts"): "roles.manage", + ("POST", "/api/accounts/{email}/roles/{role}"): "roles.manage", + ("DELETE", "/api/accounts/{email}/roles/{role}"): "roles.manage", +} +WHO = {"student": "kid@school.test", "teacher": "t@school.test", "manager": "mgr@school.test", + "admin": "adm@school.test", "developer": "dev@school.test"} + + +def api_routes(app): + for path, methods in app.openapi()["paths"].items(): + if path.startswith("/api"): + for method in sorted(methods): + yield method.upper(), path + + +@pytest.fixture(scope="module") +def world(): + store = InMemoryStore() + store.give_role(WHO["manager"], "manager", "setup") + store.give_role(WHO["admin"], "admin", "setup") + app = create_app(Settings(teachers=frozenset({WHO["teacher"]}), developers=frozenset({WHO["developer"]})), store=store) + store.add_member(store.create_class("m@x.test", "A", lessons=["t"], teacher_email=WHO["teacher"])["id"], WHO["student"]) + return app, TestClient(app) + + +def call(client, method, path, email): + url = path.format(skill_id="t_ext", lesson_id="t", attempt_id="x", test_id="1", number="1", class_id="1", email="someone@school.test", role="teacher") + sends = method in ("POST", "PUT", "PATCH") + return client.request(method, url, headers={"Authorization": f"Bearer dev:{email}"}, json={} if sends else None) + + +def test_every_route_has_a_declared_permission(world): + app, _ = world + seen = set(api_routes(app)) + undeclared = seen - PUBLIC - ANY_SIGNED_IN - set(NEEDS) + assert not undeclared, f"give these routes a permission in NEEDS: {sorted(undeclared)}" + assert not (set(NEEDS) | ANY_SIGNED_IN | PUBLIC) - seen, "NEEDS lists a route that no longer exists" + + +@pytest.mark.parametrize("role", ROLES) +def test_a_role_is_refused_exactly_where_it_lacks_the_permission(world, role): + _, client = world + for (method, path), permission in sorted(NEEDS.items()): + status = call(client, method, path, WHO[role]).status_code + if allowed([role], permission): + assert status != 403, f"{role} should reach {method} {path} but got 403" + else: + assert status == 403, f"{role} should be refused {method} {path} but got {status}" + + +@pytest.mark.parametrize("role", ROLES) +def test_every_role_can_read_its_own_access(world, role): + _, client = world + body = call(client, "GET", "/api/me", WHO[role]).json() + assert body["email"] == WHO[role] and role in body["roles"] + + +def test_the_teachers_permission_does_not_reach_other_peoples_classes(world): + _, client = world + # the teacher has class.roster, but only for classes they teach: another class is not found + other = client.post("/api/classes", json={"name": "B", "lessons": ["t"], "teacher_email": "else@school.test"}, + headers={"Authorization": f"Bearer dev:{WHO['manager']}"}).json()["id"] + refused = client.post(f"/api/classes/{other}/students", json={"emails": "x@school.test"}, + headers={"Authorization": f"Bearer dev:{WHO['teacher']}"}) + assert refused.status_code == 404 + + +def test_the_manager_and_admin_cannot_read_a_students_learning_data(world): + _, client = world + for role in ("manager", "admin"): + for path in ("/api/path", "/api/collection", "/api/skills/t_ext", "/api/lessons"): + assert call(client, "GET", path, WHO[role]).status_code == 403, (role, path) diff --git a/mathly2/tests/test_pooled.py b/mathly2/tests/test_pooled.py new file mode 100644 index 0000000000000000000000000000000000000000..051fff3e0f2aec18f94d414d5e4f234777b2f92a --- /dev/null +++ b/mathly2/tests/test_pooled.py @@ -0,0 +1,139 @@ +"""Reused connections to the database (fewer-database-calls 1.3), against a small local server.""" +import json +import threading +import urllib.error +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from mathly2 import pooled + + +class Server: + """A keep-alive HTTP/1.1 server that counts the connections it accepted and the requests it answered.""" + + def __init__(self, close_after: int | None = None, status: int = 200, body: bytes = b'[{"ok": true}]', delay: float = 0.0): + outer = self + self.connections = self.requests = 0 + self.lock = threading.Lock() + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def setup(self): + super().setup() + with outer.lock: + outer.connections += 1 + self.served = 0 + + def do_GET(self): + self.answer() + + do_POST = do_GET + + def answer(self): + length = int(self.headers.get("Content-Length") or 0) + self.rfile.read(length) + if delay: + import time + time.sleep(delay) + self.served += 1 + with outer.lock: + outer.requests += 1 + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + if close_after and self.served >= close_after: + self.close_connection = True # hang up after this answer without saying so (an idle timeout) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *a): + pass + + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}" + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + +@pytest.fixture +def server(): + made = [] + + def make(**kw): + made.append(Server(**kw)) + return made[-1] + yield make + for s in made: + s.stop() + + +def test_several_calls_reuse_one_connection(server): + s = server() + for _ in range(5): + status, body = pooled.request("GET", s.url + "/rest/v1/x?a=1") + assert status == 200 and json.loads(body) == [{"ok": True}] + assert s.requests == 5 and s.connections == 1 + + +def test_a_write_sends_its_body_and_reuses_the_connection(server): + s = server() + pooled.request("GET", s.url + "/a") + status, _ = pooled.request("POST", s.url + "/b", {"Content-Type": "application/json"}, b'{"x": 1}') + assert status == 200 and s.connections == 1 + + +def test_each_thread_has_its_own_connection(server): + s = server() + pooled.request("GET", s.url + "/a") + done = [] + threading.Thread(target=lambda: done.append(pooled.request("GET", s.url + "/b")[0])).start() + for _ in range(100): + if done: + break + threading.Event().wait(0.02) + assert done == [200] and s.connections == 2 + + +def test_a_connection_the_server_closed_is_replaced_once_and_the_call_still_works(server): + s = server(close_after=1) # the server hangs up after every answer + for _ in range(3): + status, _ = pooled.request("GET", s.url + "/a") + assert status == 200 + assert s.requests == 3 and s.connections >= 2 + + +def test_an_answer_of_400_or_more_raises_an_http_error_with_a_body_that_can_be_read(server): + s = server(status=409, body=b'{"message": "duplicate key"}') + with pytest.raises(urllib.error.HTTPError) as caught: + pooled.request("POST", s.url + "/a", None, b"{}") + assert caught.value.code == 409 and json.loads(caught.value.read())["message"] == "duplicate key" + ok = server() # a failed answer leaves the client usable + assert pooled.request("GET", ok.url + "/a")[0] == 200 + + +def test_a_connection_that_fails_is_a_url_error_and_a_slow_server_a_timeout(server): + with pytest.raises(urllib.error.URLError): + pooled.request("GET", "http://127.0.0.1:1/never") + slow = server(delay=1.0) + with pytest.raises(TimeoutError): + pooled.request("GET", slow.url + "/a", timeout=0.2) + assert pooled.request("GET", slow.url + "/a", timeout=5)[0] == 200 # the broken connection was dropped; the next call works + + +def test_the_store_and_the_authenticator_use_the_pooled_client(server): + from mathly2.auth import SupabaseAuthenticator + from mathly2.store import SupabaseStore + s = server(body=b'[{"id": 1, "name": "A", "lessons": [], "teacher_email": null, "ai_enabled": false, "ai_daily_checks": 150, "created_by": "x", "created_at": "2026-11-01T00:00:00+00:00", "students": 0}]') + store = SupabaseStore(s.url, "secret") + for _ in range(3): + store._request("GET", "m2_classes", {"select": "*"}) + assert s.requests == 3 and s.connections == 1 + user = server(body=b'{"id": "u1", "email": "a@school.test", "email_confirmed_at": "2026-01-01"}') + auth = SupabaseAuthenticator(user.url, "key") + assert auth.user("token-1") == {"id": "u1", "email": "a@school.test"} + assert auth.user("token-2") == {"id": "u1", "email": "a@school.test"} and user.requests == 2 and user.connections == 1 diff --git a/mathly2/tests/test_quiz.py b/mathly2/tests/test_quiz.py new file mode 100644 index 0000000000000000000000000000000000000000..9cb25415bc1986c164491a9e5ea43314e9e80443 --- /dev/null +++ b/mathly2/tests/test_quiz.py @@ -0,0 +1,73 @@ +"""Drawing a lesson quiz (add-lesson-quizzes 1.3).""" +import random +from collections import Counter + +import pytest + +from mathly2 import quiz +from mathly2.bank import load_bank + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +def lesson_with(bank, n): + counts = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + return next(l for l, c in counts.items() if c == n) + + +def per_skill(drawn): + return Counter(q["skill_id"] for q in drawn) + + +def test_a_lesson_of_four_skills_gives_ten_questions_with_every_skill_at_least_two(bank): + drawn = quiz.draw(bank, lesson_with(bank, 4), rng=random.Random(1)) + assert len(drawn) == 10 and len({q["key"] for q in drawn}) == 10 + assert sorted(per_skill(drawn).values()) == [2, 2, 3, 3] + + +def test_six_skills_give_quotas_2_2_2_2_1_1_and_two_skills_give_5_and_5(bank): + assert sorted(per_skill(quiz.draw(bank, lesson_with(bank, 6), rng=random.Random(2))).values()) == [1, 1, 2, 2, 2, 2] + assert sorted(per_skill(quiz.draw(bank, lesson_with(bank, 2), rng=random.Random(3))).values()) == [5, 5] + + +def test_every_skill_is_in_the_quiz_whatever_the_rng(bank): + for lesson in {s["unit"] for s in bank.skills}: + skills = {s["id"] for s in bank.skills if s["unit"] == lesson and bank.question_keys(s["id"])} + for seed in range(5): + assert set(per_skill(quiz.draw(bank, lesson, rng=random.Random(seed)))) == skills + + +def test_a_skill_without_questions_is_left_out_and_the_others_still_give_ten(bank): + lesson = next(s["unit"] for s in bank.skills if not bank.question_keys(s["id"])) + drawn = quiz.draw(bank, lesson, rng=random.Random(4)) + empty = {s["id"] for s in bank.skills if not bank.question_keys(s["id"])} + assert len(drawn) == 10 and not empty & set(per_skill(drawn)) + + +def test_a_retake_uses_new_questions_while_enough_remain_and_then_the_least_used(bank): + lesson = lesson_with(bank, 4) + used: Counter = Counter() + first = quiz.draw(bank, lesson, used, random.Random(5)) + used.update(q["key"] for q in first) + second = quiz.draw(bank, lesson, used, random.Random(6)) + used.update(q["key"] for q in second) + assert not {q["key"] for q in first} & {q["key"] for q in second} # two in a row never repeat + third = quiz.draw(bank, lesson, used, random.Random(7)) + assert not {q["key"] for q in first + second} & {q["key"] for q in third} or all(used[q["key"]] == 1 for q in third) + assert max(used[q["key"]] for q in third) <= 1 # repeats come from the least-used ones + for _ in range(12): # many retakes: nothing is drawn far more than the rest + batch = quiz.draw(bank, lesson, used, random.Random()) + used.update(q["key"] for q in batch) + pool = [k for s in bank.skills if s["unit"] == lesson for k in bank.question_keys(s["id"])] + counts = [used[k] for k in pool] + assert max(counts) - min(counts) <= 2 + + +def test_the_same_rng_gives_the_same_quiz_and_a_small_pool_gives_what_there_is(bank): + lesson = lesson_with(bank, 3) + assert quiz.draw(bank, lesson, rng=random.Random(9)) == quiz.draw(bank, lesson, rng=random.Random(9)) + assert len(quiz.draw(bank, lesson, rng=random.Random(9), size=4)) == 4 + assert quiz.draw(bank, "no-such-lesson") == [] diff --git a/mathly2/tests/test_quiz_browser.py b/mathly2/tests/test_quiz_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..8d34b92e316fff4cda0a5253f69d916108f668e3 --- /dev/null +++ b/mathly2/tests/test_quiz_browser.py @@ -0,0 +1,340 @@ +"""Lesson quizzes in a real browser: the trail node, the quiz sheet, the result, the grades screen (add-lesson-quizzes 3.1-3.4, 4.1).""" +import json +import uuid +from collections import Counter +from datetime import timedelta + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2 import attempts, clock +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID = "kid@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) +PHONE = {"width": 360, "height": 800} + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +@pytest.fixture +def browser(): + with playwright.sync_playwright() as p: + b = p.chromium.launch() + yield b + b.close() + + +def lessons_of(bank, *sizes): + counts = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + return [next(l for l, c in counts.items() if c == size) for size in sizes] + + +def world(bank, lessons): + store = InMemoryStore() + store.add_member(store.create_class("setup", "A", lessons=list(lessons))["id"], KID) + return create_app(Settings(), bank=bank, store=store), store + + +def seed_attempt(store, bank, lesson, grade=None, minutes_left=None, answers=None, n=10, seconds_left=None): + """An attempt in the store: submitted with `grade`, or open with `minutes_left` (or `seconds_left`) on its clock; negative: overdue.""" + from mathly2 import quiz + now = clock.now() + drawn = quiz.draw(bank, lesson)[:n] + if grade is None: + left = timedelta(seconds=seconds_left) if seconds_left is not None else timedelta(minutes=15 if minutes_left is None else minutes_left) + row = store.create_attempt(KID_ID, "quiz", lesson, now + left - timedelta(minutes=15), now + left, drawn) + else: + row = store.create_attempt(KID_ID, "quiz", lesson, now - timedelta(hours=1), now - timedelta(minutes=45), drawn) + store.save_attempt(row["id"], submitted_at=now - timedelta(minutes=50), grade=grade) + if answers: + store.save_attempt(row["id"], answers=answers) + return row + + +def path_page(browser, url, where="", viewport=PHONE): + page = offline_formulas(browser.new_page(viewport=viewport)) + errors = [] + page.on("pageerror", lambda e: errors.append(str(e))) + page.goto(url + where) + page.fill("#email", KID) + page.click("#dev button") + if not where: + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector(".orbit") + page.errors = errors + return page + + +def right(bank, ref, ok=True): + q = bank._questions[ref["skill_id"]][ref["key"]] + picks = [i for i, c in enumerate(q["choices"]) if bool(c.get("correct")) == ok] + return (picks if ok else ([i for i in picks if q["choices"][i].get("mistake")] or picks))[0] + + +def tap_choice(page, bank, ref, ok=True): + page.click(f"#qz-choices .qz-choice[data-i='{right(bank, ref, ok)}']") + + +def refs_on_screen(store, lesson): + return store.attempts_of(KID_ID, "quiz", lesson)[-1]["questions"] + + +# --- 3.1 the node --- + +def test_every_lesson_has_a_quiz_node_with_its_state_in_words_and_it_is_a_keyboard_link(browser, bank): + one, two, three = lessons_of(bank, 4, 3, 2) + app, store = world(bank, [one, two, three]) + seed_attempt(store, bank, two, grade=85) # graded + seed_attempt(store, bank, three, minutes_left=9) # open + with running(app) as url: + page = path_page(browser, url) + assert page.locator(".quiz-node").count() == 3 + text = lambda lesson: page.inner_text(f".quiz-node[data-quiz='{lesson}']") + assert "○ עוד לא נעשה" in text(one) and "✓ הציון: 85" in text(two) and "◐ בוחן פתוח" in text(three) + assert "בוחן" in page.get_attribute(f".quiz-node[data-quiz='{two}']", "aria-label") and "85" in page.get_attribute(f".quiz-node[data-quiz='{two}']", "aria-label") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + page.focus(f".quiz-node[data-quiz='{one}']") # reachable with the keyboard, opened with Enter + assert page.evaluate("document.activeElement.dataset.quiz") == one + page.keyboard.press("Enter") + page.wait_for_selector(".mx-sheet #qz-q") + assert page.locator("#path").count() == 1 # the path is still under the sheet + assert page.errors == [] + + +# --- 3.2 the sheet --- + +def test_the_quiz_opens_with_ten_questions_no_skill_names_and_a_countdown(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + with running(app) as url: + page = path_page(browser, url) + page.click(f".quiz-node[data-quiz='{lesson}']") + page.wait_for_selector("#qz-q") + assert page.evaluate("location.hash").startswith(f"#/quiz/{lesson}/") # the address names the attempt + assert "מתוך 10" in page.inner_text("#qz-count") and page.locator(".qz-dot").count() == 10 + assert page.inner_text("#qz-timer").startswith("14:") or page.inner_text("#qz-timer") == "15:00" + sheet = page.inner_text(".mx-sheet") + assert not any(s["name"] in sheet for s in bank.skills if s["unit"] == lesson) + assert page.locator(".qz-choice").count() >= 2 and page.locator(".qz-choice.right, .qz-choice.wrong").count() == 0 + + +def test_a_choice_is_saved_on_the_server_survives_a_reload_and_shows_no_right_or_wrong(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + with running(app) as url: + page = path_page(browser, url) + page.click(f".quiz-node[data-quiz='{lesson}']") + page.wait_for_selector("#qz-q") + refs = refs_on_screen(store, lesson) + key = page.get_attribute("#qz-q", "data-key") + ref = next(r for r in refs if r["key"] == key) + tap_choice(page, bank, ref, ok=False) + assert page.locator(".qz-choice.picked").count() == 1 and page.get_attribute(".qz-choice.picked", "aria-pressed") == "true" + assert page.locator("#qz-fb .ex-ok, #qz-fb .ex-bad").count() == 0 # no feedback at all + for _ in range(20): # the answer reached the server + saved = store.attempts_of(KID_ID, "quiz", lesson)[-1]["answers"] + if saved: + break + page.wait_for_timeout(100) + assert saved == {key: right(bank, ref, ok=False)} + before = store.attempts_of(KID_ID, "quiz", lesson)[-1]["id"] + page.reload() + page.wait_for_selector("#qz-q") # the same attempt, the same timer + assert store.attempts_of(KID_ID, "quiz", lesson)[-1]["id"] == before and len(store.attempts_of(KID_ID, "quiz", lesson)) == 1 + page.click(".qz-dot >> nth=0") + assert page.locator(".qz-dot.done").count() == 1 + assert page.inner_text("#qz-timer") < "15:01" and page.inner_text("#qz-timer") >= "14:00" + + +def test_the_board_and_calculator_are_available_in_a_quiz(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + with running(app) as url: + page = path_page(browser, url) + page.click(f".quiz-node[data-quiz='{lesson}']") + page.wait_for_selector("#qz-q") + page.wait_for_selector("[data-board-toggle]") + page.click("[data-board-toggle]") + page.wait_for_selector(".mx-board") + page.click(".mx-board [data-do='calc']") + page.wait_for_selector(".mx-calc", state="visible") + assert page.locator(".mx-calc-keys button").count() > 10 + + +def test_submitting_with_unanswered_questions_warns_first(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + with running(app) as url: + page = path_page(browser, url) + page.click(f".quiz-node[data-quiz='{lesson}']") + page.wait_for_selector("#qz-q") + ref = next(r for r in refs_on_screen(store, lesson) if r["key"] == page.get_attribute("#qz-q", "data-key")) + tap_choice(page, bank, ref) + page.click("#qz-submit") + page.wait_for_selector("#qz-warn .ex-note") + assert "9 שאלות בלי תשובה" in page.inner_text("#qz-warn") + page.click("#qz-back") # back to the quiz: nothing was submitted + assert page.locator("#qz-warn .ex-note").count() == 0 and store.attempts_of(KID_ID, "quiz", lesson)[-1]["submitted_at"] is None + page.click("#qz-submit") + page.click("#qz-yes") + page.wait_for_selector("#qz-grade") + assert store.attempts_of(KID_ID, "quiz", lesson)[-1]["submitted_at"] is not None + + +# --- 3.3 the result --- + +def answers_for(bank, refs, rights): + return {r["key"]: right(bank, r, ok) for r, ok in zip(refs, rights)} + + +def test_the_result_shows_the_grade_the_lost_skill_with_its_link_and_the_mistakes_but_no_right_answers(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + row = seed_attempt(store, bank, lesson) + refs = row["questions"] + by_skill = Counter(r["skill_id"] for r in refs) + lost_skill = next(s for s, n in by_skill.items() if n >= 2) + missed = [r for r in refs if r["skill_id"] == lost_skill][:2] + rights = [r not in missed for r in refs] + store.save_attempt(row["id"], answers=answers_for(bank, refs, rights)) + with running(app) as url: + page = path_page(browser, url, f"#/quiz/{lesson}/{row['id']}") + page.wait_for_selector("#qz-q") + page.click("#qz-submit") + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "80" and "8 תשובות נכונות מתוך 10" in page.inner_text(".qz-result") + page.wait_for_function("document.querySelector('#qz-best').innerText.includes('80')") # the lesson's grade + link = page.locator("#qz-lost a") + assert link.count() == 1 and link.get_attribute("href") == f"#/skill/{lost_skill}" and "2 שאלות שגויות" in page.inner_text("#qz-lost") + assert page.locator("#qz-missed li").count() == 2 + for item in range(2): + ref = missed[item] + mistake = bank.grade(ref["skill_id"], ref["key"], right(bank, ref, ok=False))["mistake"] + if mistake: + assert mistake["name"] in page.inner_text("#qz-missed") + text = page.inner_text(".mx-sheet") + for ref in missed: # a right choice is never written on the page + question = bank._questions[ref["skill_id"]][ref["key"]] + correct = next(c["text"] for c in question["choices"] if c.get("correct")) + if len(correct) > 3 and correct not in question["question"] and correct != question["choices"][right(bank, ref, ok=False)]["text"]: + assert correct not in text + assert page.locator(".right, [data-correct], .ex-ok").count() == 0 + page.click("#qz-lost a") # the link opens the skill over the path + page.wait_for_selector("#ex-q") + assert page.locator("#qz-grade").count() == 0 + + +def test_an_attempt_that_ran_out_of_time_shows_its_result_after_the_server_settles_it(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + row = seed_attempt(store, bank, lesson, minutes_left=-5) # its clock ended five minutes ago + store.save_attempt(row["id"], answers=answers_for(bank, row["questions"], [True] * 6)) + with running(app) as url: + page = path_page(browser, url, f"#/quiz/{lesson}/{row['id']}") + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "60" and "הזמן נגמר" in page.inner_text(".qz-result") + + +def test_when_the_countdown_reaches_zero_the_quiz_is_handed_in_as_it_stands(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + row = seed_attempt(store, bank, lesson, seconds_left=3) + store.save_attempt(row["id"], answers=answers_for(bank, row["questions"], [True] * 3)) + with running(app) as url: + page = path_page(browser, url, f"#/quiz/{lesson}/{row['id']}") + page.wait_for_selector("#qz-q") + page.wait_for_selector("#qz-grade", timeout=15000) + assert page.inner_text("#qz-grade b") == "30" and "הזמן נגמר" in page.inner_text(".qz-result") + + +def test_a_retake_draws_new_questions_and_a_second_quiz_does_not_replace_the_best_grade(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + first = seed_attempt(store, bank, lesson, grade=85) + with running(app) as url: + page = path_page(browser, url, f"#/quiz/{lesson}") # the node's address starts a quiz + page.wait_for_selector("#qz-q") + second = store.attempts_of(KID_ID, "quiz", lesson)[-1] + assert second["id"] != first["id"] and not {q["key"] for q in second["questions"]} & {q["key"] for q in first["questions"]} + page.click("#qz-submit") + page.click("#qz-yes") # an empty quiz: 0 + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "0" + page.wait_for_function("document.querySelector('#qz-best').innerText.includes('85')") # the best grade stays + page.click("#qz-retake") + page.wait_for_selector("#qz-q") + third = store.attempts_of(KID_ID, "quiz", lesson)[-1] + used = {q["key"] for a in (first, second) for q in a["questions"]} + assert third["id"] not in (first["id"], second["id"]) and len(third["questions"]) == 10 + assert len({q["key"] for q in third["questions"]} & used) <= 4 # mostly new questions + + +# --- 3.4 the grades screen --- + +def test_the_grades_screen_is_empty_at_first_then_lists_the_best_grade_attempts_and_date(browser, bank): + one, two = lessons_of(bank, 4, 3) + app, store = world(bank, [one, two]) + with running(app) as url: + page = path_page(browser, url, "#/grades") + page.wait_for_selector("#grades") + assert "עוד אין ציונים" in page.inner_text("#no-grades") and page.locator("#quiz-grades").count() == 0 + seed_attempt(store, bank, one, grade=60) + seed_attempt(store, bank, one, grade=85) # the better of two + seed_attempt(store, bank, one, grade=70) + seed_attempt(store, bank, two, grade=40) + page.reload() + page.wait_for_selector("#quiz-grades") + row = page.locator(f"#quiz-grades li[data-lesson='{one}']") + assert row.locator(".gr-num").inner_text() == "85" and "3 ניסיונות" in row.inner_text() and "האחרון ב" in row.inner_text() + assert row.locator("[role=progressbar]").get_attribute("aria-valuenow") == "85" + assert page.locator(f"#quiz-grades li[data-lesson='{two}'] .gr-num").inner_text() == "40" + assert page.locator("#quiz-grades li").count() == 2 + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + assert page.locator(".tabs a[aria-current='page']").inner_text() == "ציונים" + page.click(f"#quiz-grades li[data-lesson='{one}'] a") # a row leads to that lesson's quiz + page.wait_for_selector("#qz-q") + + +# --- 4.1 the whole quiz --- + +def test_a_whole_quiz_from_the_trail_to_the_grades_screen(browser, bank): + (lesson,) = lessons_of(bank, 4) + app, store = world(bank, [lesson]) + with running(app) as url: + page = path_page(browser, url) + page.click(f".quiz-node[data-quiz='{lesson}']") + page.wait_for_selector("#qz-q") + refs = refs_on_screen(store, lesson) + by_skill = Counter(r["skill_id"] for r in refs) + lost_skill = next(s for s, n in by_skill.items() if n >= 2) + wrong = {r["key"] for r in [r for r in refs if r["skill_id"] == lost_skill][:2]} + for _ in range(10): # answer all ten, moving with "next" + ref = next(r for r in refs if r["key"] == page.get_attribute("#qz-q", "data-key")) + tap_choice(page, bank, ref, ok=ref["key"] not in wrong) + if page.locator("#qz-count").inner_text().startswith("שאלה 10"): + break + page.click(".qz-nav button >> nth=1") + page.wait_for_function("(k) => document.querySelector('#qz-q').dataset.key !== k", arg=ref["key"]) + page.wait_for_function("document.querySelectorAll('.qz-dot.done').length === 10") + page.click("#qz-submit") # all answered: no warning + page.wait_for_selector("#qz-grade") + assert page.inner_text("#qz-grade b") == "80" + assert page.locator("#qz-lost a").get_attribute("href") == f"#/skill/{lost_skill}" + page.click("#qz-lost a") # practice the weak skill + page.wait_for_selector("#ex-q") + page.click(".mx-x") + page.wait_for_selector(f".quiz-node[data-quiz='{lesson}'].graded") + assert "✓ הציון: 80" in page.inner_text(f".quiz-node[data-quiz='{lesson}']") # the node shows the grade + page.click(".tabs a[href='#/grades']") + page.wait_for_selector("#quiz-grades") + assert page.locator(f"#quiz-grades li[data-lesson='{lesson}'] .gr-num").inner_text() == "80" diff --git a/mathly2/tests/test_quizzes_api.py b/mathly2/tests/test_quizzes_api.py new file mode 100644 index 0000000000000000000000000000000000000000..f9ed3be9bf4b02d1d9e4b7d6f903c55888b4959e --- /dev/null +++ b/mathly2/tests/test_quizzes_api.py @@ -0,0 +1,224 @@ +"""Lesson quizzes through the API (add-lesson-quizzes 2.1-2.4). The `world` fixture and helpers come from test_skills_api.""" +import json +from datetime import timedelta + +from mathly2.tests.test_skills_api import KID, MGR, MON, OTHER, auth, raw, world # noqa: F401 + +LESSON = "t" + + +def lesson_id(bank, size=4): + from collections import Counter + counts = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + return next(l for l, c in counts.items() if c == size) + + +def start(client, lesson, who=KID): + return client.post(f"/api/lessons/{lesson}/quiz/start", headers=auth(who)) + + +def right_index(bank, skill_id, key, right=True): + question = bank._questions[skill_id][key] + picks = [i for i, c in enumerate(question["choices"]) if bool(c.get("correct")) == right] + if not right: + picks = [i for i in picks if question["choices"][i].get("mistake")] or picks + return picks[0] + + +def skill_of(key): + return key.split(":")[0] + + +def answer(client, attempt, bank, key, right=True, who=KID): + return client.put(f"/api/attempts/{attempt['id']}/answers", json={"key": key, "choice": right_index(bank, skill_of(key), key, right)}, + headers=auth(who)) + + +def take(client, bank, lesson, rights, who=KID): + """Start a quiz and answer the first len(rights) questions right or wrong; submit; return the result.""" + attempt = start(client, lesson, who).json() + for question, right in zip(attempt["questions"], rights): + assert answer(client, attempt, bank, question["key"], right, who).status_code == 200 + return client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth(who)).json() + + +# --- 2.1 starting --- + +def test_a_new_student_starts_a_quiz_of_ten_questions_due_in_fifteen_minutes(world): + client, _, bank = world + lesson = lesson_id(bank) + got = start(client, lesson) + assert got.status_code == 200 + quiz = got.json() + assert quiz["state"] == "open" and len(quiz["questions"]) == 10 and quiz["answers"] == {} + from datetime import datetime + assert datetime.fromisoformat(quiz["due_at"]) - datetime.fromisoformat(quiz["now"]) == timedelta(minutes=15) + assert quiz["lesson"]["id"] == lesson + + +def test_a_served_quiz_never_carries_a_right_answer_a_mistake_or_a_skill_name(world): + client, _, bank = world + lesson = lesson_id(bank) + blob = json.dumps(start(client, lesson).json(), ensure_ascii=False) + assert '"correct"' not in blob and '"mistake"' not in blob and '"skill' not in blob + skills = {s["name"] for s in bank.skills if s["unit"] == lesson} + assert not any(name in blob for name in skills) + + +def test_starting_again_resumes_the_same_open_attempt(world): + client, _, bank = world + lesson = lesson_id(bank) + first = start(client, lesson).json() + answer(client, first, bank, first["questions"][0]["key"]) + again = start(client, lesson).json() + assert again["id"] == first["id"] and [q["key"] for q in again["questions"]] == [q["key"] for q in first["questions"]] + assert len(again["answers"]) == 1 and again["due_at"] == first["due_at"] + facts = client.get(f"/api/lessons/{lesson}/quiz", headers=auth()).json() + assert facts["open"]["id"] == first["id"] and facts["best"] is None and facts["attempts"] == 0 and facts["size"] == 10 and facts["minutes"] == 15 + + +def test_a_lesson_the_students_classes_do_not_have_is_404_and_a_manager_is_refused(world): + client, store, bank = world + store.add_member(store.create_class("setup", "B", lessons=["t"])["id"], "solo@school.test") + other_lesson = next(l["id"] for l in bank.lessons if l["id"] != "t") + assert start(client, other_lesson, "solo@school.test").status_code == 404 + assert client.get(f"/api/lessons/{other_lesson}/quiz", headers=auth("solo@school.test")).status_code == 404 + assert start(client, "no-such-lesson").status_code == 404 + assert start(client, LESSON, MGR).status_code == 403 + + +# --- 2.2 answering, submitting, time --- + +def test_an_answer_is_saved_can_be_changed_and_submitting_grades_it(world): + client, _, bank = world + attempt = start(client, lesson_id(bank)).json() + key = attempt["questions"][0]["key"] + answer(client, attempt, bank, key, right=False) + answer(client, attempt, bank, key, right=True) # changed their mind + assert client.get(f"/api/attempts/{attempt['id']}", headers=auth()).json()["answers"] == {key: right_index(bank, skill_of(key), key)} + result = client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth()).json() + assert result["state"] == "submitted" and result["grade"] == 10 and result["right"] == 1 and result["total"] == 10 and result["timed_out"] is False + + +def test_submitting_twice_returns_the_same_result(world): + client, _, bank = world + attempt = start(client, lesson_id(bank)).json() + answer(client, attempt, bank, attempt["questions"][0]["key"]) + one = client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth()).json() + two = client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth()).json() + assert one == two and client.get(f"/api/attempts/{attempt['id']}", headers=auth()).json() == one + + +def test_an_answer_after_the_deadline_is_refused_and_settles_the_attempt(world): + client, _, bank = world + attempt = start(client, lesson_id(bank)).json() + answer(client, attempt, bank, attempt["questions"][0]["key"]) + client.set_time(MON + timedelta(minutes=16)) + late = answer(client, attempt, bank, attempt["questions"][1]["key"]) + assert late.status_code == 409 + settled = client.get(f"/api/attempts/{attempt['id']}", headers=auth()).json() + assert settled["state"] == "submitted" and settled["timed_out"] is True and settled["grade"] == 10 and settled["right"] == 1 + + +def test_closing_the_app_for_twenty_minutes_leaves_a_submitted_attempt_with_the_answers_given(world): + client, _, bank = world + attempt = start(client, lesson_id(bank)).json() + for q in attempt["questions"][:6]: + answer(client, attempt, bank, q["key"]) + client.set_time(MON + timedelta(minutes=5)) # five minutes in, the app is closed + client.set_time(MON + timedelta(minutes=25)) # it is opened again 20 minutes later + back = client.get(f"/api/attempts/{attempt['id']}", headers=auth()).json() + assert back["state"] == "submitted" and back["timed_out"] is True and back["grade"] == 60 and back["right"] == 6 + + +def test_the_deadline_is_the_servers_a_late_device_clock_changes_nothing(world): + client, _, bank = world + attempt = start(client, lesson_id(bank)).json() + # the server's time is what counts: at 14 minutes the attempt is still open, whatever the device says + client.set_time(MON + timedelta(minutes=14)) + assert client.get(f"/api/attempts/{attempt['id']}", headers=auth()).json()["state"] == "open" + assert answer(client, attempt, bank, attempt["questions"][0]["key"]).status_code == 200 + + +def test_another_student_gets_404_and_bad_answers_are_422(world): + client, store, bank = world + store.add_member(store.classes()[0]["id"], OTHER) + attempt = start(client, lesson_id(bank)).json() + key = attempt["questions"][0]["key"] + for call in (lambda: client.get(f"/api/attempts/{attempt['id']}", headers=auth(OTHER)), + lambda: client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth(OTHER)), + lambda: client.put(f"/api/attempts/{attempt['id']}/answers", json={"key": key, "choice": 0}, headers=auth(OTHER))): + assert call().status_code == 404 + assert client.put(f"/api/attempts/{attempt['id']}/answers", json={"key": "nope:key", "choice": 0}, headers=auth()).status_code == 422 + assert client.put(f"/api/attempts/{attempt['id']}/answers", json={"key": key, "choice": 99}, headers=auth()).status_code == 422 + assert client.get("/api/attempts/not-an-id", headers=auth()).status_code == 404 + + +# --- 2.3 grades and the path --- + +def test_the_best_grade_stays_and_a_better_retake_replaces_it(world): + client, _, bank = world + lesson = lesson_id(bank) + take(client, bank, lesson, [True] * 6 + [False] * 4) # 60 + assert client.get(f"/api/lessons/{lesson}/quiz", headers=auth()).json()["best"] == 60 + take(client, bank, lesson, [True] * 8 + [False] * 2) # 80 + assert client.get(f"/api/lessons/{lesson}/quiz", headers=auth()).json()["best"] == 80 + take(client, bank, lesson, [True] * 7 + [False] * 3) # 70: worse + facts = client.get(f"/api/lessons/{lesson}/quiz", headers=auth()).json() + assert facts["best"] == 80 and facts["attempts"] == 3 + + +def test_the_grades_screen_data_lists_only_lessons_with_a_quiz_and_settles_overdue_ones(world): + client, _, bank = world + lesson = lesson_id(bank) + assert client.get("/api/grades", headers=auth()).json() == {"quizzes": [], "exercise_tests": [], "simulations": []} + take(client, bank, lesson, [True] * 7 + [False] * 3) + other = lesson_id(bank, 3) + abandoned = start(client, other).json() + answer(client, abandoned, bank, abandoned["questions"][0]["key"]) + assert [q["lesson"]["id"] for q in client.get("/api/grades", headers=auth()).json()["quizzes"]] == [lesson] # open: not listed yet + client.set_time(MON + timedelta(hours=1)) # the overdue attempt is settled by the read + grades = client.get("/api/grades", headers=auth()).json()["quizzes"] + assert {g["lesson"]["id"]: g["best"] for g in grades} == {lesson: 70, other: 10} + assert all(g["attempts"] == 1 and g["last"] for g in grades) + + +def test_the_path_gives_each_lesson_its_quiz_state(world): + client, _, bank = world + lesson, other = lesson_id(bank), lesson_id(bank, 3) + quizzes = lambda: {l["id"]: l["quiz"] for l in client.get("/api/path", headers=auth()).json()["lessons"]} + assert quizzes()[lesson] == {"best": None, "open": False, "due_at": None} + take(client, bank, lesson, [True] * 9 + [False]) + start(client, other) + state = quizzes() + assert state[lesson]["best"] == 90 and state[lesson]["open"] is False + assert state[other]["best"] is None and state[other]["open"] is True and state[other]["due_at"] + + +# --- 2.4 written quizzes are not lesson quizzes --- + +def test_a_lesson_with_an_authored_written_quiz_still_gets_the_multiple_choice_quiz(world): + client, _, bank = world + lesson = next(u["id"] for u in bank.data["units"] if u.get("quiz") and u["id"] == lesson_id(bank)) + assert bank.data["units"][[u["id"] for u in bank.data["units"]].index(lesson)]["quiz"]["questions"] + quiz = start(client, lesson).json() + assert len(quiz["questions"]) == 10 and all(len(q["choices"]) >= 2 for q in quiz["questions"]) + keys = {k for s in bank.skills if s["unit"] == lesson for k in bank.question_keys(s["id"])} + assert {q["key"] for q in quiz["questions"]} <= keys # only bank questions of the lesson's skills + + +def test_the_draw_never_reads_the_units_written_quiz(): + import inspect + from mathly2 import quiz as quiz_module + assert '"quiz"' not in inspect.getsource(quiz_module.draw) and "['quiz']" not in inspect.getsource(quiz_module.draw) + + +def test_a_retake_has_new_questions_through_the_api(world): + client, _, bank = world + lesson = lesson_id(bank) + first = start(client, lesson).json() + first_keys = {q["key"] for q in first["questions"]} + client.post(f"/api/attempts/{first['id']}/submit", headers=auth()) + second = start(client, lesson).json() + assert second["id"] != first["id"] and len(second["questions"]) == 10 + assert not first_keys & {q["key"] for q in second["questions"]} # none of the first attempt's questions diff --git a/mathly2/tests/test_readiness.py b/mathly2/tests/test_readiness.py new file mode 100644 index 0000000000000000000000000000000000000000..d592d27c414b3768dc738039422a4344b1873bc4 --- /dev/null +++ b/mathly2/tests/test_readiness.py @@ -0,0 +1,44 @@ +"""The readiness number (add-test-readiness 1.3).""" +import pytest + +from mathly2 import readiness + + +def test_only_mastery_so_far_gives_that_percent(): + got = readiness.compute(60, None, None) + assert got["number"] == 60 and got["capped"] is False and got["parts"] == {"M": 60, "E": None, "S": None} + + +def test_all_three_parts_are_weighted_50_20_30(): + assert readiness.compute(80, 70, 90)["number"] == 81 + assert readiness.compute(100, 100, 100)["number"] == 100 and readiness.compute(0, 0, 0)["number"] == 0 + + +def test_a_missing_part_is_left_out_and_the_others_are_scaled_up(): + assert readiness.compute(80, 60, None)["number"] == 74 # (50*80 + 20*60) / 70, rounded + assert readiness.compute(50, None, 70)["number"] == 58 # (50*50 + 30*70) / 80 + assert readiness.compute(None, None, 40)["number"] == 40 + + +def test_before_the_simulation_the_number_is_capped_at_80_and_says_so(): + got = readiness.compute(100, 95, None) + assert got["number"] == 80 and got["capped"] is True and got["waiting_for_simulation"] is True + assert readiness.compute(100, 95, 100)["number"] == 99 and readiness.compute(100, 95, 100)["waiting_for_simulation"] is False + assert readiness.compute(79, None, None)["capped"] is False + + +def test_labels_at_their_edges(): + for number, name in ((0, "מתחילים"), (39, "מתחילים"), (40, "בדרך"), (69, "בדרך"), (70, "כמעט שם"), (84, "כמעט שם"), (85, "מוכנים"), (100, "מוכנים")): + assert readiness.label(number) == name + + +@pytest.mark.parametrize("m,e", [(100, 100), (100, 0), (90, 95), (85, 85)]) +def test_ready_never_shows_without_the_simulation(m, e): + assert readiness.compute(m, e, None)["label"] != "מוכנים" + assert readiness.compute(100, 100, 100)["label"] == "מוכנים" + + +def test_nothing_known_is_zero_and_the_parts_helpers(): + assert readiness.compute(None, None, None)["number"] == 0 + assert readiness.mastery_percent(3, 4) == 75 and readiness.mastery_percent(0, 0) is None + assert readiness.exercise_average([60, 80]) == 70 and readiness.exercise_average([]) is None diff --git a/mathly2/tests/test_realtests_api.py b/mathly2/tests/test_realtests_api.py new file mode 100644 index 0000000000000000000000000000000000000000..7d21f1e22dd917bc0780baa7115cc25389c39535 --- /dev/null +++ b/mathly2/tests/test_realtests_api.py @@ -0,0 +1,432 @@ +"""Real tests through the API: the teacher's routes (add-test-readiness 2.1), and below the students' (2.2-2.4).""" +import uuid +from datetime import datetime, timedelta, timezone + +import pytest +from fastapi.testclient import TestClient + +from mathly2 import clock +from mathly2.bank import load_bank +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore + +TEACHER, OTHER_TEACHER, KID, KID2, MGR = "t@school.test", "t2@school.test", "kid@school.test", "kid2@school.test", "mgr@school.test" +MON = datetime(2026, 11, 2, 9, 0, tzinfo=timezone.utc) +DAY = timedelta(days=1) + + +def uid(email): + return str(uuid.uuid5(uuid.NAMESPACE_DNS, email)) + + +def auth(email): + return {"Authorization": f"Bearer dev:{email}"} + + +@pytest.fixture(scope="module") +def bank(): + return load_bank() + + +@pytest.fixture +def world(bank, monkeypatch): + """(client, store, lessons): class A (teacher T, students KID and KID2) studies three 4-skill lessons; class B (teacher T2) one.""" + from collections import Counter + sizes = Counter(s["unit"] for s in bank.skills if bank.question_keys(s["id"])) + lessons = [l for l, c in sizes.items() if c == 4][:4] + store = InMemoryStore() + store.give_role(MGR, "manager", "setup") + a = store.create_class("setup", "A", lessons=lessons[:3], teacher_email=TEACHER) + store.create_class("setup", "B", lessons=lessons[3:], teacher_email=OTHER_TEACHER) + for email in (KID, KID2): + store.add_member(a["id"], email) + client = TestClient(create_app(Settings(), bank=bank, store=store)) + moment = {"now": MON} + monkeypatch.setattr(clock, "now", lambda: moment["now"]) + client.set_time = lambda value: moment.update(now=value) + client.class_id = a["id"] + return client, store, lessons + + +def set_test(client, lessons, days=14, who=TEACHER, class_id=None, **extra): + day = (clock.now() + timedelta(days=days)).date().isoformat() + return client.post(f"/api/classes/{class_id or client.class_id}/tests", json={"date": day, "lessons": lessons[:2], **extra}, headers=auth(who)) + + +# --- 2.1 the teacher --- + +def test_a_test_set_without_changing_length_has_12_questions_and_45_minutes(world): + client, store, lessons = world + got = set_test(client, lessons, note="פרק 3") + assert got.status_code == 201 + test = got.json() + assert test["questions"] == 12 and test["minutes"] == 45 and test["note"] == "פרק 3" and test["days_left"] == 14 + assert [l["id"] for l in test["lessons"]] == lessons[:2] and test["class"]["name"] == "A" + assert test["simulation"] == {"taken": 0, "total": 2, "missing": [KID, KID2]} + assert store.get_test(test["id"])["created_by"] == TEACHER + + +def test_the_length_can_be_changed_and_is_limited(world): + client, _, lessons = world + ok = set_test(client, lessons, questions=20, minutes=60).json() + assert ok["questions"] == 20 and ok["minutes"] == 60 + for bad in ({"questions": 0}, {"questions": 41}, {"minutes": 4}, {"minutes": 181}): + assert set_test(client, lessons, **bad).status_code == 422 + + +def test_lessons_outside_the_class_and_a_past_date_are_refused(world): + client, _, lessons = world + foreign = client.post(f"/api/classes/{client.class_id}/tests", json={"date": "2026-12-01", "lessons": [lessons[3]]}, headers=auth(TEACHER)) + assert foreign.status_code == 422 + assert client.post(f"/api/classes/{client.class_id}/tests", json={"date": "2026-12-01", "lessons": []}, headers=auth(TEACHER)).status_code == 422 + assert set_test(client, lessons, days=-1).status_code == 422 + assert set_test(client, lessons, days=0).status_code == 201 # the test day itself is allowed + + +def test_a_teacher_of_another_class_gets_404_and_a_student_or_manager_is_refused(world): + client, _, lessons = world + assert set_test(client, lessons, who=OTHER_TEACHER).status_code == 404 + assert set_test(client, lessons, who=KID).status_code == 403 + assert set_test(client, lessons, who=MGR).status_code == 403 + test = set_test(client, lessons).json() + assert client.put(f"/api/tests/{test['id']}", json={"note": "x"}, headers=auth(OTHER_TEACHER)).status_code == 404 + assert client.delete(f"/api/tests/{test['id']}", headers=auth(OTHER_TEACHER)).status_code == 404 + assert client.get("/api/teaching/tests", headers=auth(OTHER_TEACHER)).json()[0]["tests"] == [] + + +def test_a_test_can_be_changed_before_its_date_and_the_countdown_follows(world): + client, store, lessons = world + test = set_test(client, lessons, days=10).json() + moved = client.put(f"/api/tests/{test['id']}", json={"date": (clock.now() + 12 * DAY).date().isoformat(), "note": "מועד ב", "questions": 15, + "minutes": 50, "lessons": lessons[:1]}, headers=auth(TEACHER)) + assert moved.status_code == 200 + body = moved.json() + assert body["days_left"] == 12 and body["note"] == "מועד ב" and body["questions"] == 15 and body["minutes"] == 50 and len(body["lessons"]) == 1 + home = client.get("/api/home", headers=auth(KID)).json() # every student's countdown follows the new date + assert home["tests"][0]["days_left"] == 12 + + +def test_a_test_cannot_be_changed_on_or_after_its_day(world): + client, _, lessons = world + test = set_test(client, lessons, days=2).json() + client.set_time(MON + 2 * DAY) + assert client.put(f"/api/tests/{test['id']}", json={"note": "late"}, headers=auth(TEACHER)).status_code == 409 + client.set_time(MON + DAY) + assert client.put(f"/api/tests/{test['id']}", json={"date": "2026-10-01"}, headers=auth(TEACHER)).status_code == 422 + + +def test_removing_a_test_hides_it_but_keeps_the_grades_already_earned(world): + client, store, lessons = world + test = set_test(client, lessons).json() + row = store.create_attempt(uid(KID), "exercise_test", f"{test['id']}:1", clock.now(), clock.now() + timedelta(minutes=45), []) + store.save_attempt(row["id"], submitted_at=clock.now(), grade=80) + assert client.delete(f"/api/tests/{test['id']}", headers=auth(TEACHER)).status_code == 204 + assert client.get("/api/teaching/tests", headers=auth(TEACHER)).json()[0]["tests"] == [] + assert client.get("/api/home", headers=auth(KID)).json()["tests"] == [] + assert store.get_test(test["id"])["removed_at"] is not None and store.get_attempt(row["id"])["grade"] == 80 + assert client.delete(f"/api/tests/{test['id']}", headers=auth(TEACHER)).status_code == 404 + + +def test_the_tests_tab_shows_who_took_the_simulation_and_names_those_who_did_not(world): + client, store, lessons = world + klass = client.class_id + for i in range(23): # a class of 25 + store.add_member(klass, f"s{i}@school.test") + test = set_test(client, lessons).json() + for i in range(22): + row = store.create_attempt(uid(f"s{i}@school.test"), "simulation", str(test["id"]), clock.now(), clock.now() + timedelta(minutes=45), []) + store.save_attempt(row["id"], submitted_at=clock.now(), grade=70) + store.link_user(f"s{i}@school.test", uid(f"s{i}@school.test")) + tab = client.get("/api/teaching/tests", headers=auth(TEACHER)).json() + listed = tab[0]["tests"][0] + assert listed["simulation"]["taken"] == 22 and listed["simulation"]["total"] == 25 + assert sorted(listed["simulation"]["missing"]) == sorted([KID, KID2, "s22@school.test"]) + taken = next(s for s in listed["students"] if s["email"] == "s0@school.test") + assert taken["simulation_taken"] is True and taken["readiness"]["parts"]["S"] == 70 + assert [c["class"]["name"] for c in tab] == ["A"] and tab[0]["class"]["lessons"] + + +# --- 2.2 the student's home and a test's card --- + +def covered(bank, lessons): + return [s["id"] for s in bank.skills if s["unit"] in lessons and bank.question_keys(s["id"])] + + +def master(store, skills, who=KID): + for i in skills: + store.save_progress(uid(who), i, started_at="then", mastered_at="then") + + +def finished(store, test_id, kind, scope, grade, who=KID, questions=None): + row = store.create_attempt(uid(who), kind, scope, clock.now() - 2 * DAY, clock.now() - 2 * DAY + timedelta(minutes=45), questions or []) + return store.save_attempt(row["id"], submitted_at=clock.now() - 2 * DAY + timedelta(minutes=10), grade=grade) + + +def test_with_no_test_home_has_only_the_next_skill(world): + client, _, _ = world + home = client.get("/api/home", headers=auth(KID)).json() + assert home["tests"] == [] and home["task"] is None and home["required_simulations"] == [] + assert home["next_skill"]["id"] and home["next_skill"]["name"] + + +def test_nine_days_before_the_test_todays_task_is_exercise_test_1(world): + client, _, lessons = world + test = set_test(client, lessons, days=9).json() + home = client.get("/api/home", headers=auth(KID)).json() + assert home["task"]["kind"] == "ex1" and home["task"]["test_id"] == test["id"] + assert home["tests"][0]["days_left"] == 9 and home["tests"][0]["exercise_tests"][0]["best"] is None + + +def test_twelve_days_ahead_the_task_is_finishing_the_path_with_the_next_covered_skill(world): + client, _, lessons = world + set_test(client, lessons, days=12) + task = client.get("/api/home", headers=auth(KID)).json()["task"] + assert task["kind"] == "path" and task["skill"] and task["skill_name"] + + +def test_four_days_before_the_simulation_is_required_until_it_is_taken(world): + client, store, lessons = world + set_test_ = set_test(client, lessons, days=14).json() + client.set_time(MON + 10 * DAY) # four days left + home = client.get("/api/home", headers=auth(KID)).json() + assert home["task"]["kind"] == "sim" and [r["test_id"] for r in home["required_simulations"]] == [set_test_["id"]] + assert home["tests"][0]["simulation"]["required"] is True and home["tests"][0]["simulation"]["open_now"] is True + finished(store, set_test_["id"], "simulation", str(set_test_["id"]), 70) + home = client.get("/api/home", headers=auth(KID)).json() + assert home["required_simulations"] == [] and home["tests"][0]["simulation"]["taken"] is True and home["tests"][0]["simulation"]["grade"] == 70 + + +def test_two_tests_give_the_task_of_the_closer_one(world): + client, _, lessons = world + far = set_test(client, lessons, days=10).json() + near = set_test(client, lessons, days=4).json() + home = client.get("/api/home", headers=auth(KID)).json() + assert [t["id"] for t in home["tests"]] == [near["id"], far["id"]] + assert home["task"]["test_id"] == near["id"] and home["task"]["kind"] == "ex1" # set 4 days ahead: the short plan starts with exercise test 1 today + + +def test_readiness_shows_the_parts_that_exist_and_caps_before_the_simulation(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + skills = covered(client.app.state.bank, lessons[:2]) + master(store, skills[:6]) # M = 6 of 8 = 75 + home = client.get("/api/home", headers=auth(KID)).json()["tests"][0]["readiness"] + assert home["number"] == 75 and home["parts"] == {"M": 75, "E": None, "S": None} and home["waiting_for_simulation"] is True + finished(store, test["id"], "exercise_test", f"{test['id']}:1", 60) + finished(store, test["id"], "exercise_test", f"{test['id']}:2", 80) + ready = client.get("/api/home", headers=auth(KID)).json()["tests"][0]["readiness"] + assert ready["parts"] == {"M": 75, "E": 70, "S": None} and ready["number"] == 74 # (50*75 + 20*70) / 70 + master(store, skills[6:]) + finished(store, test["id"], "simulation", str(test["id"]), 90) + full = client.get("/api/home", headers=auth(KID)).json()["tests"][0]["readiness"] + assert full["parts"] == {"M": 100, "E": 70, "S": 90} and full["number"] == 91 and full["capped"] is False and full["label"] == "מוכנים" + + +def test_the_card_has_the_plan_the_exercise_tests_and_what_to_practise_first(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + skills = covered(client.app.state.bank, lessons[:2]) + master(store, skills[:2]) + store.save_progress(uid(KID), skills[2], started_at="then") # learning; the other five are not started + card = client.get(f"/api/tests/{test['id']}", headers=auth(KID)).json() + assert [s["id"] for s in card["plan"]] == ["path", "ex1", "ex2", "sim", "review"] and card["plan"][1]["day"] == 9 + assert [e["number"] for e in card["exercise_tests"]] == [1, 2] and card["questions"] == 12 and card["minutes"] == 45 + assert [s["id"] for s in card["practice_first"]] == skills[3:] and all(s["name"] for s in card["practice_first"]) + sim = card["simulation"] + assert sim["open_now"] is False and sim["opens_in_days"] == 9 and sim["opens_on"] == (clock.now() + 9 * DAY).date().isoformat() and sim["taken"] is False + + +def test_a_student_of_another_class_and_a_missing_test_give_404(world): + client, store, lessons = world + test = set_test(client, lessons).json() + store.add_member(store.classes()[1]["id"], "outsider@school.test") + assert client.get(f"/api/tests/{test['id']}", headers=auth("outsider@school.test")).status_code == 404 + assert client.get("/api/tests/999", headers=auth(KID)).status_code == 404 + assert client.get("/api/home", headers=auth("outsider@school.test")).json()["tests"] == [] + + +# --- 2.3 exercise tests and the simulation --- + +import json # noqa: E402 + + +def right_index(bank, ref_key, right=True): + skill_id = ref_key.split(":")[0] + question = bank._questions[skill_id][ref_key] + picks = [i for i, c in enumerate(question["choices"]) if bool(c.get("correct")) == right] + if not right: + picks = [i for i in picks if question["choices"][i].get("mistake")] or picks + return picks[0] + + +def answer_all(client, bank, attempt, rights, who=KID): + """Answer the attempt's questions right (True) or wrong (False), one flag per question; submit; return the result.""" + for question, ok in zip(attempt["questions"], rights): + got = client.put(f"/api/attempts/{attempt['id']}/answers", json={"key": question["key"], "choice": right_index(bank, question["key"], ok)}, headers=auth(who)) + assert got.status_code == 200 + return client.post(f"/api/attempts/{attempt['id']}/submit", headers=auth(who)).json() + + +def started(client, store, lessons, learning=5, mastered=3, who=KID): + skills = covered(client.app.state.bank, lessons[:2]) + for i in skills[:learning]: + store.save_progress(uid(who), i, started_at="then") + master(store, skills[learning:learning + mastered], who) + return skills + + +def start_ex(client, test_id, number=1, who=KID): + return client.post(f"/api/tests/{test_id}/exercise/{number}/start", headers=auth(who)) + + +def start_sim(client, test_id, who=KID): + return client.post(f"/api/tests/{test_id}/simulation/start", headers=auth(who)) + + +def test_an_exercise_test_has_the_tests_questions_and_time_and_no_right_answers_or_skill_names(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6, minutes=30).json() + skills = started(client, store, lessons) + got = start_ex(client, test["id"]) + assert got.status_code == 200 + attempt = got.json() + assert attempt["kind"] == "exercise_test" and attempt["state"] == "open" and len(attempt["questions"]) == 6 + assert datetime.fromisoformat(attempt["due_at"]) - datetime.fromisoformat(attempt["now"]) == timedelta(minutes=30) + assert attempt["test"]["id"] == test["id"] and attempt["test"]["number"] == 1 + blob = json.dumps(attempt, ensure_ascii=False) + assert '"correct"' not in blob and '"mistake"' not in blob and '"skill' not in blob + assert not any(client.app.state.bank.skill(i)["name"] in blob for i in skills[:3]) + + +def test_an_exercise_test_can_start_early_and_resumes_while_open(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + started(client, store, lessons) + client.set_time(MON + 3 * DAY) # 11 days before the test + first = start_ex(client, test["id"]).json() + again = start_ex(client, test["id"]).json() + assert first["id"] == again["id"] and [q["key"] for q in first["questions"]] == [q["key"] for q in again["questions"]] + assert start_ex(client, test["id"], 2).json()["id"] != first["id"] # exercise test 2 is its own attempt + + +def test_a_retake_draws_new_questions_and_the_best_grade_counts(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6).json() + started(client, store, lessons) + first = start_ex(client, test["id"]).json() + keys = {q["key"] for q in first["questions"]} + low = answer_all(client, client.app.state.bank, first, [True, True, False, False, False, False]) + assert low["grade"] == 33 and low["kind"] == "exercise_test" + second = start_ex(client, test["id"]).json() + assert second["id"] != first["id"] and not keys & {q["key"] for q in second["questions"]} + high = answer_all(client, client.app.state.bank, second, [True] * 6) + assert high["grade"] == 100 + card = client.get(f"/api/tests/{test['id']}", headers=auth(KID)).json() + assert card["exercise_tests"][0]["best"] == 100 and card["exercise_tests"][0]["attempts"] == 2 + answer_all(client, client.app.state.bank, start_ex(client, test["id"]).json(), [False] * 6) # a worse third try + assert client.get(f"/api/tests/{test['id']}", headers=auth(KID)).json()["exercise_tests"][0]["best"] == 100 + + +def test_the_result_links_the_weak_skills_found_without_right_answers(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6).json() + started(client, store, lessons) + result = answer_all(client, client.app.state.bank, start_ex(client, test["id"]).json(), [False] * 6) + assert result["lost_skills"] and all(s["id"] and s["name"] for s in result["lost_skills"]) and '"correct"' not in json.dumps(result) + + +def test_an_exercise_test_with_nothing_started_is_refused_and_a_weak_skill_is_remembered(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + assert start_ex(client, test["id"]).status_code == 409 + assert start_ex(client, test["id"], 3).status_code == 404 + + +def test_the_simulation_is_refused_8_days_before_with_its_opening_date(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + started(client, store, lessons) + client.set_time(MON + 6 * DAY) # 8 days left; it opens 5 days before the test + early = start_sim(client, test["id"]) + assert early.status_code == 409 and "ייפתח" in early.json()["detail"] + assert store.attempts_of(uid(KID), "simulation") == [] # nothing was started + + +def test_the_simulation_has_the_tests_length_can_be_taken_once_and_shows_its_result_again(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() # 12 questions, 45 minutes + started(client, store, lessons) + client.set_time(MON + 10 * DAY) # four days left: open + sim = start_sim(client, test["id"]).json() + assert sim["kind"] == "simulation" and len(sim["questions"]) == 12 + assert datetime.fromisoformat(sim["due_at"]) - datetime.fromisoformat(sim["now"]) == timedelta(minutes=45) + assert start_sim(client, test["id"]).json()["id"] == sim["id"] # open: it resumes + done = answer_all(client, client.app.state.bank, sim, [True] * 8 + [False] * 4) + assert done["grade"] == 67 + again = start_sim(client, test["id"]).json() + assert again["state"] == "submitted" and again["id"] == sim["id"] and again["grade"] == 67 # a second try shows the result + assert len(store.attempts_of(uid(KID), "simulation")) == 1 + + +def test_the_skills_the_simulation_failed_are_the_review_tasks_of_the_last_days(world): + client, store, lessons = world + test = set_test(client, lessons, days=14).json() + started(client, store, lessons) + client.set_time(MON + 10 * DAY) + sim = start_sim(client, test["id"]).json() + result = answer_all(client, client.app.state.bank, sim, [False] * 12) + failed = [s["id"] for s in result["lost_skills"]] + assert failed + client.set_time(MON + 11 * DAY) # three days left + card = client.get(f"/api/tests/{test['id']}", headers=auth(KID)).json() + assert [s["id"] for s in card["simulation"]["review"]] == failed and card["simulation"]["taken"] is True + task = client.get("/api/home", headers=auth(KID)).json()["task"] + assert task["kind"] == "review" and task["skill"] == failed[0] and task["skill_name"] + # practising that skill after the simulation takes it off the list: the next failed one is the task + store.add_answer(uid(KID), failed[0], "k", True, True, None, clock.school_day()) + after = client.get("/api/home", headers=auth(KID)).json()["task"] + if len(failed) > 1: + assert after["kind"] == "review" and after["skill"] == failed[1] + else: + assert after["kind"] == "mixed_review" + + +# --- 2.4 the grades --- + +def test_the_grades_list_each_tests_best_exercise_grades_and_the_simulation(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6).json() + started(client, store, lessons) + assert client.get("/api/grades", headers=auth(KID)).json()["exercise_tests"] == [] + bank = client.app.state.bank + answer_all(client, bank, start_ex(client, test["id"]).json(), [True] * 3 + [False] * 3) # 50 + answer_all(client, bank, start_ex(client, test["id"]).json(), [True] * 5 + [False]) # 83 + answer_all(client, bank, start_ex(client, test["id"], 2).json(), [True] * 6) # 100 + client.set_time(MON + 10 * DAY) + answer_all(client, bank, start_sim(client, test["id"]).json(), [True] * 3 + [False] * 3) # 50 (6 questions) + got = client.get("/api/grades", headers=auth(KID)).json() + assert [(g["number"], g["best"], g["attempts"]) for g in got["exercise_tests"]] == [(1, 83, 2), (2, 100, 1)] + assert [(g["best"], g["attempts"]) for g in got["simulations"]] == [(50, 1)] + assert got["exercise_tests"][0]["test"]["id"] == test["id"] and got["exercise_tests"][0]["test"]["lessons"] and got["quizzes"] == [] + + +def test_a_removed_test_keeps_its_name_in_the_grades(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6).json() + started(client, store, lessons) + answer_all(client, client.app.state.bank, start_ex(client, test["id"]).json(), [True] * 6) + client.delete(f"/api/tests/{test['id']}", headers=auth(TEACHER)) + grade = client.get("/api/grades", headers=auth(KID)).json()["exercise_tests"][0] + assert grade["best"] == 100 and grade["test"]["removed"] is True and grade["test"]["lessons"] and grade["test"]["date"] + + +def test_another_students_grades_are_not_mine_and_an_unfinished_attempt_is_not_listed(world): + client, store, lessons = world + test = set_test(client, lessons, days=14, questions=6).json() + started(client, store, lessons) + started(client, store, lessons, who=KID2) + answer_all(client, client.app.state.bank, start_ex(client, test["id"], who=KID2).json(), [True] * 6, who=KID2) + start_ex(client, test["id"]) # mine is open, not finished + assert client.get("/api/grades", headers=auth(KID)).json()["exercise_tests"] == [] + assert len(client.get("/api/grades", headers=auth(KID2)).json()["exercise_tests"]) == 1 diff --git a/mathly2/tests/test_rewards.py b/mathly2/tests/test_rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..46e7cc2d70e4738e82637d685dc9aa5fa76eb39b --- /dev/null +++ b/mathly2/tests/test_rewards.py @@ -0,0 +1,247 @@ +"""Rewards (add-rewards): the daily goal and streak, fading stars, comets. Helpers and the `world` fixture come from test_skills_api.""" +from datetime import timedelta + +from mathly2.tests.test_skills_api import (KID, KID_ID, MON, TUE, auth, master, open_skill, respond, right_choice, raw, world) # noqa: F401 + +# --- 1.1 daily goal and streak --- + + +def path_of(client, who=KID): + return client.get("/api/path", headers=auth(who)).json() + + +def test_a_fifth_right_answer_shows_the_goal_reached(world): + client, _, bank = world + bare = client.ids[0] + for _ in range(4): + respond(client, bank, bare) + assert path_of(client)["today"] == {"done": 4, "goal": 5, "reached": False} + assert respond(client, bank, bare)["today"]["reached"] is True + assert path_of(client)["today"] == {"done": 5, "goal": 5, "reached": True} + + +def test_an_answer_given_after_help_counts_toward_the_goal(world): + client, _, bank = world + bare = client.ids[0] + for _ in range(4): + respond(client, bank, bare) + client.post(f"/api/skills/{bare}/help", headers=auth()) + assert respond(client, bank, bare)["today"]["reached"] is True + + +def test_a_four_day_streak_still_shows_four_on_the_morning_with_no_answers(world): + client, _, bank = world + bare = client.ids[0] + for offset in range(4): + client.set_time(MON + timedelta(days=offset)) + for _ in range(5): + respond(client, bank, bare) + client.set_time(MON + timedelta(days=4)) # the morning after: nothing answered yet + path = path_of(client) + assert path["today"]["done"] == 0 and path["streak"] == 4 + + +def test_a_missed_day_restarts_the_streak_at_today(world): + client, _, bank = world + bare = client.ids[0] + client.set_time(MON) + for _ in range(5): + respond(client, bank, bare) + client.set_time(MON + timedelta(days=2)) # yesterday (Tuesday) had no streak day + assert path_of(client)["streak"] == 0 + for _ in range(5): + respond(client, bank, bare) + assert path_of(client)["streak"] == 1 + + +# --- 2.2 fading stars (server) --- + +def skill_row(client, skill_id): + return next(s for lesson in path_of(client)["lessons"] for s in lesson["skills"] if s["id"] == skill_id) + + +def mastered_skill(client, bank): + bare = client.ids[0] + master(client, bank, bare) + return bare + + +def test_a_mastered_skill_fades_after_14_days_and_stays_mastered(world): + client, _, bank = world + skill = mastered_skill(client, bank) # its last answer is on the second day of `master` + last = client.get("/api/collection", headers=auth()).json()["skills"][0] + assert last["faded"] is False + client.set_time(TUE + timedelta(days=13)) + assert skill_row(client, skill)["faded"] is False + for days in (14, 15): + client.set_time(TUE + timedelta(days=days)) + row = skill_row(client, skill) + assert row["faded"] is True and row["state"] == "mastered" + assert client.get("/api/collection", headers=auth()).json()["skills"][0]["faded"] is True + + +def test_one_answer_right_or_wrong_relights_a_faded_star(world): + client, _, bank = world + skill = mastered_skill(client, bank) + for correct, offset in ((True, 20), (False, 60)): + client.set_time(TUE + timedelta(days=offset)) + assert skill_row(client, skill)["faded"] is True + respond(client, bank, skill, correct=correct) + row = skill_row(client, skill) + assert row["faded"] is False and row["state"] == "mastered" # even a wrong answer relights; mastery is not undone + client.set_time(TUE + timedelta(days=60 + 14)) + assert skill_row(client, skill)["faded"] is True + + +def test_a_skill_that_is_not_mastered_is_never_faded(world): + client, _, bank = world + bare = client.ids[0] + respond(client, bank, bare) + client.set_time(MON + timedelta(days=100)) + row = skill_row(client, bare) + assert row["state"] == "learning" and row["faded"] is False + assert all(not s["faded"] for lesson in path_of(client)["lessons"] for s in lesson["skills"]) + + +def test_fading_changes_nothing_that_counts(world): + client, _, bank = world + skill = mastered_skill(client, bank) + before = path_of(client) + strip = lambda p: [(l["id"], l["mastered"], l["completed"], [(s["id"], s["state"]) for s in l["skills"]]) for l in p["lessons"]] + client.set_time(TUE + timedelta(days=30)) + after = path_of(client) + assert skill_row(client, skill)["faded"] is True + assert strip(before) == strip(after) # state, the hub's mastered count and completion are the same + assert open_skill(client, skill)["state"] == "mastered" + + +# --- 3.2 a comet is due: the answer response says so --- + +def answers(client, bank, n, correct=True): + return [respond(client, bank, client.ids[0], correct=correct) for _ in range(n)] + + +def test_the_first_comet_comes_on_the_fifth_right_answer_and_not_before(world): + client, store, bank = world + client.app.state.comet_roll = lambda: 0.0 # the 12% roll would always win: only the first-comet rule is tested + got = [r["comet"] for r in answers(client, bank, 5)] + assert got == [False, False, False, False, True] + assert store.reward_state(KID_ID)["last_comet_day"] is not None + + +def test_no_second_comet_the_same_day(world): + client, _, bank = world + client.app.state.comet_roll = lambda: 0.0 + answers(client, bank, 5) + assert [r["comet"] for r in answers(client, bank, 4)] == [False] * 4 + + +def test_a_wrong_answer_never_brings_a_comet(world): + client, _, bank = world + client.app.state.comet_roll = lambda: 0.0 + answers(client, bank, 4) + wrong = respond(client, bank, client.ids[0], correct=False) + assert wrong["comet"] is False + assert respond(client, bank, client.ids[0])["comet"] is True # the fifth right one is still the first comet + + +def test_a_reload_cannot_give_a_second_comet(world): + client, _, bank = world + client.app.state.comet_roll = lambda: 0.0 + answers(client, bank, 5) + open_skill(client, client.ids[0]); open_skill(client, client.ids[0]) + client.get("/api/path", headers=auth()) + assert respond(client, bank, client.ids[0])["comet"] is False + + +def test_after_the_first_comet_a_right_answer_on_a_later_day_has_a_chance(world): + client, _, bank = world + client.app.state.comet_roll = lambda: 0.0 + answers(client, bank, 5) + client.set_time(TUE) + client.app.state.comet_roll = lambda: 0.5 + assert respond(client, bank, client.ids[0])["comet"] is False # 50% roll: no + client.app.state.comet_roll = lambda: 0.05 + assert respond(client, bank, client.ids[0])["comet"] is True # 5% roll: yes, and not a goal answer + + +def test_no_comet_comes_once_all_twelve_are_caught(world): + client, store, bank = world + from mathly2 import comets + for c in comets.IDS: + store.add_comet(KID_ID, c) + client.app.state.comet_roll = lambda: 0.0 + assert not any(r["comet"] for r in answers(client, bank, 6)) + + +# --- 3.3 catching and listing --- + +OTHER_KID = "second@school.test" + + +def offered(client, bank): + client.app.state.comet_roll = lambda: 0.0 + answers(client, bank, 5) # the fifth right answer brings the first comet + + +def catch(client, who=KID): + return client.post("/api/comets/catch", headers=auth(who)) + + +def test_a_catch_adds_a_comet_the_student_did_not_have_with_its_fact(world): + client, store, bank = world + store.add_comet(KID_ID, "pi") + offered(client, bank) + got = catch(client) + assert got.status_code == 200 + comet = got.json()["comet"] + assert comet["id"] != "pi" and comet["sym"] and comet["name"] and comet["fact"] + assert store.comets_of(KID_ID) == {"pi", comet["id"]} + + +def test_two_catches_in_a_row_give_one_comet_and_a_409(world): + client, store, bank = world + offered(client, bank) + assert catch(client).status_code == 200 + again = catch(client) + assert again.status_code == 409 and len(store.comets_of(KID_ID)) == 1 + + +def test_a_catch_with_no_comet_offered_today_is_refused(world): + client, store, bank = world + assert catch(client).status_code == 409 # nothing crossed yet + offered(client, bank) + client.set_time(TUE) # the next day the crossing is gone + assert catch(client).status_code == 409 and store.comets_of(KID_ID) == set() + + +def test_all_twelve_can_be_caught_over_twelve_days_and_the_list_shows_them(world): + client, _, bank = world + client.app.state.comet_roll = lambda: 0.0 + seen = set() + for day in range(12): + client.set_time(MON + timedelta(days=day)) + if day == 0: + answers(client, bank, 5) + else: + client.app.state.comet_roll = lambda: 0.0 # 0.0 < 12%: a comet crosses on the first right answer of the day + assert respond(client, bank, client.ids[0])["comet"] is True + seen.add(catch(client).json()["comet"]["id"]) + assert len(seen) == 12 + listed = client.get("/api/comets", headers=auth()).json() + assert listed["caught"] == 12 and listed["total"] == 12 and all(c["caught"] for c in listed["comets"]) + client.set_time(MON + timedelta(days=13)) + assert respond(client, bank, client.ids[0])["comet"] is False # all caught: no more comets + + +def test_the_list_gives_facts_only_for_caught_comets_and_is_per_student(world): + client, store, bank = world + store.add_comet(KID_ID, "pi") + store.add_comet(KID_ID, "e") + listed = client.get("/api/comets", headers=auth()).json() + caught = [c for c in listed["comets"] if c["caught"]] + assert [c["id"] for c in caught] == ["pi", "e"] and all(c["fact"] for c in caught) + missing = [c for c in listed["comets"] if not c["caught"]] + assert len(missing) == 10 and all(set(c) == {"id", "caught"} for c in missing) # a missing comet's name and fact are not sent + store.add_member(store.classes()[0]["id"], OTHER_KID) + assert client.get("/api/comets", headers=auth(OTHER_KID)).json()["caught"] == 0 diff --git a/mathly2/tests/test_rewards_browser.py b/mathly2/tests/test_rewards_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..7f38605a11e054e0c54590c81f92cadf9f5ab27b --- /dev/null +++ b/mathly2/tests/test_rewards_browser.py @@ -0,0 +1,124 @@ +"""Comets on the exercise screen, in a real browser (add-rewards 4.1) and the whole reward loop (6.1).""" +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2 import clock +from mathly2.tests.serve import offline_formulas, running +from mathly2.tests.test_exercise_browser import KID, KID_ID, PHONE, browser, choose, key_on_screen, raw, world # noqa: F401 + + +def four_right_today(store, skill): + for i in range(4): + store.add_answer(KID_ID, skill, f"seed{i}", True, True, None, clock.school_day()) + + +def sign_in_at(browser, url, skill, **options): + page = offline_formulas(browser.new_page(viewport=PHONE, **options)) + page.goto(f"{url}#/skill/{skill}") + page.fill("#email", KID) + page.click("#dev button") + page.wait_for_selector(".mx-sheet #ex-q") + return page + + +def test_the_fifth_right_answer_brings_a_comet_that_can_be_caught_while_answering_stays_possible(browser, world): + app, store, bank, ids = world + skill = ids["bare"] + four_right_today(store, skill) + app.state.comet_roll = lambda: 0.0 + with running(app) as url: + page = sign_in_at(browser, url, skill) + choose(page, bank, skill) + page.wait_for_selector("#ex-fb .ex-ok") + page.wait_for_selector("#comet") # it crosses + assert page.evaluate("document.getAnimations().some(a => a.animationName === 'comet-fly')") + page.click("#ex-skip") # answering stays possible while it flies + page.wait_for_selector("#ex-choices .ex-choice") + page.evaluate("document.getElementById('comet').click()") # a tap catches it (a script click: the target moves) + page.wait_for_selector(".comet-dialog") + text = page.inner_text(".comet-dialog") + assert "תפסתם שביט נדיר" in text and len(text) > 60 + page.click(".comet-dialog button") + assert [c for c in store.comets_of(KID_ID)] and len(store.comets_of(KID_ID)) == 1 + choose(page, bank, skill) # a sixth right answer the same day + page.wait_for_selector("#ex-fb .ex-ok") + assert page.locator("#comet").count() == 0 # no second comet today + + +def test_under_reduced_motion_a_still_comet_button_appears_once_and_nothing_flies(browser, world): + app, store, bank, ids = world + skill = ids["bare"] + four_right_today(store, skill) + app.state.comet_roll = lambda: 0.0 + with running(app) as url: + page = sign_in_at(browser, url, skill, reduced_motion="reduce") + choose(page, bank, skill) + page.wait_for_selector("#ex-fb #comet.still") + assert page.locator("#comet svg").count() == 0 # no moving drawing + assert page.evaluate("document.getAnimations().filter(a => a.animationName === 'comet-fly').length") == 0 + assert "שביט" in page.inner_text("#comet") + page.click("#comet") + page.wait_for_selector(".comet-dialog") + page.keyboard.press("Escape") + assert len(store.comets_of(KID_ID)) == 1 and page.locator("#comet").count() == 0 + + +# --- 6.1 the whole reward loop --- + +def test_the_reward_loop_goal_comet_collection_and_constellation(browser): + from datetime import timedelta + from collections import Counter + from mathly2.bank import load_bank + from mathly2.config import Settings + from mathly2.main import create_app + from mathly2.store import InMemoryStore + from mathly2.tests.test_exercise_browser import question_key + + bank = load_bank() + sizes = Counter(s["unit"] for s in bank.skills) + lesson = next(l for l, n in sizes.items() if n == 2 and all(len(s.get("questions", [])) >= 4 for s in bank.skills if s["unit"] == l)) + first, last = [s["id"] for s in bank.skills if s["unit"] == lesson] + store = InMemoryStore() + store.add_member(store.create_class("setup", "A", lessons=[lesson])["id"], KID) + store.save_progress(KID_ID, first, started_at="then", mastered_at="then") # the lesson's first skill is done + yesterday = clock.school_day() - timedelta(days=1) + keys = bank.question_keys(last) + for key in keys[:2]: # two right answers yesterday on the last skill + store.add_answer(KID_ID, last, key, True, True, None, yesterday) + app = create_app(Settings(), bank=bank, store=store) + app.state.comet_roll = lambda: 0.0 + with running(app) as url: + page = offline_formulas(browser.new_page(viewport=PHONE)) + page.goto(url) + page.fill("#email", KID) + page.click("#dev button") + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + page.wait_for_selector(".orbit") + assert "קבוצות" not in page.inner_text("#lesson-" + lesson) + page.click(f".star[data-skill='{last}']") + page.wait_for_selector("#ex-q") + for n in range(1, 6): # five right answers today + key = key_on_screen(page) + question = next(q for q in bank.skill(last)["questions"] if question_key(last, q) == key) + page.click(f"#ex-choices .ex-choice[data-i='{next(i for i, c in enumerate(question['choices']) if c.get('correct'))}']") + page.wait_for_selector("#ex-fb .ex-ok") + if n == 1: + assert page.locator("#ex-mastered").count() == 1 # the third right answer on a second day masters it + if n < 5: + assert page.locator("#comet").count() == 0 + page.click("#ex-skip") + page.wait_for_function("(k) => document.querySelector('#ex-q')?.dataset.key !== k", arg=key) + page.wait_for_selector("#comet") # the fifth brings the first comet + page.evaluate("document.getElementById('comet').click()") + page.wait_for_selector(".comet-dialog") + name = page.inner_text(".comet-dialog .comet-card b") + page.click(".comet-dialog button") + page.click(".mx-x") # back to the path: the goal is reached + page.wait_for_function("document.querySelector('#goal-text')?.innerText.includes('5 מתוך 5')") # the path is fetched again + assert "✓" in page.inner_text("#goal-text") + page.click("a[href='#/collection']") # the collection has the comet and the constellation + page.wait_for_selector("#comets") + assert name in page.inner_text("#comets .comet-tile.have") and "1 מתוך 12" in page.inner_text("#collection") + assert page.locator(f"#done-lessons .con-card[data-lesson='{lesson}']").count() == 1 diff --git a/mathly2/tests/test_roles.py b/mathly2/tests/test_roles.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d46a55567a6617789c068e634273bd175a217e --- /dev/null +++ b/mathly2/tests/test_roles.py @@ -0,0 +1,90 @@ +from mathly2.access import CACHE_SECONDS, RoleResolver +from mathly2.config import Settings +from mathly2.store import InMemoryStore + + +def build(**settings): + store = InMemoryStore() + return RoleResolver(Settings(**settings), store), store + + +def test_a_plain_email_is_a_student(): + resolver, _ = build() + assert resolver.resolve("kid@x.test") == {"student"} + + +def test_emails_are_compared_ignoring_case_and_spaces(): + resolver, _ = build(developers=frozenset({"dev@x.test"})) + assert "developer" in resolver.resolve(" Dev@X.test ") + + +def test_a_developer_from_the_settings(): + resolver, _ = build(developers=frozenset({"dev@x.test"})) + assert resolver.resolve("dev@x.test") == {"developer"} + + +def test_a_developer_row_in_the_table_is_ignored(): + resolver, store = build() + store.give_role("sneaky@x.test", "developer", "someone") + assert resolver.resolve("sneaky@x.test") == {"student"} + + +def test_a_teacher_from_the_settings_and_a_class_teacher_who_is_in_no_setting(): + resolver, store = build(teachers=frozenset({"listed@x.test"})) + store.create_class("m@x.test", "A", lessons=["t"], teacher_email="classteacher@x.test") + assert resolver.resolve("listed@x.test") == {"teacher"} + assert resolver.resolve("classteacher@x.test") == {"teacher"} + + +def test_roles_given_in_the_table(): + resolver, store = build() + for role in ("manager", "admin", "teacher", "student"): + store.give_role(f"{role}@x.test", role, "a@x.test") + assert [sorted(resolver.resolve(f"{r}@x.test")) for r in ("manager", "admin", "teacher", "student")] == [["manager"], ["admin"], ["teacher"], ["student"]] + + +def test_first_admins_from_the_settings(): + resolver, _ = build(admins=frozenset({"head@x.test"})) + assert resolver.resolve("head@x.test") == {"admin"} + + +def test_a_student_of_a_class_is_a_student_and_a_manager_without_a_class_is_not(): + resolver, store = build() + cid = store.create_class("m@x.test", "A", lessons=["t"])["id"] + store.add_member(cid, "kid@x.test") + store.give_role("boss@x.test", "manager", "a@x.test") + assert resolver.resolve("kid@x.test") == {"student"} + assert resolver.resolve("boss@x.test") == {"manager"} # no class, so no student role + + +def test_several_roles_at_once(): + resolver, store = build(teachers=frozenset({"multi@x.test"})) + cid = store.create_class("m@x.test", "A", lessons=["t"])["id"] + store.add_member(cid, "multi@x.test") + store.give_role("multi@x.test", "manager", "a@x.test") + assert resolver.resolve("multi@x.test") == {"teacher", "manager", "student"} + + +def test_roles_are_cached_for_a_while_and_a_change_shows_after_it(): + now = [0.0] + store = InMemoryStore() + resolver = RoleResolver(Settings(), store, clock=lambda: now[0]) + assert resolver.resolve("r@x.test") == {"student"} + store.give_role("r@x.test", "manager", "a@x.test") + assert resolver.resolve("r@x.test") == {"student"} # still the cached answer + now[0] = CACHE_SECONDS + 1 + assert resolver.resolve("r@x.test") == {"manager"} + + +def test_forgetting_one_email_or_all_applies_a_change_at_once(): + resolver, store = build() + resolver.resolve("r@x.test"); resolver.resolve("s@x.test") + store.give_role("r@x.test", "manager", "a@x.test"); store.give_role("s@x.test", "admin", "a@x.test") + resolver.forget("R@x.test") + assert resolver.resolve("r@x.test") == {"manager"} and resolver.resolve("s@x.test") == {"student"} + resolver.forget() + assert resolver.resolve("s@x.test") == {"admin"} + + +def test_the_cache_lasts_thirty_seconds(): + assert CACHE_SECONDS == 30 diff --git a/mathly2/tests/test_shell_browser.py b/mathly2/tests/test_shell_browser.py index b6f61ccee81ebf3e412fe7342d3a9a2966efff25..11aeae001bec751cdb857ed370d55e4b0bda15b7 100644 --- a/mathly2/tests/test_shell_browser.py +++ b/mathly2/tests/test_shell_browser.py @@ -3,17 +3,17 @@ import pytest playwright = pytest.importorskip("playwright.sync_api") from mathly2.main import create_app -from mathly2.tests.serve import running +from mathly2.tests.serve import offline_formulas, running def test_phone_shell_is_rtl_hebrew_and_does_not_scroll_sideways(): with running(create_app()) as url, playwright.sync_playwright() as p: browser = p.chromium.launch() - page = browser.new_page(viewport={"width": 390, "height": 844}) + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) page.goto(url) assert page.get_attribute("html", "dir") == "rtl" assert page.get_attribute("html", "lang") == "he" - page.wait_for_selector("#app .card") + page.wait_for_selector("#signin") assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") browser.close() @@ -41,7 +41,7 @@ def test_dev_sign_in_then_sign_out(): app = create_app(__import__("mathly2.config", fromlist=["Settings"]).Settings(teachers=frozenset({"t@school.test"}))) with running(app) as url, playwright.sync_playwright() as p: browser = p.chromium.launch() - page = browser.new_page(viewport={"width": 390, "height": 844}) + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) page.goto(url) page.wait_for_selector("#signin form#dev") # signed out: only the sign-in screen assert "מיומנויות" not in page.inner_text("body") @@ -54,44 +54,15 @@ def test_dev_sign_in_then_sign_out(): browser.close() -def test_teacher_creates_a_class_and_adds_three_students(): - from mathly2.config import Settings - app = create_app(Settings(teachers=frozenset({"t@school.test"}))) - with running(app) as url, playwright.sync_playwright() as p: - browser = p.chromium.launch() - page = browser.new_page(viewport={"width": 390, "height": 844}) - page.goto(url) - page.fill("#email", "t@school.test") - page.click("#dev button") - page.wait_for_selector("#new-class") - page.fill("#class-name", "ט'3") - page.click("#new-class button") - page.wait_for_selector("#classes li") - page.click("#classes a") - page.wait_for_selector("#add") - page.fill("#emails", "a@school.test, b@school.test\nc@school.test") - page.click("#add button") - page.wait_for_selector("#students li") - assert page.locator("#students li").count() == 3 - assert "נוספו 3 תלמידים" in page.inner_text("#report") - assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") - page.fill("#emails", "a@school.test d@school.test") - page.click("#add button") - page.wait_for_selector("#students li >> nth=3") - assert "כבר היו בכיתה" in page.inner_text("#report") - page.click("[data-remove='a@school.test']") - page.wait_for_function("document.querySelectorAll('#students li').length === 3") - browser.close() - - def test_student_not_in_a_class_sees_the_ask_your_teacher_message_with_their_email(): with running(create_app()) as url, playwright.sync_playwright() as p: browser = p.chromium.launch() - page = browser.new_page(viewport={"width": 390, "height": 844}) + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) page.goto(url) page.fill("#email", "new.kid@school.test") page.click("#dev button") page.wait_for_selector("#no-class") assert "new.kid@school.test" in page.inner_text("#no-class") + assert "ממנהל הכיתות" in page.inner_text("#no-class") assert "מיומנויות" not in page.inner_text("body") browser.close() diff --git a/mathly2/tests/test_skill_learning_journey_browser.py b/mathly2/tests/test_skill_learning_journey_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..a95a95dddacb13a55b13b2e750968ecd3b5593a1 --- /dev/null +++ b/mathly2/tests/test_skill_learning_journey_browser.py @@ -0,0 +1,81 @@ +"""One skill from the path to mastery in a real browser, with the server's clock moved to the next day.""" +import uuid +from datetime import datetime, timezone + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +from mathly2 import clock +from mathly2.bank import load_bank, question_key +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore +from mathly2.tests.serve import offline_formulas, running + +KID = "kid@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) +MONDAY = datetime(2026, 11, 2, 9, 0, tzinfo=timezone.utc) +TUESDAY = datetime(2026, 11, 3, 9, 0, tzinfo=timezone.utc) +SKILL = "t_ext" + + +def test_two_right_answers_then_a_third_the_next_day_master_the_skill_and_the_owl_moves_on(monkeypatch): + moment = {"now": MONDAY} + monkeypatch.setattr(clock, "now", lambda: moment["now"]) + bank = load_bank() + store = InMemoryStore() + store.add_member(store.create_class("setup", "A", lessons=[u["id"] for u in bank.lessons])["id"], KID) + app = create_app(Settings(), bank=bank, store=store) + + def answer_right(page): + key = page.get_attribute("#ex-q", "data-key") + question = next(q for q in bank.skill(SKILL)["questions"] if question_key(SKILL, q) == key) + page.click(f"#ex-choices .ex-choice[data-i='{next(i for i, c in enumerate(question['choices']) if c.get('correct'))}']") + page.wait_for_selector("#ex-fb .ex-ok") + + with running(app) as url, playwright.sync_playwright() as p: + browser = p.chromium.launch() + page = offline_formulas(browser.new_page(viewport={"width": 390, "height": 844})) + page.goto(url) + page.fill("#email", KID) + page.click("#dev button") + page.click(".subject-card") + page.click(".tabs a[href='#/subject/math/path']") + + # the path: nothing started, the owl on the first skill; open the skill from its star + page.wait_for_selector(".star") + assert "לא התחלת" in page.inner_text(f".star[data-skill='{SKILL}'] .lbl") + assert page.get_attribute(".star.next", "data-skill") == SKILL # t_ext is the first skill of the first lesson + page.click(f".star[data-skill='{SKILL}']") + page.wait_for_selector("#ex-q") + + # Monday: two right answers, first try, no help + answer_right(page) + assert "1 תשובה נכונה ברצף" in page.inner_text("#ex-fb") + page.click("#ex-skip") + page.wait_for_selector("#ex-q") + answer_right(page) + assert "2 תשובות נכונות ברצף" in page.inner_text("#ex-fb") and page.locator("#ex-mastered").count() == 0 # one day: not yet + page.click("#ex-skip") + page.wait_for_selector("#ex-q") + + # Tuesday on the server: the third right answer completes the rule + moment["now"] = TUESDAY + answer_right(page) + page.wait_for_selector("#ex-mastered") + assert "3 תשובות נכונות ברצף" in page.inner_text("#ex-fb") and page.locator(".ex-done").count() == 1 + + # back on the path: the star is mastered, the owl has moved on, and the collection shows it + page.click(".mx-x") + page.wait_for_selector(".mx-layer", state="detached") + page.wait_for_function("(id) => document.querySelector(`.star[data-skill='${id}'] .lbl`).innerText.includes('נשלטה')", arg=SKILL) # the path refreshes + assert page.locator(f".star[data-skill='{SKILL}'].next").count() == 0 + assert page.locator(".star.next").count() == 1 and page.get_attribute(".star.next", "data-skill") != SKILL + page.click(".tabs a[href='#/collection']") + page.wait_for_selector("#done-skills") + assert bank.skill(SKILL)["name"] in page.inner_text("#done-skills") + assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth") + browser.close() + + assert store.get_progress(KID_ID, SKILL)["mastered_at"] == TUESDAY.isoformat() diff --git a/mathly2/tests/test_skills_api.py b/mathly2/tests/test_skills_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c828e5881e48816ecfa1e4db7d12a7840a9ae7cf --- /dev/null +++ b/mathly2/tests/test_skills_api.py @@ -0,0 +1,452 @@ +import copy +import json +import uuid +from datetime import date, datetime, timezone + +import pytest +from fastapi.testclient import TestClient + +from mathly2 import clock +from mathly2.bank import Bank, load_bank, question_key +from mathly2.config import Settings +from mathly2.main import create_app +from mathly2.store import InMemoryStore + +TEACHER, KID, OTHER, MGR = "t@school.test", "kid@school.test", "other@school.test", "mgr@school.test" +KID_ID = str(uuid.uuid5(uuid.NAMESPACE_DNS, KID)) # the id the dev sign-in gives this email +MON = datetime(2026, 11, 2, 9, 0, tzinfo=timezone.utc) +TUE = datetime(2026, 11, 3, 9, 0, tzinfo=timezone.utc) +SOLVED = {"question": "$x² + 5x + 6$", "answer": "$(x + 2)(x + 3)$", + "steps": [{"do": "מוצאים 2 ו־3", "why": "המכפלה 6 והסכום 5"}, {"do": "כותבים $(x + 2)(x + 3)$", "why": "כך מפרקים"}]} + + +def auth(email=KID): + return {"Authorization": f"Bearer dev:{email}"} + + +@pytest.fixture(scope="module") +def raw(): + return copy.deepcopy(load_bank().data) + + +@pytest.fixture +def world(raw, monkeypatch): + """(client, store, bank). client.ids = (a skill with no solved example, a skill that has one). The student is in a class + that studies every lesson; the server's clock can be set with client.set_time.""" + data = copy.deepcopy(raw) + with_questions = [s for s in data["skills"] if len(s.get("questions", [])) >= 4] + bare, solved = with_questions[0]["id"], with_questions[1]["id"] + for s in data["skills"]: + if s["id"] == solved: + s["worked_example"] = copy.deepcopy(SOLVED) + bank = Bank(data) + store = InMemoryStore() + store.give_role(MGR, "manager", "setup") + store.add_member(store.create_class("setup", "A", lessons=[u["id"] for u in data["units"]])["id"], KID) + client = TestClient(create_app(Settings(teachers=frozenset({TEACHER})), bank=bank, store=store)) + moment = {"now": MON} + monkeypatch.setattr(clock, "now", lambda: moment["now"]) + client.ids = (bare, solved) + client.set_time = lambda value: moment.update(now=value) + return client, store, bank + + +def right_choice(bank, skill_id, key): + question = next(q for q in bank.skill(skill_id)["questions"] if question_key(skill_id, q) == key) + return next(i for i, c in enumerate(question["choices"]) if c.get("correct")) + + +def wrong_choice(bank, skill_id, key): + question = next(q for q in bank.skill(skill_id)["questions"] if question_key(skill_id, q) == key) + return next(i for i, c in enumerate(question["choices"]) if not c.get("correct")) + + +def open_skill(client, skill_id, who=KID): + response = client.get(f"/api/skills/{skill_id}", headers=auth(who)) + assert response.status_code == 200, response.text + return response.json() + + +def respond(client, bank, skill_id, correct=True, who=KID): + """Answer the question on screen; return the answer response.""" + shown = open_skill(client, skill_id, who)["question"] + if shown is None: # the round is done: "סבב חדש", as the student would + assert client.post(f"/api/skills/{skill_id}/round", headers=auth(who)).status_code == 200 + shown = open_skill(client, skill_id, who)["question"] + pick = (right_choice if correct else wrong_choice)(bank, skill_id, shown["key"]) + response = client.post(f"/api/skills/{skill_id}/answer", json={"question_key": shown["key"], "choice": pick}, headers=auth(who)) + assert response.status_code == 200, response.text + return response.json() + + +def master(client, bank, skill_id): + client.set_time(MON) + respond(client, bank, skill_id) + respond(client, bank, skill_id) + client.set_time(TUE) + return respond(client, bank, skill_id) + + +# --- opening a skill (spec: exercise-screen) --- + +def test_a_skill_opens_with_its_lesson_state_question_and_counts(world): + client, _, bank = world + bare = client.ids[0] + skill = open_skill(client, bare) + lesson = next(l for l in bank.lessons if l["id"] == bank.skill(bare)["unit"]) + assert skill["lesson"] == {"id": lesson["id"], "name": lesson["name"]} and skill["name"] == bank.skill(bare)["name"] + assert skill["state"] == "not_started" and skill["question"]["key"].startswith(bare + ":") + assert skill["round"]["total"] == len(bank.practice_keys(bare)) and skill["round"]["answered"] == 0 and skill["correct_in_row"] == 0 + assert skill["practice_available"] is True and set(skill) >= {"requires", "opens", "help", "today"} + assert "stage" not in skill and "faded_examples" not in skill and "worked_example" not in skill + + +def test_a_practice_question_never_carries_the_answer(world): + client, _, _ = world + text = json.dumps(open_skill(client, client.ids[0])["question"], ensure_ascii=False) + assert '"correct"' not in text and '"mistake"' not in text + + +def test_help_has_the_explanation_and_a_solved_example_only_when_the_bank_has_one(world): + client, _, bank = world + bare, solved = client.ids + assert open_skill(client, bare)["help"] == {"explanation": bank.skill(bare)["description"], "solved_example": None} + assert open_skill(client, solved)["help"]["solved_example"] == SOLVED + + +def test_requires_and_opens_list_the_neighbouring_skills_by_name(world): + client, _, bank = world + skill = next(s for s in bank.skills if s.get("prereqs") and s.get("questions")) + needed = bank.skill(skill["prereqs"][0]) + opened = open_skill(client, skill["id"]) + assert {"id": needed["id"], "name": needed["name"]} in opened["requires"] + assert {"id": skill["id"], "name": skill["name"]} in open_skill(client, needed["id"])["opens"] + + +def test_a_skill_without_questions_has_no_question_and_cannot_be_answered(world): + client, _, _ = world + empty = open_skill(client, "a_30_side") + assert empty["question"] is None and empty["practice_available"] is False and empty["round"]["total"] == 0 + assert client.post("/api/skills/a_30_side/answer", json={"question_key": "x", "choice": 0}, headers=auth()).status_code == 409 + + +def test_unknown_skill_and_the_removed_stage_route(world): + client, _, _ = world + assert client.get("/api/skills/nope", headers=auth()).status_code == 404 + assert client.post(f"/api/skills/{client.ids[0]}/stage", json={"event": "started"}, headers=auth()).status_code in (404, 405) + + +def test_a_student_in_no_class_is_refused_everywhere(world): + client, _, _ = world + skill, stranger = client.ids[0], auth("stranger@school.test") + assert client.get(f"/api/skills/{skill}", headers=stranger).status_code == 403 + assert client.get("/api/path", headers=stranger).status_code == 403 + assert client.get("/api/collection", headers=stranger).status_code == 403 + assert client.post(f"/api/skills/{skill}/help", headers=stranger).status_code == 403 + assert client.post(f"/api/skills/{skill}/answer", json={"question_key": "k", "choice": 0}, headers=stranger).status_code == 403 + + +# --- answers (spec: exercise-screen, skill-mastery) --- + +def test_a_right_answer_returns_a_different_next_question_and_counts_as_solved(world): + client, _, bank = world + bare = client.ids[0] + first = open_skill(client, bare)["question"]["key"] + result = respond(client, bank, bare) + assert result["correct"] is True and result["mistake"] is None and result["state"] == "learning" + assert result["next_question"]["key"] != first and result["round"]["answered"] == 1 and result["round"]["results"] == [True] and result["round"]["total"] == len(bank.practice_keys(bare)) + assert open_skill(client, bare)["question"]["key"] == result["next_question"]["key"] + + +def test_a_wrong_answer_names_the_mistake_hides_the_right_choice_and_is_not_solved(world): + client, _, bank = world + bare = client.ids[0] + shown = open_skill(client, bare)["question"] + question = next(q for q in bank.skill(bare)["questions"] if question_key(bare, q) == shown["key"]) + index = next(i for i, c in enumerate(question["choices"]) if c.get("mistake")) + result = client.post(f"/api/skills/{bare}/answer", json={"question_key": shown["key"], "choice": index}, headers=auth()).json() + assert result["correct"] is False and result["mistake"]["id"] == question["choices"][index]["mistake"] + assert result["mistake"]["name"] and result["mistake"]["tip"] and set(result["mistake"]) <= {"id", "name", "tip", "back", "back_name"} + assert result["next_question"]["key"] != shown["key"] and result["round"]["results"] == [False] + assert '"correct": true' not in json.dumps(result) + + +def test_a_mistake_with_a_skill_to_go_back_to_names_it(world): + client, store, bank = world + skill_id, question, index = next((s["id"], q, i) for s in bank.skills for q in s.get("questions", []) + for i, c in enumerate(q["choices"]) if c.get("mistake") and bank.mistakes[c["mistake"]].get("back")) + key = question_key(skill_id, question) + store.save_progress(KID_ID, skill_id, current_key=key) + result = client.post(f"/api/skills/{skill_id}/answer", json={"question_key": key, "choice": index}, headers=auth()).json() + back = bank.mistakes[question["choices"][index]["mistake"]]["back"] + assert result["mistake"]["back"] == back and result["mistake"]["back_name"] == bank.skill(back)["name"] + + +def test_the_server_dates_the_answer_not_the_device(world): + client, store, bank = world + bare = client.ids[0] + shown = open_skill(client, bare)["question"] + client.post(f"/api/skills/{bare}/answer", json={"question_key": shown["key"], "choice": right_choice(bank, bare, shown["key"]), + "day": "2030-01-01"}, headers={**auth(), "Date": "Tue, 01 Jan 2030 00:00:00 GMT"}) + assert store.last_counted_answers(KID_ID, bare, 1)[0]["day"] == date(2026, 11, 2) + + +def test_an_answer_for_a_question_not_on_screen_or_replayed_is_refused(world): + client, store, bank = world + bare = client.ids[0] + shown = open_skill(client, bare)["question"] + other = next(k for k in bank.question_keys(bare) if k != shown["key"]) + assert client.post(f"/api/skills/{bare}/answer", json={"question_key": other, "choice": 0}, headers=auth()).status_code == 409 + body = {"question_key": shown["key"], "choice": right_choice(bank, bare, shown["key"])} + assert client.post(f"/api/skills/{bare}/answer", json=body, headers=auth()).status_code == 200 + assert client.post(f"/api/skills/{bare}/answer", json=body, headers=auth()).status_code == 409 + assert len(store.last_counted_answers(KID_ID, bare, 5)) == 1 + + +def test_bad_choices_are_refused(world): + client, _, _ = world + bare = client.ids[0] + shown = open_skill(client, bare)["question"] + for choice in (99, -1): + assert client.post(f"/api/skills/{bare}/answer", json={"question_key": shown["key"], "choice": choice}, headers=auth()).status_code == 422 + + +def test_mastered_over_two_days_through_the_api(world): + client, _, bank = world + bare = client.ids[0] + assert respond(client, bank, bare)["state"] == "learning" + assert respond(client, bank, bare)["state"] == "learning" + client.set_time(TUE) + last = respond(client, bank, bare) + assert last["state"] == "mastered" and last["mastered_now"] is True and last["correct_in_row"] == 3 + again = respond(client, bank, bare, correct=False) + assert again["state"] == "mastered" and again["mastered_now"] is False + + +def test_three_in_a_row_on_one_day_is_not_mastered(world): + client, _, bank = world + assert [respond(client, bank, client.ids[0])["state"] for _ in range(3)] == ["learning"] * 3 + + +def test_an_answer_after_help_is_not_counted_and_does_not_break_the_run(world): + client, store, bank = world + bare = client.ids[0] + respond(client, bank, bare) + respond(client, bank, bare) + assert client.post(f"/api/skills/{bare}/help", headers=auth()).status_code == 200 + helped = respond(client, bank, bare) + assert helped["correct"] and helped["state"] == "learning" + assert len(store.last_counted_answers(KID_ID, bare, 10)) == 2 # the helped one is stored, not counted + assert store.get_progress(KID_ID, bare)["current_helped"] is False # help applies to one question only + client.set_time(TUE) + assert respond(client, bank, bare)["state"] == "mastered" # Mon, Mon, (help), Tue + + +def test_help_for_an_unknown_skill_is_404(world): + assert world[0].post("/api/skills/nope/help", headers=auth()).status_code == 404 + + +# --- the path (spec: learning-path) --- + +def test_the_path_shows_the_lessons_of_the_students_classes_only(world): + client, store, bank = world + path = client.get("/api/path", headers=auth()).json() + assert len(path["lessons"]) == 24 and sum(len(l["skills"]) for l in path["lessons"]) == 96 + small = KID.replace("kid", "small") + store.add_member(store.create_class("setup", "B", lessons=["t", "k"])["id"], small) + assert [l["id"] for l in client.get("/api/path", headers=auth(small)).json()["lessons"]] == ["t", "k"] + + +def test_a_student_of_two_classes_sees_the_union_in_the_banks_order(world): + client, store, _ = world + two = "two@school.test" + store.add_member(store.create_class("setup", "B", lessons=["k", "t"])["id"], two) + store.add_member(store.create_class("setup", "C", lessons=["t2", "k"])["id"], two) + assert [l["id"] for l in client.get("/api/path", headers=auth(two)).json()["lessons"]] == ["t", "t2", "k"] + + +def test_a_teacher_sees_every_lesson_and_a_manager_is_refused(world): + client, _, _ = world + assert len(client.get("/api/path", headers=auth(TEACHER)).json()["lessons"]) == 24 + assert client.get("/api/path", headers=auth(MGR)).status_code == 403 + + +def test_the_path_gives_each_skill_its_state_and_the_goal_and_streak(world): + client, _, bank = world + bare = client.ids[0] + path = client.get("/api/path", headers=auth()).json() + assert {s["state"] for l in path["lessons"] for s in l["skills"]} == {"not_started"} + assert path["today"] == {"done": 0, "goal": 5, "reached": False} and path["streak"] == 0 + for _ in range(3): + respond(client, bank, bare) + path = client.get("/api/path", headers=auth()).json() + states = {s["id"]: s["state"] for l in path["lessons"] for s in l["skills"]} + assert states[bare] == "learning" and path["today"]["done"] == 3 + assert set(path["lessons"][0]["skills"][0]) == {"id", "name", "short", "state", "faded"} + + +def test_streak_counts_days_with_five_correct(world): + client, _, bank = world + for day in (MON, TUE): + client.set_time(day) + for _ in range(5): + respond(client, bank, client.ids[0]) + path = client.get("/api/path", headers=auth()).json() + assert path["today"]["reached"] is True and path["streak"] == 2 + + +def test_the_next_skill_marker_follows_the_students_last_work(world): + client, _, bank = world + first = client.get("/api/path", headers=auth()).json()["lessons"][0]["skills"][0]["id"] + assert client.get("/api/path", headers=auth()).json()["next"] == first # a new student: the first skill of the first lesson + bare = client.ids[0] + respond(client, bank, bare) + assert client.get("/api/path", headers=auth()).json()["next"] == bare # continuing where they left off + master(client, bank, bare) + after = client.get("/api/path", headers=auth()).json()["next"] + assert after not in (None, bare) # the last answer mastered it: the marker moves on + + +def test_the_marker_is_none_when_everything_is_mastered_and_never_hides_a_skill(world): + client, store, _ = world + for p in client.get("/api/path", headers=auth()).json()["lessons"]: + for s in p["skills"]: + store.save_progress(KID_ID, s["id"], started_at="then", mastered_at="then") + path = client.get("/api/path", headers=auth()).json() + assert path["next"] is None and sum(len(l["skills"]) for l in path["lessons"]) == 96 + + +# --- the collection --- + +def test_collection_lists_mastered_skills_and_completed_lessons(world): + client, _, bank = world + assert client.get("/api/collection", headers=auth()).json() == {"skills": [], "lessons": []} + lesson = min((l for l in bank.lessons if all(s.get("questions") for s in bank.skills if s["unit"] == l["id"])), + key=lambda l: len([s for s in bank.skills if s["unit"] == l["id"]])) + ids = [s["id"] for s in bank.skills if s["unit"] == lesson["id"]] + assert len(ids) >= 2 + for skill_id in ids[:-1]: + master(client, bank, skill_id) + partial = client.get("/api/collection", headers=auth()).json() + assert len(partial["skills"]) == len(ids) - 1 and partial["lessons"] == [] + master(client, bank, ids[-1]) + done = client.get("/api/collection", headers=auth()).json() + assert [l["id"] for l in done["lessons"]] == [lesson["id"]] and done["lessons"][0]["skills"] == len(ids) + path = client.get("/api/path", headers=auth()).json() + assert next(l for l in path["lessons"] if l["id"] == lesson["id"])["completed"] is True + + +def test_a_new_mastery_appears_in_the_collection(world): + client, _, bank = world + bare = client.ids[0] + master(client, bank, bare) + skills = client.get("/api/collection", headers=auth()).json()["skills"] + assert [s["id"] for s in skills] == [bare] and skills[0]["lesson_name"] and skills[0]["mastered_at"] + + +def test_students_do_not_see_each_others_progress(world): + client, store, bank = world + store.add_member(store.get_class(1)["id"], OTHER) + bare = client.ids[0] + master(client, bank, bare) + assert client.get("/api/collection", headers=auth(OTHER)).json() == {"skills": [], "lessons": []} + assert open_skill(client, bare, OTHER)["state"] == "not_started" + assert client.get("/api/path", headers=auth(OTHER)).json()["next"] == client.get("/api/path", headers=auth(OTHER)).json()["lessons"][0]["skills"][0]["id"] + + +# --- ten-question-rounds: practice is a round of ten questions, each once --- + +def play_round(client, bank, skill_id, rights): + """Answer the skill's round with the given right/wrong flags, one per question; return the answers' responses and the keys shown.""" + shown, out = [], [] + for ok in rights: + shown.append(open_skill(client, skill_id)["question"]["key"]) + out.append(respond(client, bank, skill_id, correct=ok)) + return out, shown + + +def test_a_round_is_the_first_ten_questions_each_once_then_a_result_and_no_next_question(world): + client, store, bank = world + big = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 30) + first_ten = set(bank.question_keys(big)[:10]) + assert len(bank.practice_keys(big)) == 10 and len(bank.question_keys(big)) == 30 + rights = [True, True, False, True, False, True, True, True, False, True] # 7 right, 3 wrong + answers, shown = play_round(client, bank, big, rights) + assert len(shown) == 10 and set(shown) == first_ten # each of the ten once, none of the other twenty + assert [a["round"]["answered"] for a in answers] == list(range(1, 11)) and answers[-1]["round"]["results"] == rights + assert all(a["next_question"] is not None for a in answers[:-1]) and answers[-1]["next_question"] is None + last = answers[-1]["round"] + assert last["done"] is True and last["result"]["right"] == 7 and last["result"]["total"] == 10 and len(last["result"]["missed"]) == 3 + from mathly2 import quiz + drawn = {q["key"] for seed in range(20) for q in quiz.draw(bank, bank.skill(big)["unit"], rng=__import__("random").Random(seed))} + assert drawn - first_ten # quizzes still draw the other twenty + + +def test_a_wrong_question_does_not_come_back_in_the_round(world): + client, _, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + wrong = respond(client, bank, small, correct=False) + missed_key = open_skill(client, small)["round"] # (the question missed is the one just answered) + keys = [] + nxt = wrong["next_question"] + while nxt: + keys.append(nxt["key"]) + nxt = respond(client, bank, small)["next_question"] + assert len(keys) == 9 and len(set(keys)) == 9 and missed_key["results"] == [False] + assert len({*keys}) == 9 and open_skill(client, small)["question"] is None + + +def test_the_result_has_no_right_answers_and_shows_each_wrong_question_with_its_mistake(world): + client, _, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + answers, _ = play_round(client, bank, small, [False] * 4 + [True] * 6) + result = answers[-1]["round"]["result"] + assert result["right"] == 6 and len(result["missed"]) == 4 + assert all(m["question"] and (m["mistake"] is None or m["mistake"]["name"]) for m in result["missed"]) + blob = __import__("json").dumps(answers[-1], ensure_ascii=False) + assert '"correct": true' not in blob.split('"round"')[1] # the round's result carries no right choice + + +def test_leaving_in_the_middle_continues_the_round_and_a_finished_round_shows_its_result_again(world): + client, _, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + play_round(client, bank, small, [True, False, True, True]) # leave after four + back = open_skill(client, small) + assert back["round"]["answered"] == 4 and back["round"]["results"] == [True, False, True, True] and back["question"] is not None + play_round(client, bank, small, [True] * 6) + done = open_skill(client, small) + assert done["question"] is None and done["round"]["done"] and done["round"]["result"]["right"] == 9 # the result again + + +def test_a_new_round_starts_all_ten_again_with_empty_dots_and_mastery_counts_across_rounds(world): + client, _, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + play_round(client, bank, small, [True] * 10) + assert client.post(f"/api/skills/{small}/round", headers=auth()).status_code == 200 + fresh = open_skill(client, small) + assert fresh["question"] is not None and fresh["round"]["answered"] == 0 and fresh["round"]["results"] == [] and not fresh["round"]["done"] + client.set_time(TUE) # the second day, in the new round + answered = respond(client, bank, small) + assert answered["state"] == "mastered" and answered["mastered_now"] is True # 3 right in a row on two days, across the rounds + + +def test_a_new_round_before_the_round_is_done_changes_nothing_and_a_stale_answer_is_refused(world): + client, _, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + shown = open_skill(client, small)["question"]["key"] + client.post(f"/api/skills/{small}/round", headers=auth()) + assert open_skill(client, small)["question"]["key"] == shown + play_round(client, bank, small, [True] * 10) + late = client.post(f"/api/skills/{small}/answer", json={"question_key": shown, "choice": 0}, headers=auth()) + assert late.status_code == 409 # the round is over: no question is on screen + + +def test_a_student_who_practised_before_rounds_begins_a_new_one(world): + client, store, bank = world + small = next(s["id"] for s in bank.skills if len(s.get("questions", [])) == 10) + for key in bank.question_keys(small): # ten old answers, from before rounds + store.add_answer(KID_ID, small, key, True, True, None, MON.date()) + store.save_progress(KID_ID, small, started_at="then", current_key=bank.question_keys(small)[0], current_helped=False) + opened = open_skill(client, small) + assert opened["question"] is not None and opened["round"]["answered"] == 0 and not opened["round"]["done"] + assert store.get_progress(KID_ID, small)["round_start"] == 10 diff --git a/mathly2/tests/test_store.py b/mathly2/tests/test_store.py index 4fb51a3a9ad2530d46847da7d390b60c22eced19..524ed76e8fc06b7345800cb24e1baec339c81f28 100644 --- a/mathly2/tests/test_store.py +++ b/mathly2/tests/test_store.py @@ -1,8 +1,10 @@ +import io +import json import urllib.error import pytest -from mathly2.store import ClassExists, InMemoryStore, MemberExists, SupabaseStore +from mathly2.store import ClassExists, InMemoryStore, MemberExists, StoreUnavailable, SupabaseStore, TeacherIsStudent @pytest.fixture @@ -10,87 +12,552 @@ def store(): return InMemoryStore() -def test_classes_belong_to_their_teacher(store): - a = store.create_class("t1@x.test", "ט'3") - store.create_class("t2@x.test", "ח'1") - assert [c["name"] for c in store.classes_of("t1@x.test")] == ["ט'3"] - assert store.get_class(a["id"])["teacher_email"] == "t1@x.test" - assert store.get_class(999) is None +class Recorder(SupabaseStore): + """SupabaseStore with the network replaced by canned answers; records what it would have sent.""" + def __init__(self, answers): + super().__init__("https://p.supabase.test", "secret") + self.answers, self.calls = list(answers), [] + + def _request(self, method, table, params=None, body=None, returning=False, upsert=False): + self.calls.append((method, table, params, body, returning, upsert)) + answer = self.answers.pop(0) + if isinstance(answer, Exception): + raise answer + return answer + + +def conflict(): + return urllib.error.HTTPError("u", 409, "conflict", {}, None) + + + +# --- classes, students and roles (rebuild-foundation 2.2, 2.3) --- -def test_class_names_are_unique_per_teacher_ignoring_case(store): - store.create_class("t@x.test", "Alef") +def make(store, name="ט'3", **kw): + return store.create_class("m@x.test", name, lessons=kw.pop("lessons", ["t", "t2"]), **kw) + + +def test_a_new_class_has_its_lessons_teacher_and_the_ai_off(store): + row = make(store, teacher_email="t@x.test") + assert row["lessons"] == ["t", "t2"] and row["teacher_email"] == "t@x.test" and row["created_by"] == "m@x.test" + assert row["ai_enabled"] is False and row["ai_daily_checks"] == 150 and row["students"] == 0 + assert store.get_class(row["id"])["name"] == "ט'3" and store.get_class(999) is None + + +def test_class_names_are_unique_across_the_app_ignoring_case(store): + make(store, "Alef") + with pytest.raises(ClassExists): + make(store, "alef") with pytest.raises(ClassExists): - store.create_class("t@x.test", "alef") - store.create_class("other@x.test", "Alef") + store.create_class("other@x.test", "ALEF", lessons=["t"]) # another creator: still taken + + +def test_classes_lists_all_and_classes_taught_only_the_teachers(store): + a = make(store, "A", teacher_email="t1@x.test")["id"] + make(store, "B", teacher_email="t2@x.test") + make(store, "C", teacher_email="t1@x.test") + assert [c["name"] for c in store.classes()] == ["A", "B", "C"] + assert [c["name"] for c in store.classes_taught("t1@x.test")] == ["A", "C"] + assert store.classes_taught("nobody@x.test") == [] and a + + +def test_update_class_changes_only_what_is_given(store): + cid = make(store, "A", teacher_email="t@x.test")["id"] + row = store.update_class(cid, name="B", ai_enabled=True, ai_daily_checks=40) + assert (row["name"], row["ai_enabled"], row["ai_daily_checks"], row["teacher_email"], row["lessons"]) == ("B", True, 40, "t@x.test", ["t", "t2"]) + assert store.update_class(cid, lessons=["k"])["lessons"] == ["k"] + with pytest.raises(KeyError): + store.update_class(999, name="x") + with pytest.raises(ValueError): + store.update_class(cid, colour="red") -def test_a_student_belongs_to_one_class(store): - a, b = store.create_class("t@x.test", "A")["id"], store.create_class("t@x.test", "B")["id"] +def test_update_class_refuses_a_name_taken_by_another_class(store): + make(store, "A") + b = make(store, "B")["id"] + with pytest.raises(ClassExists): + store.update_class(b, name="a") + assert store.update_class(b, name="B")["name"] == "B" # its own name is not a clash + + +def test_a_student_can_be_in_several_classes(store): + a, b = make(store, "A", lessons=["t"])["id"], make(store, "B", lessons=["t2"])["id"] store.add_member(a, "s@x.test") + store.add_member(b, "s@x.test") + assert [c["name"] for c in store.classes_of_student("s@x.test")] == ["A", "B"] + assert store.classes_of_student("s@x.test")[1]["lessons"] == ["t2"] with pytest.raises(MemberExists): - store.add_member(b, "s@x.test") - assert store.membership("s@x.test")["class_name"] == "A" - assert store.classes_of("t@x.test")[0]["students"] == 1 + store.add_member(a, "s@x.test") # twice in the same class + assert store.get_class(a)["students"] == 1 + + +def test_a_teacher_is_never_a_student_of_the_same_class(store): + cid = make(store, "A", teacher_email="t@x.test")["id"] + with pytest.raises(TeacherIsStudent): + store.add_member(cid, "t@x.test") + store.add_member(cid, "s@x.test") + with pytest.raises(TeacherIsStudent): + store.update_class(cid, teacher_email="s@x.test") + other = make(store, "B")["id"] + store.add_member(other, "t@x.test") # a student of another class is fine def test_remove_member_only_from_its_own_class(store): - a, b = store.create_class("t@x.test", "A")["id"], store.create_class("t@x.test", "B")["id"] + a, b = make(store, "A")["id"], make(store, "B")["id"] store.add_member(a, "s@x.test") assert store.remove_member(b, "s@x.test") is False assert store.remove_member(a, "s@x.test") is True - assert store.membership("s@x.test") is None + assert store.classes_of_student("s@x.test") == [] + +def test_deleting_a_class_removes_its_students_but_not_their_progress(store): + cid = make(store, "A")["id"] + store.add_member(cid, "s@x.test") + store.save_progress("u-1", "skill-1", started_at="t0") + assert store.delete_class(cid) is True and store.delete_class(cid) is False + assert store.classes_of_student("s@x.test") == [] and store.get_class(cid) is None + assert store.get_progress("u-1", "skill-1")["started_at"] == "t0" -def test_link_user_sets_it_once(store): - a = store.create_class("t@x.test", "A")["id"] + +def test_link_user_sets_every_entry_of_the_email_once(store): + a, b = make(store, "A")["id"], make(store, "B")["id"] store.add_member(a, "s@x.test") + store.add_member(b, "s@x.test") store.link_user("s@x.test", "u1") store.link_user("s@x.test", "u2") - assert store.membership("s@x.test")["user_id"] == "u1" - store.link_user("nobody@x.test", "u3") # no such member: ignored + assert [m["user_id"] for m in store.members(a) + store.members(b)] == ["u1", "u1"] + store.link_user("nobody@x.test", "u3") # no such member: ignored + c = make(store, "C")["id"] + store.add_member(c, "s@x.test") + assert store.members(c)[0]["user_id"] == "u1" # a new entry takes the known id -class Recorder(SupabaseStore): - """SupabaseStore with the network replaced by canned answers; records what it would have sent.""" - def __init__(self, answers): - super().__init__("https://p.supabase.test", "secret") - self.answers, self.calls = list(answers), [] +def test_all_students_lists_each_with_their_classes(store): + a, b = make(store, "A")["id"], make(store, "B")["id"] + store.add_member(a, "y@x.test") + store.add_member(b, "y@x.test") + store.add_member(a, "n@x.test") + assert store.all_students() == [{"email": "n@x.test", "classes": ["A"]}, {"email": "y@x.test", "classes": ["A", "B"]}] - def _request(self, method, table, params=None, body=None, returning=False): - self.calls.append((method, table, params, body, returning)) - answer = self.answers.pop(0) - if isinstance(answer, Exception): - raise answer - return answer +def test_roles_are_given_once_and_taken_away(store): + assert store.roles_of("r@x.test") == set() + store.give_role("r@x.test", "manager", "admin@x.test") + store.give_role("r@x.test", "manager", "other@x.test") # idempotent + store.give_role("r@x.test", "teacher", "admin@x.test") + assert store.roles_of("r@x.test") == {"manager", "teacher"} and store.roles_of("someone@x.test") == set() + assert store.take_role("r@x.test", "manager") == "removed" + assert store.take_role("r@x.test", "manager") == "absent" + assert store.roles_of("r@x.test") == {"teacher"} -def conflict(): - return urllib.error.HTTPError("u", 409, "conflict", {}, None) + +def test_the_last_admin_cannot_be_removed_but_one_of_two_can(store): + store.give_role("a@x.test", "admin", "s") + assert store.take_role("a@x.test", "admin") == "last_admin" and store.roles_of("a@x.test") == {"admin"} + store.give_role("b@x.test", "admin", "s") + assert store.take_role("a@x.test", "admin") == "removed" + assert store.take_role("b@x.test", "admin") == "last_admin" + + +def test_an_admin_named_in_the_settings_counts_as_another_admin(store): + store.give_role("a@x.test", "admin", "s") + assert store.take_role("a@x.test", "admin", settings_admins=1) == "removed" -def test_supabase_store_requests(): - s = Recorder([[{"id": 1, "name": "A", "teacher_email": "t@x.test", "created_at": "z"}], - [{"id": 1, "name": "A", "teacher_email": "t@x.test", "created_at": "z", "m2_class_members": [{"count": 3}]}], - [{"class_id": 1, "email": "s@x.test", "user_id": None, "added_at": "z", "m2_classes": {"name": "A"}}], - [{"email": "s@x.test"}], []]) - assert s.create_class("t@x.test", "A")["id"] == 1 - assert s.classes_of("t@x.test")[0]["students"] == 3 - assert s.membership("s@x.test")["class_name"] == "A" - assert s.remove_member(1, "s@x.test") is True - assert s.remove_member(1, "s@x.test") is False - assert s.calls[0][:2] == ("POST", "m2_classes") and s.calls[0][3] == {"teacher_email": "t@x.test", "name": "A"} - assert s.calls[3][2] == {"class_id": "eq.1", "email": "eq.s@x.test"} +def test_accounts_lists_every_known_email_with_its_given_roles(store): + cid = make(store, "A", teacher_email="t@x.test")["id"] + store.add_member(cid, "s@x.test") + store.give_role("m@x.test", "manager", "a@x.test") + store.give_role("s@x.test", "teacher", "a@x.test") + assert store.accounts() == [{"email": "m@x.test", "roles": ["manager"]}, {"email": "s@x.test", "roles": ["teacher"]}, + {"email": "t@x.test", "roles": []}] -def test_supabase_store_turns_conflicts_into_domain_errors(): +def test_supabase_class_requests_and_parsing(): + row = {"id": 1, "name": "A", "created_by": "m@x.test", "teacher_email": "t@x.test", "lessons": ["t"], "ai_enabled": False, + "ai_daily_checks": 150, "created_at": "z"} + counted = {**row, "m2_class_members": [{"count": 3}]} + s = Recorder([[row], [counted], [counted], [row], [counted]]) + assert s.create_class("m@x.test", "A", lessons=["t"], teacher_email="t@x.test")["students"] == 0 + assert s.get_class(1)["students"] == 3 + assert s.classes_taught("t@x.test")[0]["students"] == 3 + assert s.update_class(1, name="B")["students"] == 3 + create, taught, patch = s.calls[0], s.calls[2], s.calls[3] + assert create[:2] == ("POST", "m2_classes") and create[3] == {"created_by": "m@x.test", "name": "A", "lessons": ["t"], + "teacher_email": "t@x.test", "ai_enabled": False, "ai_daily_checks": 150} + assert taught[2]["teacher_email"] == "eq.t@x.test" + assert patch[:3] == ("PATCH", "m2_classes", {"id": "eq.1"}) and patch[3] == {"name": "B"} + + +def test_supabase_student_and_member_requests(): + s = Recorder([[{"m2_classes": {"id": 1, "name": "A", "lessons": ["t"]}}, {"m2_classes": {"id": 2, "name": "B", "lessons": []}}], + [{"email": "y@x.test", "m2_classes": {"name": "B"}}, {"email": "y@x.test", "m2_classes": {"name": "A"}}], [{"email": "s@x.test"}], [], None]) + assert [c["name"] for c in s.classes_of_student("s@x.test")] == ["A", "B"] + assert s.all_students() == [{"email": "y@x.test", "classes": ["A", "B"]}] + assert s.remove_member(1, "s@x.test") is True and s.remove_member(1, "s@x.test") is False + s.link_user("s@x.test", "u1") + assert s.calls[0][2] == {"email": "eq.s@x.test", "select": "m2_classes(id,name,lessons)"} + assert s.calls[2][2] == {"class_id": "eq.1", "email": "eq.s@x.test"} + assert s.calls[4][2] == {"email": "eq.s@x.test", "user_id": "is.null"} + + +def refusal(code, message=""): + return urllib.error.HTTPError("u", code, "no", {}, io.BytesIO(json.dumps({"message": message}).encode())) + + +def test_supabase_store_turns_refusals_into_domain_errors(): + with pytest.raises(ClassExists): + Recorder([conflict()]).create_class("m@x.test", "A") with pytest.raises(ClassExists): - Recorder([conflict()]).create_class("t@x.test", "A") + Recorder([conflict()]).update_class(1, name="A") + with pytest.raises(TeacherIsStudent): + Recorder([refusal(400, "teacher_is_student")]).update_class(1, teacher_email="s@x.test") with pytest.raises(MemberExists): Recorder([conflict()]).add_member(1, "s@x.test") + with pytest.raises(TeacherIsStudent): + Recorder([refusal(400, "teacher_is_student")]).add_member(1, "t@x.test") + with pytest.raises(KeyError): + Recorder([[]]).update_class(1, name="B") -def test_supabase_link_only_fills_an_empty_user_id(): - s = Recorder([None]) - s.link_user("s@x.test", "u1") - assert s.calls[0][2] == {"email": "eq.s@x.test", "user_id": "is.null"} +def test_supabase_role_requests(): + s = Recorder([[{"role": "manager"}, {"role": "teacher"}], None, "removed", "last_admin", + [{"email": "a@x.test", "role": "admin"}], [{"email": "s@x.test"}], [{"teacher_email": "t@x.test"}]]) + assert s.roles_of("r@x.test") == {"manager", "teacher"} + s.give_role("r@x.test", "manager", "a@x.test") + assert s.take_role("r@x.test", "manager") == "removed" and s.take_role("a@x.test", "admin", settings_admins=0) == "last_admin" + assert [a["email"] for a in s.accounts()] == ["a@x.test", "s@x.test", "t@x.test"] + give = s.calls[1] + assert give[:2] == ("POST", "m2_roles") and give[2] == {"on_conflict": "email,role"} and give[3] == { + "email": "r@x.test", "role": "manager", "granted_by": "a@x.test"} and give[5] is True + assert s.calls[3][:2] == ("POST", "rpc/m2_take_role") and s.calls[3][3] == { + "p_email": "a@x.test", "p_role": "admin", "p_settings_admins": 0} + + +# --- skill learning (tasks 2.2 and 2.3) --- + +from datetime import date + +U, V = "u-1", "u-2" + + +def test_progress_starts_empty_and_is_created_on_save(store): + assert store.get_progress(U, "s1") is None + row = store.save_progress(U, "s1", started_at="t0") + assert set(row) == {"user_id", "skill_id", "current_key", "current_helped", "started_at", "mastered_at", "round_start"} and row["round_start"] is None + assert row["current_helped"] is False and row["started_at"] == "t0" and row["mastered_at"] is None + assert store.get_progress(U, "s1") == row + + +def test_saving_progress_changes_only_the_given_fields(store): + store.save_progress(U, "s1", current_key="s1:abc", started_at="t0") + store.save_progress(U, "s1", current_helped=True) + row = store.get_progress(U, "s1") + assert (row["current_key"], row["current_helped"], row["started_at"]) == ("s1:abc", True, "t0") + + +def test_progress_rejects_unknown_fields(store): + with pytest.raises(ValueError): + store.save_progress(U, "s1", colour="red") + with pytest.raises(ValueError): + store.save_progress(U, "s1", stage="practice") # the stages are gone + + +def test_progress_of_lists_only_that_students_rows(store): + store.save_progress(U, "s1") + store.save_progress(U, "s2") + store.save_progress(V, "s1") + assert sorted(r["skill_id"] for r in store.progress_of(U)) == ["s1", "s2"] + assert store.progress_of("nobody") == [] + + +def test_returned_progress_is_a_copy(store): + row = store.save_progress(U, "s1") + row["current_key"] = "changed" + assert store.get_progress(U, "s1")["current_key"] is None + + +def add(store, key, correct, day, counted=True, user=U, skill="s1", mistake=None): + store.add_answer(user, skill, key, correct, counted, mistake, day) + + +def test_last_counted_answers_are_oldest_first_and_skip_helped_ones(store): + d = date(2026, 11, 2) + add(store, "a", True, d) + add(store, "b", True, d, counted=False) + add(store, "c", False, d) + add(store, "d", True, date(2026, 11, 3)) + got = store.last_counted_answers(U, "s1", 3) + assert [a["question_key"] for a in got] == ["a", "c", "d"] + assert [a["correct"] for a in got] == [True, False, True] + assert got[2]["day"] == date(2026, 11, 3) + assert [a["question_key"] for a in store.last_counted_answers(U, "s1", 2)] == ["c", "d"] + + +def test_last_counted_answers_are_per_student_and_skill(store): + add(store, "a", True, date(2026, 11, 2)) + add(store, "b", True, date(2026, 11, 2), user=V) + add(store, "c", True, date(2026, 11, 2), skill="s2") + assert [a["question_key"] for a in store.last_counted_answers(U, "s1", 5)] == ["a"] + assert store.last_counted_answers("nobody", "s1", 5) == [] + + +def test_answer_counts_include_helped_answers(store): + d = date(2026, 11, 2) + add(store, "a", True, d) + add(store, "a", False, d, counted=False) + add(store, "b", True, d) + add(store, "z", True, d, skill="s2") + assert store.answer_counts(U, "s1") == {"a": 2, "b": 1} + assert store.answer_counts(U, "none") == {} + + +def test_daily_correct_counts_correct_answers_per_day_helped_included(store): + add(store, "a", True, date(2026, 11, 2)) + add(store, "b", True, date(2026, 11, 2), counted=False) + add(store, "c", False, date(2026, 11, 2)) + add(store, "d", True, date(2026, 11, 3), skill="s2") + add(store, "e", True, date(2026, 11, 2), user=V) + assert store.daily_correct(U) == {date(2026, 11, 2): 2, date(2026, 11, 3): 1} + assert store.daily_correct("nobody") == {} + + +def test_supabase_progress_requests(): + row = {"user_id": U, "skill_id": "s1", "current_key": "s1:abc"} + s = Recorder([[row], [row], [row]]) + assert s.get_progress(U, "s1") == row + assert s.save_progress(U, "s1", current_key="s1:abc") == row + assert s.progress_of(U) == [row] + get, save, listing = s.calls + assert get[:3] == ("GET", "m2_skill_progress", {"user_id": "eq.u-1", "skill_id": "eq.s1", "select": "*"}) + assert save[:2] == ("POST", "m2_skill_progress") and save[2] == {"on_conflict": "user_id,skill_id"} + assert save[3] == {"user_id": U, "skill_id": "s1", "current_key": "s1:abc"} and save[4:] == (True, True) + assert listing[2] == {"user_id": "eq.u-1", "select": "*"} + + +def test_supabase_get_progress_when_there_is_none(): + assert Recorder([[]]).get_progress(U, "s1") is None + + +def test_supabase_save_progress_rejects_unknown_fields_before_sending(): + s = Recorder([]) + with pytest.raises(ValueError): + s.save_progress(U, "s1", colour="red") + assert s.calls == [] + + +def test_supabase_answer_requests_and_parsing(): + s = Recorder([None, [{"question_key": "c", "correct": False, "day": "2026-11-03"}, + {"question_key": "b", "correct": True, "day": "2026-11-02"}], + [{"question_key": "a"}, {"question_key": "a"}, {"question_key": "b"}], + [{"day": "2026-11-02", "correct": 2}, {"day": "2026-11-03", "correct": 1}]]) + s.add_answer(U, "s1", "a", True, False, "m1", date(2026, 11, 2)) + got = s.last_counted_answers(U, "s1", 2) + counts = s.answer_counts(U, "s1") + daily = s.daily_correct(U) + assert s.calls[0][:2] == ("POST", "m2_answers") + assert s.calls[0][3] == {"user_id": U, "skill_id": "s1", "question_key": "a", "correct": True, "counted": False, + "mistake_id": "m1", "day": "2026-11-02"} + assert s.calls[1][2]["counted"] == "eq.true" and s.calls[1][2]["order"] == "id.desc" and s.calls[1][2]["limit"] == "2" + assert [a["question_key"] for a in got] == ["b", "c"] # newest first from the server, returned oldest first + assert got[0]["day"] == date(2026, 11, 2) and got[1]["correct"] is False + assert counts == {"a": 2, "b": 1} + assert s.calls[3][:2] == ("GET", "m2_daily_correct") + assert daily == {date(2026, 11, 2): 2, date(2026, 11, 3): 1} + + +def test_a_refusal_that_is_not_a_conflict_is_a_database_problem_not_a_name_clash(): + for call in (lambda s: s.create_class("m@x.test", "A"), lambda s: s.update_class(1, name="A"), lambda s: s.add_member(1, "s@x.test")): + with pytest.raises(StoreUnavailable, match="supabase refused \\(400\\): column lessons does not exist"): + call(Recorder([refusal(400, "column lessons does not exist")])) + + +# --- the next skill and progress dots (add-learning-core 1.3) --- + +def test_recent_skills_are_newest_first_each_once_and_include_wrong_and_helped_answers(store): + d = date(2026, 11, 2) + add(store, "a", True, d, skill="s1") + add(store, "b", False, d, skill="s2") + add(store, "c", True, d, counted=False, skill="s3") + add(store, "d", True, d, skill="s1") + assert store.recent_skills(U) == ["s1", "s3", "s2"] + assert store.recent_skills(U, 2) == ["s1", "s3"] + assert store.recent_skills("nobody") == [] + + +def test_recent_skills_do_not_include_other_students(store): + add(store, "a", True, date(2026, 11, 2), skill="s1") + add(store, "b", True, date(2026, 11, 2), user=V, skill="s2") + assert store.recent_skills(U) == ["s1"] and store.recent_skills(V) == ["s2"] + + +def test_solved_keys_are_the_questions_answered_right_at_least_once(store): + d = date(2026, 11, 2) + add(store, "a", False, d) + add(store, "a", True, d) # wrong first, right later: solved + add(store, "b", False, d) # only wrong: not solved + add(store, "c", True, d, counted=False) # right with help: solved + add(store, "z", True, d, skill="s2") # another skill + add(store, "y", True, d, user=V) # another student + assert store.solved_keys(U, "s1") == {"a", "c"} + assert store.solved_keys(U, "none") == set() and store.solved_keys("nobody", "s1") == set() + + +def test_supabase_recent_skills_and_solved_keys_requests(): + s = Recorder([[{"skill_id": "s1"}, {"skill_id": "s2"}, {"skill_id": "s1"}, {"skill_id": "s3"}], + [{"question_key": "a"}, {"question_key": "c"}, {"question_key": "a"}]]) + assert s.recent_skills(U, 2) == ["s1", "s2"] + assert s.solved_keys(U, "s1") == {"a", "c"} + recent, solved = s.calls + assert recent[:2] == ("GET", "m2_answers") and recent[2]["order"] == "id.desc" and recent[2]["user_id"] == "eq.u-1" + assert solved[2] == {"user_id": "eq.u-1", "skill_id": "eq.s1", "correct": "eq.true", "select": "question_key"} + + +# --- add-rewards 2.1: last_answered --- + +def test_last_answered_is_the_newest_day_per_skill_and_counts_helped_and_wrong_answers(store): + add(store, "a", True, date(2026, 11, 2)) + add(store, "b", False, date(2026, 11, 5), counted=False) + add(store, "c", True, date(2026, 11, 3), skill="s2") + add(store, "d", True, date(2026, 11, 9), user=V) + assert store.last_answered(U) == {"s1": date(2026, 11, 5), "s2": date(2026, 11, 3)} + assert store.last_answered("nobody") == {} + + +def test_supabase_last_answered_reads_the_view_for_one_student(): + s = Recorder([[{"skill_id": "s1", "day": "2026-11-05"}]]) + assert s.last_answered(U) == {"s1": date(2026, 11, 5)} + method, table, params, *_ = s.calls[0] + assert (method, table) == ("GET", "m2_last_answered") and params["user_id"] == f"eq.{U}" + + +# --- add-lesson-quizzes 1.1: timed attempts --- + +from datetime import datetime, timedelta, timezone # noqa: E402 + +T0 = datetime(2026, 11, 10, 9, 0, tzinfo=timezone.utc) +QUESTIONS = [{"skill_id": "s1", "key": "s1:a"}, {"skill_id": "s2", "key": "s2:b"}] + + +def test_an_attempt_is_created_open_and_read_back(store): + row = store.create_attempt(U, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) + assert row["submitted_at"] is None and row["grade"] is None and row["timed_out"] is False + assert row["answers"] == {} and row["questions"] == QUESTIONS and row["due_at"] - row["started_at"] == timedelta(minutes=15) + assert store.get_attempt(row["id"]) == row and store.get_attempt("nope") is None + + +def test_saving_answers_and_settling_changes_only_the_named_fields(store): + row = store.create_attempt(U, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) + store.save_attempt(row["id"], answers={"s1:a": 2}) + saved = store.save_attempt(row["id"], submitted_at=T0 + timedelta(minutes=20), timed_out=True, grade=50) + assert saved["answers"] == {"s1:a": 2} and saved["grade"] == 50 and saved["timed_out"] is True and saved["submitted_at"] is not None + assert saved["questions"] == QUESTIONS + with pytest.raises(ValueError): + store.save_attempt(row["id"], user_id="someone-else") + with pytest.raises(KeyError): + store.save_attempt("missing", grade=1) + + +def test_a_returned_attempt_is_a_copy(store): + row = store.create_attempt(U, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) + row["answers"]["x"] = 1 + row["questions"].append({"skill_id": "z", "key": "z"}) + assert store.get_attempt(row["id"])["answers"] == {} and store.get_attempt(row["id"])["questions"] == QUESTIONS + + +def test_attempts_of_one_student_kind_and_scope_oldest_first(store): + a = store.create_attempt(U, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) + b = store.create_attempt(U, "quiz", "t", T0 + timedelta(hours=1), T0 + timedelta(hours=1, minutes=15), QUESTIONS) + store.create_attempt(U, "quiz", "t2", T0, T0 + timedelta(minutes=15), QUESTIONS) + store.create_attempt(V, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) # another student's + store.create_attempt(U, "simulation", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) # another kind + assert [r["id"] for r in store.attempts_of(U, "quiz", "t")] == [a["id"], b["id"]] + assert len(store.attempts_of(U, "quiz")) == 3 and store.attempts_of("nobody", "quiz") == [] + + +def test_supabase_attempt_requests(): + row = {"id": "i1", "user_id": U, "kind": "quiz", "scope": "t", "started_at": "2026-11-10T09:00:00+00:00", "due_at": "2026-11-10T09:15:00+00:00", + "submitted_at": None, "timed_out": False, "grade": None, "questions": QUESTIONS, "answers": {}} + settled = {**row, "submitted_at": "2026-11-10T09:20:00Z", "timed_out": True, "grade": 50, "answers": {"s1:a": 2}} + s = Recorder([[row], [row], [], [settled], [row, settled]]) + made = s.create_attempt(U, "quiz", "t", T0, T0 + timedelta(minutes=15), QUESTIONS) + assert s.calls[0][:2] == ("POST", "m2_attempts") and s.calls[0][3]["due_at"] == "2026-11-10T09:15:00+00:00" and s.calls[0][3]["questions"] == QUESTIONS + assert made["due_at"] == T0 + timedelta(minutes=15) and made["answers"] == {} # real datetimes come back + assert s.get_attempt("i1")["id"] == "i1" and s.get_attempt("i2") is None + got = s.save_attempt("i1", submitted_at=T0 + timedelta(minutes=20), timed_out=True, grade=50, answers={"s1:a": 2}) + assert s.calls[3][:3] == ("PATCH", "m2_attempts", {"id": "eq.i1"}) and s.calls[3][3]["submitted_at"] == "2026-11-10T09:20:00+00:00" + assert got["submitted_at"] == T0 + timedelta(minutes=20) and got["grade"] == 50 + assert len(s.attempts_of(U, "quiz", "t")) == 2 + assert s.calls[4][2] == {"user_id": f"eq.{U}", "kind": "eq.quiz", "select": "*", "order": "started_at", "scope": "eq.t"} + + +# --- add-test-readiness 1.1: real tests --- + +TEST_DAY = date(2026, 11, 20) + + +def test_a_test_has_the_defaults_and_is_read_back(store): + row = store.create_test(1, TEST_DAY, ["t", "t2"], "t@x.test") + assert row["questions"] == 12 and row["minutes"] == 45 and row["note"] == "" and row["removed_at"] is None + assert row["date"] == TEST_DAY and row["lessons"] == ["t", "t2"] and row["created_by"] == "t@x.test" and row["created_at"].tzinfo + assert store.get_test(row["id"]) == row and store.get_test(999) is None + + +def test_a_test_can_be_changed_before_it_is_removed_but_not_after(store): + row = store.create_test(1, TEST_DAY, ["t"], "t@x.test") + changed = store.update_test(row["id"], date=date(2026, 11, 22), lessons=["t", "t2"], note="פרק 3", questions=15, minutes=60) + assert changed["date"] == date(2026, 11, 22) and changed["lessons"] == ["t", "t2"] and changed["note"] == "פרק 3" and changed["questions"] == 15 + with pytest.raises(ValueError): + store.update_test(row["id"], class_id=2) + with pytest.raises(KeyError): + store.update_test(999, note="x") + assert store.remove_test(row["id"]) is True and store.remove_test(row["id"]) is False + with pytest.raises(KeyError): + store.update_test(row["id"], note="y") + assert store.get_test(row["id"])["removed_at"] is not None # still readable: grades keep its name + + +def test_the_limits_are_enforced(store): + for bad in ({"questions": 0}, {"questions": 41}, {"minutes": 4}, {"minutes": 181}, {"lessons": []}): + with pytest.raises(ValueError): + store.create_test(1, TEST_DAY, bad.get("lessons", ["t"]), "t@x.test", **{k: v for k, v in bad.items() if k != "lessons"}) + row = store.create_test(1, TEST_DAY, ["t"], "t@x.test") + with pytest.raises(ValueError): + store.update_test(row["id"], questions=99) + + +def test_tests_of_classes_are_nearest_first_hide_removed_and_skip_other_classes(store): + late = store.create_test(1, date(2026, 12, 1), ["t"], "t@x.test") + soon = store.create_test(1, date(2026, 11, 18), ["t"], "t@x.test") + other = store.create_test(2, date(2026, 11, 10), ["t"], "t@x.test") + gone = store.create_test(1, date(2026, 11, 12), ["t"], "t@x.test") + store.remove_test(gone["id"]) + assert [r["id"] for r in store.tests_of_classes([1])] == [soon["id"], late["id"]] + assert [r["id"] for r in store.tests_of_classes([1, 2])] == [other["id"], soon["id"], late["id"]] + assert [r["id"] for r in store.tests_of_classes([1], include_removed=True)] == [gone["id"], soon["id"], late["id"]] + assert store.tests_of_classes([]) == [] + + +def test_supabase_test_requests(): + row = {"id": 5, "class_id": 1, "date": "2026-11-20", "lessons": ["t"], "note": "", "questions": 12, "minutes": 45, "created_by": "t@x.test", + "created_at": "2026-11-10T09:00:00+00:00", "removed_at": None} + s = Recorder([[row], [row], [{**row, "note": "x"}], [], [row], [row]]) + made = s.create_test(1, TEST_DAY, ["t"], "t@x.test", created_at=T0) + assert s.calls[0][:2] == ("POST", "m2_tests") and s.calls[0][3]["date"] == "2026-11-20" and s.calls[0][3]["created_at"] == T0.isoformat() + assert made["date"] == TEST_DAY and made["created_at"] == datetime(2026, 11, 10, 9, 0, tzinfo=timezone.utc) + assert s.get_test(5)["id"] == 5 + assert s.update_test(5, note="x")["note"] == "x" and s.calls[2][2] == {"id": "eq.5", "removed_at": "is.null"} + with pytest.raises(KeyError): + s.update_test(5, note="y") + assert s.remove_test(5) is True and s.calls[4][3]["removed_at"] + s.tests_of_classes([2, 1]) + assert s.calls[5][2] == {"class_id": "in.(1,2)", "select": "*", "order": "date,id", "removed_at": "is.null"} + assert s.tests_of_classes([]) == [] + + +def test_answers_of_carries_the_mistake_for_the_round_result(store): + store.add_answer(U, "s1", "k1", False, True, "m7", date(2026, 11, 2)) + store.add_answer(U, "s1", "k2", True, True, None, date(2026, 11, 2)) + assert [(r["question_key"], r["mistake_id"]) for r in store.answers_of(U, "s1")] == [("k1", "m7"), ("k2", None)] + assert store.save_progress(U, "s1", round_start=2)["round_start"] == 2 diff --git a/mathly2/tests/test_student_class.py b/mathly2/tests/test_student_class.py index b09f79edd43cf32b2fff38b269cd29c69d2f14c7..3d2dc4d041984a37b784f120288760e99f48462f 100644 --- a/mathly2/tests/test_student_class.py +++ b/mathly2/tests/test_student_class.py @@ -5,7 +5,7 @@ from mathly2.config import Settings from mathly2.main import create_app from mathly2.store import InMemoryStore -TEACHER, KID = "t@school.test", "kid@school.test" +MGR, TEACHER, KID = "mgr@school.test", "t@school.test", "kid@school.test" def auth(email): @@ -15,39 +15,58 @@ def auth(email): @pytest.fixture def setup(): store = InMemoryStore() + store.give_role(MGR, "manager", "setup") client = TestClient(create_app(Settings(teachers=frozenset({TEACHER})), store=store)) return client, store -def test_student_in_no_class_gets_no_class_and_no_lessons(setup): +def make(client, name="ט'3", lessons=("t",), students=""): + return client.post("/api/classes", json={"name": name, "lessons": list(lessons), "teacher_email": TEACHER, "students": students}, + headers=auth(MGR)).json()["id"] + + +def test_a_student_in_no_class_gets_no_class_and_no_lessons(setup): client, _ = setup me = client.get("/api/me", headers=auth(KID)).json() - assert me == {"email": KID, "role": "student", "class": None} + assert me["roles"] == ["student"] and me["classes"] == [] and me["teaching"] == [] assert client.get("/api/lessons", headers=auth(KID)).status_code == 403 def test_first_sign_in_links_the_account_to_the_class_entry(setup): client, store = setup - cid = client.post("/api/classes", json={"name": "ט'3"}, headers=auth(TEACHER)).json()["id"] - client.post(f"/api/classes/{cid}/students", json={"emails": KID}, headers=auth(TEACHER)) - assert client.get(f"/api/classes/{cid}", headers=auth(TEACHER)).json()["students"][0]["signed_in"] is False + cid = make(client, students=KID) + assert store.members(cid)[0]["user_id"] is None me = client.get("/api/me", headers=auth(KID)).json() - assert me["class"] == {"id": cid, "name": "ט'3"} - assert store.membership(KID)["user_id"] - assert client.get(f"/api/classes/{cid}", headers=auth(TEACHER)).json()["students"][0]["signed_in"] is True - assert len(client.get("/api/lessons", headers=auth(KID)).json()) == 24 + assert me["classes"] == [{"id": cid, "name": "ט'3"}] + assert store.members(cid)[0]["user_id"] + assert [lesson["id"] for lesson in client.get("/api/lessons", headers=auth(KID)).json()] == ["t"] + + +def test_a_student_of_two_classes_has_the_lessons_of_both(setup): + client, _ = setup + make(client, "A", ("t", "t2"), KID) + make(client, "B", ("t2", "k"), KID) + assert sorted(lesson["id"] for lesson in client.get("/api/lessons", headers=auth(KID)).json()) == ["k", "t", "t2"] + assert [c["name"] for c in client.get("/api/me", headers=auth(KID)).json()["classes"]] == ["A", "B"] def test_a_removed_student_loses_the_lessons(setup): client, _ = setup - cid = client.post("/api/classes", json={"name": "A"}, headers=auth(TEACHER)).json()["id"] - client.post(f"/api/classes/{cid}/students", json={"emails": KID}, headers=auth(TEACHER)) + cid = make(client, students=KID) assert client.get("/api/lessons", headers=auth(KID)).status_code == 200 client.delete(f"/api/classes/{cid}/students/{KID}", headers=auth(TEACHER)) assert client.get("/api/lessons", headers=auth(KID)).status_code == 403 -def test_teacher_has_no_class_and_still_sees_lessons(setup): +def test_a_deleted_class_takes_its_lessons_away(setup): + client, _ = setup + cid = make(client, students=KID) + client.delete(f"/api/classes/{cid}", headers=auth(MGR)) + assert client.get("/api/lessons", headers=auth(KID)).status_code == 403 + + +def test_a_teacher_sees_every_lesson_and_a_manager_no_learning_data(setup): client, _ = setup - assert client.get("/api/me", headers=auth(TEACHER)).json()["class"] is None - assert client.get("/api/lessons", headers=auth(TEACHER)).status_code == 200 + assert len(client.get("/api/lessons", headers=auth(TEACHER)).json()) == 24 + assert client.get("/api/lessons", headers=auth(MGR)).status_code == 403 + assert client.get("/api/path", headers=auth(MGR)).status_code == 403 diff --git a/openspec/changes/build-assignments/.openspec.yaml b/openspec/changes/add-ai-help/.openspec.yaml similarity index 100% rename from openspec/changes/build-assignments/.openspec.yaml rename to openspec/changes/add-ai-help/.openspec.yaml diff --git a/openspec/changes/add-ai-help/proposal.md b/openspec/changes/add-ai-help/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..3f5780037dadfd7e48a8e33ccb0befa27a27013f --- /dev/null +++ b/openspec/changes/add-ai-help/proposal.md @@ -0,0 +1,29 @@ +# Proposal + +## Why + +Students get stuck on problems outside the bank, and teachers cannot check every written answer alone. mathly1's AI help does both while students never call the AI themselves: every request goes through the teacher, within a budget (PRD 4.15, STU-6, TCH-5). + +## What Changes + +- Photo help: a student photographs a problem; after the teacher sends it, the AI's hints come one at a time, with the steps and answer only on request. +- AI checks of handwritten answers: a suggested score and comment for the teacher; the teacher's grade wins; students can ask to look again. +- The teacher's AI queue: send, decline with a note, or send a batch. +- Budgets: per class per day (default 150) and 3 personal requests per teacher per day. +- Privacy: the AI is off per class until a manager switches it on; no names or emails go to the AI. +- Clear messages when the AI fails, and a record of every call's cost. + +Screens: `docs/mockups/mathly2-screens.html` (student tab: photo help on home; teacher tab: AI queue). + +## Capabilities + +### New Capabilities +- `ai-help`: the queue, photo help, AI checks, budgets, failures, cost records and privacy (PRD AI-1 – AI-10, STU-6, TCH-5). + +### Modified Capabilities + +## Impact + +- Builds on `written-answers`, `assignments` and the class AI switch and budget from `accounts-and-classes`. +- New `m2_` tables for requests, reviews, budgets and usage. Uses `ANTHROPIC_API_KEY` and `MATH_MODEL`. +- Ports mathly1's `app/math_photo.py`, `app/answer_grading.py`, `app/ai_queue.py`, `app/ai_batches.py`, `app/teacher_ai.py`, `app/ai_usage.py` behavior. diff --git a/openspec/changes/add-ai-help/specs/ai-help/spec.md b/openspec/changes/add-ai-help/specs/ai-help/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..6ab581c73f49cb8cd62b95cac10c10cd02120e75 --- /dev/null +++ b/openspec/changes/add-ai-help/specs/ai-help/spec.md @@ -0,0 +1,105 @@ +# Spec Delta + +## Purpose + +Gives students AI help with photographed problems and AI-suggested checks of their written answers, always through their teacher, within a budget, and only where the school has switched it on. + +## ADDED Requirements + +### Requirement: Students never call the AI +A student's request (a photographed problem or an answer to check) SHALL become a request in the AI queue of their teacher, who sends it to the AI or declines it with an optional note. The student's screen SHALL show the request waiting, then its result or the note, and SHALL let them cancel it. + +#### Scenario: Declined +- **WHEN** a teacher declines a photo with the note "זה לא תרגיל במתמטיקה" +- **THEN** the student sees that it was declined, with the note + +### Requirement: Request limits +A student SHALL have at most 5 requests waiting at once and at most 20 photos a day. + +#### Scenario: Sixth request +- **WHEN** a student with 5 waiting requests sends another +- **THEN** it is refused with a message to wait for the teacher + +### Requirement: Which teacher +A student in more than one class SHALL choose which teacher a request goes to, defaulting to the teacher of the class with the nearest upcoming test and then to the one used last. The request SHALL count against that class's budget. + +#### Scenario: Two classes +- **WHEN** a student in two classes sends a photo +- **THEN** they are asked which teacher it goes to, with the default already chosen + +### Requirement: Who sends straight +A teacher or developer SHALL send their own requests without the queue. A teacher SHALL see the queue of their classes' students; a developer SHALL see every queue. + +#### Scenario: Teacher's own photo +- **WHEN** a teacher photographs a problem +- **THEN** it goes straight to the AI, within the teacher's daily allowance + +### Requirement: Photo help +The AI SHALL answer a photographed problem with: the problem as it read it, the solution as steps each with a hint and the step itself, the final answer, and the skill it practises. The student SHALL see one hint at a time, and each step and the answer only when asking. The photo MUST NOT be kept. + +#### Scenario: Hints first +- **WHEN** a student opens the result of photo help +- **THEN** they see the problem as read and the first hint, and the steps stay hidden until asked + +### Requirement: Photo help entries +The photo help button SHALL appear on the exercise screen beside "?" (telling the teacher the current skill) and on home as a card that also lists the student's requests. The "?" help SHALL end with "עדיין תקועים? צלמו", opening photo help. + +#### Scenario: From a skill +- **WHEN** a student sends a photo from the exercise screen of "פירוק טרינום" +- **THEN** the teacher's queue shows the request with that skill + +### Requirement: AI checks of written answers +The AI SHALL check a handed-in written answer against a stored copy of the question as answered, and return a score and comment as a suggestion. Where a score is used the teacher's SHALL win. The AI's check MUST NOT be edited; the teacher's review is kept beside it and older reviews stay as history. + +#### Scenario: Teacher changes the score +- **WHEN** the AI suggests 70 and the teacher gives 85 +- **THEN** the grade is 85 and the AI's 70 is still shown as its suggestion + +### Requirement: Asking to look again +A student who disagrees with a check SHALL be able to ask the teacher to look again, with at most one open request per answer and five per student. Saving a review SHALL close the request. + +#### Scenario: Look again +- **WHEN** a student asks to look again at a checked answer +- **THEN** the request appears in the teacher's inbox + +### Requirement: Budgets +Each class SHALL have a daily number of AI checks (default 150) counted by the Israel date and taken in one step, so two batches cannot pass it. A teacher SHALL have 3 personal requests a day; developers have no limit. A failed or unreadable check SHALL be given back. + +#### Scenario: Budget reached +- **WHEN** a class has used its 150 checks today +- **THEN** further checks wait until tomorrow + +### Requirement: Batches +A teacher SHALL be able to send every pending check of one assignment, or the single answers waiting, in one action, oldest first. When the budget is short the rest SHALL stay pending for the next day. + +#### Scenario: Short budget +- **WHEN** a teacher sends a batch of 30 with 10 checks left today +- **THEN** 10 are sent and 20 stay pending + +### Requirement: When the AI fails +The teacher who sent a request and developers SHALL see what went wrong and what to do (missing or invalid key, no permission, model not found, no credit, rate limit, overloaded, no connection, refused, cut short, unusable answer). The student SHALL see a short "try again later". + +#### Scenario: No credit +- **WHEN** the AI account has no credit left +- **THEN** the teacher sees "no credit" with what to do, and the student sees "try again later" + +### Requirement: Cost records +Every AI call SHALL record its tokens and estimated cost, with the class and the kind of call. + +#### Scenario: Photo help call +- **WHEN** a teacher sends a photo to the AI +- **THEN** a record with its tokens, cost, class and kind "photo" is kept + +### Requirement: AI off until switched on +The AI SHALL be off for a class until a manager switches it on, which the school does after confirming families agree. Students of a class with the AI off SHALL see no AI buttons. + +#### Scenario: New class +- **WHEN** a student of a newly created class opens the exercise screen +- **THEN** there is no photo help button + +### Requirement: Nothing identifying goes to the AI +Only the picture and the question SHALL be sent to the AI, never a student's name or email. Before a first photo the student SHALL be reminded not to write personal details in it. + +#### Scenario: First photo +- **WHEN** a student photographs for the first time +- **THEN** they see a reminder not to write their name in the picture diff --git a/openspec/changes/build-class-progress-views/.openspec.yaml b/openspec/changes/add-class-progress-views/.openspec.yaml similarity index 100% rename from openspec/changes/build-class-progress-views/.openspec.yaml rename to openspec/changes/add-class-progress-views/.openspec.yaml diff --git a/openspec/changes/add-class-progress-views/proposal.md b/openspec/changes/add-class-progress-views/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..efb6f605d72b85e08bdf25fd6b3882fbe2e0dc7b --- /dev/null +++ b/openspec/changes/add-class-progress-views/proposal.md @@ -0,0 +1,27 @@ +# Proposal + +## Why + +Teachers need a per-student picture of which skills and lessons each student has covered, to see at a glance where the class struggles (PRD Goal 3, TCH-7, TCH-8). + +## What Changes + +- A class heat map: students by skills (grouped by lesson), each cell showing the state by color and symbol. +- A lesson coverage table: students by lessons, % of skills mastered and the best quiz grade. +- Period tabs (Sep–Dec, Jan–Jun) showing states as they were at the end of the period. +- Each student's readiness for the class's upcoming test, for the teacher. +- A developer can open these views for any class. + +Screens: `docs/mockups/mathly2-screens.html` (teacher tab: heat map). + +## Capabilities + +### New Capabilities +- `class-progress-views`: the heat map, the coverage table, period tabs and readiness per student (PRD TCH-7, TCH-8, RDY-1 for teachers). + +### Modified Capabilities + +## Impact + +- Reads `skill-mastery`, `lesson-quizzes` and `readiness-meter` data; no new learning rules. +- Needs each skill's mastered date (already stored) to show states at the end of a period. diff --git a/openspec/changes/add-class-progress-views/specs/class-progress-views/spec.md b/openspec/changes/add-class-progress-views/specs/class-progress-views/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..7f5e24cce17a6fe805bb1812d194f32f419fa1d9 --- /dev/null +++ b/openspec/changes/add-class-progress-views/specs/class-progress-views/spec.md @@ -0,0 +1,49 @@ +# Spec Delta + +## Purpose + +Gives a teacher, and a developer, views of a class's progress by skill and by lesson, so they can see at a glance which skills the class struggles with and who needs help. + +## ADDED Requirements + +### Requirement: Class heat map +For a class they teach, a teacher SHALL see a heat map with a row per student and a column per skill, grouped by lesson. Each cell SHALL show the skill's state (not started, learning, mastered) by color and by a symbol, readable in light and dark mode. + +#### Scenario: Reading without color +- **WHEN** the heat map is printed in black and white +- **THEN** every cell's state can still be read from its symbol + +### Requirement: Lesson coverage +For a class they teach, a teacher SHALL see a table with a row per student and a column per lesson; each cell SHALL show the % of the lesson's skills the student mastered and their best quiz grade for it. + +#### Scenario: Half covered +- **WHEN** a student mastered 2 of a lesson's 4 skills and scored 75 on its quiz +- **THEN** their cell for that lesson shows 50% and 75 + +### Requirement: Period tabs +Both views SHALL have tabs for Sep–Dec and Jan–Jun. A period SHALL show the skills of the lessons taught in it, with states as they were at the end of the period, or today for the current period. + +#### Scenario: Last period +- **WHEN** a teacher opens the Sep–Dec tab in March +- **THEN** each cell shows the state as of 31 December + +### Requirement: Readiness per student +For each upcoming test of the class, the teacher SHALL see each student's readiness number and its parts. + +#### Scenario: Before a test +- **WHEN** a test is 5 days away +- **THEN** the teacher sees every student's readiness number for it + +### Requirement: Works on a computer +The views SHALL use the full width of a computer screen and keep student names and lesson headers visible while scrolling. + +#### Scenario: Wide class +- **WHEN** a teacher scrolls the heat map sideways on a computer +- **THEN** the student names stay visible + +### Requirement: Developer access +A developer SHALL be able to open these views for any class. + +#### Scenario: Any class +- **WHEN** a developer opens the heat map of a class they do not teach +- **THEN** it opens diff --git a/openspec/changes/build-lesson-quizzes/.openspec.yaml b/openspec/changes/add-developer-tools/.openspec.yaml similarity index 100% rename from openspec/changes/build-lesson-quizzes/.openspec.yaml rename to openspec/changes/add-developer-tools/.openspec.yaml diff --git a/openspec/changes/add-developer-tools/proposal.md b/openspec/changes/add-developer-tools/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..bf85503e22d6c5517c358e90ddb5bac948f42412 --- /dev/null +++ b/openspec/changes/add-developer-tools/proposal.md @@ -0,0 +1,23 @@ +# Proposal + +## Why + +The developers who run the app need their own tools: a teleprompter for the texts they record, a lab for testing tools, and a view of what the AI costs (PRD 4.20). + +## What Changes + +- The prompter from mathly1: saved texts per account, full-screen scrolling with keyboard and mouse controls, and an AI-written outline on request. +- An empty lab page for testing and development tools. +- An AI usage page: calls and estimated cost by day, class and kind. + +## Capabilities + +### New Capabilities +- `developer-tools`: the prompter, the lab and the AI usage page (PRD DEV-2 – DEV-4). + +### Modified Capabilities + +## Impact + +- Reads the cost records of `ai-help`. New `m2_` table for prompter texts. +- Ports mathly1's `app/prompter.py` and `static/prompter.js`, including its uncommitted outline work once that is committed in mathly1. diff --git a/openspec/changes/add-developer-tools/specs/developer-tools/spec.md b/openspec/changes/add-developer-tools/specs/developer-tools/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..4f8e621550a2aa093413e29a5658fa9b7df41efd --- /dev/null +++ b/openspec/changes/add-developer-tools/specs/developer-tools/spec.md @@ -0,0 +1,49 @@ +# Spec Delta + +## Purpose + +Tools only developers can reach: a teleprompter for their texts, a lab for testing tools, and a view of what the AI costs. + +## ADDED Requirements + +### Requirement: Developers only +The prompter, the lab and the AI usage page SHALL be reachable only by developers. + +#### Scenario: Manager +- **WHEN** a manager asks for the prompter +- **THEN** it is refused + +### Requirement: Prompter texts +A developer SHALL save texts (a title up to 120 characters, up to 200 texts) that belong to their account and appear on every device. The text being edited SHALL also be kept in the browser until it is saved. + +#### Scenario: Another device +- **WHEN** a developer saves a text on a computer and opens the prompter on a tablet +- **THEN** the text is there + +### Requirement: Prompter screen +The prompter SHALL show a text full screen and scroll it. Space starts and stops, ↑/↓ change speed, +/− change size, M mirrors, F is full screen and Esc leaves; the mouse and a presentation remote SHALL work too. + +#### Scenario: Mirror +- **WHEN** a developer presses M during scrolling +- **THEN** the text is shown mirrored + +### Requirement: Outline +On request the AI SHALL write a saved text's outline: the same slides with two to four very short topic reminders each, kept with the text and editable. Changing the text without sending an outline SHALL drop the outline. + +#### Scenario: Text changed +- **WHEN** a developer edits a text that has an outline and saves only the text +- **THEN** the outline is removed + +### Requirement: Lab +The lab SHALL be a page for testing and development tools. Until the first tool is chosen it SHALL say that tools will be added here. + +#### Scenario: Empty lab +- **WHEN** a developer opens the lab +- **THEN** it says tools will be added here + +### Requirement: AI usage +A page SHALL show the AI's calls and estimated cost by day, by class and by kind of call. + +#### Scenario: One week +- **WHEN** a developer opens the usage page +- **THEN** it shows each day's calls and cost, with totals per class and per kind diff --git a/openspec/changes/build-skill-learning/.openspec.yaml b/openspec/changes/add-written-work/.openspec.yaml similarity index 100% rename from openspec/changes/build-skill-learning/.openspec.yaml rename to openspec/changes/add-written-work/.openspec.yaml diff --git a/openspec/changes/add-written-work/design.md b/openspec/changes/add-written-work/design.md new file mode 100644 index 0000000000000000000000000000000000000000..a6bfc53bc785783bb1ec6dceede3b09864b467cc --- /dev/null +++ b/openspec/changes/add-written-work/design.md @@ -0,0 +1,98 @@ +# Design + +## Context + +See proposal.md for why. After stage 5, `mathly2/` has what a written hand-in builds on, and none of the written-work machinery: + +- **Reusable:** the smart board (`MathlyBoard.mount(layer, key, {submit, sendLabel, pages})`, copied unchanged from mathly1: `submit(page, picture)` receives the page as a picture and resolves to `{error}` or `{}`); classes with teachers and students (`m2_classes`, `store.members`, `classes_taught`); the grades screen and `/api/grades`; the student's home; the bank's four authored written quizzes (`unit.quiz`: minutes, four questions with `points` and `skills`); `exercise_test` attempts of a real test (stage 5). +- **Missing:** any file storage, image handling, assignments, submissions, phone requests and push. mathly1 has all of it (`app/answer_scans.py`, `app/worksheets.py`, `app/push.py`, `static/answer-scans.js`, `static/service-worker.js`) on Supabase RPC functions and a Hugging Face bucket; mathly2 re-implements it on its own `m2_` tables and keeps its own pictures (PRD: mathly1's tables and buckets stay untouched, so the Space can fall back). +- **Dependencies:** the build adds `Pillow` (image checks), `pypdfium2` (teacher PDFs to page images) and `pywebpush`, the same libraries mathly1 uses. mathly1's requirements are the reference for versions. + +## Goals / Non-Goals + +**Goals:** +- A student hands in pictures from the board, a phone camera, an uploaded file, or their phone on a computer's request; a teacher checks them from one inbox. +- Pictures are private (readable only through the server), cleaned of metadata, and removed on time. +- A computer can ask the student's phone for a photo, with a code and a push notification. + +**Non-Goals:** +- AI checking, the AI queue and photo help (stage 7). The inbox holds typed items so "request to look again" can join later. +- The class heat map and coverage (stage 8). +- Grading scores per question: a grade is one number 0–100 for the whole submission. + +## Decisions + +### 1. Five tables, pictures as rows + +| Table | Columns | +|---|---| +| `m2_pictures` | `id` uuid, `owner_id` uuid (the uploader), `kind` (`page` for an assignment page, `answer` for a student's picture), `path` (the object name in the bucket), `content_type`, `size`, `created_at`, `deleted_at` null | +| `m2_assignments` | `id` bigint, `class_id` → `m2_classes`, `title`, `note`, `due_date`, `kind` (`pages`, `quiz`, `exercise_test`), `pages` uuid[] (the pictures of a `pages` assignment), `quiz_lesson` text (the lesson whose written quiz it is), `test_id` + `exercise_number` (an exercise test), `created_by`, `created_at`, `removed_at` null | +| `m2_submissions` | `id` bigint, `assignment_id`, `user_id`, `pictures` uuid[], `state` (`handed_in`, `graded`, `returned`), `handed_at`, `grade` 0–100 null, `teacher_note`, `checked_at`, `checked_by`, unique (`assignment_id`, `user_id`) | +| `m2_photo_requests` | `id` uuid, `user_id`, `assignment_id`, `device` text (the computer that asked), `code` (4 digits), `state` (`waiting`, `uploading`, `received`, `failed`, `expired`, `superseded`), `created_at`, `expires_at`, `picture_id` null | +| `m2_push_subscriptions` | `id` bigint, `user_id`, `endpoint` unique, `p256dh`, `auth`, `key_id` (a fingerprint of the server's push key), `created_at` | + +A written quiz is not copied into the assignment: the row names the lesson and the questions and points are read from the bank, so the assignment always shows what the bank says. A student has one submission per assignment; a resubmission after "returned" rewrites that row (state back to `handed_in`, new pictures). Row security as the other `m2_` tables (server key only). The migration is `20261112090000_m2_written_work.sql`. *Alternative:* a version history of submissions. Rejected: the spec only needs "see the note and hand in again", and mathly1's history is not in the PRD. + +### 2. Pictures: the server is the only door + +`pictures.py` holds the logic and two stores of bytes behind one small interface (`put`, `get`, `delete`): `MemoryPictures` for tests and local development, and `SupabasePictures`, a **private** Storage bucket named by the setting `MATHLY_ANSWER_BUCKET` (default `m2-answers`, not mathly1's `mathly-answers`), read and written only with the secret key. The server creates the bucket on first use if it is missing (the Storage API, idempotent), so the migration needs no `storage` schema. *Alternative:* mathly1's Hugging Face bucket, chosen there to avoid Supabase egress. Rejected for now: a second token and library, and egress is not a problem at this size; the interface keeps it a later swap. + +- **`clean_image(bytes, content_type)`** (ported): only JPEG, PNG or WebP up to 5 MB and 20 million pixels; the orientation is applied, the metadata dropped, the image re-encoded as JPEG. Anything else is refused (415 or 413). +- **`render_pdf(bytes)`** (ported, teacher assignments only): up to 10 MB, 1600 px wide, 30 seconds for all pages, at most 20 pages; each page becomes a `page` picture, and the PDF itself is not kept. +- **Access:** `GET /api/pictures/{id}` streams the bytes, never a link into storage. Readable by: the uploader; a student of the class for a page of their class's assignment; the teacher of the class (or a developer, or a manager) for a picture an assignment or a submission of their class refers to. Anything else is 404. A deleted picture is 410. + +### 3. Handing in + +`POST /api/pictures` (kind `answer`, raw image bytes, student) returns an id; nothing refers to it yet. `POST /api/assignments/{id}/submission` with `{pictures: [ids]}` (1–10 pictures that the student uploaded) creates or replaces the submission: allowed while there is none, while it is `handed_in` (replace) or `returned` (hand in again), refused with 409 once `graded`. A hand-in after the due date is accepted and marked `late` (the due date is shown, never a lock). The board hands in a page by uploading it as an `answer` picture and adding its id to the draft the screen keeps; the phone camera and a file chooser do the same; the computer's photo request (decision 4) delivers a picture the same way. The draft lives in the page (and its ids in `sessionStorage`) until "הגשה". + +### 4. The photo request: the server holds the state, the screens poll + +```mermaid +stateDiagram-v2 + [*] --> waiting: computer asks (code made, older request -> superseded) + waiting --> uploading: phone starts the upload + uploading --> received: picture saved + uploading --> failed: upload refused or lost + waiting --> expired: 10 minutes pass + waiting --> superseded: a newer request for the same answer + received --> [*] +``` + +`POST /api/photo-requests` `{assignment_id, device}` makes the request, a random 4-digit `code`, an `expires_at` 10 minutes ahead, and supersedes the student's earlier waiting request for the same assignment. The computer polls `GET /api/photo-requests/{id}` every 2 seconds and draws the state and the code. The student's phone polls `GET /api/photo-requests/open` every 5 seconds while the app is open and at once when the service worker says a notification was tapped; any open request **not made by this device** (`device` differs) is shown in a window with the same code and a camera button. The phone's upload is `POST /api/photo-requests/{id}/picture` (raw bytes): the server sets `uploading`, cleans and stores the picture, then `received` with its id, or `failed`. Expiry is computed when a request is read (like attempts), so nothing runs in the background. A request is only ever read by its owner. + +### 5. Push notifications + +`push.py` (ported from mathly1) holds the sender behind an interface so tests use a recording fake. The key is the setting `VAPID_PRIVATE_KEY` (and `VAPID_SUBJECT`, default `mailto:` the first developer); without it push is off, `GET /api/push/key` says so and the screens do not offer notifications, while a phone that has the app open still sees requests by polling. A phone subscribes with `POST /api/push/subscribe` (only phones show the button: touch devices); each subscription stores a `key_id`, a fingerprint of the public key, and every read or send first deletes subscriptions with another `key_id` (changing the key drops them all). A push service answering 404 or 410 deletes that subscription. The push is sent when a request is created, to the student's subscriptions only (the computer never subscribes), carrying the request's address. The service worker (`/service-worker.js`, served from the root so it covers the app) is mathly1's: it shows the notification and, on a tap, focuses the app and posts it a message, or opens the address. `manifest.webmanifest` is copied from mathly1 and linked, because an iPhone delivers notifications only to the app added to the home screen (iOS 16.4+). + +### 6. Teachers: giving work and checking it + +- **Giving:** `POST /api/classes/{id}/assignments`, for a class the teacher teaches (a developer: any). The body names the title, note, due date and one source. *File:* images or a PDF uploaded first as `page` pictures (PDF pages rendered), listed in `pages`. *Photo:* the same upload from the camera. *Board:* the board's hand-in uploads each page as a `page` picture. *Bank:* `quiz_lesson`, accepted only for a lesson of the class that has an authored written quiz; the screen shows its questions with points. *Exercise test:* `test_id` and `exercise_number` of a test of that class (the PRD's EXT-2). Removing an assignment hides it (`removed_at`); grades already given stay on the student's grades screen. +- **Seeing:** `GET /api/teaching/assignments` lists a teacher's assignments with how many students handed in, graded and not. +- **The inbox:** `GET /api/teaching/inbox` lists submissions in state `handed_in`, oldest `handed_at` first, each with the student, the assignment, the picture ids, and a `kind: "submission"` field (stage 7 adds `recheck`). A `returned` submission waits for the student and is not listed. +- **Checking:** `POST /api/submissions/{id}/grade` `{grade 0–100, note, seen}` and `POST /api/submissions/{id}/return` `{note, seen}` (the note is required for a return; `seen` is the `handed_at` the teacher was looking at, and a different one gives 409). Only the class's teacher (or a developer) may; a picture of a submission is read through the picture route above. Grades are whole numbers, the same scale as every other grade. +- **Exercise-test assignments** have no submission: the student's state comes from their attempts at that exercise test (done when one is submitted, grade = the best), and nothing reaches the inbox. + +### 7. Students: my assignments and the grades + +`GET /api/assignments` lists the student's assignments (of their classes, not removed): title, class, due date, state (`not_handed`, `handed_in`, `graded`, `returned`, or for an exercise test `not_done` / `done`), `late`, grade, note. `GET /api/assignments/{id}` adds the pages (picture ids), the bank questions for a written quiz, the student's pictures, and the teacher's note. Home shows "המשימות שלי" with the open ones first (nearest due date), then done ones; `/api/grades` adds `assignments` (graded submissions and done exercise-test assignments) so the grades screen and the readiness inputs of stage 5 stay in one place. + +### 8. Keeping pictures: orphans, the school year, and on request + +- **Orphans:** a picture no assignment, submission or photo request refers to and older than 24 hours is deleted by the cleanup. +- **The school year:** `retention.expires_on(day)` is 31 August of the school year the picture was created in (1 Sep to 31 Aug); `answer` pictures are deleted on the first cleanup after it. Deleting removes the bytes and sets `deleted_at`; the submission keeps its grade and note, and the screens say "התמונות נמחקו". Assignment pages stay until their assignment is removed. +- **On request:** `DELETE /api/classes/{id}/students/{email}/pictures` by the class's teacher, a manager or a developer deletes that student's `answer` pictures for that class's assignments at once. +- **The job:** `cleanup.run(store, pictures, now)` returns what it removed, `python -m mathly2.cleanup` runs it once, and the server starts it every hour in the background when Supabase is on (the real deployment). + +## Risks / Trade-offs + +- [The board's hand-in, pen and camera cannot be fully tested headless] → The tests draw a stroke and press the board's send button, upload files, and use a stand-in for the camera input; the real camera and pen are a manual check on a phone and a tablet. +- [Polling every 2–5 seconds for a request costs requests] → Only while a request is open (10 minutes at most) and only on the two screens that show it; push makes the phone's first look immediate. +- [A student uploads someone's face or personal details] → Pictures are private, metadata stripped, deleted at the end of the school year, and the teacher can delete a student's pictures on request (PRD privacy). +- [The server creates the bucket on first use] → It needs the secret key's Storage permission; if the call is refused the screens show "האחסון לא זמין" (database-problems wording) and nothing else breaks. +- [An old submission's pictures are deleted while it is graded] → By design: the grade and note stay; only the pictures go. +- [A teacher grades a submission the student just replaced] → Grading reads the current row; a replace after the page was opened is refused with 409 ("ההגשה השתנתה"), by comparing `seen` with `handed_at`. + +## Migration Plan + +Run `20261112090000_m2_written_work.sql` after the seven earlier migrations; it only adds five tables. Set `VAPID_PRIVATE_KEY` (and `VAPID_SUBJECT`) to turn push on: without them everything else works. Make a key with `python -m mathly2.push` (printed once; keep it as a secret). Rollback: `drop table m2_push_subscriptions, m2_photo_requests, m2_submissions, m2_assignments, m2_pictures` (in the file header); the bucket `m2-answers` is left as it is. diff --git a/openspec/changes/add-written-work/proposal.md b/openspec/changes/add-written-work/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..f3eab1a0567aabd9ce490880d0efac7018260c65 --- /dev/null +++ b/openspec/changes/add-written-work/proposal.md @@ -0,0 +1,29 @@ +# Proposal + +## Why + +Teachers need to give work from the material they already have and check it, and students need to hand in full written solutions (PRD 4.14, TCH-2 – TCH-4, STU-5). Written answers are also what the AI checks in stage 7. + +## What Changes + +- A written answer is handed in as a picture: from the board, from the phone's camera, or, on a computer, by uploading or asking the student's own phone (a 4-digit code) with a push notification. +- Answer pictures are kept privately until 31 August of the school year. +- Teachers create assignments from a file, a photo, the board, or one of the bank's written quizzes, for a class; or send one of a real test's exercise tests as an assignment (EXT-2). +- Students see "המשימות שלי" on home, hand in, and see the grade and note or a request to correct. +- One teacher inbox of everything waiting, oldest first; grading 0–100 with a note, or sending back. + +Screens: `docs/mockups/mathly2-screens.html` (student tab: home assignments; teacher tab: inbox). + +## Capabilities + +### New Capabilities +- `written-answers`: handing in pictures, the phone photo request and push notifications, and where pictures are kept (PRD ANS-1 – ANS-3, PSH-1, PSH-2). +- `assignments`: giving, handing in, the inbox and grading (PRD TCH-2 – TCH-4, STU-5, QZ-6). + +### Modified Capabilities + +## Impact + +- Builds on `smart-board` (hand-in), `accounts-and-classes` and `grades`. +- New `m2_` tables for assignments, submissions, answer pictures and push subscriptions; a private storage bucket for pictures (not mathly1's). +- New settings for the push keys and the picture bucket. Ports mathly1's `static/answer-scans.js` behavior and service worker. diff --git a/openspec/changes/add-written-work/specs/assignments/spec.md b/openspec/changes/add-written-work/specs/assignments/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..8845bda8826e6a5eb8684a6d6c6600765cd1b7a3 --- /dev/null +++ b/openspec/changes/add-written-work/specs/assignments/spec.md @@ -0,0 +1,50 @@ +# Spec Delta + +## Purpose + +Lets a teacher give work from any material to a class, and check what students hand in, from one inbox. + +## ADDED Requirements + +### Requirement: Giving an assignment +A teacher SHALL create an assignment for a class they teach, with a title, a note and a due date, and its pages from: a file from the computer (PDF or images), a photo from the device camera, the board, or one of the written quizzes authored in the bank. + +#### Scenario: From the board +- **WHEN** a teacher writes an assignment on the board and saves it +- **THEN** the board's pages become the assignment's pages + +#### Scenario: From the bank +- **WHEN** a teacher picks the bank's written quiz of "טכניקה אלגברית 1" +- **THEN** its four questions become the assignment, with their points + +### Requirement: An exercise test as an assignment +A teacher SHALL be able to send one of their real test's two exercise tests to the whole class as an assignment with a due date. Students SHALL see it under "המשימות שלי"; it opens the exercise test, counts as done when the student has taken it, and its grade is the exercise test's best grade. It is not handed in as a picture and does not wait in the inbox. + +#### Scenario: Sent to the class +- **WHEN** a teacher sends exercise test 1 of a test to the class with a due date +- **THEN** every student sees it in "המשימות שלי", and it opens the exercise test + +#### Scenario: Not in the inbox +- **WHEN** a student finishes the exercise test +- **THEN** the assignment shows as done with the test's grade, and nothing is added to the teacher's inbox + +### Requirement: My assignments +A student SHALL see their assignments on home under "המשימות שלי" with the due date and state, open one, work on it on the board or on paper, and hand it in. + +#### Scenario: Hand-in +- **WHEN** a student hands in an assignment from the board +- **THEN** it shows as handed in, and the teacher's inbox lists it + +### Requirement: Teacher inbox +A teacher SHALL have one inbox of everything their students handed in that waits for them, oldest first: submissions not checked yet and requests to look again. A submission sent back waits for the student, not in the inbox. + +#### Scenario: Oldest first +- **WHEN** two students hand in on Monday and Tuesday +- **THEN** Monday's submission is first in the inbox + +### Requirement: Checking a submission +The teacher SHALL open a submission, give a grade from 0 to 100 and a note, or send it back for correction with a note. The student SHALL see the grade and note, or the request to correct. + +#### Scenario: Sent back +- **WHEN** a teacher sends a submission back with "חסר נימוק בסעיף 2" +- **THEN** the student sees the note and can hand in again diff --git a/openspec/changes/add-written-work/specs/written-answers/spec.md b/openspec/changes/add-written-work/specs/written-answers/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..fc638db80ad835bcbb1806222e484f3fd4b75742 --- /dev/null +++ b/openspec/changes/add-written-work/specs/written-answers/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## Purpose + +Lets a student hand in a handwritten or drawn solution as a picture from whatever device they have, and keeps those pictures private and only as long as needed. + +## ADDED Requirements + +### Requirement: Handing in a written answer +A written answer SHALL be handed in as a picture: from the board, or by photographing paper. On a phone the camera opens; on a computer the student uploads an image or asks their own phone to take the photo. + +#### Scenario: Photo on a phone +- **WHEN** a student on a phone chooses to photograph their answer +- **THEN** the camera opens and the picture is handed in + +### Requirement: Photo request to the phone +A computer SHALL be able to create a photo request for one answer. The student's phone, signed in to the same account, SHALL show the request with a 4-digit code that matches the one on the computer. The computer SHALL show the state: waiting for the phone, uploading, received, failed, expired, or replaced by a newer request. + +#### Scenario: Matching code +- **WHEN** a student asks for a photo from the computer and opens the app on their phone +- **THEN** the phone shows the same 4-digit code as the computer and a camera button + +#### Scenario: Newer request +- **WHEN** a student makes a second photo request for the same answer +- **THEN** the first one shows as replaced + +### Requirement: Push notification to the phone +A phone SHALL be able to turn notifications on. When the computer creates a photo request, the phone SHALL be notified even if the app is closed; tapping the notification SHALL open the request. Only phones subscribe; a subscription the push service no longer knows SHALL be deleted. + +#### Scenario: App closed +- **WHEN** a student asks for a photo from the computer while the app is closed on their phone +- **THEN** the phone shows a notification that opens the request + +### Requirement: Private pictures +Answer pictures SHALL be kept in private storage tied to the account and read only by the server. Pictures no answer refers to SHALL be removed every hour. + +#### Scenario: Direct link +- **WHEN** someone tries to open an answer picture without going through the server +- **THEN** it is refused + +### Requirement: Keeping pictures for a school year +Answer pictures SHALL be removed after 31 August of the school year they were handed in; grades and teachers' comments stay. A teacher of the class, a manager or a developer SHALL be able to delete a student's pictures earlier on request. + +#### Scenario: New school year +- **WHEN** 1 September comes +- **THEN** last year's answer pictures are gone and their grades remain diff --git a/openspec/changes/add-written-work/tasks.md b/openspec/changes/add-written-work/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..5d9c8e369b692fb9a4018bc591cccc0b70fa38b4 --- /dev/null +++ b/openspec/changes/add-written-work/tasks.md @@ -0,0 +1,44 @@ +# Tasks + +## 1. Data, pictures and retention + +- [ ] 1.1 Add the migration `20261112090000_m2_written_work.sql` (decision 1) and the store methods for pictures, assignments and submissions (create, read, list, replace, check, soft-remove, references of a picture), in both stores; verify unit tests, request tests for the Supabase store, and migration tests on PostgreSQL (defaults, the state and grade checks, one submission per student and assignment, cascade with the class, the browser roles are refused) +- [ ] 1.2 Add the store methods for photo requests (create, supersede, read, list open, set state, expire) and push subscriptions (add, list, delete, drop other keys), in both stores; verify unit tests including supersede, expiry and that one student's rows never reach another +- [ ] 1.3 Add `pictures.py` (decision 2): `clean_image`, `render_pdf`, `MemoryPictures`, `SupabasePictures` that creates its private bucket on first use; verify unit tests: a JPEG with metadata comes back without it and upright, a non-image or oversized file is refused, an image over 20 million pixels is refused, a PDF gives one picture per page and too many pages are refused, and request tests for the Supabase storage calls +- [ ] 1.4 Add `retention.py` and `cleanup.py` (decision 8): the end of the school year, orphans older than 24 hours, `run`, and the CLI; verify unit tests: a picture from October expires on 1 September of the next year, one from May on 1 September of the same year, an unreferenced picture is removed after a day and a referenced one stays, a deleted picture's submission keeps its grade and note, and assignment pages are not removed by the year's end + +## 2. The API + +- [ ] 2.1 Add `POST /api/pictures` and `GET /api/pictures/{id}` with the access rules (decisions 2 and 3); verify API tests: an upload is cleaned and stored, the uploader and the class's teacher read it, another student, another class's teacher and a signed-out request get 404, a deleted picture is 410, a page of an assignment is readable by the class's students, and the bytes are never reachable by a storage link +- [ ] 2.2 Add the teacher's assignment routes (decision 6): create from images or a PDF, a photo, the board's pages, a bank written quiz and an exercise test, list with counts, and remove; verify API tests: each of the five sources works and a bank quiz only for a lesson of the class that has one, a PDF becomes page pictures, a class the teacher does not teach is 404, an exercise test of another class is refused, removing an assignment hides it and keeps grades +- [ ] 2.3 Add the student's routes (decisions 3 and 7): `GET /api/assignments`, `GET /api/assignments/{id}`, and hand in or replace; verify API tests: only the student's classes' assignments, hand in 1 to 10 of their own pictures (none or 11 or someone else's refused), replace while handed in, refused once graded, hand in again after returned, a late hand-in is accepted and marked late, an exercise-test assignment is done after the student took it and shows the best grade, and a written quiz shows its questions with points +- [ ] 2.4 Add the inbox and checking (decision 6): `GET /api/teaching/inbox`, `POST /api/submissions/{id}/grade` and `/return`, and the assignments in `GET /api/grades`; verify API tests: Monday's submission before Tuesday's, a returned one is not listed, a grade is 0–100 whole, a return needs a note, a grade of 101 or -1 is refused, a stale `seen` gives 409, another class's teacher gets 404, the student then sees the grade and note or the request to correct, exercise-test assignments never reach the inbox, and the grades list shows graded assignments +- [ ] 2.5 Add the photo-request routes (decision 4); verify API tests: a request has a 4-digit code and expires after 10 minutes (the server's clock), a newer request for the same assignment supersedes the older, the phone's open list leaves out requests made by its own device, the states go waiting → uploading → received with the picture, a bad upload gives failed, and another student cannot read or answer a request +- [ ] 2.6 Add push (decision 5): `push.py`, `GET /api/push/key`, `POST /api/push/subscribe`, the notification on a new request, the service worker route and the manifest; verify API tests with a recording fake: a new request notifies the student's subscriptions with the request's address, a dead subscription (404 or 410) is deleted, changing the key drops every subscription, without a key push is off and says so, and everything else still works +- [ ] 2.7 Add early deletion `DELETE /api/classes/{id}/students/{email}/pictures` and start the cleanup every hour when Supabase is on; verify API tests: the class's teacher, a manager and a developer may, another class's teacher and a student may not, the student's submissions keep their grade and note, and a unit test that the hourly start is not used without Supabase + +## 3. Student screens + +- [ ] 3.1 Add "המשימות שלי" to home: open ones first by due date, then done ones, each with its due date and state in words (and "באיחור", "ציון N", "הוחזר לתיקון"); verify a Playwright test of every state at 360px +- [ ] 3.2 Build the assignment page `#/assignment/`: the note, pages (images inline) or the bank's questions or the exercise-test link, the student's pictures with removal, work on the board with a hand-in button, a camera input, an upload, and "הגשה"; after hand-in the state, and the grade and note or the request to correct; verify a Playwright test that a file upload and a board hand-in (a stroke drawn and the send button pressed) add pictures, hand-in shows "הוגש", a returned submission shows the note and can be handed in again, and a graded one cannot be changed +- [ ] 3.3 Add the photo request to the computer's screen (a "בקשת צילום מהטלפון" button, the code and the state in words, newer request marks the older replaced) and the phone's request window (the same code, a camera button, once per request, not on the device that asked); verify a Playwright test with two pages standing for the computer and the phone: the code matches, the phone uploads, the computer shows "התשובה התקבלה" and the picture joins the draft, and the computer never shows its own request window +- [ ] 3.4 Add notifications on the phone: the service worker and manifest linked, a toggle shown only on touch devices and only when the server has a key, and a tap that opens the request; verify a Playwright test that the toggle is absent without a key and on a desktop pointer, present with both, that subscribing sends the subscription to the server, and that a `notified` message from the worker makes the phone look for requests at once +- [ ] 3.5 Add assignments to the grades screen (graded assignments and done exercise-test assignments, with the teacher's note); verify a Playwright test + +## 4. Teacher screens + +- [ ] 4.1 Add the assignments tab to the teacher's screen: create (class, title, note, due date, and one source: file, camera photo, board, bank written quiz or an exercise test of a test of the class), the list with "N הגישו, M נבדקו", and removal; verify a Playwright test of each source at 360px and on a computer +- [ ] 4.2 Add the inbox tab: oldest first, open a submission to see its pictures, grade with a note, or send back with a required note, then the student's screen shows the result; verify a Playwright test that two submissions come oldest first, a grade empties its item, a return needs a note and leaves the inbox, and a stale submission shows "ההגשה השתנתה" + +## 5. Wrap-up + +- [ ] 5.1 Walk the whole flow in a browser with two students' devices: a teacher gives an assignment from a file and from the bank, a student hands in from the board and a second student by a phone request, the teacher's inbox shows both in order, one is graded and one is sent back, the second student hands in again and is graded, the grades screen shows both, and the teacher deletes a student's pictures while the grade stays; verify the test passes +- [ ] 5.2 Update `docs/mockups/mathly2-screens.html` where the home assignments or the teacher's inbox no longer match what was built; verify by opening it beside screenshots +- [ ] 5.3 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate add-written-work --strict`; verify both pass + +## Workflow follow-up + +- Apply the new migration after the seven earlier ones (on a test project first); set `VAPID_PRIVATE_KEY` to turn push on. +- Add `Pillow`, `pypdfium2` and `pywebpush` to `mathly2/requirements.txt` (task 1.3 and 2.6 do it). +- Check the camera, the pen on the board and a real push notification on a phone, including an iPhone from the home screen (a headless browser cannot). +- Archive this change once it is reviewed; then propose `add-ai-help` (stage 7), which adds the AI queue, photo help and the recheck items in the inbox. diff --git a/openspec/changes/build-test-prep/.openspec.yaml b/openspec/changes/archive/2026-11-08-add-learning-core/.openspec.yaml similarity index 100% rename from openspec/changes/build-test-prep/.openspec.yaml rename to openspec/changes/archive/2026-11-08-add-learning-core/.openspec.yaml diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/design.md b/openspec/changes/archive/2026-11-08-add-learning-core/design.md new file mode 100644 index 0000000000000000000000000000000000000000..7967b169a681b21b3a8f461eeb53c58cca043fee --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/design.md @@ -0,0 +1,99 @@ +# Design + +Target screens, from `docs/mockups/mathly2-screens.html` (sample data): + +| Path (light) | Path (dark) | Exercise, wrong answer (light) | +|---|---|---| +| ![Path, light](./screenshots/path-light.png) | ![Path, dark](./screenshots/path-dark.png) | ![A wrong answer names the mistake](./screenshots/exercise-wrong-light.png) | + +## Context + +See proposal.md for why. After `rebuild-foundation`, `mathly2/` has roles, classes and the sky look, plus student code from an earlier plan that this stage reshapes: + +- `learning.py` already holds the rules this stage needs: the mastery rule (3 correct, first try, no help, 2 days), skill states, the next question (least seen, never the one just answered). Their tests already cover every scenario in `skill-mastery`. +- `skills.py` serves a skill in three stages (worked example, faded examples, practice) and has `/stage`. The PRD dropped the first two. +- `static/path.js` is a plain list; `skill.js` is the three-stage screen; `collection.js` and `figures.js` stay. +- mathly1 has the board (`static/math-board.js`, `board-math.js`, `vendor/mathlive/`) and its CSS block inside `static/math.css` (lines 675–824, plus the sheet rules at 62–76). + +## Goals / Non-Goals + +**Goals:** +- A student can practice a skill on mathly1's exercise screen with instant feedback, and see their progress on the orbit path. +- The board works as in mathly1: beside the exercise on a desktop, full screen on a phone, with its tools and the calculator. + +**Non-Goals:** +- The daily goal and streak display, fading stars, the collection, and comets (stage 3, `add-rewards`). +- Quiz nodes on the trail (stage 4). Handing a sketch in (stage 6 uses the board's hand-in; here the board is for working out). +- Writing the solved examples (content work). The help button shows one when the bank has it. + +## Decisions + +### 1. The solved example is static text, and there is one per skill + +The help button shows the skill's explanation and, if the bank has it, a solved example under `worked_example`: `{question, steps: [{do, why}], answer}`, with `why` as plain text (not a choice). `check_bank` validates this shape only. A skill with `faded_examples` is ignored (nothing reads it). The drafting tool writes this shape: one example per skill, no faded ones. *Alternative:* keep the multiple-choice "why this step?" steps. Rejected: the PRD dropped the staged teaching they belonged to. + +### 2. The skill API loses its stages + +| Route | Now | +|---|---| +| `GET /api/skills/{id}` | the skill, its lesson, state, the question on screen, `solved` of `total` questions, `correct_in_row`, `requires` and `opens` (id and name), and `help` (explanation, solved example if any) | +| `POST /api/skills/{id}/answer` | unchanged rules; a stale question key is refused (409) | +| `POST /api/skills/{id}/help` | unchanged | +| `POST /api/skills/{id}/stage` | **removed** | +| `GET /api/path` | the lessons of the student's classes (all lessons for a teacher or developer), each skill with its state, the `next` skill id (or null), today's goal and the streak | + +`solved` counts the distinct questions the student answered correctly (a new store method), so "question n of N" and the dots show progress through the skill. The next skill is `learning.next_skill`: walk the student's recently answered skills, newest first, and take the first that is not mastered; otherwise the first unmastered skill in the bank's order. A new store method `recent_skills(user_id, n)` reads the newest answers, so no migration changes. + +```mermaid +sequenceDiagram + participant S as Student + participant P as Path + participant X as Exercise sheet + participant A as Server + S->>P: taps a star + P->>X: opens the sheet (#/skill/id) + X->>A: GET /api/skills/id + A-->>X: question (no correct flag), progress, help, chips + S->>X: taps a choice + X->>A: POST answer {question_key, choice} + A->>A: grade, date by server, mastery rule, pick next + A-->>X: right or wrong, mistake name+tip, next question, state + S->>X: closes the sheet + X->>P: path is fetched again, the star shows its new state +``` + +### 3. The path: orbits in CSS, drawn from one list + +Each lesson is a `section` with a hub and a ring. A star's place comes from its number *i* of *n*: angle = -90° + 360°·*i*/*n*, passed as `--dx` and `--dy`, so the page needs no layout code. The ring's radius is `min(112px, 30cqw)` (the section is a size container), so the six-skill lesson fits a 360px screen. Each star is an `` whose accessible name is its number, the skill's name and its state in words; under it the visible word and symbol. The owl (from `sky.js`) perches on the `next` star; the start marker has the owl, the end marker a spark. Ring arcs between neighbouring stars come from mathly1's `orbitRing`, ported into `sky.js`. The sky colors stay the `--sky-*` tokens from the foundation. + +States and looks (spec: Stars show state in words): + +| State | Look | Word | +|---|---|---| +| not started | dim outline | ○ לא התחלת | +| learning | half-filled star | ◐ בלמידה | +| mastered | gold star | ✓ נשלטה | +| next (extra) | larger, pulsing, owl | ממשיכים כאן | + +### 4. The exercise screen is a dialog over the path + +The route `#/skill/` keeps the path drawn and puts a `role="dialog"` sheet on top (`.mx-layer > .mx-scrim + .mx-sheet`, the structure the board expects). Opening from a link or a reload draws the path first, then the sheet. Closing removes the sheet, goes back to `#/`, fetches `/api/path` again and updates the stars without losing the scroll. Choices are shown in a new random order with their bank positions as `data-i`; a tap sends the answer at once. A right answer: a short sparkle and `navigator.vibrate` where the device has it, the count in a row, and a 3-second countdown the student can skip or cancel. A wrong answer is quiet: the mistake's name and tip, a link to the skill to go back to when the bank names one, and a "another question" button; the right choice is never marked. A refused (stale) answer reloads the question that is on screen. + +### 5. The board is copied, not rewritten + +`math-board.js`, `board-math.js` and `vendor/mathlive/` are copied from mathly1 unchanged. Its CSS block (the board, the toolbar, the calculator, the full-screen mode, the typed-math bar) goes into `static/board.css` together with the sheet, layer and scrim rules the board's layout relies on. The block uses mathly1's variable names (`--ink`, `--mx-accent`, `--sumac`, ...); a small block at the top of `board.css` defines each from the sky tokens, so the board follows the sky with no edits to its rules. The sheet calls `MathlyBoard.mount(layer, ":", {question: () => questionElement})` every time a question is shown, so each question keeps its own sketch; the header carries `MathlyBoard.button()`, and a click on `[data-board-toggle]` calls `MathlyBoard.toggle()`. On a phone this opens the board full screen; on a desktop (`min-width:1000px` and a fine pointer) it sits beside the sheet. Hand-in (`submit`) is left unset in this stage. + +### 6. Removing the old stages + +`skill.js` is replaced by `exercise.js` (the sheet); the worked and faded screens, the `/stage` route, the stage logic in `skills.py`, the faded checks in `bank.py`, the faded part of the drafting tool, the old skill-screen CSS and the progress table's two stage columns are deleted, together with the tests that only covered them. + +## Risks / Trade-offs + +- [The board's CSS and JS are large (65 KB and 1.2 MB of MathLive) and came from a different theme] -> They load only when the board is first opened (`board.css` and the scripts are added then); a Playwright test opens it on a phone and on a desktop width. +- [The orbit looks wrong with 2 or 6 skills] -> A browser test draws the lessons with 2, 3 and 6 skills at 360px and checks that no star leaves the screen or overlaps the hub. +- [Copying board.css selectors from mathly1 could clash with the sky CSS] -> `board.css` is scoped to `.mx-*` classes, which nothing in mathly2 uses; the `.row`, `.tag` and `.card` classes are not touched. +- [Pen, palm and calculator behaviour cannot be fully tested in a headless browser] -> The tests cover tools, drawing, undo, the calculator's result and the layout; palm rejection and pen pressure are left to a manual check on a tablet. + +## Migration Plan + +One small migration, `20261108090000_m2_progress_without_stages.sql`: it drops the two columns of `m2_skill_progress` that remembered a skill's stage (`stage`, `faded_done`), which nothing reads any more. Only an `m2_` table changes; the answers table is untouched. It must run after the three earlier migrations. Removing the `/stage` route and the faded checks is the only other breaking change, and nothing outside `mathly2/` uses them. Rollback: the migration's header lists the statements that add the columns back; the code is in git. diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/proposal.md b/openspec/changes/archive/2026-11-08-add-learning-core/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..451af686843f73402947bf532ed0d36d8b0a16f2 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/proposal.md @@ -0,0 +1,32 @@ +# Proposal + +## Why + +After the foundation, students can sign in but cannot learn. This stage is the smallest product a class can use: mathly1's path of stars, its exercise screen with instant feedback, its smart board, and mastery proven over two days (PRD 4.4–4.7). + +## What Changes + +- The exercise screen from mathly1: one question at a time, choices in a new order each time, instant server grading, quiet wrong answers that name the mistake without revealing the answer, a different next question, a "?" help with the explanation and a solved example, related-skill chips. +- The subject choice from mathly1: after sign-in a card per subject (math only) with a progress bar, leading to the path. +- The path from mathly1: lesson hubs with numbered rings of stars on a trail, the owl on the next skill, every lesson open. +- The smart board kept as files from mathly1, opened beside or over the exercise. +- Mastery: 3 correct in a row, first try, no help, on 2 days; never decays. +- **BREAKING** (for the current `mathly2` code): the worked-example and faded-example stages are removed. + +Screens: `docs/mockups/mathly2-screens.html` (student tab: path and exercise). + +## Capabilities + +### New Capabilities +- `skill-mastery`: skill states, the mastery rule, help that does not count, server-dated answers (PRD MST-1 – MST-5). +- `exercise-screen`: practicing one skill (PRD EXR-1 – EXR-10). +- `learning-path`: the trail of lesson hubs and stars, the next skill, all lessons open (PRD PTH-1 – PTH-9 without the quiz node and the daily goal). +- `smart-board`: the drawing board, its tools and handing in a sketch (PRD BRD-1 – BRD-12). + +### Modified Capabilities + +## Impact + +- Reuses from today's `mathly2`: answers and progress tables, `learning.py` (mastery, next question), question keys, figures, the practice API. +- Removes: the worked/faded example stages, their bank checks and screens, and the old list-style path. +- Copies `static/math-board.js`, `static/board-math.js` and `static/vendor/mathlive/` from mathly1 unchanged. diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-dark.png b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..c418d5b9f75ecc35c2c9a9d44326d37ed518b2dc --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-dark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59ee8fa4d6f49a542fd2a9db5c34077a71c61a278b2f891841825a4cfc7ca2f1 +size 82318 diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-light.png b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-light.png new file mode 100644 index 0000000000000000000000000000000000000000..585143c96b59bf8014c18ae70f0637704db36171 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/exercise-wrong-light.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:466f4d47fab9c6bc9ad8b83f2e2e62bcf680eb72a524461c4dffba0eb43048ad +size 81329 diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-dark.png b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..67d11242bb9a8b3d6f8e98d09835fe5882d67cc1 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-dark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38bc14911f5351fb355adcd831fbf6b0f42c3795f8325cebbbe6ed51bc77b57a +size 145839 diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-light.png b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-light.png new file mode 100644 index 0000000000000000000000000000000000000000..6f4dbe896587ebde0786629e55d189b348c377e6 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/screenshots/path-light.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4e62ec95c8b5e20f6756475c630e92bc6095f8577b63289941b50c71de1ea70 +size 143090 diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/specs/exercise-screen/spec.md b/openspec/changes/archive/2026-11-08-add-learning-core/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..98a0591ee0e1881a32fb3688a84903b8e4bcd9a0 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/specs/exercise-screen/spec.md @@ -0,0 +1,70 @@ +# Spec Delta + +## Purpose + +The screen where a student practices one skill with the exercise bank's questions: instant feedback that teaches from the mistake, help when stuck, and the board to work things out. + +## ADDED Requirements + +### Requirement: Layout +The exercise screen SHALL open as a sheet over the path. Its header SHALL show the lesson's name, the skill's name, a completed mark when the skill is mastered, a board button, a "?" help button and a close button, with the skill's short explanation under it. + +#### Scenario: Opening a skill +- **WHEN** a student opens the skill "פירוק טרינום" +- **THEN** the sheet shows the lesson's name, "פירוק טרינום", the board, "?" and close buttons, and the explanation + +### Requirement: One question at a time +The sheet SHALL show one question: its text with formulas, its figure or graph if any, and its choices in a new random order each time it is shown, with "question n of N" and a row of dots for the skill's questions. + +#### Scenario: Same question again +- **WHEN** a question is shown a second time +- **THEN** its choices may be in a different order, and the server still grades by the bank's choice + +### Requirement: A right answer +A right answer SHALL get a short celebration and the count of right answers in a row. After a short countdown the next question SHALL appear; the student can skip or cancel the countdown. + +#### Scenario: Countdown +- **WHEN** a student answers correctly +- **THEN** a countdown to the next question starts, and pressing "next" shows it at once + +### Requirement: A wrong answer +A wrong answer SHALL be quiet and SHALL show the name and tip of the mistake attached to the chosen choice, about the mistake and not the student. It MUST NOT reveal the correct answer. When the mistake names a skill to go back to, the feedback SHALL link to it. + +#### Scenario: Sign mistake +- **WHEN** a student picks a choice tagged with "טעות סימן באיבר האמצעי" +- **THEN** the mistake's name and tip are shown and no choice is marked as correct + +### Requirement: A different next question +After any answer the next question SHALL be another question of the same skill, picked at random among those this student has seen least, never the one just answered. A skill with one question repeats it. + +#### Scenario: After a mistake +- **WHEN** a student answers a question wrongly +- **THEN** the next question is not the one just answered + +### Requirement: Help +The "?" button SHALL show the skill's explanation and, where the bank has one, a solved example. Opening it SHALL make the answer to the question on screen not count for mastery; that answer still counts for the daily goal. + +#### Scenario: Help opened +- **WHEN** a student opens "?" and then answers correctly +- **THEN** the answer is stored as given with help and does not count toward mastery + +### Requirement: Related skills +The sheet SHALL show the skills this one requires and the skills it opens as tappable chips, which open those skills and never lock anything. + +#### Scenario: Required skill +- **WHEN** a student taps a "requires" chip +- **THEN** that skill's exercise screen opens + +### Requirement: Resuming +Reopening a skill SHALL continue with the question that was on screen, and an answer to a question that is no longer on screen SHALL be refused. + +#### Scenario: Two tabs +- **WHEN** a student answers in one tab a question that another tab already replaced +- **THEN** the answer is refused and the screen shows the current question + +### Requirement: Skill without questions +A skill with no questions SHALL say there is no practice for it yet, and cannot be mastered. + +#### Scenario: Empty skill +- **WHEN** a student opens a skill with no questions +- **THEN** the sheet says there is no practice yet diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/specs/learning-path/spec.md b/openspec/changes/archive/2026-11-08-add-learning-core/specs/learning-path/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..ce347098d0e3a9b5a22492baeda0303a0c6147f6 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/specs/learning-path/spec.md @@ -0,0 +1,75 @@ +# Spec Delta + +## Purpose + +The student's main screen: every lesson of their classes as a hub with its skills as stars, joined in one trail, so they always see where they stand and where to continue. + +## ADDED Requirements + +### Requirement: Choosing a subject +After sign-in a student SHALL first see the subjects of their classes as cards, each with an icon, the subject's name and a bar "N מתוך M מיומנויות" (skills mastered of all skills in their lessons). Math (מתמטיקה) is the only subject; other subjects are not built. Tapping a card SHALL open that subject's path, and the path SHALL have a way back to the subjects. A reload or a link to a skill SHALL open its path directly. + +#### Scenario: After signing in +- **WHEN** a student signs in +- **THEN** they see a card "מתמטיקה" with "N מתוך M מיומנויות", and no path yet + +#### Scenario: Opening the subject +- **WHEN** the student taps the math card +- **THEN** the path of their lessons opens, with a way back to the subjects + +#### Scenario: A link to a skill +- **WHEN** a student opens `#/skill/` directly +- **THEN** the math path opens with that skill's exercise screen over it + +### Requirement: Trail of lesson hubs +Every lesson of the student's classes SHALL be a hub showing its name and "mastered of total", with its skills in a ring around it, in order, numbered from the top and clockwise. The hubs SHALL be joined by a vertical trail from a start marker with the owl to an end marker. + +#### Scenario: Opening the path +- **WHEN** a student opens the path +- **THEN** each of their lessons is a hub with its numbered skills around it, on one trail + +### Requirement: Stars show state in words +Each skill SHALL be a star whose look shows its state, with a symbol and word under it: "○ לא התחלת", "◐ בלמידה" or "✓ נשלטה". A mastered star SHALL look clearly different from the other two. + +#### Scenario: Three states +- **WHEN** a lesson has a mastered, a learning and a not-started skill +- **THEN** their stars show "✓ נשלטה", "◐ בלמידה" and "○ לא התחלת" + +### Requirement: Next skill +One skill SHALL carry the owl as the suggested next: the unmastered skill answered most recently, else the first unmastered skill in the bank's order. When all are mastered none is marked. The marker MUST NOT lock, hide or reorder anything. + +#### Scenario: New student +- **WHEN** a student who answered nothing opens the path +- **THEN** the owl is on the first skill of the first lesson and every skill can be opened + +#### Scenario: Continuing +- **WHEN** a student's last answer was on an unmastered skill +- **THEN** the owl is on that skill + +### Requirement: All open +The student SHALL be able to open any lesson and any skill in it at any time, in any order. + +#### Scenario: Jumping ahead +- **WHEN** a student opens a skill in the last lesson first +- **THEN** its exercise screen opens + +### Requirement: Opening a skill from the path +Tapping a star SHALL open its exercise screen over the path; closing it SHALL show the path with the star updated. The path SHALL open scrolled to the next skill. + +#### Scenario: Back from practice +- **WHEN** a student masters a skill and closes the sheet +- **THEN** its star on the path shows "✓ נשלטה" + +### Requirement: Accessible stars +Each star SHALL be a control whose accessible name is its number, the skill's name and its state in words, reachable and opened from the keyboard. + +#### Scenario: Keyboard +- **WHEN** a student moves to a star with Tab and presses Enter +- **THEN** its exercise screen opens + +### Requirement: Fits a phone +The path SHALL fit a 360px-wide screen without sideways scrolling, including the lesson with the most skills. + +#### Scenario: Six skills +- **WHEN** the lesson with six skills is shown on a 360px screen +- **THEN** all six stars and their words are visible without sideways scrolling diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/specs/skill-mastery/spec.md b/openspec/changes/archive/2026-11-08-add-learning-core/specs/skill-mastery/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f55eea7fdb25dacd37750a9b88c0c3bfb5e3ba91 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/specs/skill-mastery/spec.md @@ -0,0 +1,50 @@ +# Spec Delta + +## Purpose + +Decides, on the server, which state each skill is in for each student, so mastery is proven by answers over time and never assumed. + +## ADDED Requirements + +### Requirement: Skill states +Every skill SHALL be, for every student, in exactly one state: not started (no answers yet), learning (at least one answer, not mastered) or mastered. + +#### Scenario: First answer +- **WHEN** a student answers the first question of a skill +- **THEN** the skill moves from not started to learning + +### Requirement: Mastery rule +A skill SHALL become mastered when the student answers 3 of its questions correctly in a row, each on the first try and without opening help, and these 3 answers fall on at least 2 different calendar days. + +#### Scenario: Two days +- **WHEN** a student answers 2 correctly on Monday and 1 correctly on Tuesday, all first try and without help +- **THEN** the skill becomes mastered + +#### Scenario: One day +- **WHEN** a student answers 3 correctly in a row on the same day +- **THEN** the skill is still learning + +#### Scenario: A wrong answer +- **WHEN** a student answers 2 correctly, then 1 wrongly, then 1 correctly +- **THEN** the run restarts from the last correct answer + +### Requirement: Help does not break the run +An answer given after the student opened help on that question SHALL be skipped for mastery: it neither counts toward the 3 nor breaks the run. + +#### Scenario: Help between correct answers +- **WHEN** a student answers 2 correctly on Monday, a third with help, and a fourth correctly on Tuesday without help +- **THEN** the skill becomes mastered + +### Requirement: Mastery does not decay +A mastered skill SHALL stay mastered, even after later wrong answers or months without practice. + +#### Scenario: Months later +- **WHEN** a student who mastered a skill in October answers a question on it wrongly in March +- **THEN** the skill is still mastered + +### Requirement: Answers are dated by the server +Every answer SHALL be stored with the server's calendar day in Israel, and mastery SHALL be decided from these days. + +#### Scenario: Device clock changed +- **WHEN** a student changes the device's date before answering +- **THEN** the answer is dated by the server, and mastery uses that date diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/specs/smart-board/spec.md b/openspec/changes/archive/2026-11-08-add-learning-core/specs/smart-board/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..8b6b3eef850db57957b13c4a47629f15c66e6d7e --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/specs/smart-board/spec.md @@ -0,0 +1,70 @@ +# Spec Delta + +## Purpose + +A drawing board for working out and handing in a full solution with pen, shapes, typed math and a calculator, beside the question on a computer and over it on a phone. + +## ADDED Requirements + +### Requirement: Opening the board +The board SHALL open from a button in the header of the exercise screen and of every other screen that offers it. On a computer it SHALL sit beside the exercise and the device SHALL remember whether it is on; on a phone or tablet it SHALL open full screen over the exercise and close back to the question. + +#### Scenario: Phone +- **WHEN** a student presses the board button on a phone +- **THEN** the board covers the screen, and closing it shows the same question + +### Requirement: Tools +The board SHALL offer: move; pen with three ink colors following pen pressure; straight line; circle dragged from its center; angle with an arc, its words and one to three arcs or a right-angle square; typed math with a ninth-grade math keyboard; eraser in three sizes; undo; and clear. + +#### Scenario: Typed math +- **WHEN** a student types a fraction with the math keyboard +- **THEN** it appears on the board as a formatted fraction that can be moved + +### Requirement: Everything is an object +Every stroke, line, circle, angle and formula SHALL be selectable, movable and erasable. Line ends and circle centers SHALL snap to existing ends and centers, and lines joined that way SHALL move together. + +#### Scenario: Closing a triangle +- **WHEN** a student draws three lines whose ends meet +- **THEN** the ends snap together and moving one corner moves both lines + +### Requirement: The question on the board +A copy of the question (text and figures) SHALL be placeable on the board. The eraser SHALL leave it alone; it is removed by selecting and deleting it. + +#### Scenario: Erasing near the question +- **WHEN** the eraser passes over the question's copy +- **THEN** the copy stays + +### Requirement: Endless paper with palm rejection +The paper SHALL grow downward and to the right and scroll with the wheel, two fingers, or dragging empty paper. Once a pen has touched the screen a single finger SHALL be ignored, and while the pen writes every touch and any wide contact SHALL be ignored. + +#### Scenario: Resting palm +- **WHEN** a student writes with a pen while their palm rests on the screen +- **THEN** only the pen draws + +### Requirement: Sketches stay on the device +Each question SHALL keep its own sketch while the page is open, and nothing SHALL be sent anywhere unless the student hands it in. + +#### Scenario: Switching questions +- **WHEN** a student draws on question 1, moves to question 2 and back +- **THEN** question 1's sketch is still there, and nothing was sent + +### Requirement: Handing in a sketch +Where a screen accepts a written answer, the board SHALL turn the sketch into a picture that the student hands in from the board. + +#### Scenario: Hand-in +- **WHEN** a student presses the board's hand-in button on such a screen +- **THEN** a picture of the sketch is handed in + +### Requirement: Calculator +A scientific calculator in the layout of a Casio fx-991ES PLUS, with SHIFT functions, SHALL open on a panel over a corner of the paper from a toolbar button, wherever the board is. + +#### Scenario: Sine +- **WHEN** a student opens the calculator and computes sin 30 in degrees +- **THEN** it shows 0.5 + +### Requirement: Labels and input +Every tool SHALL have a Hebrew label and an icon, and the board SHALL work with touch, pen and mouse. + +#### Scenario: Screen reader +- **WHEN** a screen reader reaches the pen tool +- **THEN** it reads its Hebrew name diff --git a/openspec/changes/archive/2026-11-08-add-learning-core/tasks.md b/openspec/changes/archive/2026-11-08-add-learning-core/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..915943098a4eeb8077f5a124273fd9163f782734 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-learning-core/tasks.md @@ -0,0 +1,51 @@ +# Tasks + +## 1. Bank and rules + +- [x] 1.1 Change the bank check to the single static solved example (`worked_example` = question, steps of `do` and text `why`, answer) and stop checking faded examples (decision 1); verify tests pass for a valid example and fail for a step without `why` or an example without an answer, and the real bank still loads +- [x] 1.2 Change `scripts/draft_examples.py` to draft one solved example per skill in that shape (no faded examples); verify its tests with the fake client for draft, a flagged draft and merge, and that the dry run sends nothing and leaves the bank unchanged +- [x] 1.3 Add `recent_skills(user_id, n)` and `solved_keys(user_id, skill_id)` to both stores; verify unit tests for each, including that other students' answers do not count, and request tests for the Supabase store +- [x] 1.4 Add `learning.next_skill` (decision 2); verify tests for the four scenarios in `learning-path`: continuing, a new student gets the first skill, a just-mastered last answer moves the marker, and everything mastered gives none + +## 2. API + +- [x] 2.1 Reshape `GET /api/skills/{id}` and remove `POST /api/skills/{id}/stage` (decision 2); verify tests that a skill with and without a solved example both open at their question, `solved` and `total` are right, `requires` and `opens` list the neighbours, a skill with no questions has no question, and the permission matrix test is updated and passes +- [x] 2.2 Keep answering, help and stale-question refusal on the reshaped skill; verify the `skill-mastery` and `exercise-screen` scenarios through the API: two days, one day, wrong answer, help between correct answers, mastery not undone months later, a device clock change, no correct flag anywhere in a served question, the next question differs, and a stale key is refused +- [x] 2.3 Reshape `GET /api/path`: the lessons of the student's classes (every lesson for a teacher or developer), each skill with its state, `next`, today's goal and streak; verify tests for a student of two classes, a student whose class has one lesson, the marker rule, and that a manager is refused + +## 3. The smart board + +- [x] 3.1 Copy `math-board.js`, `board-math.js` and `vendor/mathlive/` unchanged, and add `board.css` (the board's block, the sheet, layer and scrim rules, and the variable map from the sky tokens); verify the files are byte-identical to mathly1's and a Playwright test loads the board in light and dark with no console error +- [x] 3.2 Test the board's behaviour in a browser: it opens full screen on a phone and beside the sheet on a 1280px desktop, every tool has its Hebrew label, a pen stroke changes the canvas and undo restores it, the question can be copied onto it and the eraser leaves the copy, a sketch stays when moving between two questions, and nothing is sent to the server; verify the test passes +- [x] 3.3 Test the calculator in a browser: it opens from the toolbar, sin 30 in degrees shows 0.5, and 7 × 6 shows 42; verify the test passes + +## 4. The path screen + +- [x] 4.1 Add the star, ring arcs and spark drawings to `sky.js` and the path styles to `app.css` (decision 3); verify a Playwright test draws rings for lessons of 2, 3 and 6 skills at 360px, with every star inside the screen and none over the hub +- [x] 4.2 Rewrite `path.js` as the trail of hubs with start and end markers, numbered stars, state symbol and word, and the owl on the next star; verify a Playwright test that a student sees only their class's lessons, each state shows its word, a mastered star differs from a learning one, the owl is on the next star, and nothing scrolls sideways at 360px in light and dark +- [x] 4.3 Test the path's access: every star is a link reachable with Tab and opened with Enter, its accessible name has the number, the name and the state, and no animation runs with reduced motion; verify the test passes + +## 5. The exercise screen + +- [x] 5.1 Build `exercise.js`: the sheet over the path with the header, explanation, "question n of N" with dots, the question with its figure, shuffled choices and tap-to-answer (decision 4); verify a Playwright test that opening a skill shows its parts, the same question can be shown in a different order, and the server grades by the bank position +- [x] 5.2 Add the right and wrong answers: the celebration, the count in a row and the skippable countdown; the quiet wrong answer with the mistake's name and tip, a link to the skill to go back to when the bank names one, and a different next question; verify a Playwright test for each, that no choice is marked as correct, and that mastering a skill is announced +- [x] 5.3 Add the "?" help (explanation, solved example if any, and "this answer will not count") and the requires and opens chips; verify a Playwright test that help makes the next right answer not count toward mastery, a chip opens its skill, and a skill without a solved example shows only the explanation +- [x] 5.4 Add resuming and stale answers: reopening shows the question that was on screen, and a refused answer reloads the current question; verify a Playwright test with two tabs, and a skill with no questions says there is no practice yet +- [x] 5.5 Close the sheet back to a refreshed path and honour `#/skill/` links and reloads; wire the header's board button and mount the board for every question (decision 5); verify a Playwright test that closing shows the updated star, a link opens the sheet over the path, and the board opens from the sheet's button with a sketch per question + +## 6. Cleanup and integration + +- [x] 6.1 Delete the worked and faded screens, `skill.js`, the stage logic and their tests (decision 6); verify no file refers to `faded` or `/stage`, the tests still pass, and the old "stage" mockup note in `docs` is not left behind +- [x] 6.2 Walk one skill end to end in a browser: sign in as a student, open it from the path, answer two right on Monday, move the server clock to Tuesday, answer one more, see it mastered on the path with the owl moved on; verify the test passes +- [x] 6.3 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate add-learning-core --strict`; verify both pass + +## 7. Subject choice, sign-in logo and dark sky (align with mathly1) + +- [x] 7.1 Copy mathly1's `logo.svg` and show it on the sign-in page; verify a Playwright test that the sign-in page shows the logo and no content +- [x] 7.2 Make the app always dark with a starry sky (foundation decision 6); verify a Playwright test that a light-mode device still gets the dark background and that the tests for light mode are removed +- [x] 7.3 Add the subject cards (PTH-9) as the student's first screen, with the path at `#/subject/math`, a way back, and direct links to a skill still working; verify a Playwright test for the card, its progress bar, opening the path, going back and a deep link + +## Workflow follow-up + +- Archive this change once it is reviewed, so `skill-mastery`, `exercise-screen`, `learning-path` and `smart-board` move into `openspec/specs/`; then propose `add-rewards` in full (design and tasks). +- Check pen pressure, palm rejection and the full-screen board on a real tablet and phone (a headless browser cannot). diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/.openspec.yaml b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e582ee4a2c22919eed558b194fa58fb923e0f359 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/design.md b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/design.md new file mode 100644 index 0000000000000000000000000000000000000000..ef2ef1d2dc9b7e4a61e257a42bcbf4d907e5a4ec --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/design.md @@ -0,0 +1,96 @@ +# Design + +## Context + +See proposal.md for why. After `add-rewards`, `mathly2/` has what a quiz needs and lacks what makes it timed and graded: + +- **Reusable:** `bank.practice_question` serves a question with no `correct` flag; `bank.grade` grades one choice by its bank position and names the mistake (`name`, `tip`, `back`); `clock.now()` is the one source of time; the exercise sheet (`exercise.js`) already mounts the smart board per question and the board's calculator; `GET /api/path` lists each lesson with its skills. +- **Missing:** any stored attempt, a server deadline, a grade, and a screen for either. Nothing in `mathly2` is timed yet, and stage 5 (`add-test-readiness`) needs the same machinery for exercise tests and the simulation, so the engine is built once here and kept generic. +- **The bank:** 95 of 96 skills have questions (90 have 10, five have 30); the skill `a_30_side` (lesson `l`) has none, so a quiz can never assume a question for every skill. Each lesson has 2–6 skills. Every lesson also carries an authored written `quiz` (minutes, questions), which this change ignores (spec: Written quizzes are not lesson quizzes). + +## Goals / Non-Goals + +**Goals:** +- A quiz per lesson with a server timer, answers saved as they are given, a grade on the 0–100 scale, and a result that never shows right answers. +- One attempt engine (`attempts.py`) that the exercise test and simulation can use without a new table. +- A trail node per lesson and a grades screen. + +**Non-Goals:** +- Exercise tests, the simulation, the test countdown and the readiness meter (stage 5), and assignment grades (stage 6): the grades screen lists only quiz grades now and takes the others as they arrive. +- Teacher views of quiz grades (stage 8). +- Pen or photo answers: a quiz is multiple choice only. + +## Decisions + +### 1. One generic attempts table + +| Table | Columns | Meaning | +|---|---|---| +| `m2_attempts` | `id` uuid, `user_id`, `kind` (`quiz` now; `exercise_test`, `simulation` later), `scope` (the lesson id for a quiz), `started_at`, `due_at`, `submitted_at` null, `timed_out` bool, `grade` int null (0–100), `questions` jsonb `[{skill_id, key}]` in order, `answers` jsonb `{ "": choice }` (a question key already starts with its skill id) | one timed, graded try | + +A row with `submitted_at` null is open. Questions are stored as references into the bank (never the questions themselves), so a bank edit cannot change an old attempt's grade as long as the question keys exist; the grade is stored, not recomputed. `answers` is rewritten with each saved answer. Row security as the other `m2_` tables (server key only). A migration `20261110090000_m2_attempts.sql` adds the table; nothing else changes. *Alternative:* a `m2_quiz_attempts` table plus an `m2_answers`-style row per answer. Rejected: three more tables for data that is always read and written as one attempt, and stage 5 would need copies. + +### 2. The server finishes an attempt when time is up, on the next read + +There is no background job. Every read or write of an attempt first runs `attempts.settle(row, now)`: if `now >= due_at` and the attempt is open, it is graded from the answers saved so far, `timed_out` is set, and it is stored. So a student who closes the app and returns 20 minutes later reads a submitted attempt with the answers they had given (spec: When time ends), and the grades screen settles any overdue attempt the same way before it lists. An answer that arrives after `due_at` is refused with 409 and the attempt is settled. A manual submit before the deadline grades at once. Both paths use one function, so they cannot disagree. *Alternative:* a scheduler that submits at the deadline. Rejected: a thing to run and keep alive, and reads must be right even if it were late. + +```mermaid +stateDiagram-v2 + [*] --> Open: start (questions drawn, due_at = now + 15 min) + Open --> Open: answer saved (before due_at) + Open --> Submitted: student submits + Open --> Submitted: next read after due_at (timed_out = true) + Submitted --> [*] +``` + +### 3. Starting resumes an open attempt, otherwise draws a new quiz + +`POST /api/lessons/{id}/quiz/start` returns the student's open attempt for that lesson if there is one that has not timed out; otherwise it draws and stores a new one. So a refresh, a second tab or a lost connection continues the same attempt instead of burning a try. The timer is the stored `due_at`: the response carries `due_at` and the server's `now`, and the screen counts down from their difference, so a wrong device clock changes nothing. + +### 4. How a quiz is drawn + +`quiz.draw(bank, lesson_id, used, rng)` where `used` is how often the student had each question in earlier attempts of this lesson: + +1. Skills without questions are left out (today only `a_30_side`; the spec's "one per skill" then applies to the skills that have questions). +2. Each skill gets `10 // k` questions and the remaining `10 % k` go to distinct skills chosen at random, so quotas differ by at most one (4 skills: 3,3,2,2; 6 skills: 2,2,2,2,1,1). +3. Within a skill, questions are taken least-used first, ties in random order; so a retake takes new questions while the skill has enough unused ones (10 per skill, quota at most 5: the first two attempts are always completely new for a quota up to 5), and repeats the least-used after that. +4. The final order of the 10 is shuffled; the order of choices is shuffled on the screen by the existing `shuffled` helper, with bank positions kept as `index`. + +`rng` is a parameter so tests are exact. *Alternative:* pick 10 at random from the whole pool. Rejected: it can leave a skill out entirely, which breaks "at least one per skill". + +### 5. Grading and what is revealed + +`attempts.grade(bank, questions, answers)` counts right answers with `bank.grade` (a missing answer is wrong) and returns `(100·right/n)` rounded half up (`(200·right + n) // (2n)`: 7/10 → 70, 8/12 → 67). The result adds, for each wrong or missing question: the skill (id, name, a link), the question text, the choice the student picked, and the mistake's `name` and `tip` (none for a missing answer). It never carries a `correct` flag, the right choice's text or its position, and `GET /api/attempts/{id}` of an **open** attempt serves questions through `practice_question` only. A submitted attempt can be read again later; each read gives the same result. + +### 6. Routes + +| Route | Does | +|---|---| +| `GET /api/lessons/{id}/quiz` | the quiz node's facts: `best` grade or null, `attempts` count, whether an attempt is `open` | +| `POST /api/lessons/{id}/quiz/start` | decision 3; refused (404) for a lesson the student does not have | +| `GET /api/attempts/{id}` | the open attempt (questions, saved answers, `due_at`, `now`) or the result | +| `PUT /api/attempts/{id}/answers` | `{skill_id, key, choice}` saved; 409 when the attempt is over | +| `POST /api/attempts/{id}/submit` | grade now (idempotent: a submitted attempt returns its result) | +| `GET /api/grades` | every lesson with a quiz grade: lesson, best grade, attempts, last taken | + +`GET /api/path` adds to each lesson `quiz: {best, open}`. Only the attempt's owner can read it (404 for anyone else). All use the `path.use` permission, as the rest of the student's routes, and the permission matrix test is extended. + +### 7. The quiz screen: a sheet like the exercise screen, with a timer and no feedback + +`#/quiz/` draws the path under a sheet (the same `.mx-layer` structure, so the board mounts as in the exercise screen, with the calculator, one sketch per question). The sheet shows "שאלה n מתוך 10" with dots for answered questions, the countdown (text, updated each second, with `aria-live` only at 5, 1 minute and the end, so it does not chatter), the question with its shuffled choices, previous/next, and "הגשה". A choice is saved on tap (`PUT answers`) and can be changed until submitting; nothing says whether it is right. "הגשה" asks once ("יש N שאלות בלי תשובה") then submits. At zero the screen asks the server for the attempt, which settles it, and shows the result. Skill names are not on the question; the lesson's name is. The result shows the grade as a big number, "הציון של השיעור: best", the skills that lost points each linking to `#/skill/`, and the missed questions with the mistake's name and tip, and a "בוחן חוזר" button. Closing the sheet leaves an open attempt open, and the node says "בוחן פתוח, נשארו mm:ss". + +### 8. The trail node and the grades screen + +After a lesson's ring the trail gets a node (an ``) in the style of the stars: a dashed hub with "בוחן" and its state in words: "○ עוד לא נעשה", "✓ הציון: 85" or "◐ בוחן פתוח". It is always open. The student's tabs become path, grades (`#/grades`) and collection. The grades screen lists lessons with a quiz grade (name, best grade as a number and a bar, attempts, date), best first within the order of the path, and says "עוד אין ציונים" when empty. Later stages add their rows to the same list. + +## Risks / Trade-offs + +- [A student gets the same questions on the 3rd retake] -> Least-used-first makes repeats the exception; the spec only promises new questions "as long as the lesson has enough unused ones", and a test pins both sides of that. +- [Answers saved one by one make many small requests] -> At most 10 writes per quiz, each a single-row update; acceptable. +- [Clock tricks on the device] -> The deadline is the server's `due_at`; the countdown is cosmetic and the server refuses late answers. +- [Open attempts pile up if students never come back] -> They are settled on the next read, so they become submitted attempts with whatever was answered; a quiz abandoned empty becomes a 0 attempt but never lowers the best grade. +- [A bank edit removes a question an old attempt used] -> The stored grade stays; re-reading a result skips a question the bank no longer has instead of failing. + +## Migration Plan + +Run `20261110090000_m2_attempts.sql` after the five earlier migrations. It only adds one table, so it is safe to run before the code, and rollback is `drop table m2_attempts` (in the file header). Existing students have no attempts, so every quiz node starts at "עוד לא נעשה". diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/proposal.md b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..2997a25bfa7a316f2086f3be8ce1900a0a5d5ca1 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/proposal.md @@ -0,0 +1,28 @@ +# Proposal + +## Why + +Each lesson needs a grade that reflects what the student knows now, and a way to improve it (PRD 4.9). Quizzes also introduce the timed, server-graded attempt and the 0–100 scale that the test stages reuse (PRD GRD-1, GRD-2). + +## What Changes + +- A quiz per lesson: the "boss level" node on the trail after the lesson's ring. 10 multiple-choice questions drawn from the lesson's skills, 15 minutes, server timer, feedback at the end. +- Retakes prefer new questions; the best grade is the lesson's grade. +- After a quiz: the grade, the skills where points were lost (linked to their stars), and the mistakes' names and tips, never the correct answers. +- One grade scale (0–100) and one rule for timers that end; a grades screen for the student. +- The four written quizzes authored in the bank are left for assignments (stage 6). + +Screens: `docs/mockups/mathly2-screens.html` (student tab: quiz node and grades). + +## Capabilities + +### New Capabilities +- `lesson-quizzes`: the per-lesson quiz, its format, retakes and result (PRD QZ-1 – QZ-6). +- `grades`: the grade scale, timed attempts, and the student's grades screen (PRD GRD-1, GRD-2, STU-3). + +### Modified Capabilities + +## Impact + +- Builds on `learning-path` (the quiz node) and the bank's questions. New `m2_` tables for attempts and grades. +- The timed-attempt engine is reused by `add-test-readiness`. diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/grades/spec.md b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/grades/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..69690b58d4143176db789a99b6c446a3618a51da --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/grades/spec.md @@ -0,0 +1,32 @@ +# Spec Delta + +## Purpose + +One grade scale and one rule for timed attempts across quizzes, exercise tests, the simulation and assignments, and the screen where a student sees all their grades. + +## ADDED Requirements + +### Requirement: One grade scale +Every grade SHALL be a whole number from 0 to 100. In a multiple-choice quiz or test every question SHALL be worth the same, and the grade SHALL be the share of right answers, rounded. + +#### Scenario: Seven of ten +- **WHEN** a student answers 7 of 10 questions correctly +- **THEN** the grade is 70 + +#### Scenario: Eight of twelve +- **WHEN** a student answers 8 of 12 questions correctly +- **THEN** the grade is 67 + +### Requirement: When time ends +When the timer of a timed attempt ends, the server SHALL submit it as it stands, and unanswered questions SHALL count as wrong. Closing or refreshing the app MUST NOT stop or reset the timer. + +#### Scenario: Closed the app +- **WHEN** a student closes the app 5 minutes into a 15-minute quiz and opens it 20 minutes later +- **THEN** the quiz has been submitted with the answers given + +### Requirement: Grades screen +The student SHALL have a grades screen listing every grade they have: each lesson's quiz (best grade), and every exercise test, simulation and assignment grade as those exist. + +#### Scenario: After a quiz +- **WHEN** a student finishes a lesson's quiz +- **THEN** the grades screen shows that lesson's best quiz grade diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/lesson-quizzes/spec.md b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/lesson-quizzes/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..2342ec5aab864fb49b4f5787a1831e8d3f402679 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/specs/lesson-quizzes/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## Purpose + +A retakeable quiz for every lesson that gives the lesson its grade and points the student back to the skills that lost points. + +## ADDED Requirements + +### Requirement: A quiz per lesson +Every lesson SHALL have one quiz, shown as a node on the trail after the lesson's ring and always open. The student SHALL be able to retake it at any time; the best grade SHALL be the lesson's grade. + +#### Scenario: Better retake +- **WHEN** a student scores 60 and then 85 on a lesson's quiz +- **THEN** the lesson's grade is 85 + +#### Scenario: Worse retake +- **WHEN** a student scores 85 and then 70 +- **THEN** the lesson's grade stays 85 + +### Requirement: Quiz format +A quiz SHALL be 10 multiple-choice questions drawn from the bank questions of the lesson's skills, at least one per skill and the rest spread evenly, in 15 minutes. Skill names MUST NOT be shown, and there SHALL be no feedback until the end. The board and calculator SHALL be available. + +#### Scenario: Lesson with four skills +- **WHEN** a quiz is drawn for a lesson with four skills +- **THEN** it has 10 questions and every skill has at least two + +### Requirement: Retakes draw new questions +Each retake SHALL prefer questions the student has not had in earlier attempts at this quiz, the least-used first. + +#### Scenario: Second attempt +- **WHEN** a student retakes a quiz +- **THEN** none of its questions were in the first attempt, as long as the lesson has enough unused questions + +### Requirement: After a quiz +After a quiz the student SHALL see the grade, the skills where points were lost (each linked to its star) and, for each missed question, the name and tip of the mistake. The correct answers MUST NOT be shown. + +#### Scenario: Two misses +- **WHEN** a student misses two questions of one skill +- **THEN** the result lists that skill with a link and shows the two mistakes' names and tips, without the right answers + +### Requirement: Written quizzes are not lesson quizzes +The written quizzes authored in the bank SHALL NOT be used as lesson quizzes; they are offered to teachers as assignments. + +#### Scenario: Lesson with an authored written quiz +- **WHEN** a student opens the quiz of a lesson that has an authored written quiz in the bank +- **THEN** the quiz is the 10-question multiple-choice quiz diff --git a/openspec/changes/archive/2026-11-08-add-lesson-quizzes/tasks.md b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..0b8299f2c19bf74bdbff29c4f78506a2fe0ab1ba --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-lesson-quizzes/tasks.md @@ -0,0 +1,32 @@ +# Tasks + +## 1. The attempt engine + +- [x] 1.1 Add the migration `20261110090000_m2_attempts.sql` for `m2_attempts` (decision 1) and the store methods to create, read, save answers of and settle an attempt, list a student's attempts, and read open attempts, in both stores; verify unit tests for each, that one student's attempts are never read for another, request tests for the Supabase store, and migration tests on PostgreSQL (the table's defaults, the browser roles are refused) +- [x] 1.2 Add `attempts.py` with `grade` and `settle` (decisions 2 and 5) and the result builder; verify unit tests: 7 of 10 gives 70, 8 of 12 gives 67, an unanswered question counts as wrong, a settled attempt is graded from the answers saved, settling twice changes nothing, an attempt before `due_at` is not settled, and the result lists the lost skills and the mistake name and tip but never a `correct` flag, a right choice or its position (checked over the whole JSON) +- [x] 1.3 Add `quiz.py` with `draw` (decision 4); verify unit tests with a fixed `rng`: a lesson of 4 skills gives 10 questions with every skill at least 2, 6 skills give quotas 2,2,2,2,1,1, 2 skills give 5 and 5, a skill without questions is left out and the others still give 10, a retake takes only unused questions while enough remain (two attempts in a row never repeat) and then the least-used, and the draw is the same for the same `rng` + +## 2. The API + +- [x] 2.1 Add `GET /api/lessons/{id}/quiz` and `POST /api/lessons/{id}/quiz/start` (decisions 3 and 6); verify API tests: a new student starts a quiz with 10 questions and `due_at` 15 minutes after the server's now, starting again resumes the same open attempt, a lesson the student's classes do not have gives 404, a manager is refused, and no served question carries `correct`, `mistake` or a skill name +- [x] 2.2 Add `GET /api/attempts/{id}`, `PUT /api/attempts/{id}/answers` and `POST /api/attempts/{id}/submit`; verify API tests: an answer is saved and can be changed, submitting grades it, submitting twice returns the same result, an answer after `due_at` is refused with 409 and settles the attempt, a read 20 minutes after a 15-minute start returns the submitted attempt with the answers given and `timed_out`, a device clock change changes nothing, another student gets 404, and an unknown question or choice gives 422 +- [x] 2.3 Add `GET /api/grades` and the `quiz` facts on each lesson in `GET /api/path`; verify API tests: 60 then 85 gives 85, 85 then 70 stays 85, a lesson never attempted has no grade, an overdue open attempt is settled by the grades read, and the permission matrix test lists every new route and passes +- [x] 2.4 Check the written quizzes are not used: a lesson whose unit has an authored `quiz` in the bank still gets the 10-question multiple-choice quiz; verify the API test with that lesson, and that the draw never reads the unit's `quiz` + +## 3. The screens + +- [x] 3.1 Add the quiz node to the trail after each lesson's ring, its three states in words, and the tab bar with "ציונים"; verify a Playwright test that every lesson shows a node with "○ עוד לא נעשה", a best grade shows "✓ הציון: 85", an open attempt shows "◐ בוחן פתוח", the node is a link reachable with Tab, and nothing scrolls sideways at 360px +- [x] 3.2 Build `quiz.js`: the sheet at `#/quiz/` with the countdown from the server's `due_at`, "שאלה n מתוך 10" with dots, shuffled choices saved on tap, previous and next, the board and calculator per question, and the submit with its warning about unanswered questions; verify a Playwright test that the quiz opens with 10 questions and no skill names, a choice is saved and survives a reload on the same attempt and the same timer, no right or wrong is shown, the board opens with its calculator, and the submit shows the warning +- [x] 3.3 Add the result: the grade, the lesson's best, the lost skills as links to their stars, the missed questions with the mistake's name and tip, and "בוחן חוזר"; verify a Playwright test that a quiz with two misses in one skill lists that skill with its link and two mistakes, no right answer appears anywhere in the page, a timed-out attempt shows the result after the server settles it, and a retake draws new questions +- [x] 3.4 Add the grades screen at `#/grades`; verify a Playwright test that it says "עוד אין ציונים" when empty, shows each lesson's best grade, attempts and date after quizzes, shows the better of two attempts, and fits 360px + +## 4. Wrap-up + +- [x] 4.1 Walk a quiz end to end in a browser: sign in as a student, open a lesson's quiz from the trail, answer all 10, submit, see the grade and the lost skills, open one, close back to the path where the node shows the grade, and find it on the grades screen; verify the test passes +- [x] 4.2 Update `docs/mockups/mathly2-screens.html` only where the quiz node or the grades tab no longer match what was built; verify by opening it beside a screenshot of each +- [x] 4.3 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate add-lesson-quizzes --strict`; verify both pass + +## Workflow follow-up + +- Apply the new migration after the five earlier ones (on a test project first). +- Archive this change once it is reviewed, so `lesson-quizzes` and `grades` move into `openspec/specs/`; then propose `add-test-readiness` in full (design and tasks), which reuses `attempts.py` for exercise tests and the simulation. diff --git a/openspec/changes/archive/2026-11-08-add-rewards/.openspec.yaml b/openspec/changes/archive/2026-11-08-add-rewards/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e582ee4a2c22919eed558b194fa58fb923e0f359 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-rewards/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/archive/2026-11-08-add-rewards/design.md b/openspec/changes/archive/2026-11-08-add-rewards/design.md new file mode 100644 index 0000000000000000000000000000000000000000..72b4db2513d1304dbe1f8f191d4c1cb7e3d79780 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-rewards/design.md @@ -0,0 +1,86 @@ +# Design + +## Context + +See proposal.md for why. After `add-learning-core`, `mathly2/` already has more of this stage than the proposal assumes: + +- **Daily goal and streak are built and tested.** `learning.today_progress` and `learning.streak` count the student's correct answers per Israel calendar day (`store.daily_correct`, helped answers included), `GET /api/path` returns `today` and `streak`, and `ui.goalBar` draws them at the top of the path. This stage adds no code for them, only the scenario tests of `rewards` that are missing (see tasks 1.1). +- **A plain collection exists** (`GET /api/collection`, `collection.js`): two lists, mastered skills and completed lessons, with no drawings. +- **Fading and comets do not exist.** The answers table already holds every answer with its server-set day, so fading needs no new data; comets need a small amount of per-student state. +- mathly1 has the rules and drawings in `static/math-sky.js`: `COMETS` (12, with symbol, name, fact), `cometDue`, `catchComet`, `SHAPES`/`shape()` (a constellation per unit) and `comet()`/`cometCard()` drawings. mathly1 keeps this state in the browser (`P.comets`, `P.cometDay`); mathly2 must keep it on the server like everything else (PRD MST-5). + +## Goals / Non-Goals + +**Goals:** +- Faded stars on the path and in the collection, decided by the server from answer dates. +- The collection as mathly1 draws it: a star per mastered skill, a constellation per completed lesson, the twelve comets. +- Comets that cross after a right answer, are caught by tapping, and are remembered per student; the server decides when one is due and which one is caught. + +**Non-Goals:** +- Sounds, vibration patterns and the celebration overlays of mathly1 beyond what the exercise screen already does. +- A teacher's or the readiness meter's view of fading. Fading never leaves the student's own screens (spec: Fading stars). +- Any change to mastery, grades or the streak. + +## Decisions + +### 1. The server decides fading and sends a flag + +`GET /api/path` and `GET /api/collection` add `faded: true` to a mastered skill whose newest answer is 14 or more school days old; every other skill has `faded: false`. A new store method `last_answered(user_id)` returns `{skill_id: date}` from the answers table (one query, newest per skill), in both stores. The state itself stays `mastered`, so every consumer of state (readiness, heat map, exercise tests) is unchanged and cannot be affected by fading. The client shows a dimmed star and the word "דועך" under it, plus the symbol "◌" so it is not by color alone. An answer on the skill, right or wrong, writes a row dated today, so the next read relights it with no extra code. *Alternative:* store a `faded` column and update it with a job. Rejected: derived data that can go stale, and a job to run. + +### 2. Comet state is two small `m2_` tables + +| Table | Columns | Meaning | +|---|---|---| +| `m2_comets` | `user_id`, `comet_id`, `caught_at`; primary key (`user_id`, `comet_id`) | the comets a student caught | +| `m2_reward_state` | `user_id` primary key, `last_comet_day` date, `last_catch_day` date | the day a comet last crossed, and the day one was last caught | + +The twelve comets (id, symbol, name, fact) live in a Python module `comets.py` and are served by `GET /api/comets` together with which ones the student has; the client does not carry its own copy. Row security follows the other `m2_` tables (the server's key only). A new migration `20261109090000_m2_rewards.sql` creates both and is the only database change. + +### 3. When a comet is due: the answer response says so + +The answer route (`POST /api/skills/{id}/answer`) already knows the day's count. After a **right** answer it calls `comets.due(state, caught, today, goal_just_reached, rng)`: + +```mermaid +flowchart TD + A[Right answer] --> B{All 12 caught?} + B -- yes --> N[No comet] + B -- no --> C{Comet already crossed today?} + C -- yes --> N + C -- no --> D{Ever offered a comet?} + D -- never --> E{This answer reached the goal of 5?} + E -- yes --> Y[Comet: set last_comet_day = today] + E -- no --> N + D -- before --> F{random < 12%?} + F -- yes --> Y + F -- no --> N +``` + +"Ever offered" is `last_comet_day is not null`. So the first comet is certain on the first goal-reaching answer and never before; after any offer, 12% a right answer. The response gets `comet: true` only when due; the day is stored at that moment, so a reload cannot give a second comet. `rng` is a parameter so tests pass a fixed value. *Alternative:* roll the chance in the browser, as mathly1 does. Rejected: the device would decide, which the PRD forbids for anything that is stored (a student could farm comets with dev tools). + +### 4. Catching: one catch per offered comet, picked by the server + +`POST /api/comets/catch` accepts only when `last_comet_day` is today and `last_catch_day` is not today; it picks a random comet the student does not have, writes the row and `last_catch_day`, and returns the comet (symbol, name, fact). Otherwise it answers 409 ("אין שביט לתפוס"). Tapping a comet twice, or a second tab, therefore catches at most one. When all twelve are held, none is ever offered (decision 3), so the route cannot be reached in that state. + +### 5. The comet on screen is drawn by the exercise screen + +After a right answer with `comet: true`, `exercise.js` draws a comet that crosses the sheet in about 4 seconds (CSS animation on `transform`, ported from `Sky.comet`). Under reduced motion it draws no moving comet: a still "☄ שביט!" button appears once, below the feedback, and disappears when the next question loads. A tap calls the catch route and shows the comet card (symbol, name, fact) in a small dialog the student closes with a button or Escape. The comet never blocks answering: it is `position:absolute` over the sheet with `pointer-events` only on the comet itself. + +### 6. The collection draws constellations + +`collection.js` is rewritten as three parts: the lessons completed as constellations, the mastered skills as stars, and the twelve comets. A constellation is an inline SVG drawn by `sky.js` from a port of mathly1's `SHAPES` and `shape()`: the lesson's id picks a shape (a fallback zig-zag when none is defined), and the lesson's skills sit on it in order, as small gold stars with the skill's number. A mastered skill in the stars list is a link to it, faded ones dimmed with "דועך". Each comet is a button: caught ones show symbol and name and open a card with the fact; missing ones show "?" with "עוד לא נתפס" and open nothing but a one-line hint. `GET /api/collection` adds `faded` per skill and the comets list moves to `GET /api/comets`. + +### 7. No other state changes + +Nothing is stored for fading, and no existing table changes. The path's daily goal and streak stay as they are. + +## Risks / Trade-offs + +- [The drawing of 20+ shapes is a lot of ported code] -> Port `SHAPES`, `shape()` and `along`/`onCorners` as they are, and test two lessons of different sizes plus the fallback in a browser; only the labels logic of mathly1 is left behind (the collection needs numbers, not names beside the stars). +- [A 12% random chance is hard to test] -> `rng` is injected; unit tests cover 0.11 and 0.13, the browser test uses a server started with a fixed value. +- [Reduced motion changes the flow, and a still button can be missed] -> It stays under the feedback until the next question; the test checks it appears once and that the comet is not animated. +- [The first comet on the first goal day needs five right answers in one session] -> That is the PRD's rule ("the reward arrives early"); the test drives five answers through the API. +- [Fading dims a star the student may never need again] -> Only a cue, and the word says "דועך", not "forgotten"; the spec forbids it from reaching any grade. + +## Migration Plan + +Run `20261109090000_m2_rewards.sql` after the four earlier migrations. It only creates two new `m2_` tables, so nothing breaks if it runs before the code, and rolling back is `drop table m2_comets, m2_reward_state` (listed in the file header). Existing students simply start with no comets and no `last_comet_day`, so their first goal-reaching answer after the deploy brings the first comet. diff --git a/openspec/changes/archive/2026-11-08-add-rewards/proposal.md b/openspec/changes/archive/2026-11-08-add-rewards/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..a7c578bf03fb46bd2ccb6443ebf4bdf8ad507280 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-rewards/proposal.md @@ -0,0 +1,27 @@ +# Proposal + +## Why + +Practice works after stage 2, but nothing pulls a student back tomorrow. mathly1's game layer does: a daily goal and streak, stars that fade when neglected, a collection of stars and constellations, and rare comets to catch (PRD MST-6 – MST-8, CMT-1 – CMT-4). + +## What Changes + +- A daily goal of 5 correct answers and a streak, shown at the top of the path. +- Fading stars: a mastered skill not practiced for 14 days dims and says "דועך"; one answer relights it. Only a cue: the skill stays mastered. +- A collection screen: mastered skills as stars, completed lessons as constellations, caught comets with their facts. +- Twelve comets that may cross the exercise screen after a right answer; the first comes with the first daily goal reached. + +Screens: `docs/mockups/mathly2-screens.html` (student tab: path top, collection). + +## Capabilities + +### New Capabilities +- `rewards`: the daily goal and streak, fading stars, the collection and comets. + +### Modified Capabilities + +## Impact + +- Builds on `skill-mastery`, `learning-path` and `exercise-screen` (stage 2). Reuses today's daily-goal and streak rules. +- Stores caught comets per student (an `m2_` table). +- Ports the constellation and comet drawings from mathly1's `static/math-sky.js`. diff --git a/openspec/changes/archive/2026-11-08-add-rewards/specs/rewards/spec.md b/openspec/changes/archive/2026-11-08-add-rewards/specs/rewards/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..7dd681512e293d1f1d652f661e7e9465823f9f5d --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-rewards/specs/rewards/spec.md @@ -0,0 +1,75 @@ +# Spec Delta + +## Purpose + +Rewards that bring a student back to practice: a daily goal and streak, stars that fade when neglected, a collection of what they achieved, and rare comets to catch. None of them changes a skill's state or a grade. + +## ADDED Requirements + +### Requirement: Daily goal +A day with 5 correct answers SHALL be a streak day. The path SHALL show today's count toward 5. Answers given after opening help SHALL count toward the goal. + +#### Scenario: Goal reached +- **WHEN** a student answers a fifth question correctly today +- **THEN** today's goal shows as reached + +### Requirement: Streak +The path SHALL show the number of streak days in a row. Until today's 5 are reached, the streak SHALL be counted up to yesterday and shown as still alive. + +#### Scenario: Morning +- **WHEN** a student with a 4-day streak opens the app in the morning with no answers yet today +- **THEN** the streak still shows 4 + +#### Scenario: Missed day +- **WHEN** a student had no streak day yesterday +- **THEN** the streak starts again from today + +### Requirement: Fading stars +A mastered skill the student has not answered for 14 days SHALL show a faded star that says "דועך". One answer on that skill SHALL relight it. Fading MUST NOT change the skill's state, the readiness meter, the heat map or the exercise tests. + +#### Scenario: Two weeks +- **WHEN** a student has not answered a mastered skill for 15 days +- **THEN** its star is dimmed with "דועך", and the skill still counts as mastered + +#### Scenario: Relighting +- **WHEN** the student answers one question of that skill, right or wrong +- **THEN** the star is bright again + +### Requirement: Collection +A collection screen SHALL show each mastered skill as a star and each completed lesson (all its skills mastered) as a constellation drawn from its stars. + +#### Scenario: Completed lesson +- **WHEN** a student masters the last skill of a lesson +- **THEN** that lesson's constellation appears in the collection + +### Requirement: Comets cross +After a right answer on the exercise screen a comet MAY cross the screen for a few seconds, at most once a day. The first comet SHALL come the first time the student reaches the daily goal; afterwards each right answer has a chance of about 12% while comets are left to catch. + +#### Scenario: First daily goal +- **WHEN** a student reaches the daily goal for the first time ever +- **THEN** a comet crosses the screen + +#### Scenario: Once a day +- **WHEN** a student already saw a comet today +- **THEN** no other comet comes today + +### Requirement: Catching comets +Tapping a crossing comet SHALL catch it: a comet the student does not have yet, at random, shown with its name and fact. There SHALL be twelve: π, Fibonacci, the golden ratio, infinity, e, √2, zero, Pythagoras, primes, Pascal's triangle, Euler's formula and the Möbius strip. Comets stop when all are caught. + +#### Scenario: Catch +- **WHEN** a student taps a crossing comet +- **THEN** a comet they did not have is added to their collection with its fact + +### Requirement: Comets in the collection +The collection SHALL show every caught comet with its symbol, name and fact, and every missing one as "?" with "עוד לא נתפס". + +#### Scenario: Three caught +- **WHEN** a student caught three comets +- **THEN** the collection shows three comets and nine "?" + +### Requirement: Comets with reduced motion +With reduced motion a comet SHALL NOT cross the screen; the student SHALL be offered it once as a tappable item instead. + +#### Scenario: Reduced motion +- **WHEN** a comet is due and the device asks for reduced motion +- **THEN** a still comet button appears once instead of a moving comet diff --git a/openspec/changes/archive/2026-11-08-add-rewards/tasks.md b/openspec/changes/archive/2026-11-08-add-rewards/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..46e757f7aa3bed9b779083fb0cb0727b61c140e6 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-rewards/tasks.md @@ -0,0 +1,37 @@ +# Tasks + +## 1. Daily goal and streak (already built, now covered by the spec's scenarios) + +- [x] 1.1 Add the missing tests for the `rewards` scenarios on the existing rules and path: a fifth right answer shows the goal reached (also when one of the five came after opening help), a 4-day streak still shows 4 in the morning, a missed day restarts the streak at today, and the goal and streak are on the path screen in a browser; verify the tests pass without changing `learning.py` + +## 2. Fading stars + +- [x] 2.1 Add `last_answered(user_id)` (newest answer day per skill) to both stores; verify unit tests for each, that other students' answers do not count, and request tests for the Supabase store +- [x] 2.2 Add `faded` to `GET /api/path` and `GET /api/collection` (decision 1): true only for a mastered skill whose newest answer is 14 or more school days old; verify API tests for 13 days (not faded), 14 and 15 days (faded, still `mastered`), an answer on it relights it (right or wrong), a skill not mastered is never faded, and that readiness inputs (`state`, mastery counts, the lesson's `mastered` and `completed`) are the same with and without fading +- [x] 2.3 Show a faded star on the path: dimmed, "◌ דועך" under it and in its accessible name; verify a Playwright test that a faded star differs from a bright mastered one, says "דועך" in text and name, still counts in the hub's "נשלטו" figure, and relights after one answer + +## 3. Comets: server + +- [x] 3.1 Add `comets.py` with the twelve comets (id, symbol, name, fact, ported from mathly1) and `due(...)` (decision 3), plus the migration `20261109090000_m2_rewards.sql` for `m2_comets` and `m2_reward_state`, and the store methods to read and write them in both stores; verify unit tests of `due` with a fixed `rng` for every branch (all caught, already today, first comet only on the goal-reaching answer, 11% and 13% afterwards), migration tests on PostgreSQL, and that the twelve ids are unique +- [x] 3.2 Return `comet: true` from the answer route when due and store the day at that moment; verify API tests: five right answers give a comet on the fifth and not before, a second right answer the same day gives none, a wrong answer never does, a reload cannot give a second one, and an answer after all twelve are caught gives none +- [x] 3.3 Add `POST /api/comets/catch` and `GET /api/comets` (decisions 2 and 4); verify API tests: a catch adds a comet the student did not have, two catches in a row give one comet and a 409, a catch with no comet offered today is refused with 409, the twelve comets are all reachable over repeated days, and one student's comets are not another's; the permission matrix test is updated and passes + +## 4. Comets: screens + +- [x] 4.1 Draw the crossing comet and the catch card on the exercise screen (decision 5), with a still "☄ שביט!" button under reduced motion; verify a Playwright test that after the fifth right answer a comet crosses, a tap catches it and shows name and fact, answering stays possible while it crosses, no second comet comes the same day, and under reduced motion no animation runs and the still button appears once +- [x] 4.2 Add the reward drawings to `sky.js`: the comet, the comet card, and the constellation (port of `SHAPES`, `shape`, `along`, `onCorners`, with the fallback shape); verify a Playwright test that constellations of 2, 4 and 6 stars and the fallback fit a 360px screen with every star inside the picture + +## 5. The collection + +- [x] 5.1 Rewrite `collection.js` (decision 6): completed lessons as constellations, mastered skills as stars linking to them (faded ones dimmed with "דועך"), and the twelve comets, caught ones with symbol and name, missing ones as "?" with "עוד לא נתפס"; verify a Playwright test that mastering a lesson's last skill adds its constellation, three caught comets show three comets and nine "?", a caught comet opens its fact, and nothing scrolls sideways at 360px +- [x] 5.2 Update `docs/mockups/mathly2-screens.html` only if the collection tab no longer matches what was built; verify by opening it beside a screenshot of the collection + +## 6. Wrap-up + +- [x] 6.1 Walk the whole reward loop in a browser: a new student answers five right on the path, sees the goal reached, a comet crosses, catches it, finds it in the collection, and finds the lesson's constellation after mastering its last skill; verify the test passes +- [x] 6.2 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate add-rewards --strict`; verify both pass + +## Workflow follow-up + +- Apply the new migration after the four earlier ones (on a test project first). +- Archive this change once it is reviewed, so `rewards` moves into `openspec/specs/`; then propose `add-lesson-quizzes` in full (design and tasks). diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/.openspec.yaml b/openspec/changes/archive/2026-11-08-add-test-readiness/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e582ee4a2c22919eed558b194fa58fb923e0f359 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/design.md b/openspec/changes/archive/2026-11-08-add-test-readiness/design.md new file mode 100644 index 0000000000000000000000000000000000000000..ab3fb2e0c3ca7037c91ea6ba7146607b9881e6e8 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/design.md @@ -0,0 +1,104 @@ +# Design + +## Context + +See proposal.md for why. What `mathly2/` gives this stage after `add-lesson-quizzes`: + +- **The attempt engine** (`attempts.py`, table `m2_attempts`): a timed try with a server deadline, saved answers, settle-on-read, the 0–100 grade and a result that never reveals right answers. `kind` already allows `exercise_test` and `simulation`, and `scope` is free text. So exercise tests and the simulation need **no change to attempts**, only a draw and their own routes and screens. +- **The quiz sheet** (`quiz.js`): countdown from the server's `due_at`, question dots, saved choices, board and calculator, submit with a warning, the result. It is written for a lesson's quiz; this stage generalises its titles and routes so the same sheet runs all three kinds. +- **Skill states** (`learning.skill_state`, `store.progress_of`), classes with their lessons and teacher (`m2_classes`), the teacher's home (`teacher.js`, `GET /api/teaching`), and the grades screen (quizzes only so far). +- **Student screens:** the subject card opens the path; the tabs (path, grades, collection) sit at the top of the page. The user decided (2026-11-08) that the card opens the subject's **home**, as in mathly1, with the tab bar at the bottom (the `learning-path` delta in this change). + +## Goals / Non-Goals + +**Goals:** +- A teacher sets a real test; every student of the class gets a countdown, two exercise tests and a simulation from it, without anything being created per student in advance. +- The readiness number and today's task are computed by pure functions, tested on their own, and served by the server. +- One quiz sheet for quizzes, exercise tests and the simulation. + +**Non-Goals:** +- A teacher sending an exercise test as an assignment (EXT-2): it needs assignments (stage 6). +- The rest of the home: assignments, AI requests, photo help (stages 6 and 7). Home is built so they can be added as cards. +- Notifications about the test (stage 7, push). +- Teacher views beyond the tests tab (heat map, coverage: stage 8). + +## Decisions + +### 1. One new table; everything else is derived + +| Table | Columns | +|---|---| +| `m2_tests` | `id` bigint, `class_id` → `m2_classes`, `date` (the test day, Israel calendar), `lessons` text[], `note` text, `questions` int default 12 (1–40), `minutes` int default 45 (5–180), `created_by`, `created_at`, `removed_at` null | + +The two exercise tests and the simulation are not rows: they exist because the test exists. Their attempts go into `m2_attempts` with `kind = exercise_test` and `scope = ":1"` or `":2"`, and `kind = simulation` with `scope = ""`. So "the app creates 2 exercise tests for every student" (EXT-1) holds for students added later too, and moving the date moves everyone's countdown with no update (spec: Moving the date). Removing a test sets `removed_at` (soft delete), so the grades already earned keep their test's name on the grades screen. The migration is `20261111090000_m2_tests.sql`. *Alternative:* a row per student per exercise test. Rejected: it must be kept in step with the roster and the date, for no information that cannot be derived. + +### 2. The countdown is a pure function of days left + +`countdown.plan(days_total)` gives each step a recommended day; `countdown.today(test, facts, today)` gives the one task for today. The steps and their days for a test set 9 or more days ahead are the PRD's: path until 9, exercise test 1 at 9, exercise test 2 at 7, simulation window from 5, review 4 → 1 (the last day "light mixed review"). For a test set `n < 9` days ahead every day `d` of the plan becomes `round(d · n / 9)`, keeping the order (6 days: exercise test 1 at 6, exercise test 2 at 5, simulation from 3, review 3 → 1; days are rounded half up); `n` is the days between the day the test was set and the test day, so the plan does not shift as days pass. + +Today's task, from the closest test (spec: Several tests): + +```mermaid +flowchart TD + A[days left = test date - today] --> B{the step recommended for today done?} + B -- no --> T[that step] + B -- yes --> C{a later step not done?} + C -- yes --> L[the next later step, early] + C -- no --> R{simulation taken?} + R -- yes --> V[review: next failed skill not practised since; day before: the covered skill answered longest ago] + R -- no --> P[continue the path] +``` + +A step is **done** when: path, every covered skill is mastered; an exercise test, it has a submitted attempt; simulation, it was taken. During "until 9" the task is "finish the path" and opens the next unmastered covered skill. The days are recommendations only: every step can be opened at any time (except the simulation's window, decision 4). + +### 3. Exercise test questions + +`exam.draw_exercise(bank, lessons, states, weak_from_tests, n, share, used, rng)`, with `share` 0.6 for test 1 and 0.3 for test 2: + +1. Covered skills = the skills of the test's lessons that have questions. **Not started** ones are left out and returned as `practice_first` (shown on the test's card). +2. **Weak** = covered skills in the learning state, plus any covered skill answered wrong in an earlier exercise test of this real test. **Other** = the remaining started covered skills. +3. `w = round(n · share)`. Weak questions: **one per weak skill**, the weak skills in random order, up to `w` (so 3 weak skills give 3, as in the spec's scenario). The rest, `n − weak taken`, comes from the other skills, one per skill round after round, then from weak skills again if the others run out. Within a skill the least-used question first (`used` counts this student's earlier exercise-test and simulation attempts of this real test), as in the quiz draw. +4. If no covered skill is started there are no questions: the test cannot start and its card says "practice these first". + +The simulation uses the same draw with no weak share (`share = 0`): an even spread over all started covered skills, one per skill round after round; not-started skills are still left out (they are the student's own gap, and the simulation reports them as not ready). *Alternative:* allow several questions per weak skill to reach 60%. Rejected: a mixed test should touch many skills, and the spec's scenario counts one per skill. + +### 4. The simulation's window and its one attempt + +Open when `days_left ≤ window` (5, or `round(5 · n / 9)` for a short-notice test) and `days_left ≥ 0`, so it stays open through the test day. Before that `POST .../simulation/start` answers 409 with the opening date, and the screen says when it opens. One attempt: the start route returns the existing attempt (open or submitted) if there is one and never draws a second. The failed skills of a submitted simulation (skills with at least one missed question) are the review list (spec: Review tasks). + +### 5. Readiness + +`readiness.compute(M, E, S)` in one pure function: `M` = mastered covered skills ÷ covered skills (skills with questions), as 0–100; `E` = the average of the best grade of each exercise test taken (one or two); `S` = the simulation grade. The number is `Σ(weight·part)/Σ(weight)` over the parts that exist (M 50, E 20, S 30), rounded half up; without `S` it is capped at 80 and the response says `capped: true`. Labels: 0–39 "מתחילים", 40–69 "בדרך", 70–84 "כמעט שם", 85–100 "מוכנים" (only reachable with S). Unit tests pin the spec's numbers: 60 → 60; 80, 70, 90 → 81; 100, 95, none → 80 capped. + +### 6. Routes + +| Route | Who | Does | +|---|---|---| +| `GET /api/teaching/tests` | teacher of the class (`class.teach`) | the teacher's classes' tests, each with its students: simulation taken or not, readiness | +| `POST /api/classes/{id}/tests` | teacher of that class | set a test (date not in the past, lessons ⊆ the class's lessons, defaults 12/45) | +| `PUT /api/tests/{id}` / `DELETE /api/tests/{id}` | teacher of its class | change before its date / remove (soft) | +| `GET /api/home` | `path.use` | the student's upcoming tests (closest first) with days left, readiness, today's task, the simulation's state, and the path's next skill | +| `GET /api/tests/{id}` | a student of the class | the test's card: plan, readiness, both exercise tests (best grade, practise first), the simulation (window, taken, review list) | +| `POST /api/tests/{id}/exercise/{1\|2}/start`, `POST /api/tests/{id}/simulation/start` | a student of the class | start or resume, as the quiz start; attempts are then read, answered and submitted through the existing `/api/attempts/{id}` routes | + +`_mine` in `quizzes.py` accepts the three kinds; the result of an exercise test or simulation links weak skills exactly as a quiz result does. `GET /api/grades` adds exercise tests (best per test and number) and simulations, by test, after the quizzes. The permission matrix test lists every new route; a teacher of another class gets 404 for a test that is not theirs. + +### 7. Screens + +- **Tab bar at the bottom** (`ui.tabs`): בית, מסלול, ציונים, האוסף, fixed to the bottom with the safe-area inset, each at least 44px; the page gets bottom padding so nothing hides under it. The card opens `#/subject/math` = home; the path moves to `#/subject/math/path`. Old links to `#/subject/math` therefore land on home, which is what the card now does. +- **Home** (`home.js`): for the closest test, a card with its name (the lessons), "בעוד N ימים", the readiness bar with M, E, S under it and the cap note, and **one big button** for today's task; a "חובה" card for an open, untaken simulation; "להמשיך במסלול" (opens the next skill); other upcoming tests as small rows. With no test: only the continue button and a line that the teacher has not set a test. +- **A test's card** (`#/test/`): the plan as a list of steps with their recommended days and done marks, the two exercise tests with best grade and "התחלה" / "שוב", "practise these first" with links, the simulation (opens on…, required, taken with its grade and review list). +- **The sheet**: `quiz.js` takes the kind from the attempt and changes only its title ("בוחן", "מבחן תרגול 1", "מבחן סימולציה") and, for the simulation, removes "בוחן חוזר" and says it can be taken once. Addresses: `#/exam//<1|2>[/]`, `#/sim/[/]`. +- **Teacher's tests tab** (`#/tests` in `teacher.js`, a second tab beside the classes): per class, "קביעת מבחן" (date, lesson checkboxes from the class's lessons, note, questions, minutes with the defaults filled), and each test with edit/remove, "N מתוך M עשו סימולציה", the names of those who have not, and each student's readiness. + +## Risks / Trade-offs + +- [Rounding the plan for very short notice makes steps share a day (2 days: everything on days 2 and 1)] → The order is kept and every step stays startable; a test for 2 days with 4 steps cannot be spread further. +- [A student with almost nothing started gets a tiny or empty exercise test] → The card says what to practise first; the test is shorter rather than padded with not-started skills, which the spec forbids. +- [Readiness and the plan on every home load cost several store reads] → One `progress_of`, one `attempts_of` per kind, and the class's tests per request; fine at class size, and the functions are pure, so caching can be added later. +- [Moving the tabs to the bottom changes every student screen's tests] → The tab bar is one helper; browser tests find tabs by their link, not by position. +- [The teacher sees each student's readiness, which some students may not like] → It is the PRD's rule (RDY-1); only the class's own teacher sees it. + +## Migration Plan + +Run `20261111090000_m2_tests.sql` after the six earlier migrations; it only adds `m2_tests`. No existing table changes (`m2_attempts.kind` already allows the new kinds). Rollback: `drop table m2_tests` (in the file header); attempts of removed tests stay as harmless rows. Students see no test until a teacher sets one. diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/proposal.md b/openspec/changes/archive/2026-11-08-add-test-readiness/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..ffebcf0ccd81b7f43ffbf113069acfa66c079164 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/proposal.md @@ -0,0 +1,34 @@ +# Proposal + +## Why + +Students arrive at the real test without having practised mixed, timed questions or knowing their gaps (PRD Goal 2). This stage turns a test the teacher sets into a plan the student follows day by day, with two exercise tests, one required simulation and a readiness meter (PRD 4.10–4.13). + +## What Changes + +- The teacher sets a real test: date, lessons, number of questions and time limit (default 12 and 45 minutes), and sees who took the simulation. +- The countdown plan from the PRD's table, shortened evenly when the test is less than 9 days away. +- Two exercise tests per student, created automatically, weighted toward weak skills (60/40, then 30/70), retakeable. +- One required simulation, like the real test, open from ~5 days before until the test day, one attempt. +- The readiness meter: one 0–100 number from mastery, exercise tests and the simulation, capped at 80 until the simulation. +- The student's home: the nearest test, its readiness and one task for today, and a button that continues the path. The subject card now opens home (as in mathly1) instead of the path, and the tab bar (home, path, grades, collection) moves to the bottom of the screen. + +Screens: `docs/mockups/mathly2-screens.html` (student tab: home; teacher tab: tests). + +## Capabilities + +### New Capabilities +- `real-tests`: setting a test and the teacher's tests tab (PRD TST-1, TCH-6). +- `test-countdown`: the day-by-day plan (PRD TST-2). +- `exercise-tests`: the two weighted, retakeable practice tests (PRD EXT-1 – EXT-7). +- `simulation-test`: the one required full simulation (PRD SIM-1 – SIM-5). +- `readiness-meter`: the readiness number and its parts (PRD RDY-1 – RDY-3). +- `student-home`: the student's home with today's task (PRD STU-1, TST-3). + +### Modified Capabilities +- `learning-path`: "Choosing a subject": the card opens the subject's home instead of the path. + +## Impact + +- Reuses the timed-attempt engine and grade scale from `add-lesson-quizzes`, and skill states from `skill-mastery`. +- New `m2_` tables for tests, exercise tests and simulations. diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/exercise-tests/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/exercise-tests/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..bd8e562b20b0d4d94193ce3e5b1d8269422cb47b --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/exercise-tests/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## Purpose + +Two timed, mixed practice tests per real test that train the student under test conditions and aim at their weak skills, retakeable until they are good. + +## ADDED Requirements + +### Requirement: Created by the app +When a teacher sets a test, the app SHALL create 2 exercise tests for every student of the class and place them on the student's countdown. + +#### Scenario: New test +- **WHEN** a teacher sets a test for a class of 25 +- **THEN** each of the 25 students has exercise test 1 and exercise test 2 on their countdown + +### Requirement: Like the real test +An exercise test SHALL have the real test's number of questions and time limit, mix questions from all the covered lessons, hide skill names, and give feedback only at the end. + +#### Scenario: During the test +- **WHEN** a student answers a question in an exercise test +- **THEN** no right or wrong is shown until the test ends + +### Requirement: Question mix +Exercise test 1 SHALL draw 60% of its questions from weak skills and 40% from other covered skills; exercise test 2 SHALL draw 30% and 70%. A weak skill is one in the learning state or answered wrong in an earlier exercise test. Not-started skills MUST NOT appear; they are listed as "practice these first". Missing weak questions are filled from other covered skills. + +#### Scenario: Few weak skills +- **WHEN** exercise test 1 needs 7 weak questions and the student has weak skills for only 3 +- **THEN** the other 9 questions come from other covered skills + +#### Scenario: Not started +- **WHEN** a covered skill is not started +- **THEN** it has no question in the test and is listed under "practice these first" + +### Requirement: Retakes +The student SHALL be able to start or retake an exercise test at any time. Each retake SHALL draw new questions; the best grade counts. + +#### Scenario: Retake +- **WHEN** a student retakes exercise test 2 +- **THEN** it has new questions, and their best grade of the two attempts counts + +### Requirement: Result links back +After an exercise test the student SHALL see their grade and the weak skills found, each linked to its star on the path. The correct answers MUST NOT be shown. + +#### Scenario: Result +- **WHEN** a student finishes an exercise test with mistakes in two skills +- **THEN** the result lists those two skills with links to their stars diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/learning-path/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/learning-path/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..dd15a6c7eb36c282d520ab869e15dcf5282578ba --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/learning-path/spec.md @@ -0,0 +1,16 @@ +## MODIFIED Requirements + +### Requirement: Choosing a subject +After sign-in a student SHALL first see the subjects of their classes as cards, each with an icon, the subject's name and a bar "N מתוך M מיומנויות" (skills mastered of all skills in their lessons). Math (מתמטיקה) is the only subject; other subjects are not built. Tapping a card SHALL open that subject's home (as in mathly1), from where the tab bar leads to the path, the grades and the collection; the subject's screens SHALL have a way back to the subjects. A reload or a link to a skill SHALL open its path directly. + +#### Scenario: After signing in +- **WHEN** a student signs in +- **THEN** they see a card "מתמטיקה" with "N מתוך M מיומנויות", and no path yet + +#### Scenario: Opening the subject +- **WHEN** the student taps the math card +- **THEN** the math home opens, with the tab bar and a way back to the subjects + +#### Scenario: A link to a skill +- **WHEN** a student opens `#/skill/` directly +- **THEN** the math path opens with that skill's exercise screen over it diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/readiness-meter/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/readiness-meter/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f8e0d043838bf324f39397a4e606325a79c21618 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/readiness-meter/spec.md @@ -0,0 +1,32 @@ +# Spec Delta + +## Purpose + +Shows the student and the teacher, as one honest number, how ready the student is for an upcoming test, and what it is made of. + +## ADDED Requirements + +### Requirement: One readiness number +For each upcoming test the app SHALL show the student and the teacher a number from 0 to 100, drawn as a level bar, with its parts under it: M, the % of covered skills mastered; E, the average of the best grade of each exercise test taken; S, the simulation grade once taken. + +#### Scenario: Parts shown +- **WHEN** a student opens the reminder of a test +- **THEN** the bar shows the number with M, E and S under it + +### Requirement: How the number is made +The number SHALL be the weighted average of the parts that exist, with weights M 50, E 20 and S 30; a part that does not exist yet is left out and the others are scaled up. + +#### Scenario: Only mastery so far +- **WHEN** a student has mastered 60% of the covered skills and taken no tests +- **THEN** the number is 60 + +#### Scenario: All three parts +- **WHEN** M is 80, E is 70 and S is 90 +- **THEN** the number is 81 + +### Requirement: No false confidence +Until the simulation is taken the number SHALL be capped at 80, and the bar SHALL say so. The label SHALL be "מתחילים" for 0–39, "בדרך" for 40–69, "כמעט שם" for 70–84 and "מוכנים" for 85–100; "מוכנים" can only show after the simulation. + +#### Scenario: Strong before the simulation +- **WHEN** M is 100 and E is 95 and the simulation is not taken +- **THEN** the number shows 80 with a note that the simulation is still missing diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/real-tests/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/real-tests/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..b1c216a5b823b25bb36086dde8e1c5d30cf84289 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/real-tests/spec.md @@ -0,0 +1,28 @@ +# Spec Delta + +## Purpose + +Lets a teacher put a class's real school test into the app, so the app can prepare the students for it, and lets the teacher follow who has taken the required simulation. + +## ADDED Requirements + +### Requirement: Setting a test +The teacher of a class SHALL be able to set a test for it: a date, the lessons it covers (from the class's lessons), an optional note, the number of questions and the time limit. The number of questions SHALL default to 12 and the time limit to 45 minutes; both can be changed. + +#### Scenario: Defaults +- **WHEN** a teacher sets a test without changing the number of questions or the time +- **THEN** the test has 12 questions and 45 minutes + +### Requirement: Changing or removing a test +The teacher SHALL be able to change a test's date, lessons, note, length and time before its date, and remove it. Grades already earned in its exercise tests and simulation SHALL stay. + +#### Scenario: Moving the date +- **WHEN** a teacher moves a test two days later +- **THEN** every student's countdown follows the new date + +### Requirement: Tests tab +The teacher SHALL have a tests tab listing their classes' tests and, for each test, which students have taken the simulation and which have not. + +#### Scenario: Three missing +- **WHEN** 22 of 25 students took the simulation +- **THEN** the tab shows 22 done and names the 3 who have not diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/simulation-test/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/simulation-test/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..29c7ace0f5e3624cdf4c38e6c4678b1bb54618be --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/simulation-test/spec.md @@ -0,0 +1,35 @@ +# Spec Delta + +## Purpose + +One full rehearsal of the real test a few days before it, so the student knows where they stand while there is still time to fix the gaps it finds. + +## ADDED Requirements + +### Requirement: Required, one attempt +Every student SHALL take one simulation per real test, and it SHALL be possible to take it only once. + +#### Scenario: Second try +- **WHEN** a student who finished the simulation opens it again +- **THEN** they see their result and cannot start it again + +### Requirement: Like the real test +The simulation SHALL cover all the lessons of the real test, with its number of questions and time limit, no skill names and no feedback until the end. + +#### Scenario: Length +- **WHEN** the real test has 12 questions and 45 minutes +- **THEN** the simulation has 12 questions and 45 minutes + +### Requirement: Window +The simulation SHALL be open from about 5 days before the test until the test day, and SHALL be shown as required on the student's home until it is taken. + +#### Scenario: Too early +- **WHEN** a student opens the simulation 8 days before the test +- **THEN** it says when it opens and does not start + +### Requirement: Review tasks +After the simulation the app SHALL list the skills that failed and make them the review tasks of the last days of the countdown. + +#### Scenario: Two failed skills +- **WHEN** a student fails two skills in the simulation +- **THEN** those two skills are today's review tasks in the last days diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/student-home/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/student-home/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..e68a27b0b32cff0d5a2a425f6376ecdb8585c476 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/student-home/spec.md @@ -0,0 +1,35 @@ +# Spec Delta + +## Purpose + +The first screen of a subject, opened from its card: what to do today in one obvious button, the nearest test and its readiness, and a way back into the path. + +## ADDED Requirements + +### Requirement: Today's task +The home SHALL show, for the nearest test, the days left, the readiness meter and one task for today taken from the countdown plan, as a single obvious button that opens that task. + +#### Scenario: Exercise test due +- **WHEN** the nearest test is 9 days away and exercise test 1 is not taken +- **THEN** home shows one button that opens exercise test 1 + +### Requirement: Required simulation +While the simulation of an upcoming test is open and not taken, home SHALL show it as required. + +#### Scenario: Window open +- **WHEN** a test is 4 days away and the student has not taken its simulation +- **THEN** home shows the simulation marked as required + +### Requirement: Continue the path +Home SHALL have a button that opens the path's next skill. + +#### Scenario: No test +- **WHEN** a student has no upcoming test +- **THEN** home shows the button to continue at the next skill + +### Requirement: Tab bar +The student's screens (home, path, grades, collection) SHALL be reachable from a tab bar at the bottom of the screen. + +#### Scenario: Switching +- **WHEN** a student taps "ציונים" in the tab bar +- **THEN** the grades screen opens diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/specs/test-countdown/spec.md b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/test-countdown/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..0b0f9954f51d18702e8422295ab53a05eab28d80 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/specs/test-countdown/spec.md @@ -0,0 +1,35 @@ +# Spec Delta + +## Purpose + +Plans a student's last weeks before a real test, so they finish the path, practise under test conditions, take one simulation and review what failed, without planning it themselves. + +## ADDED Requirements + +### Requirement: The countdown plan +From the moment a test is set, every student of the class SHALL see a plan by days left: until 9, finish the path for the covered lessons; about 9, exercise test 1; about 7, exercise test 2; about 5, the simulation; 4 to 1, review the skills that failed in the simulation, with light mixed review the day before. + +#### Scenario: Twelve days ahead +- **WHEN** a test is 12 days away +- **THEN** the plan asks the student to finish the path for the covered lessons + +### Requirement: The days are recommendations +The student SHALL be able to start any step earlier or later than its day. + +#### Scenario: Early exercise test +- **WHEN** a student opens exercise test 1 eleven days before the test +- **THEN** it starts + +### Requirement: Short notice +When a test is set less than 9 days ahead, the plan SHALL keep the same order and shorten the gaps evenly. + +#### Scenario: Six days ahead +- **WHEN** a test is set 6 days ahead +- **THEN** the plan still runs path, exercise test 1, exercise test 2, simulation, review, in that order, within the 6 days + +### Requirement: Several tests +When several tests are coming up, today's task SHALL come from the closest one. + +#### Scenario: Two tests +- **WHEN** a student has tests in 4 and in 10 days +- **THEN** today's task comes from the test in 4 days diff --git a/openspec/changes/archive/2026-11-08-add-test-readiness/tasks.md b/openspec/changes/archive/2026-11-08-add-test-readiness/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..1a9ea07fc2ab255b346e36338822713995492082 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-add-test-readiness/tasks.md @@ -0,0 +1,38 @@ +# Tasks + +## 1. Real tests (data and rules) + +- [x] 1.1 Add the migration `20261111090000_m2_tests.sql` (decision 1) and the store methods to create, read, change, soft-remove and list a class's tests, in both stores; verify unit tests, request tests for the Supabase store, and migration tests on PostgreSQL (defaults 12 and 45, the limits on questions and minutes, the browser roles are refused) +- [x] 1.2 Add `countdown.py` (decision 2): the plan for a test set 9 or more days ahead and for short notice, and today's task from the closest test; verify unit tests for 12 days (finish the path), 9 (exercise test 1), 7 (exercise test 2), 5 (simulation), 3 after a simulation with two failed skills (review one of them), 1 (light mixed review), a test set 6 days ahead keeps the order within 6 days, a done step moves to the next one early, and with tests in 4 and 10 days the task comes from the one in 4 +- [x] 1.3 Add `readiness.py` (decision 5); verify unit tests: 60 → 60, (80, 70, 90) → 81, (100, 95, none) → 80 with `capped`, each label at its edges, and "מוכנים" never shown without a simulation +- [x] 1.4 Add the exercise-test and simulation draw (decision 3); verify unit tests with a fixed `rng`: test 1 with 7 weak needed and 3 weak skills gives 3 weak and 9 other, test 2 takes 30%, a not-started skill is never drawn and is listed under "practise first", a skill answered wrong in an earlier exercise test counts as weak, a retake takes new questions while enough remain, the simulation spreads one per skill round after round, and nothing started gives no questions + +## 2. The API + +- [x] 2.1 Add the teacher's routes: `GET /api/teaching/tests`, `POST /api/classes/{id}/tests`, `PUT` and `DELETE /api/tests/{id}` (decision 6); verify API tests: defaults 12 and 45, lessons outside the class are refused, a past date is refused, a change after the date is refused, removing keeps the students' grades, moving the date moves every student's days left, 22 of 25 took the simulation shows 22 and names the 3, a teacher of another class gets 404, and the permission matrix test lists every new route +- [x] 2.2 Add `GET /api/home` and `GET /api/tests/{id}` for students; verify API tests: no test gives only the next skill, a test 9 days away with exercise test 1 not taken gives it as today's task, a test 4 days away with the simulation open and not taken marks it required, two tests take the task from the closer one, readiness has M, E and S as they exist, and a student of another class gets 404 +- [x] 2.3 Add starting exercise tests and the simulation, and let the attempt routes read, answer and submit them (decisions 3 and 4); verify API tests: an exercise test has the test's questions and minutes, starts early (11 days before), resumes when open, a retake draws new questions and the best grade counts; the simulation is refused 8 days before with its opening date, has 12 questions and 45 minutes, can be taken once (a second start returns the result), and its failed skills become the review list; no served question carries a right answer or a skill name +- [x] 2.4 Add exercise tests and simulations to `GET /api/grades`; verify API tests that the grades list each test's best exercise grades and the simulation grade, and that a removed test keeps its name there + +## 3. Student screens + +- [x] 3.1 Move the tab bar to the bottom with בית, מסלול, ציונים and האוסף, the card to open home at `#/subject/math`, and the path to `#/subject/math/path` (decision 7); update the browser tests that open the path; verify a Playwright test that the card opens home, each tab opens its screen, the bar stays at the bottom at 360px with 44px targets and covers nothing, and a link to a skill still opens the path with its sheet +- [x] 3.2 Build `home.js`: the closest test with days left, the readiness bar with M, E, S and the cap note, one button for today's task, the required simulation, other tests, and "continue the path"; verify a Playwright test for no test, a test 9 days away (the button opens exercise test 1), a test 4 days away with the simulation required, the readiness bar's parts and cap note, and that nothing scrolls sideways at 360px +- [x] 3.3 Build the test's card at `#/test/`: the plan with recommended days and done marks, both exercise tests with best grade and start or retake, "practise these first" with links, and the simulation (when it opens, required, its result and review list); verify a Playwright test of each state +- [x] 3.4 Generalise `quiz.js` to the three kinds (title, retake only for quiz and exercise test, once-only note for the simulation) and add the addresses `#/exam/...` and `#/sim/...`; verify a Playwright test that an exercise test runs with the test's length and timer and shows its weak skills as links at the end, that the simulation cannot be started twice, and that the quiz tests still pass +- [x] 3.5 Add exercise tests and simulations to the grades screen; verify a Playwright test that both appear with their grades + +## 4. Teacher screen + +- [x] 4.1 Add the tests tab to `teacher.js`: per class, set a test (date, lesson checkboxes, note, questions, minutes with defaults), edit or remove it, "N מתוך M עשו סימולציה" with the names of those missing, and each student's readiness; verify a Playwright test that a teacher sets a test with the defaults, changes its date, sees who has not taken the simulation, and removes it, at 360px and on a computer + +## 5. Wrap-up + +- [x] 5.1 Walk the whole countdown in a browser with the server's clock moved day by day: the teacher sets a test 12 days ahead; the student's home asks to finish the path, then offers exercise test 1, takes it, then exercise test 2, then the required simulation, then a review skill, and the readiness bar moves and loses its cap after the simulation; the teacher sees the simulation taken; verify the test passes +- [x] 5.2 Update `docs/mockups/mathly2-screens.html` where home, the bottom tab bar or the teacher's tests tab no longer match what was built; verify by opening it beside screenshots +- [x] 5.3 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate add-test-readiness --strict`; verify both pass + +## Workflow follow-up + +- Apply the new migration after the six earlier ones (on a test project first). +- Archive this change once it is reviewed (it creates six capabilities and modifies `learning-path`); then propose `add-written-work` (stage 6), which adds assignments, the teacher sending an exercise test as one (EXT-2), and assignment rows on home and the grades screen. diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/.openspec.yaml b/openspec/changes/archive/2026-11-08-rebuild-foundation/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e582ee4a2c22919eed558b194fa58fb923e0f359 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-07 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/design.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/design.md new file mode 100644 index 0000000000000000000000000000000000000000..cca0d0d881e25605401702ae6763a1d777274062 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/design.md @@ -0,0 +1,151 @@ +# Design + +Screens: `docs/mockups/mathly2-screens.html` (student, teacher and manager tabs). The screenshots below are taken from that mockup (sample data); the admin's accounts screen is not drawn yet. + +## Screens in this stage + +| Sign-in (light) | Sign-in (dark) | +|---|---| +| ![Sign-in page, light](./screenshots/sign-in-light.png) | ![Sign-in page, dark](./screenshots/sign-in-dark.png) | + +Spec: Google sign-in. mathly1's page: logo, owl, one status line, one Google button. + +**Manager: class list** (spec: Class and student lists) + +![Manager's class list](./screenshots/manager-classes.png) + +**Manager: class editor** (spec: Manager creates classes; Editing and deleting a class). The AI switch starts off. + +![Manager's class editor](./screenshots/manager-class-editor.png) + +**Manager: students list**, with a student in two classes + +![Manager's students list](./screenshots/manager-students.png) + +**Teacher home: my classes and their rosters** (spec: Teacher home; Teacher adds students by email) + +![Teacher's classes on a computer](./screenshots/teacher-classes.png) + +On a phone: [teacher-classes-phone.png](./screenshots/teacher-classes-phone.png) + +## Context + +See proposal.md for why. Today `mathly2/` has: Google sign-in through Supabase plus a dev sign-in (`auth.py`); two roles, teacher from `TEACHER_EMAILS`, everyone else a student (`auth.current_user`); classes created by a teacher (`classes.py`); the tables `m2_classes` (with `teacher_email` = the creator) and `m2_class_members` (email is the primary key, so a student can be in one class only); a light/dark CSS with a plain accent (`static/app.css`); and the student practice code from the retired `build-skill-learning` change, which stage 2 reshapes. + +The migrations have never been applied to the real Supabase project, so the `m2_` tables can still change shape through a new migration. + +## Goals / Non-Goals + +**Goals:** +- One place decides roles and permissions, used by every route, so later stages only declare what a route needs. +- Classes and roles that match the PRD before any learning feature depends on them. +- The sky look as app-wide tokens, so every later screen inherits it. + +**Non-Goals:** +- The path, exercise screen and board (stage 2). The current student screens stay as they are until then. +- Using the AI switch and budget: this stage stores them; stage 7 uses them. + +## Decisions + +### 1. Roles: settings, a roles table and class teachers, merged on every request + +```mermaid +flowchart LR + E[signed-in email] --> S{in DEVELOPER_EMAILS?} + S -- yes --> D[developer] + E --> T{in TEACHER_EMAILS, or a class's teacher?} + T -- yes --> TT[teacher] + E --> R[(m2_roles rows for the email)] + R --> X[student / teacher / manager / admin] + E --> A{in ADMIN_EMAILS?} + A -- yes --> AD[admin] + D & TT & X & AD --> U[roles = union, else student] +``` + +- A new table `m2_roles (email, role, granted_by, granted_at)`, with the key (email, role) and the role one of student, teacher, manager, admin. Roles are keyed by **email**, so they work before the first sign-in (spec: Admin gives roles). +- The developer role exists only in settings, so the roles table can never create one. +- Roles are resolved on every request. A 30-second cache per email keeps it to one store call per page load; a role change shows within 30 seconds. *Alternative:* roles in the sign-in token. Rejected: a removed role would live until the token expires. + +### 2. Permissions are named, and routes ask for a permission, not a role + +`access.py` holds the matrix (as mathly1's `app/access.py` does): `path.use`, `class.view` (a class one teaches), `class.roster`, `classes.manage`, `roles.manage`, `*` for developers. A route declares `Depends(need("classes.manage"))`; class-scoped routes also check that the class is one the caller teaches. One test reads every route from the app and checks each refuses the roles it must refuse. + +### 3. Class tables reshaped with one new migration + +```mermaid +erDiagram + m2_classes ||--o{ m2_class_members : has + m2_classes { + bigint id PK + text name "unique ignoring case" + text teacher_email "nullable: at most one teacher" + text[] lessons "at least one" + bool ai_enabled "default false" + int ai_daily_checks "default 150" + text created_by + } + m2_class_members { + bigint class_id PK + text email PK "a student may be in many classes" + uuid user_id + } + m2_roles { + text email PK + text role PK + text granted_by + timestamptz granted_at + } +``` + +- `m2_class_members` gets the key (class_id, email) instead of email alone; `m2_classes.name` becomes unique ignoring case across all classes, as in mathly1. `teacher_email` keeps its column but now means "the class's teacher" and may be empty. +- A check refuses a class whose teacher is also one of its students. +- *Alternative:* edit the old migration file. Rejected: a migration that already ran anywhere must not change; a new one is safe on any database. + +### 4. API + +| Route | Who | Does | +|---|---|---| +| `GET /api/me` | anyone signed in | email, roles, permissions, classes as student, classes as teacher | +| `GET/POST/PUT/DELETE /api/classes[/{id}]` | manager, developer | list, create, edit, delete classes | +| `POST/DELETE /api/classes/{id}/students` | the class's teacher, manager | add pasted emails, remove one | +| `GET /api/students` | manager | every student with their classes | +| `GET /api/teaching` | teacher | the classes I teach, with students | +| `GET /api/accounts`, `POST/DELETE /api/accounts/{email}/roles/{role}` | admin | known accounts, give, take away | + +Taking away the last admin role is checked in one store call that counts admins and deletes together, so two admins removing each other at once cannot leave none. + +### 5. Screens: a role switcher in the header + +A person with several roles sees a row of role chips in the header (תלמיד, מורה, מנהל כיתות, מנהל הרשאות, מפתח), each opening that role's home; the device remembers the last one. Homes: student (the current screens), teacher (classes and rosters), manager (classes, editor, students), admin (accounts and roles). The sign-in page is mathly1's: logo, owl, status line, one pill button. + +### 6. The sky look as global tokens + +`app.css` defines `--sky-*` tokens on `:root`, in one dark set (night blue, aurora, starlight, gold), plus the owl as an inline SVG. Reduced motion turns every animation off in one rule. Later stages use only these tokens. The `body` background is the sky itself: two soft radial glows as in mathly1 (blue and purple, strength `--sky-glow`) and eight tiny stars drawn in `--sky-star`, all fixed to the viewport. There is no light set, as in mathly1. It is static, so it needs no reduced-motion rule. + +### 7. Settings come from three places, in a fixed order + +Real environment variables, then `mathly2/.env` if it exists, then the repository's `.env`, which mathly1 also uses (same Supabase project, so one copy of the keys). The earlier source wins. A test that passes its own file reads only that file, and the test setup blanks the settings the app reads, so a developer's real keys never reach a test. *Alternative:* a second copy of the keys in `mathly2/.env`. Rejected: two copies of secrets that can drift apart, and the later one silently wins. + +### 8. A refused save keeps the form and shows its reason in view + +The class editor is long (every lesson is a checkbox), so a reason shown above the form is out of sight when the save button at the bottom was pressed, and redrawing the form from the saved class throws away what was typed. The editor keeps what was typed (a draft kept in the browser until the save works or the person leaves), shows "לא נשמר: …" right above the buttons, and scrolls and focuses it. Found when a developer tried to make a student the class's teacher and saw nothing happen. + +### 9. Database refusals are reported as what they are + +In the Supabase store only a 409 means "already exists". Any other refusal (a column missing because a migration was not applied, bad data) becomes a `StoreUnavailable` error; the server turns it into a 503 with a message that says the database did not answer or refused and that migrations may be missing, and writes the reason to the log. The database's error body can be read only once, so it is read once and kept on the error. *Alternative:* treat every 400 as a name clash (what the first version did). Rejected: it told people the wrong thing. + +### 10. The address after "#" belongs to the open screen + +A small router holds one handler for the open screen. The shell forgets it, and clears the address, only when the person switches role; the first screen shown after sign-in keeps the address, so a link or a reload lands where it points. + +## Risks / Trade-offs + +- [The current student screens look unchanged until stage 2] -> Accepted; this stage is about who may do what. +- [A role change takes up to 30 seconds to apply] -> Acceptable for school use; the admin screen says so. +- [Students can now be in several classes, which the current practice code assumes not] -> The practice code reads only the student's own answers, never the class, so it keeps working; a test covers a student in two classes. +- [Existing tests assume teachers create classes] -> Rewritten in this stage, not deleted: the same cases move to the manager. + +## Migration Plan + +- One new migration: `m2_roles`, the new `m2_classes` columns and constraint, the new key on `m2_class_members`. `m2_` tables only (spec: mathly1 stays available). Rollback: drop `m2_roles` and the new columns, and restore the old key. +- New settings `DEVELOPER_EMAILS` and `ADMIN_EMAILS` go into `mathly2/.env.example` and the README. diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/proposal.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..cd9fca5e0939690b737c81e2a774303b81433009 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/proposal.md @@ -0,0 +1,32 @@ +# Proposal + +## Why + +The PRD (`docs/tasks/prd-mathly.md`) now describes the whole app with five roles, classes created by a manager, and mathly1's look. The foundation built so far has two roles and teacher-created classes, so every later stage would build on the wrong base. This stage puts the base right: who signs in, what each role may do, how classes are made, and the rules every screen follows. + +## What Changes + +- **BREAKING** Five roles: student, teacher, manager, admin, developer (PRD 4.1). Roles belong to an email; an admin gives and takes them; developers come only from the settings. +- **BREAKING** Classes are created, edited and deleted by a **manager** (PRD 4.2, 4.18), not by teachers. A class has lessons, one teacher, students, an AI switch (off) and a daily AI budget. +- **BREAKING** A student may belong to **more than one class**. A class's teacher can add and remove its students (TCH-9). +- The sign-in page and each role's home shell follow mathly1 (ACC-1, TCH-1, MGR-1, ADM-1). The sky look, always dark, becomes the rule for every screen. +- The exercise bank's rules are corrected: no worked or faded examples; content gaps are listed, not required before use. +- mathly1's database stays untouched, so the Hugging Face Space can be switched back (PRD 7.3, Fallback). + +Screens: static mockup at `docs/mockups/mathly2-screens.html` (student, teacher, manager); this stage's screenshots are in [design.md](./design.md#screens-in-this-stage) and [screenshots/](./screenshots/). + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `accounts-and-classes`: five roles, admin-given roles, manager-made classes, students in several classes, the teacher's roster. +- `app-basics`: the sky look, readability without color or motion, server-side time and decisions, the mathly1 fallback, safe settings. +- `exercise-bank`: the content rules match the PRD (mistakes, figures, start-up checks, no answers on the device, listed content gaps). + +## Impact + +- `mathly2/auth.py`, `mathly2/classes.py`, `mathly2/store.py`, `mathly2/config.py`, `mathly2/main.py`, the role screens in `mathly2/static/`. +- A new migration adds a roles table and the new class columns, and lets a student be in several classes (`m2_` tables only). +- New settings: `DEVELOPER_EMAILS`, `ADMIN_EMAILS` (the first admins). +- Later stages (`add-learning-core` onwards) build on these roles and classes. diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-class-editor.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-class-editor.png new file mode 100644 index 0000000000000000000000000000000000000000..b3771f259682dcd60c2254979dc53c4374099a0d --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-class-editor.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:275d5af051e691f9bebbfe8e78921bff82696c8cdb1d8c5306b714a816ac8539 +size 62214 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-classes.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-classes.png new file mode 100644 index 0000000000000000000000000000000000000000..e54466a42eb8a273df7c1684fbdfe6aa72bb0915 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-classes.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b0094f48844ce7402b263eedccbeadd7e7a6f1f771a3e6af8b71e0779bbeaaf +size 43428 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-students.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-students.png new file mode 100644 index 0000000000000000000000000000000000000000..379ac6d777670bade44d52c366d568b7d782594c --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/manager-students.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c13410e2218554dfee64661319d2623767531e937e4b23f935d9b654cb0a9baf +size 31806 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-dark.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-dark.png new file mode 100644 index 0000000000000000000000000000000000000000..79594b0253c55239b5ca68332670864a46037b2b --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-dark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:629f4c249c926822465dfd60688f0a0cf3987cddc6a3113ffc5393f8b15e6e44 +size 67037 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-light.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-light.png new file mode 100644 index 0000000000000000000000000000000000000000..3ab9059991e867180839cab382b9d6ae414d0f56 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/sign-in-light.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56148f7b5105144d0f43eec34137bf3a5caad0add323840d0b2ab1c810967c84 +size 65657 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes-phone.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes-phone.png new file mode 100644 index 0000000000000000000000000000000000000000..f4e0ee22a36e7e5495487566cfb6d5c9bfc4e164 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes-phone.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc1ed428ec0336f7a82aba13fd7a8c2415af3bd494fdff49dcfc28240357737d +size 123574 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes.png b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes.png new file mode 100644 index 0000000000000000000000000000000000000000..64a11ba9b7138ddea7658333a6530ac22243256e --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/screenshots/teacher-classes.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55ffdda9f3ea639fb97057908b34b520e05142a0854dd380b24ebc160ab3ea3e +size 54548 diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/accounts-and-classes/spec.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/accounts-and-classes/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..8dec60b96cc4cfbf4c1ce58c0db062f699ce04bc --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/accounts-and-classes/spec.md @@ -0,0 +1,190 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Google sign-in +Students, teachers, managers, admins and developers SHALL sign in with their Google account. Before sign-in the only screen SHALL be the sign-in page: the animated logo "לומדים בכיף" (from mathly1) and the owl mascot, one line of status text and one button "כניסה עם Google". The app MUST NOT show or serve any student content, class or progress before sign-in. The session SHALL stay on the device, and sign-out SHALL be available on every screen. + +#### Scenario: Signing in +- **WHEN** a student opens the app and signs in with Google +- **THEN** they see the app as a student + +#### Scenario: Not signed in +- **WHEN** someone opens the app without signing in +- **THEN** only the sign-in page is shown + +#### Scenario: Coming back the next day +- **WHEN** a signed-in student closes the app and opens it the next day on the same device +- **THEN** they are still signed in + +### Requirement: Teacher adds students by email +The teacher of a class, and a manager, SHALL be able to add students to that class by pasting email addresses (one per line; commas and spaces also separate them) and to remove them. Repeated addresses SHALL be ignored and invalid ones reported. A student MAY belong to more than one class. Removing a student SHALL NOT delete their progress. + +#### Scenario: Adding a list +- **WHEN** the teacher of "ט'3" pastes 25 email addresses into the class +- **THEN** the 25 students are listed in "ט'3" + +#### Scenario: Student in another class +- **WHEN** a teacher adds a student who already belongs to another class +- **THEN** the student is added, and now belongs to both classes + +#### Scenario: Invalid address +- **WHEN** the pasted text contains "dana@" among valid addresses +- **THEN** the valid ones are added and "dana@" is reported as invalid + +#### Scenario: The teacher in the list +- **WHEN** the teacher of "ט'3" pastes their own address among others +- **THEN** their own address is reported as not allowed, and the others are added + +### Requirement: Student not in a class +A signed-in student who is in no class SHALL see a message asking them to ask their teacher or a manager to add them, showing the email they signed in with, and nothing else. + +#### Scenario: Not added yet +- **WHEN** a student signs in before a teacher or manager added their email +- **THEN** they see the message with their email, and no lessons + +## REMOVED Requirements + +### Requirement: Teacher accounts +**Reason**: Replaced by five roles decided per email (Requirement: Five roles). +**Migration**: Teachers listed in the settings keep the teacher role; other roles are given by an admin. + +### Requirement: Teacher creates classes +**Reason**: Classes are created by a manager (PRD CLS-1). +**Migration**: Use Requirement: Manager creates classes. The app starts empty, so there are no teacher-made classes to move. + +## ADDED Requirements + +### Requirement: Five roles +The app SHALL have five roles: student, teacher, manager, admin and developer. The server SHALL decide a signed-in email's roles on every request: developer when the email is in the developer setting; teacher when it is in the teacher setting, is a class's teacher, or was given the role; manager or admin when given the role; student otherwise. A person MAY hold several roles and gets the screens of each. + +#### Scenario: Class teacher +- **WHEN** an email that is in no setting is named as the teacher of a class and signs in +- **THEN** it gets the teacher screens for that class + +#### Scenario: Several roles +- **WHEN** a person has both the manager and the teacher role +- **THEN** they can reach both the classes screen and their teacher home + +### Requirement: Permissions per role +Each role SHALL be limited to: student, their own path and data; teacher, the data of the students of the classes they teach and those classes' rosters; manager, classes and their AI settings with no learning data; admin, roles of accounts with no learning data; developer, everything. The server SHALL refuse any request outside the caller's permissions. + +#### Scenario: Teacher of another class +- **WHEN** a teacher asks for the progress of a student who is not in a class they teach +- **THEN** the server refuses + +#### Scenario: Manager and learning data +- **WHEN** a manager asks for a student's answers or grades +- **THEN** the server refuses + +### Requirement: Admin gives roles +An admin SHALL see the accounts the app knows and give or take away the roles student, teacher, manager and admin. Roles SHALL belong to an email address, so a role can be given before the person's first sign-in. The developer role MUST NOT be given here. The last admin MUST NOT be able to take away their own admin role. + +#### Scenario: Role before first sign-in +- **WHEN** an admin gives "rina@school.org" the manager role and Rina signs in for the first time a day later +- **THEN** Rina gets the manager screens + +#### Scenario: Last admin +- **WHEN** the only admin tries to remove their own admin role +- **THEN** the change is refused with a message + +#### Scenario: A change shows soon +- **WHEN** an admin takes the manager role from someone who is signed in +- **THEN** within 30 seconds that person no longer has the manager screens + +### Requirement: The first admins +The app's settings SHALL be able to name admin emails, so a new installation has an admin before anyone gives roles. + +#### Scenario: Empty installation +- **WHEN** the app starts with no roles stored and the settings name "head@school.org" as an admin +- **THEN** "head@school.org" gets the admin screens at sign-in + +### Requirement: Role switcher +A person with more than one role SHALL get a chip for each role in the header, each opening that role's home; a developer SHALL get all five. A person with one role SHALL see no chips. The last role chosen SHALL be remembered on the device. A link or a reload SHALL land on the screen it points to, and switching role SHALL clear the address. + +#### Scenario: Two roles +- **WHEN** a person who is a manager and a teacher signs in +- **THEN** the header has a chip for each, and the one they used last opens first + +#### Scenario: A link +- **WHEN** a student opens the app through a link to their collection +- **THEN** after signing in they see their collection, and reloading shows it again + +#### Scenario: Switching clears the address +- **WHEN** a person with two roles switches from one to the other +- **THEN** the address no longer carries the first role's screen + +### Requirement: Own access +Every signed-in account SHALL be able to see its own roles and what they allow. + +#### Scenario: Checking own roles +- **WHEN** a teacher opens the page of their own access +- **THEN** it lists the teacher role and what it allows + +### Requirement: Manager creates classes +A manager (or a developer) SHALL create, edit and delete classes. A class SHALL have a name (1–80 characters, unique ignoring case), the lessons it studies (at least one, from the bank), its students, at most one teacher (an email, never also a student of that class), an AI switch that starts off, and a daily AI budget (default 150). + +#### Scenario: New class +- **WHEN** a manager creates "ט'3" with two lessons, a teacher and 25 students +- **THEN** "ט'3" appears in the class list with those lessons, that teacher and 25 students, and its AI switch is off + +#### Scenario: Teacher listed as a student +- **WHEN** a manager names "t@school.org" as the teacher and also lists it as a student of the same class +- **THEN** the class is not saved and the manager is told why + +#### Scenario: A refused save keeps what was typed +- **WHEN** a manager changes a class's name and teacher, presses save at the bottom of the form, and the save is refused +- **THEN** the reason is shown next to the save button and in view, the typed name and teacher are still in the form, and nothing was saved + +### Requirement: Editing and deleting a class +A manager SHALL be able to change a class's name, lessons, students, teacher, AI switch and budget, and delete a class after confirming. Neither SHALL delete any student's progress. + +#### Scenario: Deleting a class +- **WHEN** a manager deletes a class and confirms +- **THEN** the class is gone, and its students' progress is still there + +### Requirement: Class and student lists +A manager SHALL see every class with its name, lessons, number of students and their emails and its teacher, and a list of all students with the classes each belongs to. + +#### Scenario: A student in two classes +- **WHEN** a manager opens the students list and a student belongs to "ט'3" and "ט'4" +- **THEN** that student's row shows both classes + +### Requirement: Teacher home +A teacher's home SHALL list the classes they teach, each with its students. A teacher MUST NOT be able to change a class's name, lessons, teacher, AI switch or budget. + +#### Scenario: Two classes +- **WHEN** a teacher who teaches "ט'3" and "ט'4" signs in +- **THEN** their home lists both classes with their students + +#### Scenario: No class yet +- **WHEN** a teacher who teaches no class signs in +- **THEN** their home says that a manager chooses who teaches each class + +### Requirement: A student's lessons +A student's lessons SHALL be the lessons of all the classes they belong to. + +#### Scenario: Two classes, different lessons +- **WHEN** a student is in one class studying lessons A and B and another studying B and C +- **THEN** the student's lessons are A, B and C + +### Requirement: First sign-in links the account +The first time a person signs in, their account SHALL be linked to the class entries and roles stored for their email. + +#### Scenario: Added before signing in +- **WHEN** a manager adds "noa@school.org" to "ט'3" and Noa signs in for the first time +- **THEN** Noa is a student of "ט'3" + +### Requirement: Sign-in problems are explained +When the sign-in service cannot be reached the sign-in page SHALL say so and offer to try again. When a session has expired the person SHALL return to the sign-in page with a short message. + +#### Scenario: Service down +- **WHEN** the sign-in service does not answer +- **THEN** the sign-in page says it could not connect and shows a "try again" button + +### Requirement: Every request is checked +The server SHALL check the sign-in and the caller's permissions on every request except the health check. + +#### Scenario: No sign-in +- **WHEN** any request other than the health check arrives without a valid sign-in +- **THEN** the server refuses it diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/app-basics/spec.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/app-basics/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..5fb95ba533c90bc50288b43e8c95c47457830819 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/app-basics/spec.md @@ -0,0 +1,73 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Hebrew, right-to-left, phone first +Every screen SHALL be in Hebrew, laid out right-to-left, and designed for phones first. The teacher, manager, admin and developer screens SHALL also work well on a computer. + +#### Scenario: Opening on a phone +- **WHEN** a student opens the app on a phone +- **THEN** the screen is in Hebrew, right-to-left, and fits the phone's width + +#### Scenario: Manager on a computer +- **WHEN** a manager opens the classes screen on a computer +- **THEN** the class list uses the wide screen and nothing is cut off + +## ADDED Requirements + +### Requirement: The sky look +Every screen SHALL follow one "sky" look: a dark-blue night with aurora and starlight accents, gold for mastery, and an owl mascot. The app SHALL always be dark, as mathly1 is; there is no light mode. The page background SHALL be a dark night with two soft glows and small fixed stars. + +#### Scenario: A light device +- **WHEN** the device asks for light mode +- **THEN** every screen is still dark, with readable text + +#### Scenario: The sky behind the page +- **WHEN** any screen is open +- **THEN** the page background is dark, with two soft glows (blue at the top right, purple at the left) and small stars, all fixed while the page scrolls, and nothing in the background moves + +### Requirement: Readable without color or motion +State and result SHALL never be shown by color alone: every state has a symbol or a word. Touch targets SHALL be at least 44px. Animations SHALL stop when the device asks for reduced motion. + +#### Scenario: Reduced motion +- **WHEN** the device asks for reduced motion +- **THEN** no element of the app animates + +### Requirement: Server time and decisions +The server SHALL decide the date of every event by its own clock and the calendar day in Israel, never the device's. Correctness of answers, mastery, grades, budgets and timers SHALL be decided and stored on the server. + +#### Scenario: Device clock changed +- **WHEN** a student sets the device's date to tomorrow and answers a question +- **THEN** the answer is dated by the server's today + +### Requirement: mathly1 stays available +The app SHALL only add its own tables (named with an `m2_` prefix) and MUST NOT change, empty or delete any table, policy or storage bucket that mathly1 uses, so the Hugging Face Space can be switched back to mathly1 with its data as it was. + +#### Scenario: Switching back +- **WHEN** the Space is switched back to mathly1 after mathly2 has run +- **THEN** mathly1's students find their data as they left it + +### Requirement: Safe settings +The server SHALL refuse to start when only some of the Supabase settings are given. With none given it SHALL run for local development with an in-memory store and a sign-in, marked "dev only", that accepts an email address. + +#### Scenario: Half-configured +- **WHEN** the server starts with a Supabase URL but no secret key +- **THEN** it does not start and says which settings are missing + +### Requirement: Where settings come from +The server SHALL read its settings from real environment variables first, then from the app's own `.env` file if it has one, then from the repository's `.env` file shared with mathly1. A setting found in an earlier source SHALL win over the same setting in a later one. + +#### Scenario: Shared file +- **WHEN** the app has no `.env` of its own and the repository's `.env` holds the Supabase settings +- **THEN** the app uses those settings + +#### Scenario: A real variable wins +- **WHEN** the teacher list is set in the environment and in a file +- **THEN** the environment's list is used + +### Requirement: Database problems are explained +When the database cannot be reached, or refuses a request that is not a conflict the person caused, the person SHALL see a message saying the database did not answer or refused, with a hint that the migrations may be missing, and the reason SHALL be written to the server log. The app MUST NOT report such a failure as a different problem, such as a name already in use. + +#### Scenario: Missing column +- **WHEN** a manager saves a class and the database refuses because a migration was not applied +- **THEN** the manager sees that the database refused the request, not that the class name is taken, and the server log names the refusal diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/exercise-bank/spec.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/exercise-bank/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f398d72267a5c98cc3ed460908290b3f476483ac --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/specs/exercise-bank/spec.md @@ -0,0 +1,54 @@ +# Spec Delta + +## MODIFIED Requirements + +### Requirement: Bank is the content source +Lessons, skills, multiple-choice questions and mistakes SHALL come from the exercise bank kept from mathly1. Every question SHALL have exactly one correct choice, and each wrong choice SHALL point to a mistake with a name and a tip. A mistake MAY also name a skill to go back to. + +#### Scenario: Wrong choice +- **WHEN** a student picks a wrong choice +- **THEN** the mistake it points to supplies the feedback's name and tip + +#### Scenario: Mistake without a skill to go back to +- **WHEN** a mistake names no skill to go back to +- **THEN** the feedback shows its name and tip with no link + +### Requirement: Math is rendered +Math written inside `$…$` in the bank SHALL be shown as formulas. A question with a geometry figure or a graph SHALL show it. + +#### Scenario: Question with math +- **WHEN** a question's text contains `$x^2+5x+6$` +- **THEN** the student sees it as a formatted formula + +#### Scenario: Question with a figure +- **WHEN** a question has a geometry figure +- **THEN** the figure is drawn under the question's text + +## REMOVED Requirements + +### Requirement: Content gaps are filled before use +**Reason**: The worked-example and faded-example stages are not part of the app, lesson quizzes are drawn from existing questions, and every skill works without extra content. +**Migration**: Use Requirement: Content gaps are listed. + +## ADDED Requirements + +### Requirement: Bank checked at start +The server SHALL check the bank when it starts: unique ids, one correct choice per question, and every mistake and skill referred to exists. A broken bank SHALL stop the server from starting and say what is wrong. + +#### Scenario: Unknown mistake +- **WHEN** a choice points to a mistake id that does not exist +- **THEN** the server does not start and names the question and the id + +### Requirement: No answers on the device +A practice, quiz or test question sent to the device MUST NOT carry any sign of which choice is correct. The server SHALL grade. + +#### Scenario: Reading the network +- **WHEN** a student looks at the question the device received +- **THEN** nothing in it marks the correct choice + +### Requirement: Content gaps are listed +A tool SHALL list what the bank still lacks: skills without a solved example, skills without questions or with few, and mistakes without a skill to go back to. + +#### Scenario: Skill without questions +- **WHEN** the tool runs on the current bank +- **THEN** it lists the skill that has no multiple-choice question diff --git a/openspec/changes/archive/2026-11-08-rebuild-foundation/tasks.md b/openspec/changes/archive/2026-11-08-rebuild-foundation/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..d5a6f347fdfb57f3537d839e768d94e135b46829 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-rebuild-foundation/tasks.md @@ -0,0 +1,51 @@ +# Tasks + +## 1. Roles and permissions + +- [x] 1.1 Add `DEVELOPER_EMAILS` and `ADMIN_EMAILS` to `config.py`, `.env.example` and the README; verify config tests read them from the environment and from `mathly2/.env` +- [x] 1.2 Add `access.py` with the permission matrix and `need(permission)` (design decision 2); verify unit tests for each role's permissions, and that a developer has every permission +- [x] 1.3 Resolve roles per request from the settings, `m2_roles` and class teachers, with a 30-second cache (decision 1); verify tests for a settings developer, a class teacher not in any setting, a role given in the table, several roles at once, and a plain student + +## 2. Storage + +- [x] 2.1 Add the migration for `m2_roles`, the new `m2_classes` columns and check, the case-insensitive unique name, and the (class_id, email) key (decision 3); verify a pgserver test applies all migrations, a student can join two classes, a teacher listed as a student is refused, and browser roles are refused +- [x] 2.2 Add role and class methods to `InMemoryStore` (roles by email, give, take with the last-admin guard, classes with lessons and AI fields, students in several classes, known accounts); verify unit tests for each +- [x] 2.3 Add the same methods to `SupabaseStore`; verify request tests with the faked PostgREST, including the one-step last-admin guard + +## 3. API + +- [x] 3.1 Extend `GET /api/me` with roles, permissions and classes as student and as teacher; verify tests for each role and for a person with several roles +- [x] 3.2 Move class creation, editing and deletion to the manager (`/api/classes`), with lessons, teacher, AI switch and budget; verify tests that a manager can and a teacher cannot, that names are unique ignoring case, and that deleting keeps progress +- [x] 3.3 Add the roster routes for a class's teacher or a manager (`/api/classes/{id}/students`); verify tests for pasting, invalid addresses, a student in two classes, removing, and a teacher of another class refused +- [x] 3.4 Add `GET /api/teaching` and `GET /api/students`; verify tests for a teacher of two classes and the manager's list showing a student's two classes +- [x] 3.5 Add the admin routes (`/api/accounts`, give and take a role); verify tests for a role given before first sign-in, the developer role refused, and the last admin unable to remove themselves +- [x] 3.6 Add a test that reads every route and checks each refuses the roles outside its permission (spec: Permissions per role); verify it passes and the "no content before sign-in" test still passes + +## 4. Screens + +- [x] 4.1 Replace the color tokens in `app.css` with the `--sky-*` tokens (one dark set), the owl SVG and one reduced-motion rule, and the sky background of two glows and small stars (decision 6); verify a Playwright test that the background is dark even when the device asks for light mode and that nothing animates under reduced motion +- [x] 4.2 Rebuild the sign-in page as mathly1's (logo, owl, status line, one Google button; the dev sign-in when Supabase is not set), with the "could not connect, try again" state; verify Playwright tests for the page and for the failure state +- [x] 4.3 Add the role switcher in the header for people with several roles, remembering the last choice; verify a Playwright test with a manager who is also a teacher +- [x] 4.4 Build the manager's screens: class list, class editor (name, lessons, teacher, students, AI switch, budget) and students list; verify Playwright tests at 390px and 1280px that create, edit and delete a class with no sideways scrolling +- [x] 4.5 Build the teacher's home: classes taught, each with its students, adding and removing students; verify a Playwright test that a teacher adds 3 emails and removes one, and cannot reach the class editor +- [x] 4.6 Build the admin's accounts screen and every account's own-access page; verify Playwright tests for giving the manager role to a new email and for the last-admin message + +## 5. Exercise bank + +- [x] 5.1 Update `scripts/content_gaps.py` to list skills without a solved example, skills without or with few questions, and mistakes without a skill to go back to; verify its tests on the real bank (96 without a solved example, 1 without questions, 204 mistakes without one) + +## 6. Integration + +- [x] 6.1 Walk the roles end to end in a browser test: an admin gives the manager role, the manager creates a class with a teacher and two students, the teacher adds a third, a student signs in and sees their lessons; verify the test passes +- [x] 6.2 Run `venv/bin/python -m pytest mathly2/tests` and `openspec validate rebuild-foundation --strict`; verify both pass + +## 7. Found while using it (decisions 7 to 10) + +- [x] 7.1 Read the repository's `.env` after the app's own (`config.py`), keeping the environment first; verify config tests for the order and for a test file being read alone, and that the whole suite stays independent of real keys +- [x] 7.2 Keep what was typed when a class save is refused and show the reason above the save buttons, scrolled into view; verify a Playwright test that a student named as teacher is refused in view, keeps the typed values, and saves after the fix +- [x] 7.3 Report database refusals that are not conflicts as a 503 with a clear message and a log line, and read the database's error body once; verify store tests for refusals other than 409 and an API test for the 503 +- [x] 7.4 Keep the address on the first screen after sign-in and clear it only when the role is switched; verify a Playwright test that a link and a reload land on the collection and a role switch clears the address + +## Workflow follow-up + +- Archive this change once it is reviewed, so `accounts-and-classes`, `app-basics` and `exercise-bank` carry the new requirements; then propose `add-learning-core` in full (design and tasks). diff --git a/openspec/changes/archive/2026-11-08-serve-fresh-files/.openspec.yaml b/openspec/changes/archive/2026-11-08-serve-fresh-files/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/archive/2026-11-08-serve-fresh-files/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/archive/2026-11-08-serve-fresh-files/proposal.md b/openspec/changes/archive/2026-11-08-serve-fresh-files/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..e870fd3d95f1f280584ea9d00b207df062732265 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-serve-fresh-files/proposal.md @@ -0,0 +1,23 @@ +# Proposal + +## Why + +After an update, a browser can keep showing the app's old look: the server sends its page, styles and scripts with no caching instruction, so the browser may reuse a saved copy without asking. This happened with the always-dark sky (a white background until a forced reload), and it would happen to students' phones after every update. + +## What Changes + +- The server tells the browser to check with it before reusing the app page and its files (`Cache-Control: no-cache`), so an unchanged file still comes from the cache (the server answers "not modified") and a changed one is fetched. +- The page declares mathly1's icon, so the tab shows it and the browser's request for a missing `/favicon.ico` (an error in the console) stops. +- Two new requirements in `app-basics`. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `app-basics`: adds "Updates reach every device" and "The app's icon". + +## Impact + +- `mathly2/main.py` (the page and `/static`); the API routes are unchanged. +- PRD 7.3 notes for the build gets one line. diff --git a/openspec/changes/archive/2026-11-08-serve-fresh-files/specs/app-basics/spec.md b/openspec/changes/archive/2026-11-08-serve-fresh-files/specs/app-basics/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..217b17b6355e12aee187f390b8774c77680612d8 --- /dev/null +++ b/openspec/changes/archive/2026-11-08-serve-fresh-files/specs/app-basics/spec.md @@ -0,0 +1,19 @@ +## ADDED Requirements + +### Requirement: Updates reach every device +After the app is updated, every device SHALL get the new page, styles and scripts the next time it opens the app, without the user clearing a cache. A file that did not change MAY still come from the device's cache once the server confirms it is unchanged. + +#### Scenario: New look after an update +- **WHEN** the styles change on the server and a student who used the app before opens it again +- **THEN** the student sees the new styles without a forced reload + +#### Scenario: Unchanged files +- **WHEN** a device asks again for a file that did not change +- **THEN** the server answers that it is unchanged and the device uses its saved copy + +### Requirement: The app's icon +The app SHALL declare its icon (mathly1's, from `static/icons/`), so the browser tab shows it and the browser does not ask for a missing icon. + +#### Scenario: Opening the app +- **WHEN** someone opens the app +- **THEN** the tab shows the app's icon and no request for an icon fails diff --git a/openspec/changes/archive/2026-11-08-serve-fresh-files/tasks.md b/openspec/changes/archive/2026-11-08-serve-fresh-files/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..1c959063b191c2bd351eba87428e6045816c018d --- /dev/null +++ b/openspec/changes/archive/2026-11-08-serve-fresh-files/tasks.md @@ -0,0 +1,7 @@ +# Tasks + +## 1. Fresh files + +- [x] 1.1 Send `Cache-Control: no-cache` with the app page and every file under `/static`, keeping the ETag; verify tests that the page and a static file carry the header, that a repeat request with the file's ETag gets 304, and that the API routes are unchanged +- [x] 1.3 Copy mathly1's `static/icons/` into `mathly2/static/icons/` unchanged and link `icon-192.png` from the page; verify a Playwright test that the page loads with no failed request and no console error, and that the icon file is served +- [x] 1.2 Add the line to the PRD's notes for the build; verify `openspec validate serve-fresh-files --strict` and the mathly2 tests pass diff --git a/openspec/changes/build-assignments/proposal.md b/openspec/changes/build-assignments/proposal.md deleted file mode 100644 index 35bdbaf851f758a97e35ecffaef262b4ba362677..0000000000000000000000000000000000000000 --- a/openspec/changes/build-assignments/proposal.md +++ /dev/null @@ -1,24 +0,0 @@ -# Proposal - -## Why - -Teachers need to give work from the material they already have and check it (see `docs/tasks/prd-mathly.md`, 4.8). Students need to hand in full written solutions. - -## What Changes - -- Teachers create assignments from a file, a camera photo or the drawing board. -- Students hand in their solutions, including on the drawing board. -- Teachers grade from 0 to 100 with a note, or send work back for correction. -- The drawing board is copied from the current app. - -## Capabilities - -### New Capabilities -- `assignments`: creating, handing in and checking assignments. -- `drawing-board`: solving on the board and handing in the board, using the board kept from the current app. - -### Modified Capabilities - -## Impact - -- Builds on `build-foundation`. Adds assignment and submission tables and file storage in `mathly2/`. Copies `math-board.js`, `board-math.js` and `vendor/mathlive/`. diff --git a/openspec/changes/build-assignments/specs/assignments/spec.md b/openspec/changes/build-assignments/specs/assignments/spec.md deleted file mode 100644 index 5fd472a24844f2cb256477999cf5196886fa5916..0000000000000000000000000000000000000000 --- a/openspec/changes/build-assignments/specs/assignments/spec.md +++ /dev/null @@ -1,36 +0,0 @@ -# Spec Delta - -## Purpose - -Lets the teacher give assignments from a file, a photo or the drawing board, and check what students hand in with a grade and feedback. - -## ADDED Requirements - -### Requirement: Create an assignment -The teacher SHALL be able to create an assignment with a title, a note and a due date, and load its content from a file upload (PDF or images), a photo taken with the device camera, or the drawing board, where what the teacher writes is saved as the assignment's pages. - -#### Scenario: From a PDF -- **WHEN** a teacher creates an assignment and uploads a PDF -- **THEN** students see the assignment with the PDF's pages - -#### Scenario: From the board -- **WHEN** a teacher writes an assignment on the drawing board and saves it -- **THEN** the board is saved as the assignment's page - -### Requirement: Students hand in assignments -Assignments SHALL appear in the student's "המשימות שלי", and the student SHALL be able to hand in their solution, including on the drawing board. - -#### Scenario: Handing in -- **WHEN** a student solves an assignment on the board and hands it in -- **THEN** the teacher sees the submission - -### Requirement: Check assignments -The teacher SHALL be able to open each student's submission and give a grade from 0 to 100 and a note, or send it back for correction. - -#### Scenario: Grading -- **WHEN** a teacher gives a submission 88 with a note -- **THEN** the student sees 88 and the note, and the grade appears on their grades screen - -#### Scenario: Send back -- **WHEN** a teacher sends a submission back for correction -- **THEN** the student can hand in the assignment again diff --git a/openspec/changes/build-assignments/specs/drawing-board/spec.md b/openspec/changes/build-assignments/specs/drawing-board/spec.md deleted file mode 100644 index a019dff2fad8ef79ad5ec10c7b87f2941b9f575e..0000000000000000000000000000000000000000 --- a/openspec/changes/build-assignments/specs/drawing-board/spec.md +++ /dev/null @@ -1,21 +0,0 @@ -# Spec Delta - -## Purpose - -Lets students write full solutions, and teachers write assignments, on the existing drawing board, and hand in the board as a picture. - -## ADDED Requirements - -### Requirement: Solve on the board -Wherever a question needs a written solution (open questions and assignments), the student SHALL be able to solve it on the drawing board and hand in the board as their answer. - -#### Scenario: Open question -- **WHEN** a student solves an open quiz question on the board and hands it in -- **THEN** the board is saved as a picture and submitted as the answer - -### Requirement: Board is kept from the current app -The drawing board, including typed math on the board and the math keyboard, SHALL be the one kept from the current app rather than rebuilt. - -#### Scenario: Typed math -- **WHEN** a student types math on the board -- **THEN** the board's math keyboard is offered and the math is rendered on the board diff --git a/openspec/changes/build-class-progress-views/proposal.md b/openspec/changes/build-class-progress-views/proposal.md deleted file mode 100644 index 4155e1f66bc69bc1db7f252e77f3704bfda8b52a..0000000000000000000000000000000000000000 --- a/openspec/changes/build-class-progress-views/proposal.md +++ /dev/null @@ -1,22 +0,0 @@ -# Proposal - -## Why - -Teachers need a per-student picture of which skills and lessons each student has covered (see `docs/tasks/prd-mathly.md`, 4.8). - -## What Changes - -- A class heat map of skill states per student, readable without relying on color. -- A lesson coverage table: % mastered and best quiz grade per student and lesson. -- Period tabs (Sep–Dec, Jan–Jun), showing states as of the end of each period. - -## Capabilities - -### New Capabilities -- `class-progress-views`: the heat map, lesson coverage and period tabs. - -### Modified Capabilities - -## Impact - -- Builds on `build-skill-learning` (skill states and answer dates) and `build-lesson-quizzes` (best quiz grades). diff --git a/openspec/changes/build-class-progress-views/specs/class-progress-views/spec.md b/openspec/changes/build-class-progress-views/specs/class-progress-views/spec.md deleted file mode 100644 index 07ef85f1cd9890adc9ca141752b7e42fba91ce2a..0000000000000000000000000000000000000000 --- a/openspec/changes/build-class-progress-views/specs/class-progress-views/spec.md +++ /dev/null @@ -1,35 +0,0 @@ -# Spec Delta - -## Purpose - -Gives the teacher a per-student picture of the class: a heat map of skill states and a table of lesson coverage, each by school period. - -## ADDED Requirements - -### Requirement: Class heat map -The teacher SHALL see a heat map with a row per student and a column per skill, grouped by lesson. Each cell SHALL be colored by the skill state and also show a symbol or text, so it does not rely on color alone and reads in light and dark mode. - -#### Scenario: Reading a cell -- **WHEN** a student is "learning" a skill -- **THEN** that cell has the learning color and the learning symbol - -### Requirement: Lesson coverage -The teacher SHALL see a table with a row per student and a column per lesson. Each cell SHALL show the percentage of the lesson's skills the student mastered and their best quiz grade for that lesson. - -#### Scenario: Coverage cell -- **WHEN** a student mastered 3 of 4 skills of a lesson and their best quiz grade is 80 -- **THEN** the cell shows 75% and 80 - -### Requirement: Period tabs -Both views SHALL have period tabs "Sep–Dec" and "Jan–Jun". A period SHALL show the skills or lessons taught in it, with states as they were at the end of the period, or today for the current period. - -#### Scenario: Past period -- **WHEN** in February a teacher opens the "Sep–Dec" tab -- **THEN** it shows the lessons taught September to December, with states as of the end of December - -### Requirement: Works on a computer -The heat map and coverage views SHALL work well on a computer screen as well as on a phone. - -#### Scenario: Wide class -- **WHEN** a teacher opens the heat map of 30 students on a laptop -- **THEN** all rows and the lesson-grouped skill columns can be read and scrolled diff --git a/openspec/changes/build-lesson-quizzes/proposal.md b/openspec/changes/build-lesson-quizzes/proposal.md deleted file mode 100644 index d5cca9c2b805db51cb43c9793fe63f5455a11030..0000000000000000000000000000000000000000 --- a/openspec/changes/build-lesson-quizzes/proposal.md +++ /dev/null @@ -1,23 +0,0 @@ -# Proposal - -## Why - -Each lesson needs a grade that reflects what the student knows now, and a way to improve it (see `docs/tasks/prd-mathly.md`, 4.2). - -## What Changes - -- One retakeable quiz (בוחן) per lesson. Each retake draws new questions, and the best grade is the lesson's grade. -- After a quiz, the skills where points were lost are listed. -- Grades are computed and stored on the server. -- Quizzes are added to the bank for the 20 lessons that lack one. - -## Capabilities - -### New Capabilities -- `lesson-quizzes`: the quiz per lesson, retakes, best grade, and skills to practise. - -### Modified Capabilities - -## Impact - -- Builds on `build-foundation` and `build-skill-learning` (skill states and the path). Adds quiz attempt tables in `mathly2/`. diff --git a/openspec/changes/build-lesson-quizzes/specs/lesson-quizzes/spec.md b/openspec/changes/build-lesson-quizzes/specs/lesson-quizzes/spec.md deleted file mode 100644 index 828e1166bbc22f6452857304a4d5cf2efbbb8619..0000000000000000000000000000000000000000 --- a/openspec/changes/build-lesson-quizzes/specs/lesson-quizzes/spec.md +++ /dev/null @@ -1,42 +0,0 @@ -# Spec Delta - -## Purpose - -Gives every lesson a retakeable quiz (בוחן) whose best grade is the lesson's grade, and points the student to the skills to practise before retaking it. - -## ADDED Requirements - -### Requirement: Quiz per lesson -Each lesson SHALL have a quiz on that lesson. It SHALL be the only quiz type; there MUST NOT be a one-time summary quiz. - -#### Scenario: Opening a lesson's quiz -- **WHEN** a student opens the quiz of טכניקה אלגברית 1 -- **THEN** its questions are on that lesson's skills - -### Requirement: Retakes draw new questions -The student SHALL be able to retake a quiz any number of times. Each retake SHALL draw new questions. - -#### Scenario: Second attempt -- **WHEN** a student retakes a lesson's quiz -- **THEN** the questions are drawn anew rather than repeating the previous attempt's set - -### Requirement: Best grade is the lesson's grade -The quiz grade that counts SHALL be the student's best grade across attempts, and it SHALL be the lesson's grade. - -#### Scenario: Lower retake -- **WHEN** a student got 85 and then 70 on a lesson's quiz -- **THEN** the lesson's grade is 85 - -### Requirement: Skills to practise after a quiz -After a quiz, the system SHALL list the skills where the student lost points, so they can practise them before retaking. - -#### Scenario: Lost points -- **WHEN** a student loses points on questions of 2 skills -- **THEN** the result lists those 2 skills - -### Requirement: Quiz grades kept on the server -Quiz grades SHALL be computed and stored on the server, so a student cannot change them from the device. - -#### Scenario: Handing in -- **WHEN** a student hands in a quiz -- **THEN** the server computes and stores the grade diff --git a/openspec/changes/build-skill-learning/design.md b/openspec/changes/build-skill-learning/design.md deleted file mode 100644 index ca99be39a840343e61c92777834b500ccbe72ea5..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/design.md +++ /dev/null @@ -1,199 +0,0 @@ -# Design - -UI sketch: [static mockup](./mockups/skill-learning.html). It predates decision 4: its faded-example screen shows typed boxes, while the design uses multiple-choice steps. - -## Context - -See proposal.md for why. Current state in `mathly2/` after `build-foundation`: - -- `bank.py` loads and checks `content/math_algebra9.json`. `GET /api/lessons` serves lessons and skills without questions. -- `store.py` has `InMemoryStore` (tests, local development) and `SupabaseStore` (PostgREST, secret key) with the same methods. Tables are `m2_*`, row-level security on, no browser grants. -- `clock.school_day()` gives the calendar day in Asia/Jerusalem. It was built for the mastery rule. -- `static/student.js` only lists lessons. Screens are plain ES modules that render HTML strings into `#app`. - -Facts about the bank that shape this design: - -| Fact | Consequence | -|---|---| -| 96 skills, 1,050 questions, median 10 per skill. `a_30_side` has none. | Enough for "a different question". One skill cannot be practised yet. | -| Questions have no id. Within a skill, no two are fully identical (10 share the same text but differ in figure or choices). | A key must be derived (decision 3). | -| 410 questions have a `figure` (geometry text such as `A=0,2; ... poly A B C D`) and 53 have a `graph` (points and axis ranges), across 48 skills. | Practice must draw them (decision 9). | -| Every wrong choice has a `mistake`. Only 40 of 244 mistakes have a `back` skill. | Feedback can always name the mistake. A "go back to" link is shown only when `back` exists. | -| No skill has `worked_example` or `faded_examples`. `scripts/content_gaps.py` already looks for those two field names. | The new content uses those names (decision 4). Stages without content are skipped (spec). | - -## Goals / Non-Goals - -**Goals:** -- Every rule that counts for mastery is decided on the server from rows it wrote itself: correctness, the date, whether help was opened. -- The whole path works today with the bank as it is. Examples are added skill by skill without code changes. -- One code path for both stores, so every rule is tested on `InMemoryStore` and runs the same on Supabase. - -**Non-Goals:** -- Writing the 96 skills' examples. This change defines their shape, checks them, and ports the drafting tool. Teachers write and approve the content. -- Anti-cheating beyond the server owning the rules. A student can still look answers up elsewhere. -- Quizzes, exercise tests and teacher views. They read the skill states this change produces (later changes). - -## Decisions - -### 1. Two new tables: an answer log and a per-skill progress row - -```mermaid -erDiagram - m2_class_members ||--o{ m2_answers : "user_id" - m2_class_members ||--o{ m2_skill_progress : "user_id" - m2_answers { - bigint id PK - uuid user_id - text skill_id - text question_key - bool correct - bool counted "false when help was opened" - text mistake_id "null when correct" - date day "school_day() at answer time" - timestamptz answered_at "default now()" - } - m2_skill_progress { - uuid user_id PK - text skill_id PK - text stage "example | faded | practice" - int faded_done - text current_key "question being shown" - bool current_helped - timestamptz started_at "first answer of any kind" - timestamptz mastered_at "set once, never cleared" - } -``` - -A view `m2_daily_correct (user_id, day, correct)` counts correct practice answers per day for the goal and streak. - -- `m2_answers` is append-only. It is the evidence for mastery and later for weak skills, quizzes and the heat map. -- `m2_skill_progress` holds what the server must remember between requests: the stage, the question on screen, whether help was opened for it, and `mastered_at`. -- *Alternative:* derive everything from the log on every read. Rejected: the path screen would scan every answer for 96 skills, and "question on screen + help opened" is not an answer at all. - -### 2. Mastery is stored once, when the rule is first met - -After each counted practice answer the server reads the student's last 3 counted answers on that skill. If all 3 are correct and they fall on 2 or more distinct `day` values, it sets `mastered_at` if it is still null. Nothing ever clears it. - -```mermaid -stateDiagram-v2 - [*] --> NotStarted - NotStarted --> Learning: first answer of any kind - Learning --> Learning: answer, rule not met - Learning --> Mastered: last 3 counted answers correct, on 2+ days - Mastered --> Mastered: any later answer -``` - -- State is derived from the progress row: no row or no `started_at` means not started; `mastered_at` set means mastered; anything else means learning. -- "First answer of any kind" includes "why this step?" and faded steps, so a student working through the example sees "learning". Only practice answers count for mastery. -- "Counted" means no help was opened for that question. Uncounted answers are skipped: they neither extend nor break the run (spec: Help between correct answers). -- *Alternative:* recompute mastery on every read. Rejected: mastery must never decay, and a stored timestamp also gives the collection screen and the later period views "mastered as of a date" for free. - -### 3. Question key = skill id + hash of the question - -`question_key = f"{skill_id}:{sha1(canonical JSON of the question)[:10]}"`. - -- Stable when questions are reordered or added. Editing a question gives it a new key, which is right: it is a different question. -- `check_bank` rejects two questions with the same key in one skill. -- *Alternative:* skill id + index. Rejected: inserting a question would silently re-key every answer after it. - -### 4. Shape of worked and faded examples, with multiple-choice steps - -```json -"worked_example": { - "question": "$x^2 + 5x + 6$", - "steps": [ - {"do": "two numbers: product 6, sum 5 -> 2 and 3", - "why": [{"text": "...", "correct": true}, {"text": "..."}, {"text": "..."}]} - ], - "answer": "$(x+2)(x+3)$" -}, -"faded_examples": [ - {"question": "...", - "steps": [{"do": "...", "choices": [{"text": "...", "correct": true}, {"text": "...", "mistake": "sign_mid"}]}], - "answer": "..."} -] -``` - -- A missing faded step is filled in by choosing among options. A wrong option names its mistake, reusing the bank's `mistakes`. *Alternative:* typed math. Rejected for now: it needs a math answer checker, and the spec only requires that the student fill the step and get feedback. -- Each skill has **2 faded examples**: the first hides its last step, the second its last 2 steps. Fading goes backwards, so the student first finishes a solution and then starts one. Backward fading is the variant with the stronger research support. A faded example therefore needs at least 2 steps, and the second needs one step more than it hides, so the student never faces an empty solution. -- `check_bank` checks the shape when present: exactly 2 faded examples, the first with at least 2 steps and the second with at least 3, exactly one correct `why` and one correct choice per step, mistake ids exist. - -### 5. Teaching stages are checked in the browser; practice on the server - -```mermaid -flowchart LR - open[Open skill] --> hasW{worked_example?} - hasW -- yes --> W[1 Worked example] - hasW -- no --> hasF - W --> hasF{faded_examples?} - hasF -- yes --> F[2 Faded examples] - hasF -- no --> P - F --> P[3 Practice] - P -- wrong --> FB[4 Mistake name + tip] --> P - P -- correct --> M{mastery rule?} - M -- met --> done[Mastered] - M -- not yet --> P -``` - -- Worked and faded examples are sent whole, including which choice is right, and checked in the browser for instant feedback. They are teaching material and do not count for mastery. The browser reports progress (`stage done`, `faded k done`) so the server can resume and mark the skill as started. -- Practice questions are sent **without** `correct` or `mistake`. Choices carry their original index, and the browser may shuffle them for display. The server grades by index. - -### 6. Practice API and one answer, end to end - -| Endpoint | Purpose | -|---|---| -| `GET /api/path` | All lessons and skills with state, today's correct count and the streak | -| `GET /api/skills/{id}` | Stage, worked and faded examples (if any), and the current practice question | -| `POST /api/skills/{id}/stage` | Browser reports a finished stage or faded example | -| `POST /api/skills/{id}/help` | Marks the question on screen as helped | -| `POST /api/skills/{id}/answer` | `{question_key, choice}` -> result, feedback, next question, new state | -| `GET /api/collection` | Mastered skills and completed lessons | - -```mermaid -sequenceDiagram - participant B as Browser - participant S as Server - participant DB as Store - B->>S: POST /api/skills/t_ext/answer {question_key, choice} - S->>DB: progress(user, skill) - S->>S: reject if question_key != current_key (stale tab) - S->>S: grade from bank, day = school_day() - S->>DB: insert m2_answers (counted = not current_helped) - S->>DB: last 3 counted answers - S->>S: mastery rule -> maybe set mastered_at - S->>S: pick next question (decision 7) - S->>DB: update progress (current_key, current_helped=false, mastered_at) - S-->>B: correct?, mistake {name, tip, back}, next question, state -``` - -- The answer must match `current_key`, so a second tab or a replayed request cannot answer a question that is not on screen. -- On a wrong answer the response has the mistake's name and tip and never the correct choice. - -### 7. Next question: least seen, never the one just answered - -Pick at random among the skill's questions with the fewest past answers by this student, excluding the question just answered. With about 10 questions per skill, a student meets every question before any repeats. A skill with one question repeats it, and a skill with none shows "no practice yet" and cannot be mastered. - -### 8. Daily goal and streak from the view - -Today's goal = correct practice answers on `school_day()`. The streak = consecutive days with at least 5, ending today, or ending yesterday when today is not yet at 5, so the streak is not shown as lost in the morning. Helped answers count toward the goal: it measures effort, not mastery. - -### 9. Draw figures and graphs by porting the old renderer - -Copy the `figure` (geometry) and `plot` (graph) drawing functions from the old `static/math.js` into `mathly2/static/figures.js`, with a Playwright check that one of each draws. This follows the precedent of `math-tex.js` in build-foundation: it is part of showing the exercise bank, not the old app's behaviour. *Alternative:* skip figure questions. Rejected: that removes most practice from 48 skills. - -### 10. Drafting tool ported, not run - -`scripts/draft_examples.py` moves to `mathly2/scripts/` and is changed to produce the decision 4 shape (multiple-choice `why`, faded examples with choices). Its review-file flow (draft -> teacher approves -> merge) stays. Running it spends API money and needs a teacher, so it is a tool in this change, not a task. - -## Risks / Trade-offs - -- [Teaching-stage answers are checked in the browser, so a student can see the right "why" choice in the network tab] -> Accepted: they do not count for anything, and instant feedback matters more there. -- [Help is reported by the browser through `/help`. A modified client could skip the call and get a "counted" answer] -> Accepted for now: the student would also need 3 correct on 2 days. The same holds for any client-side app, and the alternative (serving help only from the server) is what `/help` already does for the honest client. -- [Editing a question gives it a new key, so its old answers stop matching it] -> Intended. Mastery and the log are by skill, so nothing is lost. -- [Students mastering one skill with 0 or 1 question] -> `a_30_side` cannot be mastered until it gets questions. `content_gaps.py` already lists it. -- [The ported figure renderer drags old-app code in] -> Copy only the two drawing functions and what they need, with their own tests. - -## Migration Plan - -- One additive migration: `m2_answers`, `m2_skill_progress`, the `m2_daily_correct` view. Row-level security on, no browser grants, as in `m2_classes`. Rollback: drop the three objects. Nothing else reads them yet. -- The bank file gains optional fields only, so the current bank still loads. diff --git a/openspec/changes/build-skill-learning/mockups/skill-learning.html b/openspec/changes/build-skill-learning/mockups/skill-learning.html deleted file mode 100644 index f86648cc968ff4eb0fd9930c3cc8061368553eda..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/mockups/skill-learning.html +++ /dev/null @@ -1,189 +0,0 @@ - - - - - -Mathly - skill learning mockup - - - -
    -

    Mathly - skill learning (static mockup)

    -

    Illustrates the draft specs in openspec/changes/build-skill-learning. Not the real app: fixed sample data, no server.

    -
    - - -
    - - -
    -

    המסלול שלי

    -

    כל השיעורים פתוחים, בכל סדר

    -
    -
    יעד יומי: 3 מתוך 5
    -
    🔥 רצף: 4 ימים
    -
    -
    טכניקה אלגברית 1
    - - - -
    משוואות ריבועיות
    - -

    Every skill shows state as text + symbol, not colour alone.

    -
    - - -
    -

    פירוק טרינום

    -
    1 דוגמה2 השלמה3 תרגול
    -
    x² + 5x + 6 = ?
    -
    שלב 1Find two numbers: product 6, sum 5 → 2 and 3
    -

    למה עושים את השלב הזה?

    - - - -
    -

    The next step appears only after "why this step?" is answered.

    -
    - - -
    -

    פירוק טרינום

    -
    1 דוגמה2 השלמה3 תרגול
    -

    דוגמה 2 מתוך 3 - חסרים 2 שלבים

    -
    x² + 7x + 12
    -
    Step 1: product 12, sum 7 → 3 and 4 ✓
    -
    Step 2: ( x + __ )( x + __ ) -
    -
    -
    Step 3: ____
    -
    -

    Help fades: example 1 = 1 gap, example 2 = 2 gaps, ...

    -
    - - -
    -

    חוק הפילוג המורחב

    -
    1 דוגמה2 השלמה3 תרגול
    -
    (x + 3)(x − 5) = ?
    - - - - -
    -
    - - -
    -
    נכונות ברצף:  (ביום אחר יהפוך לנשלטה)
    -

    Wrong answers name the mistake (from the bank) and never reveal the correct one.

    -
    - - -
    -

    האוסף שלי

    -

    מה השגתי

    -
    מיומנויות שנשלטו (1)
    -
    ✓ חוק הפילוג המורחב
    -
    שיעורים שהושלמו (0)
    -
    עדיין אין - נשלוט בכל מיומנויות השיעור
    -
    - -
    - - - - diff --git a/openspec/changes/build-skill-learning/proposal.md b/openspec/changes/build-skill-learning/proposal.md deleted file mode 100644 index 212331e5e5eb7fa26fafadcf0377f75989b28ca4..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/proposal.md +++ /dev/null @@ -1,27 +0,0 @@ -# Proposal - -## Why - -Students often finish a topic without mastering it (see `docs/tasks/prd-mathly.md`). The path teaches each skill step by step and proves mastery instead of assuming it. - -## What Changes - -- Each skill teaches in four stages: a worked example with "why this step?", faded examples, practice, and feedback that names the mistake and gives a similar question. -- Mastery: 3 correct in a row, first try, no help, over 2 calendar days, checked on the server. Mastery never decays. -- A path screen with every lesson open, a daily goal and streak, and a collection screen. -- Worked examples, faded examples and "why this step?" choices are added to the bank, skill by skill. A stage with no content is skipped, so every skill works through practice from day one. - -UI sketch: [static mockup](./mockups/skill-learning.html) (path, worked example, faded example, practice, collection). - -## Capabilities - -### New Capabilities -- `skill-learning`: the four stages of learning a skill. -- `skill-mastery`: the mastery rule and skill states. -- `learning-path`: lessons open in any order, the path screen, daily goal and streak, collection. - -### Modified Capabilities - -## Impact - -- Builds on `build-foundation`. Adds answer storage (`m2_` tables) and student screens in `mathly2/`. diff --git a/openspec/changes/build-skill-learning/specs/learning-path/spec.md b/openspec/changes/build-skill-learning/specs/learning-path/spec.md deleted file mode 100644 index 45e8cf0c2b12751e8fdbff321373c3ab9b96f518..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/specs/learning-path/spec.md +++ /dev/null @@ -1,39 +0,0 @@ -# Spec Delta - -## Purpose - -Gives the student a self-paced path through every lesson (שיעור) and skill, open in any order, with a daily goal and streak and a collection of what they achieved. - -## ADDED Requirements - -### Requirement: All lessons open -The student SHALL be able to open any lesson, and any skill inside it, at any time and in any order. Lessons MUST NOT be locked, and the app MUST NOT force an order. - -#### Scenario: Jumping ahead -- **WHEN** a student who has not started the first lesson opens a skill in a later lesson -- **THEN** the skill opens at its first stage - -### Requirement: Path screen -The path screen SHALL list all lessons and their skills, each skill showing its state (not started, learning or mastered). Mastered skills SHALL look clearly different from learning and not-started ones. - -#### Scenario: Viewing the path -- **WHEN** a student opens the path -- **THEN** every lesson is listed with its skills, and each skill shows its state - -### Requirement: Daily goal and streak -A day with 5 correct answers SHALL count toward the student's streak. The path SHALL show the day's progress toward 5 and the current streak. - -#### Scenario: Goal reached -- **WHEN** a student answers a fifth question correctly today -- **THEN** today's goal is shown as reached and the streak counts today - -#### Scenario: Goal missed -- **WHEN** a student has 3 correct answers today -- **THEN** today's goal shows 3 of 5 and today does not yet count toward the streak - -### Requirement: Collection screen -The student SHALL have a collection screen that shows each skill they mastered and each lesson they completed. - -#### Scenario: New mastery -- **WHEN** a student masters a skill -- **THEN** the skill appears on their collection screen diff --git a/openspec/changes/build-skill-learning/specs/skill-learning/spec.md b/openspec/changes/build-skill-learning/specs/skill-learning/spec.md deleted file mode 100644 index b591cf1ac010126b9755dce4e7a3037d8d000196..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/specs/skill-learning/spec.md +++ /dev/null @@ -1,57 +0,0 @@ -# Spec Delta - -## Purpose - -Teaches each skill (מיומנות) through four stages in a fixed order: a worked example, faded examples, practice, and feedback that names the student's mistake, so the student learns to solve alone. - -## ADDED Requirements - -### Requirement: Worked example with "why this step?" -The system SHALL start a skill with a fully solved example shown one step at a time. After each step, the system SHALL ask the student "why this step?" as a multiple-choice question before revealing the next step. - -#### Scenario: Stepping through the example -- **WHEN** a student opens the worked example of פירוק טרינום and sees its first step -- **THEN** a "why this step?" multiple-choice question is shown, and the second step appears only after the student answers it - -### Requirement: Faded examples -After the worked example, the system SHALL show solved examples with steps removed: first one step missing, then two, and so on. The student SHALL fill in each missing step. A wrong step SHALL get immediate feedback on the mistake. - -#### Scenario: Help fades -- **WHEN** the student finishes the faded example with one missing step -- **THEN** the next faded example has two missing steps - -#### Scenario: Wrong step -- **WHEN** the student fills in a missing step wrongly -- **THEN** feedback on the mistake is shown right away - -### Requirement: Stages without content are skipped -The system SHALL skip a stage for a skill whose bank entry has no content for it: no worked example skips stage 1, and no faded examples skips stage 2. A skill MUST always be learnable through practice, so a missing example MUST NOT block it. - -#### Scenario: Skill with no examples -- **WHEN** a student opens a skill that has no worked example and no faded examples -- **THEN** the skill opens directly at the practice stage - -#### Scenario: Worked example but no faded examples -- **WHEN** a student finishes the worked example of a skill that has no faded examples -- **THEN** the skill moves to the practice stage - -### Requirement: Practice from the exercise bank -After the faded examples, the system SHALL give the student practice questions on the skill, taken from the exercise bank. - -#### Scenario: Practice questions -- **WHEN** the student reaches the practice stage of a skill -- **THEN** the questions shown are exercise-bank questions of that skill - -### Requirement: Feedback names the mistake -After a wrong answer in practice, the system SHALL show the name and tip of the mistake attached to the chosen wrong answer in the exercise bank. It MUST NOT reveal the correct answer. - -#### Scenario: Wrong choice with a mistake -- **WHEN** a student picks a wrong choice tagged with the mistake "טעות סימן באיבר האמצעי" -- **THEN** the mistake's name and tip are shown, and the correct choice is not marked - -### Requirement: Similar question after a mistake -After a wrong answer in practice, the system SHALL give the student a similar question: the same skill, a different question. It MUST NOT give the same question again. - -#### Scenario: Next question after a mistake -- **WHEN** a student answers a practice question wrongly -- **THEN** the next question is on the same skill and is not the question just answered diff --git a/openspec/changes/build-skill-learning/specs/skill-mastery/spec.md b/openspec/changes/build-skill-learning/specs/skill-mastery/spec.md deleted file mode 100644 index 4896faa5d0a6f7d851a449692a86810b3e332cfd..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/specs/skill-mastery/spec.md +++ /dev/null @@ -1,51 +0,0 @@ -# Spec Delta - -## Purpose - -Defines when a skill counts as mastered and the state every skill is in for every student, so mastery is proven rather than assumed and stays once earned. - -## ADDED Requirements - -### Requirement: Mastery rule -A skill SHALL become mastered when the student answers 3 questions on it correctly in a row, each on the first try, without opening help or the worked example, and these answers are spread over at least 2 different calendar days. - -#### Scenario: Mastered over two days -- **WHEN** a student answers 2 questions of a skill correctly on Monday and a third correctly on Tuesday, all first try and without help -- **THEN** the skill becomes mastered - -#### Scenario: All on one day -- **WHEN** a student answers 3 questions of a skill correctly in a row on the same day -- **THEN** the skill is not yet mastered - -#### Scenario: Help opened -- **WHEN** a student opens help or the worked example before answering a question -- **THEN** that answer is skipped for mastery: it neither counts toward the run nor breaks it - -#### Scenario: Help between correct answers -- **WHEN** a student answers 2 questions correctly without help on Monday, answers a third with help, and answers a fourth correctly without help on Tuesday -- **THEN** the skill becomes mastered, since the run of counted answers is the Monday, Monday and Tuesday ones - -#### Scenario: Streak broken -- **WHEN** a student answers 2 correctly, then 1 wrongly, then 1 correctly -- **THEN** the run of correct answers in a row restarts from the last correct answer - -### Requirement: Skill states -Every skill, for every student, SHALL be in exactly one state: "not started" (no answers yet), "learning" (at least one answer, not yet mastered) or "mastered" (met the mastery rule). - -#### Scenario: First answer -- **WHEN** a student answers the first question of a skill -- **THEN** the skill moves from "not started" to "learning" - -### Requirement: Mastery does not decay -A mastered skill SHALL stay mastered. It MUST NOT fade, decay or require re-mastering over time, even after later wrong answers. - -#### Scenario: Months later -- **WHEN** a student mastered a skill in October and answers a question on it wrongly in March -- **THEN** the skill is still mastered - -### Requirement: Mastery is checked on the server -The server SHALL store the date of each answer and decide mastery from it, so the "2 different days" rule cannot be changed from the device. - -#### Scenario: Device clock changed -- **WHEN** a student changes the device date before answering -- **THEN** the answer is dated by the server, and mastery uses that date diff --git a/openspec/changes/build-skill-learning/tasks.md b/openspec/changes/build-skill-learning/tasks.md deleted file mode 100644 index 2a849ee0d0af4a64b308d7a05848285152c58082..0000000000000000000000000000000000000000 --- a/openspec/changes/build-skill-learning/tasks.md +++ /dev/null @@ -1,53 +0,0 @@ -# Tasks - -## 1. Bank: question keys and example content - -- [ ] 1.1 Add `question_key(skill_id, question)` to `bank.py` (design decision 3) and make `check_bank` reject two questions with the same key in a skill; verify tests pass on the real bank and fail on a sample with a duplicated question -- [ ] 1.2 Add checks for the optional `worked_example` and `faded_examples` shapes (decision 4: exactly 2 faded examples with at least 2 and 3 steps, one correct `why` and one correct choice per step, mistake ids exist); verify tests pass on a valid sample and fail on each broken case, and the real bank (with no examples) still loads -- [ ] 1.3 Add `Bank` helpers for practice: a question for the browser without `correct` or `mistake` (choices keep their original index), grading a choice index, and a mistake's name, tip and `back`; verify unit tests, including that a served question has no `correct` field anywhere -- [ ] 1.4 Update `scripts/content_gaps.py` to the decision 4 shape (a step without `why` choices, a faded step without choices); verify its test still lists `a_30_side` and flags a sample step without choices - -## 2. Storage - -- [ ] 2.1 Add the migration `mathly2/supabase/migrations/…_m2_skill_learning.sql` with `m2_answers`, `m2_skill_progress` and the `m2_daily_correct` view (decision 1), row-level security on and no browser grants; verify a pgserver test applies it, the view counts only correct practice answers per day, and an authenticated-role insert is refused -- [ ] 2.2 Add the progress and answer methods to `InMemoryStore` (get or create progress, update progress, insert answer, last N counted answers, answer counts per question, daily correct counts, progress rows of a user); verify unit tests for each method -- [ ] 2.3 Add the same methods to `SupabaseStore`; verify `test_store.py`-style tests against the faked PostgREST pass with the same cases as 2.2 - -## 3. Rules: mastery, next question, goal and streak - -- [ ] 3.1 Add `learning.py` with the mastery rule over counted answers (decision 2); verify a test for every scenario in `specs/skill-mastery/spec.md`: two days, one day, help opened, help between correct answers, streak broken, months later still mastered -- [ ] 3.2 Add the skill state from a progress row (not started, learning, mastered); verify tests that a "why this step?" answer moves a skill to learning and only practice answers can master it -- [ ] 3.3 Add next-question picking (decision 7): fewest past answers, never the one just answered; verify tests with 10 questions (no repeat before all are seen), 1 question (repeats) and 0 questions (none) -- [ ] 3.4 Add today's goal and the streak from daily counts (decision 8), using `clock.school_day()`; verify tests for 3 of 5, reaching 5, a streak kept overnight before today's 5, and a broken streak - -## 4. Practice API - -- [ ] 4.1 Add `GET /api/skills/{id}` (stage, examples if any, current question) and `POST /api/skills/{id}/stage`; verify tests that a skill with no examples opens at practice, a skill with a worked example but no faded examples moves to practice after it (spec: Stages without content are skipped), and any skill opens in any order (spec: Jumping ahead) -- [ ] 4.2 Add `POST /api/skills/{id}/answer` per the decision 6 sequence; verify tests that the server dates the answer (spec: Device clock changed), a wrong answer returns the mistake's name and tip but not the correct choice, the next question differs from the one answered, and an answer for a question not on screen is refused -- [ ] 4.3 Add `POST /api/skills/{id}/help`; verify a test that the next answer is stored with `counted = false` and does not break a run -- [ ] 4.4 Add `GET /api/path` and `GET /api/collection`; verify tests for states, today's goal, the streak, mastered skills, and a lesson counted as completed only when all its skills are mastered -- [ ] 4.5 Extend the "no content before sign-in" test to the new endpoints, and refuse a student with no class (403) as `/api/lessons` does; verify the test passes - -## 5. Student screens - -- [ ] 5.1 Port the `figure` and `plot` drawing functions from the old `static/math.js` into `mathly2/static/figures.js` (decision 9); verify a Playwright test draws one bank question with a `figure` and one with a `graph` -- [ ] 5.2 Replace the lesson list in `student.js` with the path screen: every lesson and skill with its state as text and symbol, today's goal and the streak; verify a Playwright test at 390px shows all 24 lessons, a mastered skill's label, and no horizontal scroll -- [ ] 5.3 Add the worked-example screen: one step at a time, the next step only after "why this step?" is answered; verify a Playwright test against a test bank with one worked example -- [ ] 5.4 Add the faded-example screen with backward fading and mistake feedback on a wrong step; verify a Playwright test that example 1 hides one step, example 2 hides two, and a wrong choice shows its mistake -- [ ] 5.5 Add the practice screen: choices, help, mistake feedback with a "similar question" button and a "go back to" link when the mistake has `back`, and the run of correct answers; verify a Playwright test that answers wrongly, sees the mistake name, and gets a different question -- [ ] 5.6 Add the collection screen; verify a Playwright test that a skill mastered through the API appears on it - -## 6. Drafting tool - -- [ ] 6.1 Port `scripts/draft_examples.py` to `mathly2/scripts/draft_examples.py`, producing the decision 4 shape (one worked example and 2 faded examples per skill) and merging only approved drafts through `check_bank`; verify tests with a faked AI client for draft, a rejected draft, and merge, and `--dry-run` sends nothing -- [ ] 6.2 Document the draft -> teacher approves -> merge flow in `mathly2/README.md`; verify the documented `--dry-run` command runs as written - -## 7. Integration - -- [ ] 7.1 Walk one skill end to end in a browser test: open from the path, answer 2 correctly, move the server clock to the next day, answer 1 more, and see the skill as mastered on the path and in the collection; verify the test passes -- [ ] 7.2 Run the whole suite `venv/bin/python -m pytest mathly2/tests` and `openspec validate build-skill-learning`; verify both pass - -## Workflow follow-up - -- Write worked and faded examples for a first lesson with the drafting tool and have a teacher approve them (content work, outside this change). -- Archive this change once it is deployed and reviewed, so `skill-learning`, `skill-mastery` and `learning-path` move into `openspec/specs/`. diff --git a/openspec/changes/build-test-prep/proposal.md b/openspec/changes/build-test-prep/proposal.md deleted file mode 100644 index d1bb6faf3a1cae41baec8a185136baf07a535605..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/proposal.md +++ /dev/null @@ -1,28 +0,0 @@ -# Proposal - -## Why - -Students arrive at the real test without having practised mixed, timed questions or knowing their gaps (see `docs/tasks/prd-mathly.md`, 4.3–4.7). - -## What Changes - -- The teacher sets a real test (date, lessons, number of questions, time limit) and sees who took the simulation. -- The student gets a countdown plan, two retakeable exercise tests weighted toward weak skills, and one required simulation with a timer kept on the server. -- A readiness meter for the student and the teacher. -- The student's home (assignments, test reminder with today's task, continue the path) and the grades screen. - -## Capabilities - -### New Capabilities -- `real-tests`: setting a test and the tests tab. -- `test-countdown`: the plan by days left and today's task. -- `exercise-tests`: two exercise tests with a weak-skill question mix. -- `simulation-test`: the one-time simulation with a window and a server timer. -- `readiness-meter`: readiness per upcoming test. -- `student-screens`: the student's home and grades screen. - -### Modified Capabilities - -## Impact - -- Builds on `build-foundation`, `build-skill-learning`, `build-lesson-quizzes` and `build-assignments` (home and grades show their items). diff --git a/openspec/changes/build-test-prep/specs/exercise-tests/spec.md b/openspec/changes/build-test-prep/specs/exercise-tests/spec.md deleted file mode 100644 index 4a838c3b10f2f2acf40be09a38d72cab9b0153c2..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/exercise-tests/spec.md +++ /dev/null @@ -1,60 +0,0 @@ -# Spec Delta - -## Purpose - -Gives each student two retakeable, timed, mixed exercise tests (מבחן תרגול) before a real test, weighted toward their weak skills, so the real test does not surprise them. - -## ADDED Requirements - -### Requirement: Two exercise tests per test -When the teacher sets a test, the system SHALL create 2 exercise tests for every student in the class and place them on the student's countdown. - -#### Scenario: Test set -- **WHEN** a teacher sets a test for a class of 25 -- **THEN** each of the 25 students has exercise test 1 and exercise test 2 on their countdown - -### Requirement: Teacher can assign an exercise test -The teacher SHALL be able to send an exercise test to the whole class as an assignment. - -#### Scenario: Assigning -- **WHEN** a teacher sends exercise test 1 to the class -- **THEN** every student in the class sees it among their assignments - -### Requirement: Retakes and best grade -The student SHALL be able to start or retake an exercise test at any time. Each retake SHALL draw new questions, and the best grade SHALL count. - -#### Scenario: Retake -- **WHEN** a student got 60 and then 75 on exercise test 1 -- **THEN** exercise test 1's grade is 75, and the second attempt had new questions - -### Requirement: Built like the real test -An exercise test SHALL have the real test's number of questions and time limit, mix questions from all covered lessons, not show skill names, and give feedback only at the end. - -#### Scenario: Taking the test -- **WHEN** a student takes an exercise test for a test of 12 questions and 90 minutes -- **THEN** it has 12 questions from the covered lessons, a 90-minute limit, no skill names, and no feedback until handed in - -### Requirement: Question mix by weak skills -Exercise test 1 SHALL draw 60% of its questions from weak skills and 40% from other covered skills; exercise test 2, 30% and 70%. A weak skill is one in the "learning" state or answered wrongly in a previous exercise test. With too few weak skills, the rest SHALL come from other covered skills. - -#### Scenario: Test 1 mix -- **WHEN** a student with enough weak skills opens exercise test 1 of 10 questions -- **THEN** 6 questions are on weak skills and 4 on other covered skills - -#### Scenario: Few weak skills -- **WHEN** a student has only enough weak-skill questions for 2 of the 6 weak slots -- **THEN** the other slots are filled from other covered skills - -### Requirement: Skills not started are left out -Skills in the "not started" state MUST NOT appear in an exercise test. The exercise test card SHALL list them as "practice these first". - -#### Scenario: Not started skill -- **WHEN** a covered skill is "not started" for the student -- **THEN** no question on it appears, and the card lists it under "practice these first" - -### Requirement: Result links back to the path -After an exercise test, the system SHALL show the weak skills it found and link each to its place in the path. The grade SHALL be computed and stored on the server. - -#### Scenario: Result -- **WHEN** a student hands in an exercise test with mistakes on 3 skills -- **THEN** the result lists those skills, each opening its place in the path diff --git a/openspec/changes/build-test-prep/specs/readiness-meter/spec.md b/openspec/changes/build-test-prep/specs/readiness-meter/spec.md deleted file mode 100644 index b6e3579d61535ae3abab99f8d019a92fd759e662..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/readiness-meter/spec.md +++ /dev/null @@ -1,18 +0,0 @@ -# Spec Delta - -## Purpose - -Shows the student and the teacher how ready the student is for each upcoming test, from mastered skills, exercise test grades and the simulation grade. - -## ADDED Requirements - -### Requirement: Readiness meter -For each upcoming test, the system SHALL show a readiness meter made of the percentage of covered skills that are mastered, the best grade of each exercise test, and the simulation grade once taken. Both the student and the teacher SHALL see it. - -#### Scenario: Before the simulation -- **WHEN** a student mastered 15 of 20 covered skills and has best grades 70 and 80 on the exercise tests -- **THEN** the meter shows 75% mastered, 70 and 80, and no simulation grade - -#### Scenario: Teacher view -- **WHEN** the teacher looks at the student's readiness for that test -- **THEN** the same meter is shown diff --git a/openspec/changes/build-test-prep/specs/real-tests/spec.md b/openspec/changes/build-test-prep/specs/real-tests/spec.md deleted file mode 100644 index 4d00302b4c82817a59a6f0b9e8c56a1050f6796c..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/real-tests/spec.md +++ /dev/null @@ -1,32 +0,0 @@ -# Spec Delta - -## Purpose - -Lets the teacher put a real school test (מבחן) in the app, with its date, covered lessons, number of questions and time limit, so the app can prepare students for it. - -## ADDED Requirements - -### Requirement: Teacher sets a test -The teacher SHALL be able to set a test with a date, the lessons it covers, an optional note, the number of questions and the time limit. The number of questions SHALL default to 12 and the time limit to 90 minutes, and the teacher SHALL be able to change both. - -#### Scenario: Defaults -- **WHEN** a teacher sets a test without changing the question count or time limit -- **THEN** the test has 12 questions and 90 minutes - -#### Scenario: Custom limits -- **WHEN** a teacher sets a test with 10 questions and 45 minutes -- **THEN** the test is saved with 10 questions and 45 minutes - -### Requirement: Tests tab -The teacher SHALL have a tests tab to set tests and see, for each test, which students have taken its simulation test and which have not. - -#### Scenario: Simulation status -- **WHEN** a teacher opens a test in the tests tab and 20 of 25 students took the simulation -- **THEN** the 20 are shown as taken and the 5 as not taken - -### Requirement: Real test grades are not handled -The app MUST NOT grade the real school test or import its grades. - -#### Scenario: After the test date -- **WHEN** a test's date has passed -- **THEN** the app offers no way to enter or import grades for it diff --git a/openspec/changes/build-test-prep/specs/simulation-test/spec.md b/openspec/changes/build-test-prep/specs/simulation-test/spec.md deleted file mode 100644 index ea5106028bc3a2d8e5d02ddef3aff1f410013ac5..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/simulation-test/spec.md +++ /dev/null @@ -1,46 +0,0 @@ -# Spec Delta - -## Purpose - -Gives each student one required, one-time full simulation (מבחן סימולציה) of the real test, so they know where they stand while there is still time to fix gaps. - -## ADDED Requirements - -### Requirement: One required attempt -Every student SHALL take one simulation test per real test. It SHALL be possible to take it only once. - -#### Scenario: Second try -- **WHEN** a student who handed in the simulation opens it again -- **THEN** they see their result and cannot start another attempt - -### Requirement: Built like the real test -The simulation SHALL cover all lessons of the real test, with the real test's number of questions and time limit, no skill names, and no feedback until the end. - -#### Scenario: Taking the simulation -- **WHEN** a student starts the simulation of a test with 12 questions and 90 minutes -- **THEN** it has 12 questions from all covered lessons, a 90-minute limit, no skill names and no feedback until handed in - -### Requirement: Window and home reminder -The simulation SHALL become available about 5 days before the test and stay available until the test day. Until taken, it SHALL be shown as required on the student's home screen. - -#### Scenario: Too early -- **WHEN** the test is 8 days away -- **THEN** the simulation cannot be started yet - -#### Scenario: Required on home -- **WHEN** the test is 4 days away and the student has not taken the simulation -- **THEN** home shows the simulation as required - -### Requirement: Timer kept on the server -The simulation's timer SHALL be kept on the server, so refreshing or closing the app does not reset it. The grade SHALL be computed and stored on the server. - -#### Scenario: Refresh mid-test -- **WHEN** a student refreshes the app 30 minutes into a 90-minute simulation -- **THEN** the timer shows about 60 minutes left - -### Requirement: Failed skills become review tasks -After the simulation, the system SHALL list the skills that failed and make them the review tasks of the plan's last days. - -#### Scenario: Review tasks -- **WHEN** a student hands in the simulation with 3 failed skills -- **THEN** the result lists them, and the countdown's last days ask to review those 3 skills diff --git a/openspec/changes/build-test-prep/specs/student-screens/spec.md b/openspec/changes/build-test-prep/specs/student-screens/spec.md deleted file mode 100644 index 20a3e2395061facb22307cb539c1300f0e26bd84..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/student-screens/spec.md +++ /dev/null @@ -1,32 +0,0 @@ -# Spec Delta - -## Purpose - -Defines the student's main screens: home with assignments, the test reminder and a way back to the path, and a grades screen with every grade that counts. - -## ADDED Requirements - -### Requirement: Student home -The student's home SHALL show their assignments from the teacher ("המשימות שלי"), the reminder for the nearest test (days left, readiness meter and today's task), and a way to continue the path. - -#### Scenario: Assignment and test -- **WHEN** a student has an open assignment and a test in 6 days -- **THEN** home shows the assignment, the test reminder with today's task, and continue the path - -#### Scenario: Nothing scheduled -- **WHEN** a student has no assignments and no upcoming test -- **THEN** home still offers to continue the path - -### Requirement: Grades screen -The student SHALL have a grades screen listing every lesson quiz (best grade), every exercise test (best grade), every simulation grade and every assignment grade. - -#### Scenario: Quiz retaken -- **WHEN** a student got 70 and then 90 on a lesson's quiz -- **THEN** the grades screen shows 90 for that quiz - -### Requirement: No student-to-student features -The app MUST NOT offer student-to-student features such as chat or leaderboards, and MUST NOT show a student other students' results. - -#### Scenario: Grades screen -- **WHEN** a student opens their grades -- **THEN** no other student's grade or rank is shown diff --git a/openspec/changes/build-test-prep/specs/test-countdown/spec.md b/openspec/changes/build-test-prep/specs/test-countdown/spec.md deleted file mode 100644 index d1cf2c7dba37884c90ce87c75e6e02a0b47745bc..0000000000000000000000000000000000000000 --- a/openspec/changes/build-test-prep/specs/test-countdown/spec.md +++ /dev/null @@ -1,35 +0,0 @@ -# Spec Delta - -## Purpose - -Plans the student's last days before a real test: finish the path, take two exercise tests, take the simulation, then review what failed, with one clear task for today. - -## ADDED Requirements - -### Requirement: Countdown plan -Once a test is set, the student SHALL see a plan based on days left: until ~9 days, finish the path for every covered lesson; ~9, exercise test 1; ~7, exercise test 2; ~5, the required simulation test; 4 to 1, review the skills that failed in the simulation, with light mixed review the day before. - -#### Scenario: Plan at 12 days -- **WHEN** a test is set 12 days ahead -- **THEN** the plan shows finishing the covered skills now, exercise test 1 at ~9 days, exercise test 2 at ~7, the simulation at ~5 and review in the last 4 days - -### Requirement: Days are recommendations -The plan's day numbers SHALL be recommendations. The student SHALL be able to start each step earlier or later. - -#### Scenario: Starting early -- **WHEN** a student opens exercise test 2 with 11 days left -- **THEN** the exercise test starts - -### Requirement: Short notice shortens the gaps -If a test is set less than 9 days ahead, the plan SHALL keep the same order of steps and shorten the gaps between them evenly. - -#### Scenario: Test in 6 days -- **WHEN** a test is set 6 days ahead -- **THEN** the plan keeps the order exercise test 1, exercise test 2, simulation, review, spread evenly over the 6 days - -### Requirement: Today's task -Home SHALL show, for the nearest test, the days left, the readiness meter and one task for today taken from the plan, as a single obvious button. When several tests are coming up, today's task SHALL come from the closest one. - -#### Scenario: Two tests ahead -- **WHEN** a student has tests in 4 and 10 days -- **THEN** home shows one task for today, taken from the plan of the test in 4 days diff --git a/openspec/changes/fewer-database-calls/.openspec.yaml b/openspec/changes/fewer-database-calls/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/fewer-database-calls/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/fewer-database-calls/proposal.md b/openspec/changes/fewer-database-calls/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..955dd70c5fbf35ae6c06153db02cd6b71b86da49 --- /dev/null +++ b/openspec/changes/fewer-database-calls/proposal.md @@ -0,0 +1,25 @@ +# Proposal + +## Why + +mathly2 is slow: opening a screen makes 3 to 7 database calls and grading one practice answer makes 14, one after another, and each call to a remote Supabase takes about 0.4 seconds (measured 2026-11-08). An answer takes 5 to 6 seconds, a screen 2 to 3. mathly1 grades on the device, which mathly2 must not (the server decides), so the server has to make fewer, parallel calls. + +## What Changes + +- The same fact is read once per request (a student's classes were read up to 3 times, their progress 3 times per answer). +- Reads that do not depend on each other are made at the same time. +- Writes of one answer are combined (one progress write instead of two). +- The server keeps its connections to the database open and reuses them, instead of opening a new secure connection for every call. +- A requirement and a test with an artificial delay on every database call (waits in a row, not call counts), so it cannot get slow again unnoticed. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `app-basics`: adds "Few database round trips". + +## Impact + +- `mathly2/store.py` (connection reuse), `mathly2/skills.py`, `mathly2/learning.py`, `mathly2/access.py`, `mathly2/realtests.py` and `mathly2/quizzes.py` (fewer and parallel calls). No screen, route or database table changes. +- PRD 7.3 gets one line. diff --git a/openspec/changes/fewer-database-calls/specs/app-basics/spec.md b/openspec/changes/fewer-database-calls/specs/app-basics/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..82c5f6a471762ef8eda555b6394cc3ee9cf25966 --- /dev/null +++ b/openspec/changes/fewer-database-calls/specs/app-basics/spec.md @@ -0,0 +1,16 @@ +## ADDED Requirements + +### Requirement: Few database round trips +The server SHALL read the same fact once per request, make reads that do not depend on each other at the same time, and keep its connections to the database open for reuse. Opening a student's screen (home, path, skill, grades, collection) SHALL wait for the database at most 3 times in a row, and grading one practice answer at most 4 times in a row. + +#### Scenario: Opening a screen +- **WHEN** a student opens the path, home, a skill, the grades or the collection and every database call takes 0.1 seconds +- **THEN** the screen's data arrives in under 0.55 seconds + +#### Scenario: Answering +- **WHEN** a student answers a practice question and every database call takes 0.1 seconds +- **THEN** the answer is graded in under 0.75 seconds + +#### Scenario: Connections +- **WHEN** the server makes several calls to the database in a row +- **THEN** they reuse an open connection instead of opening a new one each time diff --git a/openspec/changes/fewer-database-calls/tasks.md b/openspec/changes/fewer-database-calls/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..a5591da39b21245b2c76f013412e6aff5dcd6b44 --- /dev/null +++ b/openspec/changes/fewer-database-calls/tasks.md @@ -0,0 +1,11 @@ +# Tasks + +## 1. Fewer and parallel calls + +- [x] 1.1 Add the timing test: a store that waits 0.1 seconds on every call, then home, path, a skill, grades and the collection each answer in under 0.55 seconds and an answer in under 0.75; verify it fails on today's code (it is the measurement) and passes after 1.2 and 1.3 +- [x] 1.2 Read each fact once per request (a student's classes) and make independent reads at the same time (a small shared thread pool); combine the answer's two progress writes into one and pass the progress along instead of reading it again; verify the existing answer, mastery, rewards, quiz and test tests still pass unchanged +- [x] 1.3 Keep the database connections open: one connection per thread, reused, reconnecting once when the server closed it; verify request tests that several calls reuse one connection, a dropped connection is retried once, and an error from the database is still reported as before + +## 2. Wrap-up + +- [x] 2.1 Add the PRD line; measure again with the counting script and report the new counts; verify `openspec validate fewer-database-calls --strict` and the mathly2 tests pass diff --git a/openspec/changes/launch-on-space/.openspec.yaml b/openspec/changes/launch-on-space/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91d15c31aaca8dae561cbfd4b7ff7e99ee95e504 --- /dev/null +++ b/openspec/changes/launch-on-space/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-07 +skip_specs: true diff --git a/openspec/changes/launch-on-space/proposal.md b/openspec/changes/launch-on-space/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..36e1637167dcd80de420710485ab43dbedfce41b --- /dev/null +++ b/openspec/changes/launch-on-space/proposal.md @@ -0,0 +1,25 @@ +# Proposal + +## Why + +mathly2 must replace mathly1 on its Hugging Face Space without risking mathly1's students: the old database stays untouched and the Space can be switched back at any time (PRD 7.3, Fallback). + +## What Changes + +- Commit and tag mathly1's current code, including its uncommitted work, so the fallback is exactly what ran before. +- Apply the `m2_` migrations to the shared Supabase project; check that no mathly1 table, policy or bucket changed. +- Deploy the `mathly2` image to the Space with its settings (Supabase, teacher, developer and admin emails, AI key, push keys, picture bucket). +- Rehearse the fallback: switch the Space back to mathly1, confirm a mathly1 student's data, switch forward again. +- Pilot solved examples for one lesson with the drafting tool and a teacher's review. + +No behavior of the app changes here; the behavior is in the earlier stages' specs (for the fallback: `app-basics`, "mathly1 stays available"). + +## Capabilities + +### New Capabilities + +### Modified Capabilities + +## Impact + +- The Hugging Face Space, the shared Supabase project, and the repository's tags. Tasks are written when this stage starts. diff --git a/openspec/changes/mark-wrong-choice/.openspec.yaml b/openspec/changes/mark-wrong-choice/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/mark-wrong-choice/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/mark-wrong-choice/proposal.md b/openspec/changes/mark-wrong-choice/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..bd02e01940ae700d2b017ee00e1651e926107b9c --- /dev/null +++ b/openspec/changes/mark-wrong-choice/proposal.md @@ -0,0 +1,21 @@ +# Proposal + +## Why + +When a student answers wrong, the chosen choice only gets a faint salmon border and tint, which is easy to miss, and it carries no symbol or word on the choice itself, so it is shown by colour alone (the app promises never to do that). + +## What Changes + +- The chosen wrong choice is marked clearly: a stronger border and tint, and a label "✗ לא נכון" on the choice itself. +- Nothing else is marked: the right choice is still never shown. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `exercise-screen`: "A wrong answer" says the chosen choice is marked with a symbol and a word. + +## Impact + +- `mathly2/static/exercise.js` and `app.css`. No server change. PRD EXR-5. diff --git a/openspec/changes/mark-wrong-choice/specs/exercise-screen/spec.md b/openspec/changes/mark-wrong-choice/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..e90ad2992977a8871e2cb2ce95ae946529b10a93 --- /dev/null +++ b/openspec/changes/mark-wrong-choice/specs/exercise-screen/spec.md @@ -0,0 +1,12 @@ +## MODIFIED Requirements + +### Requirement: A wrong answer +A wrong answer SHALL be quiet and SHALL show the name and tip of the mistake attached to the chosen choice, about the mistake and not the student. The chosen choice SHALL be marked as wrong with a symbol and a word on the choice itself ("✗ לא נכון"), not by colour alone, and no other choice SHALL be marked. It MUST NOT reveal the correct answer. When the mistake names a skill to go back to, the feedback SHALL link to it. + +#### Scenario: Sign mistake +- **WHEN** a student picks a choice tagged with "טעות סימן באיבר האמצעי" +- **THEN** the mistake's name and tip are shown and no choice is marked as correct + +#### Scenario: The chosen choice is marked +- **WHEN** a student picks a wrong choice +- **THEN** that choice shows "✗ לא נכון" and a stronger border, and every other choice looks as it did diff --git a/openspec/changes/mark-wrong-choice/tasks.md b/openspec/changes/mark-wrong-choice/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..63b5c5c6f7edd91bacd5d83c6270a3956cae837a --- /dev/null +++ b/openspec/changes/mark-wrong-choice/tasks.md @@ -0,0 +1,6 @@ +# Tasks + +## 1. Mark the wrong choice + +- [x] 1.1 Mark the chosen wrong choice with "✗ לא נכון" on the choice and a stronger border and tint; verify a Playwright test that after a wrong answer the chosen choice has the label and the class, no other choice has a label or class, no choice is marked as right, and the label is in the choice's accessible text +- [x] 1.2 Add the PRD line; verify `openspec validate mark-wrong-choice --strict` and the exercise tests pass diff --git a/openspec/changes/practice-ten-questions/.openspec.yaml b/openspec/changes/practice-ten-questions/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/practice-ten-questions/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/practice-ten-questions/proposal.md b/openspec/changes/practice-ten-questions/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..3f0f4a2569a237ce362e771a94a59ce8c63dde0f --- /dev/null +++ b/openspec/changes/practice-ten-questions/proposal.md @@ -0,0 +1,22 @@ +# Proposal + +## Why + +Five skills (`t_ext`, `t_simplify`, `t_ext_eq`, `t_area`, `t_formulas`) have 30 questions in the bank, so their exercise screen says "question n of 30" while every other skill says "of 10". Practice should look the same for every skill. + +## What Changes + +- Practice on the exercise screen uses 10 questions per skill: the first 10 of the skill's questions in the bank. The count "question n of N", the dots, the progress and the next question all use those 10. +- The bank is untouched: the other questions of those five skills stay, and lesson quizzes, exercise tests and the simulation still draw from all of a skill's questions, so retakes keep their variety. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `exercise-screen`: "One question at a time" counts the skill's practice questions, at most 10. + +## Impact + +- `mathly2/bank.py` (the practice set) and `mathly2/skills.py` (practice uses it); quizzes and tests are unchanged. +- PRD EXR-2 and a new BNK-6. diff --git a/openspec/changes/practice-ten-questions/specs/exercise-screen/spec.md b/openspec/changes/practice-ten-questions/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..2ba5c35ac6524728ca4982317be9bdd3214b044d --- /dev/null +++ b/openspec/changes/practice-ten-questions/specs/exercise-screen/spec.md @@ -0,0 +1,12 @@ +## MODIFIED Requirements + +### Requirement: One question at a time +The sheet SHALL show one question: its text with formulas, its figure or graph if any, and its choices in a new random order each time it is shown, with "question n of N" and a row of dots for the skill's practice questions. Practice SHALL use at most 10 questions per skill, the first 10 of the skill's questions in the bank, so N is never more than 10; the skill's other questions stay available to quizzes and tests. + +#### Scenario: Same question again +- **WHEN** a question is shown a second time +- **THEN** its choices may be in a different order, and the server still grades by the bank's choice + +#### Scenario: A skill with 30 questions +- **WHEN** a student opens a skill that has 30 questions in the bank +- **THEN** the sheet says "question n of 10" and shows 10 dots, and only those 10 questions come up in practice diff --git a/openspec/changes/practice-ten-questions/tasks.md b/openspec/changes/practice-ten-questions/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..67439bcf3916a8ce0f7e27ad0b881d53f5e020bf --- /dev/null +++ b/openspec/changes/practice-ten-questions/tasks.md @@ -0,0 +1,6 @@ +# Tasks + +## 1. Ten practice questions + +- [x] 1.1 Add `Bank.practice_keys(skill_id)` (the first 10 question keys of the skill) and use it for the exercise screen's count, dots, progress and next question; verify tests: a skill with 30 questions gives total 10 and only questions from its first 10, a skill with 10 or fewer is unchanged, a student whose current question is outside the first 10 is moved to a practice question, answering grades any question of the skill, and quizzes, exercise tests and the simulation still draw from all 30 +- [x] 1.2 Add the PRD lines; verify `openspec validate practice-ten-questions --strict`, the mathly2 tests pass, and the exercise screen of `t_ext` shows "מתוך 10" in a browser diff --git a/openspec/changes/show-answer-pending/.openspec.yaml b/openspec/changes/show-answer-pending/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/show-answer-pending/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/show-answer-pending/proposal.md b/openspec/changes/show-answer-pending/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..151f2a50768df838975c7fe7e3d4064371fb55e8 --- /dev/null +++ b/openspec/changes/show-answer-pending/proposal.md @@ -0,0 +1,22 @@ +# Proposal + +## Why + +Tapping a choice waits for the server to grade it, and over a slow connection that takes seconds with nothing on screen changing, so the student does not know whether the tap worked and may tap again. + +## What Changes + +- The moment a choice is tapped it shows it is being checked: a spinner and a short line "בודקים…", the other choices are dimmed and cannot be tapped, and the choice the student tapped stays marked. +- The hint disappears when the answer arrives (right, wrong, or an error). +- It does not depend on motion: with reduced motion the words "בודקים…" are shown without the spinner turning. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `exercise-screen`: adds "Thinking indicator". + +## Impact + +- `mathly2/static/exercise.js` and `app.css`. No server change. PRD EXR-3. diff --git a/openspec/changes/show-answer-pending/specs/exercise-screen/spec.md b/openspec/changes/show-answer-pending/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..adb958f2fd45644fee05e881150b3b9ce1062541 --- /dev/null +++ b/openspec/changes/show-answer-pending/specs/exercise-screen/spec.md @@ -0,0 +1,12 @@ +## ADDED Requirements + +### Requirement: Thinking indicator +As soon as a choice is tapped, the sheet SHALL show that the answer is being checked: the tapped choice shows a spinner, a status line says "בודקים…", and the other choices are dimmed and cannot be tapped. The indicator SHALL go away when the answer arrives or fails, and it MUST NOT depend on motion: with reduced motion the words are shown and the spinner is still. + +#### Scenario: A slow answer +- **WHEN** a student taps a choice and the server takes two seconds +- **THEN** during those two seconds the tapped choice shows a spinner, "בודקים…" is shown and the other choices cannot be tapped, and the result replaces them when it arrives + +#### Scenario: An error +- **WHEN** the answer cannot be sent +- **THEN** the indicator goes away, the choices can be tapped again and the error is shown diff --git a/openspec/changes/show-answer-pending/tasks.md b/openspec/changes/show-answer-pending/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..ec281ba849c968780570fa11cbe35238190d2eec --- /dev/null +++ b/openspec/changes/show-answer-pending/tasks.md @@ -0,0 +1,6 @@ +# Tasks + +## 1. The indicator + +- [x] 1.1 Show the thinking indicator on a tapped choice in `exercise.js` with its styles (spinner, dimmed other choices, status line, still under reduced motion); verify a Playwright test that delays the answer by 1.5 seconds: during the wait the tapped choice has the spinner, "בודקים…" shows, the other choices are disabled, then the result replaces them; and that after an error the choices work again +- [x] 1.2 Add the PRD line; verify `openspec validate show-answer-pending --strict` and the exercise tests pass diff --git a/openspec/changes/ten-question-rounds/.openspec.yaml b/openspec/changes/ten-question-rounds/.openspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0ad5ed4ddd76cfbcbe0305fb342023fb1f59e7e --- /dev/null +++ b/openspec/changes/ten-question-rounds/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-08 diff --git a/openspec/changes/ten-question-rounds/proposal.md b/openspec/changes/ten-question-rounds/proposal.md new file mode 100644 index 0000000000000000000000000000000000000000..9bc9f269b52cb1a9c1472e2c22b5740119071faa --- /dev/null +++ b/openspec/changes/ten-question-rounds/proposal.md @@ -0,0 +1,24 @@ +# Proposal + +## Why + +Practice on a skill should be a clear task: answer its 10 questions, each once, and see how it went. Today questions come round again by "least seen", a wrong answer is queued to return, and the counter ("question n of 10") counts only right answers, so with a wrong answer it never reaches 10 and practice never ends. + +## What Changes + +- Practising a skill is a **round** of its 10 questions (all of them when it has fewer), each shown once in a random order. A wrong answer is wrong: the question does not come back in the round. +- After the 10th answer the sheet shows the round's result ("N מתוך 10") with the mistakes' names and tips, and offers "סבב חדש" (a new round, the questions again in a new order) and a way back to the path. +- The counter and the dots show how far the student is in the round: a dot per question, filled for a right answer and marked for a wrong one. +- Mastery does not change (3 right in a row on the first try, on 2 days), and is counted across rounds. +- The round is remembered on the server: leaving and coming back continues it, and a finished round shows its result again. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `exercise-screen`: "One question at a time", "A right answer", "A wrong answer" and "A different next question" change; a round's result and a new round are added. + +## Impact + +- A migration adds `round_start` to `m2_skill_progress` (one column, nothing else changes); `mathly2/learning.py`, `mathly2/skills.py`, `mathly2/store.py`, `mathly2/static/exercise.js`. PRD EXR-2, EXR-4 to EXR-6 and a new EXR-12. diff --git a/openspec/changes/ten-question-rounds/specs/exercise-screen/spec.md b/openspec/changes/ten-question-rounds/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f8de752a9ac55442286cb57d4e64a8c5371ed7b2 --- /dev/null +++ b/openspec/changes/ten-question-rounds/specs/exercise-screen/spec.md @@ -0,0 +1,73 @@ +## MODIFIED Requirements + +### Requirement: One question at a time +The sheet SHALL show one question: its text with formulas, its figure or graph if any, and its choices in a new random order each time it is shown, with "question n of N" and a row of N dots, one for each question of the round. A round SHALL be the skill's practice questions, at most 10, each shown once. A dot SHALL be filled for a right answer and marked "✗" for a wrong one, and empty for a question not yet answered. + +#### Scenario: Same question again +- **WHEN** a question is shown a second time +- **THEN** its choices may be in a different order, and the server still grades by the bank's choice + +#### Scenario: A skill with 30 questions +- **WHEN** a student opens a skill that has 30 questions in the bank +- **THEN** the sheet says "question n of 10" and shows 10 dots, and only the first 10 questions come up in the round + +#### Scenario: Dots after a mistake +- **WHEN** a student answers the 1st question right and the 2nd wrongly +- **THEN** the first dot is filled, the second is marked wrong, and the sheet says "question 3 of 10" + +### Requirement: A right answer +A right answer SHALL get a short celebration and the count of right answers in a row. After a short countdown the next question SHALL appear; the student can skip or cancel the countdown. After the last question of the round there is no countdown: the sheet offers the round's result. + +#### Scenario: Countdown +- **WHEN** a student answers correctly +- **THEN** a countdown to the next question starts, and pressing "next" shows it at once + +### Requirement: A wrong answer +A wrong answer SHALL be quiet and SHALL show the name and tip of the mistake attached to the chosen choice, about the mistake and not the student. The chosen choice SHALL be marked as wrong with a symbol and a word on the choice itself ("✗ לא נכון"), not by colour alone, and no other choice SHALL be marked. It MUST NOT reveal the correct answer, and the question MUST NOT come back in the same round. The sheet SHALL offer "לשאלה הבאה" (after the last question: the round's result). When the mistake names a skill to go back to, the feedback SHALL link to it. + +#### Scenario: Sign mistake +- **WHEN** a student picks a choice tagged with "טעות סימן באיבר האמצעי" +- **THEN** the mistake's name and tip are shown and no choice is marked as correct + +#### Scenario: The chosen choice is marked +- **WHEN** a student picks a wrong choice +- **THEN** that choice shows "✗ לא נכון" and a stronger border, and every other choice looks as it did + +#### Scenario: A wrong question does not return +- **WHEN** a student answers the 3rd question wrongly +- **THEN** it is not shown again in the round, and the round ends after the 10th question + +### Requirement: A different next question +After any answer the next question SHALL be a question of the round that was not answered yet, picked at random. When every question of the round was answered, there is no next question and the sheet shows the round's result. A skill with one question has a round of one question. + +#### Scenario: After a mistake +- **WHEN** a student answers a question wrongly +- **THEN** the next question is not the one just answered + +#### Scenario: Never twice in a round +- **WHEN** a student answers all 10 questions of a skill +- **THEN** each question was shown exactly once, and none came back + +## ADDED Requirements + +### Requirement: A round's result +After the last answer of a round the sheet SHALL show how many questions were answered right out of the round's questions ("N מתוך 10") and, for each wrong answer, the question, the mistake's name and tip and a link to the skill to go back to when the bank names one. It MUST NOT show the correct answers. The result SHALL be shown again after leaving and returning, until a new round is started. + +#### Scenario: Result +- **WHEN** a student answers the 10th question of a round with 7 right +- **THEN** the sheet shows "7 מתוך 10" and the three mistakes with their names and tips + +#### Scenario: Leaving in the middle +- **WHEN** a student leaves after the 4th question and comes back +- **THEN** the round continues with the 5th question, and the dots show the first four answers + +### Requirement: A new round +The result SHALL offer "סבב חדש", which starts a new round with all the skill's practice questions again in a new random order, and a way back to the path. Mastery SHALL be counted across rounds as before. + +#### Scenario: Another round +- **WHEN** a student presses "סבב חדש" after a finished round +- **THEN** a round of the 10 questions starts again, with empty dots + +#### Scenario: Coming back after a finished round +- **WHEN** a student leaves after finishing a round and opens the skill again +- **THEN** the result is shown, and "סבב חדש" starts a round of the 10 questions again diff --git a/openspec/changes/ten-question-rounds/tasks.md b/openspec/changes/ten-question-rounds/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..697296be01b0bcc353532c89ac0b9269c1c830f6 --- /dev/null +++ b/openspec/changes/ten-question-rounds/tasks.md @@ -0,0 +1,16 @@ +# Tasks + +## 1. The round on the server + +- [x] 1.1 Add the migration `20261111100000_m2_rounds.sql` (`round_start` on `m2_skill_progress`), `mistake_id` and the round in `answers_of`, in both stores; verify unit and migration tests (the column defaults to nothing, nothing else changes, the browser roles are still refused) +- [x] 1.2 Replace the next-question rule by the round: the answers since `round_start`, the next question is an unanswered one at random, none when all are answered; remove the "missed returns" rule; verify unit tests: each question once, never twice in a round, a one-question skill, the 10 questions of a 30-question skill, an old student without a round start begins a new round +- [x] 1.3 Reshape `GET /api/skills/{id}` and the answer to carry the round (answered, total, a result per answer, done, and when done the result with the mistakes) and add `POST /api/skills/{id}/round`; verify API tests: ten answers end the round with no next question and a result, a wrong question never returns, leaving and coming back continues or shows the result, a new round starts all ten again in a new order, mastery counts across rounds, and the waits test still passes + +## 2. The screen + +- [x] 2.1 Show the counter and dots by the round (filled, marked wrong, empty), the wrong-answer feedback with "לשאלה הבאה", and no countdown after the last question; verify a Playwright test +- [x] 2.2 Add the round's result view with "סבב חדש" and the way back; verify a Playwright test: ten answers with three wrong show "7 מתוך 10", the mistakes with names and tips and no right answers, a reload shows the result again, "סבב חדש" starts again with ten dots + +## 3. Wrap-up + +- [x] 3.1 Update the PRD, the older tests that assumed repeated questions, and run the whole suite and `openspec validate ten-question-rounds --strict`; verify they pass diff --git a/openspec/specs/accounts-and-classes/spec.md b/openspec/specs/accounts-and-classes/spec.md index 01cad127db53743fd629afa0bc2f36644ccbf689..05703647815d8386c4ffd7f9a3265ec759e7939b 100644 --- a/openspec/specs/accounts-and-classes/spec.md +++ b/openspec/specs/accounts-and-classes/spec.md @@ -7,7 +7,7 @@ Lets students and teachers sign in with their school Google accounts, and lets a ## Requirements ### Requirement: Google sign-in -Students and teachers SHALL sign in with their Google account. The app MUST NOT show any student content before sign-in. +Students, teachers, managers, admins and developers SHALL sign in with their Google account. Before sign-in the only screen SHALL be the sign-in page: the animated logo "לומדים בכיף" (from mathly1) and the owl mascot, one line of status text and one button "כניסה עם Google". The app MUST NOT show or serve any student content, class or progress before sign-in. The session SHALL stay on the device, and sign-out SHALL be available on every screen. #### Scenario: Signing in - **WHEN** a student opens the app and signs in with Google @@ -15,42 +15,36 @@ Students and teachers SHALL sign in with their Google account. The app MUST NOT #### Scenario: Not signed in - **WHEN** someone opens the app without signing in -- **THEN** only the sign-in screen is shown +- **THEN** only the sign-in page is shown -### Requirement: Teacher accounts -Only accounts listed as teachers in the app's settings SHALL get the teacher screens. Every other signed-in account SHALL be treated as a student. - -#### Scenario: Listed teacher -- **WHEN** an account listed as a teacher signs in -- **THEN** they see the teacher screens - -#### Scenario: Not listed -- **WHEN** an account not listed as a teacher signs in -- **THEN** they see no teacher screens - -### Requirement: Teacher creates classes -A teacher SHALL be able to create a class with a name and see the classes they created. - -#### Scenario: New class -- **WHEN** a teacher creates the class "ט'3" -- **THEN** "ט'3" appears in their list of classes +#### Scenario: Coming back the next day +- **WHEN** a signed-in student closes the app and opens it the next day on the same device +- **THEN** they are still signed in ### Requirement: Teacher adds students by email -A teacher SHALL be able to add students to a class by their email addresses, one or many at once, and remove them. A student SHALL belong to one class at a time. +The teacher of a class, and a manager, SHALL be able to add students to that class by pasting email addresses (one per line; commas and spaces also separate them) and to remove them. Repeated addresses SHALL be ignored and invalid ones reported. A student MAY belong to more than one class. Removing a student SHALL NOT delete their progress. #### Scenario: Adding a list -- **WHEN** a teacher pastes 25 email addresses into class "ט'3" +- **WHEN** the teacher of "ט'3" pastes 25 email addresses into the class - **THEN** the 25 students are listed in "ט'3" #### Scenario: Student in another class - **WHEN** a teacher adds a student who already belongs to another class -- **THEN** the teacher is told which class the student is in, and the student is not added twice +- **THEN** the student is added, and now belongs to both classes + +#### Scenario: Invalid address +- **WHEN** the pasted text contains "dana@" among valid addresses +- **THEN** the valid ones are added and "dana@" is reported as invalid + +#### Scenario: The teacher in the list +- **WHEN** the teacher of "ט'3" pastes their own address among others +- **THEN** their own address is reported as not allowed, and the others are added ### Requirement: Student not in a class -A signed-in student who is in no class SHALL see a message asking them to ask their teacher to add them, showing the email they signed in with. +A signed-in student who is in no class SHALL see a message asking them to ask their teacher or a manager to add them, showing the email they signed in with, and nothing else. #### Scenario: Not added yet -- **WHEN** a student signs in before the teacher added their email +- **WHEN** a student signs in before a teacher or manager added their email - **THEN** they see the message with their email, and no lessons ### Requirement: Fresh start @@ -59,3 +53,137 @@ The new app SHALL start with no students, classes or progress. Nothing SHALL be #### Scenario: First teacher sign-in - **WHEN** a teacher signs in to the new app for the first time - **THEN** they have no classes, even if they had classes in the current app + +### Requirement: Five roles +The app SHALL have five roles: student, teacher, manager, admin and developer. The server SHALL decide a signed-in email's roles on every request: developer when the email is in the developer setting; teacher when it is in the teacher setting, is a class's teacher, or was given the role; manager or admin when given the role; student otherwise. A person MAY hold several roles and gets the screens of each. + +#### Scenario: Class teacher +- **WHEN** an email that is in no setting is named as the teacher of a class and signs in +- **THEN** it gets the teacher screens for that class + +#### Scenario: Several roles +- **WHEN** a person has both the manager and the teacher role +- **THEN** they can reach both the classes screen and their teacher home + +### Requirement: Permissions per role +Each role SHALL be limited to: student, their own path and data; teacher, the data of the students of the classes they teach and those classes' rosters; manager, classes and their AI settings with no learning data; admin, roles of accounts with no learning data; developer, everything. The server SHALL refuse any request outside the caller's permissions. + +#### Scenario: Teacher of another class +- **WHEN** a teacher asks for the progress of a student who is not in a class they teach +- **THEN** the server refuses + +#### Scenario: Manager and learning data +- **WHEN** a manager asks for a student's answers or grades +- **THEN** the server refuses + +### Requirement: Admin gives roles +An admin SHALL see the accounts the app knows and give or take away the roles student, teacher, manager and admin. Roles SHALL belong to an email address, so a role can be given before the person's first sign-in. The developer role MUST NOT be given here. The last admin MUST NOT be able to take away their own admin role. + +#### Scenario: Role before first sign-in +- **WHEN** an admin gives "rina@school.org" the manager role and Rina signs in for the first time a day later +- **THEN** Rina gets the manager screens + +#### Scenario: Last admin +- **WHEN** the only admin tries to remove their own admin role +- **THEN** the change is refused with a message + +#### Scenario: A change shows soon +- **WHEN** an admin takes the manager role from someone who is signed in +- **THEN** within 30 seconds that person no longer has the manager screens + +### Requirement: The first admins +The app's settings SHALL be able to name admin emails, so a new installation has an admin before anyone gives roles. + +#### Scenario: Empty installation +- **WHEN** the app starts with no roles stored and the settings name "head@school.org" as an admin +- **THEN** "head@school.org" gets the admin screens at sign-in + +### Requirement: Role switcher +A person with more than one role SHALL get a chip for each role in the header, each opening that role's home; a developer SHALL get all five. A person with one role SHALL see no chips. The last role chosen SHALL be remembered on the device. A link or a reload SHALL land on the screen it points to, and switching role SHALL clear the address. + +#### Scenario: Two roles +- **WHEN** a person who is a manager and a teacher signs in +- **THEN** the header has a chip for each, and the one they used last opens first + +#### Scenario: A link +- **WHEN** a student opens the app through a link to their collection +- **THEN** after signing in they see their collection, and reloading shows it again + +#### Scenario: Switching clears the address +- **WHEN** a person with two roles switches from one to the other +- **THEN** the address no longer carries the first role's screen + +### Requirement: Own access +Every signed-in account SHALL be able to see its own roles and what they allow. + +#### Scenario: Checking own roles +- **WHEN** a teacher opens the page of their own access +- **THEN** it lists the teacher role and what it allows + +### Requirement: Manager creates classes +A manager (or a developer) SHALL create, edit and delete classes. A class SHALL have a name (1–80 characters, unique ignoring case), the lessons it studies (at least one, from the bank), its students, at most one teacher (an email, never also a student of that class), an AI switch that starts off, and a daily AI budget (default 150). + +#### Scenario: New class +- **WHEN** a manager creates "ט'3" with two lessons, a teacher and 25 students +- **THEN** "ט'3" appears in the class list with those lessons, that teacher and 25 students, and its AI switch is off + +#### Scenario: Teacher listed as a student +- **WHEN** a manager names "t@school.org" as the teacher and also lists it as a student of the same class +- **THEN** the class is not saved and the manager is told why + +#### Scenario: A refused save keeps what was typed +- **WHEN** a manager changes a class's name and teacher, presses save at the bottom of the form, and the save is refused +- **THEN** the reason is shown next to the save button and in view, the typed name and teacher are still in the form, and nothing was saved + +### Requirement: Editing and deleting a class +A manager SHALL be able to change a class's name, lessons, students, teacher, AI switch and budget, and delete a class after confirming. Neither SHALL delete any student's progress. + +#### Scenario: Deleting a class +- **WHEN** a manager deletes a class and confirms +- **THEN** the class is gone, and its students' progress is still there + +### Requirement: Class and student lists +A manager SHALL see every class with its name, lessons, number of students and their emails and its teacher, and a list of all students with the classes each belongs to. + +#### Scenario: A student in two classes +- **WHEN** a manager opens the students list and a student belongs to "ט'3" and "ט'4" +- **THEN** that student's row shows both classes + +### Requirement: Teacher home +A teacher's home SHALL list the classes they teach, each with its students. A teacher MUST NOT be able to change a class's name, lessons, teacher, AI switch or budget. + +#### Scenario: Two classes +- **WHEN** a teacher who teaches "ט'3" and "ט'4" signs in +- **THEN** their home lists both classes with their students + +#### Scenario: No class yet +- **WHEN** a teacher who teaches no class signs in +- **THEN** their home says that a manager chooses who teaches each class + +### Requirement: A student's lessons +A student's lessons SHALL be the lessons of all the classes they belong to. + +#### Scenario: Two classes, different lessons +- **WHEN** a student is in one class studying lessons A and B and another studying B and C +- **THEN** the student's lessons are A, B and C + +### Requirement: First sign-in links the account +The first time a person signs in, their account SHALL be linked to the class entries and roles stored for their email. + +#### Scenario: Added before signing in +- **WHEN** a manager adds "noa@school.org" to "ט'3" and Noa signs in for the first time +- **THEN** Noa is a student of "ט'3" + +### Requirement: Sign-in problems are explained +When the sign-in service cannot be reached the sign-in page SHALL say so and offer to try again. When a session has expired the person SHALL return to the sign-in page with a short message. + +#### Scenario: Service down +- **WHEN** the sign-in service does not answer +- **THEN** the sign-in page says it could not connect and shows a "try again" button + +### Requirement: Every request is checked +The server SHALL check the sign-in and the caller's permissions on every request except the health check. + +#### Scenario: No sign-in +- **WHEN** any request other than the health check arrives without a valid sign-in +- **THEN** the server refuses it diff --git a/openspec/specs/app-basics/spec.md b/openspec/specs/app-basics/spec.md index f4d055931e99acf25d9817c1366c2a79c8b8695f..83c98388d387acec2fec029ba611bce585cf4db6 100644 --- a/openspec/specs/app-basics/spec.md +++ b/openspec/specs/app-basics/spec.md @@ -7,15 +7,94 @@ Sets the rules every Mathly screen follows: Hebrew right-to-left, phone first, a ## Requirements ### Requirement: Hebrew, right-to-left, phone first -Every screen SHALL be in Hebrew, laid out right-to-left, and designed for phones first. +Every screen SHALL be in Hebrew, laid out right-to-left, and designed for phones first. The teacher, manager, admin and developer screens SHALL also work well on a computer. #### Scenario: Opening on a phone - **WHEN** a student opens the app on a phone - **THEN** the screen is in Hebrew, right-to-left, and fits the phone's width +#### Scenario: Manager on a computer +- **WHEN** a manager opens the classes screen on a computer +- **THEN** the class list uses the wide screen and nothing is cut off + ### Requirement: Grades that count are kept on the server Quiz, exercise test and simulation grades SHALL be computed and stored on the server, so a student cannot change them from the device. #### Scenario: Tampered device - **WHEN** a student changes a grade stored on their device - **THEN** the grade shown to them and the teacher is still the server's grade + +### Requirement: The sky look +Every screen SHALL follow one "sky" look: a dark-blue night with aurora and starlight accents, gold for mastery, and an owl mascot. The app SHALL always be dark, as mathly1 is; there is no light mode. The page background SHALL be a dark night with two soft glows and small fixed stars. + +#### Scenario: A light device +- **WHEN** the device asks for light mode +- **THEN** every screen is still dark, with readable text + +#### Scenario: The sky behind the page +- **WHEN** any screen is open +- **THEN** the page background is dark, with two soft glows (blue at the top right, purple at the left) and small stars, all fixed while the page scrolls, and nothing in the background moves + +### Requirement: Readable without color or motion +State and result SHALL never be shown by color alone: every state has a symbol or a word. Touch targets SHALL be at least 44px. Animations SHALL stop when the device asks for reduced motion. + +#### Scenario: Reduced motion +- **WHEN** the device asks for reduced motion +- **THEN** no element of the app animates + +### Requirement: Server time and decisions +The server SHALL decide the date of every event by its own clock and the calendar day in Israel, never the device's. Correctness of answers, mastery, grades, budgets and timers SHALL be decided and stored on the server. + +#### Scenario: Device clock changed +- **WHEN** a student sets the device's date to tomorrow and answers a question +- **THEN** the answer is dated by the server's today + +### Requirement: mathly1 stays available +The app SHALL only add its own tables (named with an `m2_` prefix) and MUST NOT change, empty or delete any table, policy or storage bucket that mathly1 uses, so the Hugging Face Space can be switched back to mathly1 with its data as it was. + +#### Scenario: Switching back +- **WHEN** the Space is switched back to mathly1 after mathly2 has run +- **THEN** mathly1's students find their data as they left it + +### Requirement: Safe settings +The server SHALL refuse to start when only some of the Supabase settings are given. With none given it SHALL run for local development with an in-memory store and a sign-in, marked "dev only", that accepts an email address. + +#### Scenario: Half-configured +- **WHEN** the server starts with a Supabase URL but no secret key +- **THEN** it does not start and says which settings are missing + +### Requirement: Where settings come from +The server SHALL read its settings from real environment variables first, then from the app's own `.env` file if it has one, then from the repository's `.env` file shared with mathly1. A setting found in an earlier source SHALL win over the same setting in a later one. + +#### Scenario: Shared file +- **WHEN** the app has no `.env` of its own and the repository's `.env` holds the Supabase settings +- **THEN** the app uses those settings + +#### Scenario: A real variable wins +- **WHEN** the teacher list is set in the environment and in a file +- **THEN** the environment's list is used + +### Requirement: Database problems are explained +When the database cannot be reached, or refuses a request that is not a conflict the person caused, the person SHALL see a message saying the database did not answer or refused, with a hint that the migrations may be missing, and the reason SHALL be written to the server log. The app MUST NOT report such a failure as a different problem, such as a name already in use. + +#### Scenario: Missing column +- **WHEN** a manager saves a class and the database refuses because a migration was not applied +- **THEN** the manager sees that the database refused the request, not that the class name is taken, and the server log names the refusal + +### Requirement: Updates reach every device +After the app is updated, every device SHALL get the new page, styles and scripts the next time it opens the app, without the user clearing a cache. A file that did not change MAY still come from the device's cache once the server confirms it is unchanged. + +#### Scenario: New look after an update +- **WHEN** the styles change on the server and a student who used the app before opens it again +- **THEN** the student sees the new styles without a forced reload + +#### Scenario: Unchanged files +- **WHEN** a device asks again for a file that did not change +- **THEN** the server answers that it is unchanged and the device uses its saved copy + +### Requirement: The app's icon +The app SHALL declare its icon (mathly1's, from `static/icons/`), so the browser tab shows it and the browser does not ask for a missing icon. + +#### Scenario: Opening the app +- **WHEN** someone opens the app +- **THEN** the tab shows the app's icon and no request for an icon fails diff --git a/openspec/specs/exercise-bank/spec.md b/openspec/specs/exercise-bank/spec.md index f6d1f1186363bedbaa2f19149c4e6fb60508e001..06c2ef1af5add6f07712482a3522244dfe2c554b 100644 --- a/openspec/specs/exercise-bank/spec.md +++ b/openspec/specs/exercise-bank/spec.md @@ -7,22 +7,44 @@ Defines the exercise bank kept from the current app as the source of lessons, sk ## Requirements ### Requirement: Bank is the content source -Lessons, skills, multiple-choice questions and mistakes SHALL come from the exercise bank kept from the current app. Each wrong choice of a question SHALL point to a mistake with a name, a tip and the skill to go back to. +Lessons, skills, multiple-choice questions and mistakes SHALL come from the exercise bank kept from mathly1. Every question SHALL have exactly one correct choice, and each wrong choice SHALL point to a mistake with a name and a tip. A mistake MAY also name a skill to go back to. #### Scenario: Wrong choice - **WHEN** a student picks a wrong choice - **THEN** the mistake it points to supplies the feedback's name and tip +#### Scenario: Mistake without a skill to go back to +- **WHEN** a mistake names no skill to go back to +- **THEN** the feedback shows its name and tip with no link + ### Requirement: Math is rendered -Math written in LaTeX inside `$…$` in the bank SHALL be rendered as math in the app. +Math written inside `$…$` in the bank SHALL be shown as formulas. A question with a geometry figure or a graph SHALL show it. #### Scenario: Question with math - **WHEN** a question's text contains `$x^2+5x+6$` - **THEN** the student sees it as a formatted formula -### Requirement: Content gaps are filled before use -Worked examples, faded examples, "why this step?" choices and quizzes for every lesson SHALL be added to the bank, since it lacks them today. Each skill SHALL have enough questions for similar questions and for retakes that draw new questions. +#### Scenario: Question with a figure +- **WHEN** a question has a geometry figure +- **THEN** the figure is drawn under the question's text + +### Requirement: Bank checked at start +The server SHALL check the bank when it starts: unique ids, one correct choice per question, and every mistake and skill referred to exists. A broken bank SHALL stop the server from starting and say what is wrong. + +#### Scenario: Unknown mistake +- **WHEN** a choice points to a mistake id that does not exist +- **THEN** the server does not start and names the question and the id + +### Requirement: No answers on the device +A practice, quiz or test question sent to the device MUST NOT carry any sign of which choice is correct. The server SHALL grade. + +#### Scenario: Reading the network +- **WHEN** a student looks at the question the device received +- **THEN** nothing in it marks the correct choice + +### Requirement: Content gaps are listed +A tool SHALL list what the bank still lacks: skills without a solved example, skills without questions or with few, and mistakes without a skill to go back to. -#### Scenario: Skill without a worked example -- **WHEN** a skill has no worked example in the bank yet -- **THEN** it is listed as a content gap to fill +#### Scenario: Skill without questions +- **WHEN** the tool runs on the current bank +- **THEN** it lists the skill that has no multiple-choice question diff --git a/openspec/specs/exercise-screen/spec.md b/openspec/specs/exercise-screen/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..2f6e4967861f102a0c593e7e79534eb93d11cf37 --- /dev/null +++ b/openspec/specs/exercise-screen/spec.md @@ -0,0 +1,69 @@ +# exercise-screen Specification + +## Purpose +The screen where a student practices one skill with the exercise bank's questions: instant feedback that teaches from the mistake, help when stuck, and the board to work things out. + +## Requirements + +### Requirement: Layout +The exercise screen SHALL open as a sheet over the path. Its header SHALL show the lesson's name, the skill's name, a completed mark when the skill is mastered, a board button, a "?" help button and a close button, with the skill's short explanation under it. + +#### Scenario: Opening a skill +- **WHEN** a student opens the skill "פירוק טרינום" +- **THEN** the sheet shows the lesson's name, "פירוק טרינום", the board, "?" and close buttons, and the explanation + +### Requirement: One question at a time +The sheet SHALL show one question: its text with formulas, its figure or graph if any, and its choices in a new random order each time it is shown, with "question n of N" and a row of dots for the skill's questions. + +#### Scenario: Same question again +- **WHEN** a question is shown a second time +- **THEN** its choices may be in a different order, and the server still grades by the bank's choice + +### Requirement: A right answer +A right answer SHALL get a short celebration and the count of right answers in a row. After a short countdown the next question SHALL appear; the student can skip or cancel the countdown. + +#### Scenario: Countdown +- **WHEN** a student answers correctly +- **THEN** a countdown to the next question starts, and pressing "next" shows it at once + +### Requirement: A wrong answer +A wrong answer SHALL be quiet and SHALL show the name and tip of the mistake attached to the chosen choice, about the mistake and not the student. It MUST NOT reveal the correct answer. When the mistake names a skill to go back to, the feedback SHALL link to it. + +#### Scenario: Sign mistake +- **WHEN** a student picks a choice tagged with "טעות סימן באיבר האמצעי" +- **THEN** the mistake's name and tip are shown and no choice is marked as correct + +### Requirement: A different next question +After any answer the next question SHALL be another question of the same skill, picked at random among those this student has seen least, never the one just answered. A skill with one question repeats it. + +#### Scenario: After a mistake +- **WHEN** a student answers a question wrongly +- **THEN** the next question is not the one just answered + +### Requirement: Help +The "?" button SHALL show the skill's explanation and, where the bank has one, a solved example. Opening it SHALL make the answer to the question on screen not count for mastery; that answer still counts for the daily goal. + +#### Scenario: Help opened +- **WHEN** a student opens "?" and then answers correctly +- **THEN** the answer is stored as given with help and does not count toward mastery + +### Requirement: Related skills +The sheet SHALL show the skills this one requires and the skills it opens as tappable chips, which open those skills and never lock anything. + +#### Scenario: Required skill +- **WHEN** a student taps a "requires" chip +- **THEN** that skill's exercise screen opens + +### Requirement: Resuming +Reopening a skill SHALL continue with the question that was on screen, and an answer to a question that is no longer on screen SHALL be refused. + +#### Scenario: Two tabs +- **WHEN** a student answers in one tab a question that another tab already replaced +- **THEN** the answer is refused and the screen shows the current question + +### Requirement: Skill without questions +A skill with no questions SHALL say there is no practice for it yet, and cannot be mastered. + +#### Scenario: Empty skill +- **WHEN** a student opens a skill with no questions +- **THEN** the sheet says there is no practice yet diff --git a/openspec/specs/exercise-tests/spec.md b/openspec/specs/exercise-tests/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..701bf48c03fd354a0acca0119b14dcb4f3d19a06 --- /dev/null +++ b/openspec/specs/exercise-tests/spec.md @@ -0,0 +1,45 @@ +# exercise-tests Specification + +## Purpose +Two timed, mixed practice tests per real test that train the student under test conditions and aim at their weak skills, retakeable until they are good. + +## Requirements + +### Requirement: Created by the app +When a teacher sets a test, the app SHALL create 2 exercise tests for every student of the class and place them on the student's countdown. + +#### Scenario: New test +- **WHEN** a teacher sets a test for a class of 25 +- **THEN** each of the 25 students has exercise test 1 and exercise test 2 on their countdown + +### Requirement: Like the real test +An exercise test SHALL have the real test's number of questions and time limit, mix questions from all the covered lessons, hide skill names, and give feedback only at the end. + +#### Scenario: During the test +- **WHEN** a student answers a question in an exercise test +- **THEN** no right or wrong is shown until the test ends + +### Requirement: Question mix +Exercise test 1 SHALL draw 60% of its questions from weak skills and 40% from other covered skills; exercise test 2 SHALL draw 30% and 70%. A weak skill is one in the learning state or answered wrong in an earlier exercise test. Not-started skills MUST NOT appear; they are listed as "practice these first". Missing weak questions are filled from other covered skills. + +#### Scenario: Few weak skills +- **WHEN** exercise test 1 needs 7 weak questions and the student has weak skills for only 3 +- **THEN** the other 9 questions come from other covered skills + +#### Scenario: Not started +- **WHEN** a covered skill is not started +- **THEN** it has no question in the test and is listed under "practice these first" + +### Requirement: Retakes +The student SHALL be able to start or retake an exercise test at any time. Each retake SHALL draw new questions; the best grade counts. + +#### Scenario: Retake +- **WHEN** a student retakes exercise test 2 +- **THEN** it has new questions, and their best grade of the two attempts counts + +### Requirement: Result links back +After an exercise test the student SHALL see their grade and the weak skills found, each linked to its star on the path. The correct answers MUST NOT be shown. + +#### Scenario: Result +- **WHEN** a student finishes an exercise test with mistakes in two skills +- **THEN** the result lists those two skills with links to their stars diff --git a/openspec/specs/grades/spec.md b/openspec/specs/grades/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..419274ff4fac11c562746e32bef04cee5840df1e --- /dev/null +++ b/openspec/specs/grades/spec.md @@ -0,0 +1,31 @@ +# grades Specification + +## Purpose +One grade scale and one rule for timed attempts across quizzes, exercise tests, the simulation and assignments, and the screen where a student sees all their grades. + +## Requirements + +### Requirement: One grade scale +Every grade SHALL be a whole number from 0 to 100. In a multiple-choice quiz or test every question SHALL be worth the same, and the grade SHALL be the share of right answers, rounded. + +#### Scenario: Seven of ten +- **WHEN** a student answers 7 of 10 questions correctly +- **THEN** the grade is 70 + +#### Scenario: Eight of twelve +- **WHEN** a student answers 8 of 12 questions correctly +- **THEN** the grade is 67 + +### Requirement: When time ends +When the timer of a timed attempt ends, the server SHALL submit it as it stands, and unanswered questions SHALL count as wrong. Closing or refreshing the app MUST NOT stop or reset the timer. + +#### Scenario: Closed the app +- **WHEN** a student closes the app 5 minutes into a 15-minute quiz and opens it 20 minutes later +- **THEN** the quiz has been submitted with the answers given + +### Requirement: Grades screen +The student SHALL have a grades screen listing every grade they have: each lesson's quiz (best grade), and every exercise test, simulation and assignment grade as those exist. + +#### Scenario: After a quiz +- **WHEN** a student finishes a lesson's quiz +- **THEN** the grades screen shows that lesson's best quiz grade diff --git a/openspec/specs/learning-path/spec.md b/openspec/specs/learning-path/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..6fbe115b72e6cfaef3a2e2fb1330b662db80060c --- /dev/null +++ b/openspec/specs/learning-path/spec.md @@ -0,0 +1,74 @@ +# learning-path Specification + +## Purpose +The student's main screen: every lesson of their classes as a hub with its skills as stars, joined in one trail, so they always see where they stand and where to continue. + +## Requirements + +### Requirement: Choosing a subject +After sign-in a student SHALL first see the subjects of their classes as cards, each with its name and a bar "N מתוך M מיומנויות". Math (מתמטיקה) is the only subject. Tapping a card SHALL open the subject's home, reached by the tab bar, and every screen of the subject SHALL have a way back to the subjects. + +#### Scenario: After signing in +- **WHEN** a student signs in +- **THEN** they see a card "מתמטיקה" with "N מתוך M מיומנויות", and no path yet + +#### Scenario: Opening the subject +- **WHEN** the student taps the math card +- **THEN** the math home opens, with the tab bar and a way back to the subjects + +#### Scenario: A link to a skill +- **WHEN** a student opens `#/skill/` directly or reloads the page on it +- **THEN** the math path opens with that skill's exercise screen over it + +### Requirement: Trail of lesson hubs +Every lesson of the student's classes SHALL be a hub showing its name and "mastered of total", with its skills in a ring around it, in order, numbered from the top and clockwise. The hubs SHALL be joined by a vertical trail from a start marker with the owl to an end marker. + +#### Scenario: Opening the path +- **WHEN** a student opens the path +- **THEN** each of their lessons is a hub with its numbered skills around it, on one trail + +### Requirement: Stars show state in words +Each skill SHALL be a star whose look shows its state, with a symbol and word under it: "○ לא התחלת", "◐ בלמידה" or "✓ נשלטה". A mastered star SHALL look clearly different from the other two. + +#### Scenario: Three states +- **WHEN** a lesson has a mastered, a learning and a not-started skill +- **THEN** their stars show "✓ נשלטה", "◐ בלמידה" and "○ לא התחלת" + +### Requirement: Next skill +One skill SHALL carry the owl as the suggested next: the unmastered skill answered most recently, else the first unmastered skill in the bank's order. When all are mastered none is marked. The marker MUST NOT lock, hide or reorder anything. + +#### Scenario: New student +- **WHEN** a student who answered nothing opens the path +- **THEN** the owl is on the first skill of the first lesson and every skill can be opened + +#### Scenario: Continuing +- **WHEN** a student's last answer was on an unmastered skill +- **THEN** the owl is on that skill + +### Requirement: All open +The student SHALL be able to open any lesson and any skill in it at any time, in any order. + +#### Scenario: Jumping ahead +- **WHEN** a student opens a skill in the last lesson first +- **THEN** its exercise screen opens + +### Requirement: Opening a skill from the path +Tapping a star SHALL open its exercise screen over the path; closing it SHALL show the path with the star updated. The path SHALL open scrolled to the next skill. + +#### Scenario: Back from practice +- **WHEN** a student masters a skill and closes the sheet +- **THEN** its star on the path shows "✓ נשלטה" + +### Requirement: Accessible stars +Each star SHALL be a control whose accessible name is its number, the skill's name and its state in words, reachable and opened from the keyboard. + +#### Scenario: Keyboard +- **WHEN** a student moves to a star with Tab and presses Enter +- **THEN** its exercise screen opens + +### Requirement: Fits a phone +The path SHALL fit a 360px-wide screen without sideways scrolling, including the lesson with the most skills. + +#### Scenario: Six skills +- **WHEN** the lesson with six skills is shown on a 360px screen +- **THEN** all six stars and their words are visible without sideways scrolling diff --git a/openspec/specs/lesson-quizzes/spec.md b/openspec/specs/lesson-quizzes/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..5b4ba6a6ca6eb606998f5eaa84f636dc4d48f74b --- /dev/null +++ b/openspec/specs/lesson-quizzes/spec.md @@ -0,0 +1,45 @@ +# lesson-quizzes Specification + +## Purpose +A retakeable quiz for every lesson that gives the lesson its grade and points the student back to the skills that lost points. + +## Requirements + +### Requirement: A quiz per lesson +Every lesson SHALL have one quiz, shown as a node on the trail after the lesson's ring and always open. The student SHALL be able to retake it at any time; the best grade SHALL be the lesson's grade. + +#### Scenario: Better retake +- **WHEN** a student scores 60 and then 85 on a lesson's quiz +- **THEN** the lesson's grade is 85 + +#### Scenario: Worse retake +- **WHEN** a student scores 85 and then 70 +- **THEN** the lesson's grade stays 85 + +### Requirement: Quiz format +A quiz SHALL be 10 multiple-choice questions drawn from the bank questions of the lesson's skills, at least one per skill and the rest spread evenly, in 15 minutes. Skill names MUST NOT be shown, and there SHALL be no feedback until the end. The board and calculator SHALL be available. + +#### Scenario: Lesson with four skills +- **WHEN** a quiz is drawn for a lesson with four skills +- **THEN** it has 10 questions and every skill has at least two + +### Requirement: Retakes draw new questions +Each retake SHALL prefer questions the student has not had in earlier attempts at this quiz, the least-used first. + +#### Scenario: Second attempt +- **WHEN** a student retakes a quiz +- **THEN** none of its questions were in the first attempt, as long as the lesson has enough unused questions + +### Requirement: After a quiz +After a quiz the student SHALL see the grade, the skills where points were lost (each linked to its star) and, for each missed question, the name and tip of the mistake. The correct answers MUST NOT be shown. + +#### Scenario: Two misses +- **WHEN** a student misses two questions of one skill +- **THEN** the result lists that skill with a link and shows the two mistakes' names and tips, without the right answers + +### Requirement: Written quizzes are not lesson quizzes +The written quizzes authored in the bank SHALL NOT be used as lesson quizzes; they are offered to teachers as assignments. + +#### Scenario: Lesson with an authored written quiz +- **WHEN** a student opens the quiz of a lesson that has an authored written quiz in the bank +- **THEN** the quiz is the 10-question multiple-choice quiz diff --git a/openspec/specs/readiness-meter/spec.md b/openspec/specs/readiness-meter/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..f2bc2a8f697689e4f62de5feb586fe2c3af8f42c --- /dev/null +++ b/openspec/specs/readiness-meter/spec.md @@ -0,0 +1,31 @@ +# readiness-meter Specification + +## Purpose +Shows the student and the teacher, as one honest number, how ready the student is for an upcoming test, and what it is made of. + +## Requirements + +### Requirement: One readiness number +For each upcoming test the app SHALL show the student and the teacher a number from 0 to 100, drawn as a level bar, with its parts under it: M, the % of covered skills mastered; E, the average of the best grade of each exercise test taken; S, the simulation grade once taken. + +#### Scenario: Parts shown +- **WHEN** a student opens the reminder of a test +- **THEN** the bar shows the number with M, E and S under it + +### Requirement: How the number is made +The number SHALL be the weighted average of the parts that exist, with weights M 50, E 20 and S 30; a part that does not exist yet is left out and the others are scaled up. + +#### Scenario: Only mastery so far +- **WHEN** a student has mastered 60% of the covered skills and taken no tests +- **THEN** the number is 60 + +#### Scenario: All three parts +- **WHEN** M is 80, E is 70 and S is 90 +- **THEN** the number is 81 + +### Requirement: No false confidence +Until the simulation is taken the number SHALL be capped at 80, and the bar SHALL say so. The label SHALL be "מתחילים" for 0–39, "בדרך" for 40–69, "כמעט שם" for 70–84 and "מוכנים" for 85–100; "מוכנים" can only show after the simulation. + +#### Scenario: Strong before the simulation +- **WHEN** M is 100 and E is 95 and the simulation is not taken +- **THEN** the number shows 80 with a note that the simulation is still missing diff --git a/openspec/specs/real-tests/spec.md b/openspec/specs/real-tests/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..39c2bf47ba4538896bb3285b79457c0f432c210d --- /dev/null +++ b/openspec/specs/real-tests/spec.md @@ -0,0 +1,27 @@ +# real-tests Specification + +## Purpose +Lets a teacher put a class's real school test into the app, so the app can prepare the students for it, and lets the teacher follow who has taken the required simulation. + +## Requirements + +### Requirement: Setting a test +The teacher of a class SHALL be able to set a test for it: a date, the lessons it covers (from the class's lessons), an optional note, the number of questions and the time limit. The number of questions SHALL default to 12 and the time limit to 45 minutes; both can be changed. + +#### Scenario: Defaults +- **WHEN** a teacher sets a test without changing the number of questions or the time +- **THEN** the test has 12 questions and 45 minutes + +### Requirement: Changing or removing a test +The teacher SHALL be able to change a test's date, lessons, note, length and time before its date, and remove it. Grades already earned in its exercise tests and simulation SHALL stay. + +#### Scenario: Moving the date +- **WHEN** a teacher moves a test two days later +- **THEN** every student's countdown follows the new date + +### Requirement: Tests tab +The teacher SHALL have a tests tab listing their classes' tests and, for each test, which students have taken the simulation and which have not. + +#### Scenario: Three missing +- **WHEN** 22 of 25 students took the simulation +- **THEN** the tab shows 22 done and names the 3 who have not diff --git a/openspec/specs/rewards/spec.md b/openspec/specs/rewards/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..565a3ee1d462b4c6d5f0863c4629c89e12f1c08c --- /dev/null +++ b/openspec/specs/rewards/spec.md @@ -0,0 +1,74 @@ +# rewards Specification + +## Purpose +Rewards that bring a student back to practice: a daily goal and streak, stars that fade when neglected, a collection of what they achieved, and rare comets to catch. None of them changes a skill's state or a grade. + +## Requirements + +### Requirement: Daily goal +A day with 5 correct answers SHALL be a streak day. The path SHALL show today's count toward 5. Answers given after opening help SHALL count toward the goal. + +#### Scenario: Goal reached +- **WHEN** a student answers a fifth question correctly today +- **THEN** today's goal shows as reached + +### Requirement: Streak +The path SHALL show the number of streak days in a row. Until today's 5 are reached, the streak SHALL be counted up to yesterday and shown as still alive. + +#### Scenario: Morning +- **WHEN** a student with a 4-day streak opens the app in the morning with no answers yet today +- **THEN** the streak still shows 4 + +#### Scenario: Missed day +- **WHEN** a student had no streak day yesterday +- **THEN** the streak starts again from today + +### Requirement: Fading stars +A mastered skill the student has not answered for 14 days SHALL show a faded star that says "דועך". One answer on that skill SHALL relight it. Fading MUST NOT change the skill's state, the readiness meter, the heat map or the exercise tests. + +#### Scenario: Two weeks +- **WHEN** a student has not answered a mastered skill for 15 days +- **THEN** its star is dimmed with "דועך", and the skill still counts as mastered + +#### Scenario: Relighting +- **WHEN** the student answers one question of that skill, right or wrong +- **THEN** the star is bright again + +### Requirement: Collection +A collection screen SHALL show each mastered skill as a star and each completed lesson (all its skills mastered) as a constellation drawn from its stars. + +#### Scenario: Completed lesson +- **WHEN** a student masters the last skill of a lesson +- **THEN** that lesson's constellation appears in the collection + +### Requirement: Comets cross +After a right answer on the exercise screen a comet MAY cross the screen for a few seconds, at most once a day. The first comet SHALL come the first time the student reaches the daily goal; afterwards each right answer has a chance of about 12% while comets are left to catch. + +#### Scenario: First daily goal +- **WHEN** a student reaches the daily goal for the first time ever +- **THEN** a comet crosses the screen + +#### Scenario: Once a day +- **WHEN** a student already saw a comet today +- **THEN** no other comet comes today + +### Requirement: Catching comets +Tapping a crossing comet SHALL catch it: a comet the student does not have yet, at random, shown with its name and fact. There SHALL be twelve: π, Fibonacci, the golden ratio, infinity, e, √2, zero, Pythagoras, primes, Pascal's triangle, Euler's formula and the Möbius strip. Comets stop when all are caught. + +#### Scenario: Catch +- **WHEN** a student taps a crossing comet +- **THEN** a comet they did not have is added to their collection with its fact + +### Requirement: Comets in the collection +The collection SHALL show every caught comet with its symbol, name and fact, and every missing one as "?" with "עוד לא נתפס". + +#### Scenario: Three caught +- **WHEN** a student caught three comets +- **THEN** the collection shows three comets and nine "?" + +### Requirement: Comets with reduced motion +With reduced motion a comet SHALL NOT cross the screen; the student SHALL be offered it once as a tappable item instead. + +#### Scenario: Reduced motion +- **WHEN** a comet is due and the device asks for reduced motion +- **THEN** a still comet button appears once instead of a moving comet diff --git a/openspec/specs/simulation-test/spec.md b/openspec/specs/simulation-test/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..2b92e631764954528789fe3680c206d06cde0946 --- /dev/null +++ b/openspec/specs/simulation-test/spec.md @@ -0,0 +1,34 @@ +# simulation-test Specification + +## Purpose +One full rehearsal of the real test a few days before it, so the student knows where they stand while there is still time to fix the gaps it finds. + +## Requirements + +### Requirement: Required, one attempt +Every student SHALL take one simulation per real test, and it SHALL be possible to take it only once. + +#### Scenario: Second try +- **WHEN** a student who finished the simulation opens it again +- **THEN** they see their result and cannot start it again + +### Requirement: Like the real test +The simulation SHALL cover all the lessons of the real test, with its number of questions and time limit, no skill names and no feedback until the end. + +#### Scenario: Length +- **WHEN** the real test has 12 questions and 45 minutes +- **THEN** the simulation has 12 questions and 45 minutes + +### Requirement: Window +The simulation SHALL be open from about 5 days before the test until the test day, and SHALL be shown as required on the student's home until it is taken. + +#### Scenario: Too early +- **WHEN** a student opens the simulation 8 days before the test +- **THEN** it says when it opens and does not start + +### Requirement: Review tasks +After the simulation the app SHALL list the skills that failed and make them the review tasks of the last days of the countdown. + +#### Scenario: Two failed skills +- **WHEN** a student fails two skills in the simulation +- **THEN** those two skills are today's review tasks in the last days diff --git a/openspec/specs/skill-mastery/spec.md b/openspec/specs/skill-mastery/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..8d9d4d9aa96780fa6dcb2a1ed0b1b8e27070e4b1 --- /dev/null +++ b/openspec/specs/skill-mastery/spec.md @@ -0,0 +1,49 @@ +# skill-mastery Specification + +## Purpose +Decides, on the server, which state each skill is in for each student, so mastery is proven by answers over time and never assumed. + +## Requirements + +### Requirement: Skill states +Every skill SHALL be, for every student, in exactly one state: not started (no answers yet), learning (at least one answer, not mastered) or mastered. + +#### Scenario: First answer +- **WHEN** a student answers the first question of a skill +- **THEN** the skill moves from not started to learning + +### Requirement: Mastery rule +A skill SHALL become mastered when the student answers 3 of its questions correctly in a row, each on the first try and without opening help, and these 3 answers fall on at least 2 different calendar days. + +#### Scenario: Two days +- **WHEN** a student answers 2 correctly on Monday and 1 correctly on Tuesday, all first try and without help +- **THEN** the skill becomes mastered + +#### Scenario: One day +- **WHEN** a student answers 3 correctly in a row on the same day +- **THEN** the skill is still learning + +#### Scenario: A wrong answer +- **WHEN** a student answers 2 correctly, then 1 wrongly, then 1 correctly +- **THEN** the run restarts from the last correct answer + +### Requirement: Help does not break the run +An answer given after the student opened help on that question SHALL be skipped for mastery: it neither counts toward the 3 nor breaks the run. + +#### Scenario: Help between correct answers +- **WHEN** a student answers 2 correctly on Monday, a third with help, and a fourth correctly on Tuesday without help +- **THEN** the skill becomes mastered + +### Requirement: Mastery does not decay +A mastered skill SHALL stay mastered, even after later wrong answers or months without practice. + +#### Scenario: Months later +- **WHEN** a student who mastered a skill in October answers a question on it wrongly in March +- **THEN** the skill is still mastered + +### Requirement: Answers are dated by the server +Every answer SHALL be stored with the server's calendar day in Israel, and mastery SHALL be decided from these days. + +#### Scenario: Device clock changed +- **WHEN** a student changes the device's date before answering +- **THEN** the answer is dated by the server, and mastery uses that date diff --git a/openspec/specs/smart-board/spec.md b/openspec/specs/smart-board/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..681ffe35345fceb229abf8f033dacc984d03d57b --- /dev/null +++ b/openspec/specs/smart-board/spec.md @@ -0,0 +1,69 @@ +# smart-board Specification + +## Purpose +A drawing board for working out and handing in a full solution with pen, shapes, typed math and a calculator, beside the question on a computer and over it on a phone. + +## Requirements + +### Requirement: Opening the board +The board SHALL open from a button in the header of the exercise screen and of every other screen that offers it. On a computer it SHALL sit beside the exercise and the device SHALL remember whether it is on; on a phone or tablet it SHALL open full screen over the exercise and close back to the question. + +#### Scenario: Phone +- **WHEN** a student presses the board button on a phone +- **THEN** the board covers the screen, and closing it shows the same question + +### Requirement: Tools +The board SHALL offer: move; pen with three ink colors following pen pressure; straight line; circle dragged from its center; angle with an arc, its words and one to three arcs or a right-angle square; typed math with a ninth-grade math keyboard; eraser in three sizes; undo; and clear. + +#### Scenario: Typed math +- **WHEN** a student types a fraction with the math keyboard +- **THEN** it appears on the board as a formatted fraction that can be moved + +### Requirement: Everything is an object +Every stroke, line, circle, angle and formula SHALL be selectable, movable and erasable. Line ends and circle centers SHALL snap to existing ends and centers, and lines joined that way SHALL move together. + +#### Scenario: Closing a triangle +- **WHEN** a student draws three lines whose ends meet +- **THEN** the ends snap together and moving one corner moves both lines + +### Requirement: The question on the board +A copy of the question (text and figures) SHALL be placeable on the board. The eraser SHALL leave it alone; it is removed by selecting and deleting it. + +#### Scenario: Erasing near the question +- **WHEN** the eraser passes over the question's copy +- **THEN** the copy stays + +### Requirement: Endless paper with palm rejection +The paper SHALL grow downward and to the right and scroll with the wheel, two fingers, or dragging empty paper. Once a pen has touched the screen a single finger SHALL be ignored, and while the pen writes every touch and any wide contact SHALL be ignored. + +#### Scenario: Resting palm +- **WHEN** a student writes with a pen while their palm rests on the screen +- **THEN** only the pen draws + +### Requirement: Sketches stay on the device +Each question SHALL keep its own sketch while the page is open, and nothing SHALL be sent anywhere unless the student hands it in. + +#### Scenario: Switching questions +- **WHEN** a student draws on question 1, moves to question 2 and back +- **THEN** question 1's sketch is still there, and nothing was sent + +### Requirement: Handing in a sketch +Where a screen accepts a written answer, the board SHALL turn the sketch into a picture that the student hands in from the board. + +#### Scenario: Hand-in +- **WHEN** a student presses the board's hand-in button on such a screen +- **THEN** a picture of the sketch is handed in + +### Requirement: Calculator +A scientific calculator in the layout of a Casio fx-991ES PLUS, with SHIFT functions, SHALL open on a panel over a corner of the paper from a toolbar button, wherever the board is. + +#### Scenario: Sine +- **WHEN** a student opens the calculator and computes sin 30 in degrees +- **THEN** it shows 0.5 + +### Requirement: Labels and input +Every tool SHALL have a Hebrew label and an icon, and the board SHALL work with touch, pen and mouse. + +#### Scenario: Screen reader +- **WHEN** a screen reader reaches the pen tool +- **THEN** it reads its Hebrew name diff --git a/openspec/specs/student-home/spec.md b/openspec/specs/student-home/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..26065c2f60951c0cde39d352863a7b64add0b696 --- /dev/null +++ b/openspec/specs/student-home/spec.md @@ -0,0 +1,34 @@ +# student-home Specification + +## Purpose +The first screen of a subject, opened from its card: what to do today in one obvious button, the nearest test and its readiness, and a way back into the path. + +## Requirements + +### Requirement: Today's task +The home SHALL show, for the nearest test, the days left, the readiness meter and one task for today taken from the countdown plan, as a single obvious button that opens that task. + +#### Scenario: Exercise test due +- **WHEN** the nearest test is 9 days away and exercise test 1 is not taken +- **THEN** home shows one button that opens exercise test 1 + +### Requirement: Required simulation +While the simulation of an upcoming test is open and not taken, home SHALL show it as required. + +#### Scenario: Window open +- **WHEN** a test is 4 days away and the student has not taken its simulation +- **THEN** home shows the simulation marked as required + +### Requirement: Continue the path +Home SHALL have a button that opens the path's next skill. + +#### Scenario: No test +- **WHEN** a student has no upcoming test +- **THEN** home shows the button to continue at the next skill + +### Requirement: Tab bar +The student's screens (home, path, grades, collection) SHALL be reachable from a tab bar at the bottom of the screen. + +#### Scenario: Switching +- **WHEN** a student taps "ציונים" in the tab bar +- **THEN** the grades screen opens diff --git a/openspec/specs/test-countdown/spec.md b/openspec/specs/test-countdown/spec.md new file mode 100644 index 0000000000000000000000000000000000000000..ddcfadf04e62c204841dec9b7516d127bf46aa2b --- /dev/null +++ b/openspec/specs/test-countdown/spec.md @@ -0,0 +1,34 @@ +# test-countdown Specification + +## Purpose +Plans a student's last weeks before a real test, so they finish the path, practise under test conditions, take one simulation and review what failed, without planning it themselves. + +## Requirements + +### Requirement: The countdown plan +From the moment a test is set, every student of the class SHALL see a plan by days left: until 9, finish the path for the covered lessons; about 9, exercise test 1; about 7, exercise test 2; about 5, the simulation; 4 to 1, review the skills that failed in the simulation, with light mixed review the day before. + +#### Scenario: Twelve days ahead +- **WHEN** a test is 12 days away +- **THEN** the plan asks the student to finish the path for the covered lessons + +### Requirement: The days are recommendations +The student SHALL be able to start any step earlier or later than its day. + +#### Scenario: Early exercise test +- **WHEN** a student opens exercise test 1 eleven days before the test +- **THEN** it starts + +### Requirement: Short notice +When a test is set less than 9 days ahead, the plan SHALL keep the same order and shorten the gaps evenly. + +#### Scenario: Six days ahead +- **WHEN** a test is set 6 days ahead +- **THEN** the plan still runs path, exercise test 1, exercise test 2, simulation, review, in that order, within the 6 days + +### Requirement: Several tests +When several tests are coming up, today's task SHALL come from the closest one. + +#### Scenario: Two tests +- **WHEN** a student has tests in 4 and in 10 days +- **THEN** today's task comes from the test in 4 days diff --git a/static/math.css b/static/math.css index afa98025f7dd077ff82dfd745c25b112cbf563b5..9f243384c054e465b1cafed8bd8dce821d8f6ee7 100644 --- a/static/math.css +++ b/static/math.css @@ -186,6 +186,7 @@ html.math-on, html.math-on body{overflow:hidden} .mx-prompter-acts,.mx-prompter-row{display:flex;flex-wrap:wrap;gap:8px} .mx-prompter-list article[aria-current="true"]{outline:2px solid var(--mx-accent)} .mx-prompter-text{width:100%;box-sizing:border-box;min-height:220px;padding:12px;border:1px solid var(--line);border-radius:12px;font:inherit;font-size:17px;line-height:1.5;resize:vertical;background:var(--bg);color:inherit;margin-block:10px} +.mx-prompter-outline{margin-block:4px 12px}.mx-prompter-outline summary{cursor:pointer;font-weight:600;padding:6px 0}.mx-prompter-outline .mx-prompter-text{min-height:160px} .mx-manage-spacer{flex:1} .mx-manage-state{min-height:18px;margin:0;color:var(--muted);font-size:13px} .mx-manage-modes{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:4px;padding:4px;border-radius:14px;background:var(--line)} diff --git a/static/math.js b/static/math.js index f740ea6798fad646cfe3272d9ebaa6c8e19cd481..26100cc89e49e31121d4f5efe97f4de435bd622c 100644 --- a/static/math.js +++ b/static/math.js @@ -1752,6 +1752,7 @@ function onClick(e){ if(t.dataset.id) return open(t.dataset.id); if(t.dataset.manageMode) return showManageMode(t.dataset.manageMode); if(t.dataset.prompterPlay) return window.MathlyPrompter?.open(PR.texts.find(x=>x.id===t.dataset.prompterPlay)?.body); + if(t.dataset.prompterOutline) return prOutline(t.dataset.prompterOutline,t); if(t.dataset.prompterOpen) return prEdit(t.dataset.prompterOpen); if(t.dataset.prompterDel) return prDelete(t.dataset.prompterDel); if(t.dataset.classAction) return manageClassAction(t.dataset.classAction,t.dataset.classId); @@ -1771,6 +1772,7 @@ function onClick(e){ case "manage-lab": return showManageMode("lab"); case "manage-prompter": return showManageMode("prompter"); case "prompter-go": return window.MathlyPrompter?.open(sheet.querySelector("#mxPrompterText")?.value); + case "prompter-outline-go": return window.MathlyPrompter?.open(sheet.querySelector("#mxPrompterOutline")?.value); case "prompter-save": return prSave(false); case "prompter-save-new": return prSave(true); case "prompter-new": return prNew(); @@ -1912,20 +1914,31 @@ function showManageMode(mode){ /* Prompter (פרומפטר): a developer writes or picks a text and shows it full screen (static/prompter.js). Saved texts are kept with the account (app/prompter.py), so they are on every device; the text being edited is - also kept in this browser, so nothing is lost before it is saved. */ -let PR={texts:[],id:null,loaded:false}; + also kept in this browser, so nothing is lost before it is saved. + ראשי פרקים: for talking from reminders rather than reading, Claude writes a saved text's outline once (2–4 short + topics per slide, app/prompter.py); it is kept with the text and can be edited here. Saving a changed text + without touching its outline drops the outline, since it was written from the old text. */ +let PR={texts:[],id:null,loaded:false,outlineEdited:false}; function prDraft(){ try{return JSON.parse(localStorage.getItem("mathly.prompterDraft")||"null")||{title:"",body:localStorage.getItem("mathly.prompterText")||"",id:null};}catch{return {title:"",body:"",id:null};} } function prKeep(){ - const title=sheet.querySelector("#mxPrompterTitle"), body=sheet.querySelector("#mxPrompterText"); if(!title||!body) return; - try{localStorage.setItem("mathly.prompterDraft",JSON.stringify({title:title.value,body:body.value,id:PR.id}));}catch{} + const title=sheet.querySelector("#mxPrompterTitle"), body=sheet.querySelector("#mxPrompterText"), outline=sheet.querySelector("#mxPrompterOutline"); if(!title||!body) return; + try{localStorage.setItem("mathly.prompterDraft",JSON.stringify({title:title.value,body:body.value,outline:outline?.value||"",outlineEdited:PR.outlineEdited,id:PR.id}));}catch{} +} +function prShowOutline(text){ + const box=sheet.querySelector(".mx-prompter-outline"), area=sheet.querySelector("#mxPrompterOutline"); if(!box||!area) return; + area.value=text||""; box.open=!!text; PR.outlineEdited=false; } function prSay(text){ const el=sheet.querySelector(".mx-prompter-state"); if(el) el.textContent=text; } function prDate(at){ try{return new Date(at).toLocaleString("he-IL",{day:"numeric",month:"numeric",year:"2-digit",hour:"2-digit",minute:"2-digit"});}catch{return "";} } function drawPrompter(box){ - const draft=prDraft(); PR.id=draft.id||null; + const draft=prDraft(); PR.id=draft.id||null; PR.outlineEdited=!!draft.outlineEdited; box.innerHTML=`

    פרומפטר

    טקסט לקריאה מול המצלמה
    +
    ראשי פרקים +

    תזכורות קצרות לכל שקף, במקום לקרוא את הטקסט. לחצו „ראשי פרקים” ליד טקסט שמור ו־Claude יכין אותן; אפשר לערוך כאן ולשמור. כותרת שקף בשורה משלה, ואחריה שורות שמתחילות ב־•

    + +
    @@ -1937,6 +1950,7 @@ function drawPrompter(box){

    טקסטים שמורים

    טוענים…

    `; box.querySelectorAll("#mxPrompterTitle,#mxPrompterText").forEach(el=>el.addEventListener("input",prKeep)); + box.querySelector("#mxPrompterOutline").addEventListener("input",()=>{PR.outlineEdited=true; prKeep();}); prMark(); box.querySelector("#mxPrompterText").focus(); prLoad(); } @@ -1945,7 +1959,7 @@ function prList(){ const list=sheet.querySelector(".mx-prompter-list"); if(!list) return; sheet.querySelector(".mx-prompter-count").textContent=PR.texts.length?`${PR.texts.length} טקסטים`:""; list.innerHTML=PR.texts.length?PR.texts.map(t=>`${esc(t.title)}${esc(prDate(t.updated_at))} · ${t.body.length.toLocaleString("he-IL")} תווים - `).join("") + `).join("") :'

    עדיין אין טקסטים שמורים. כתבו טקסט ולחצו „שמירה”.

    '; } 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=`
    - + + + - - + + +
    +
    +
    +
    +
    + +
    `; + if(deck){ const he=/[\u0590-\u05ff\u0600-\u06ff]/.test(deck.map(d=>d.title).join(" ")); root.querySelector(".mxp-slide").dir=he?"rtl":"ltr"; } + root.querySelector(".mxp-sbody").addEventListener("scroll",()=>root&&more(),{passive:true}); scroller=root.querySelector(".mxp-scroll"); textEl=root.querySelector(".mxp-text"); guide=root.querySelector(".mxp-guide"); bar=root.querySelector(".mxp-bar"); - textEl.textContent=text; + if(deck){ // scrolling a slide script: the headings and timings are shown small and grey, not read out + const lines=String(text).split(/\r?\n/); + textEl.replaceChildren(...lines.flatMap((l,i)=>{ + const out=[]; if(i) out.push("\n"); + if(parsed.kinds[i]){ const s=document.createElement("span"); s.className="mxp-dir"; s.textContent=l; out.push(s); } else out.push(l); + return out; + })); + } else textEl.textContent=text; bar.addEventListener("click",e=>{const b=e.target.closest("[data-p]"); if(b) act(b.dataset.p);}); bar.querySelector(".mxp-speed").addEventListener("input",e=>{speed=+e.target.value; save(); sync();}); scroller.addEventListener("scroll",progress,{passive:true}); const view=root.querySelector(".mxp-view"); - view.addEventListener("click",()=>act("play")); + // a finger swipe across the slide: to the left the next slide, to the right the one before (up and down scroll a long slide) + view.addEventListener("pointerdown",e=>{ touch={x:e.clientX,y:e.clientY}; swiped=false; }); + view.addEventListener("pointercancel",()=>{ touch=null; }); + view.addEventListener("pointerup",e=>{ + if(!touch||mode!=="slides") return; + const dx=e.clientX-touch.x, dy=e.clientY-touch.y; touch=null; + if(Math.abs(dx)>50&&Math.abs(dx)>Math.abs(dy)*1.5){ swiped=true; act(dx<0?"next":"prev"); } + else if(Math.abs(dx)>10||Math.abs(dy)>10) swiped=true; // a drag that scrolled the notes is not a tap + }); + view.addEventListener("click",()=>{ if(swiped){swiped=false; return;} act(mode==="slides"?"next":"play"); }); view.addEventListener("wheel",e=>{ // while playing the wheel is a speed knob: down faster, up slower - if(!playing){acc=0; return;} + if(mode==="slides"||!playing){acc=0; return;} e.preventDefault(); wheel+=e.deltaMode?e.deltaY*40:e.deltaY; if(Math.abs(wheel)>=60){act(wheel>0?"faster":"slower"); wheel=0;} },{passive:false}); - view.addEventListener("contextmenu",e=>{e.preventDefault(); act("back");}); + view.addEventListener("contextmenu",e=>{e.preventDefault(); act(mode==="slides"?"prev":"back");}); // middle and side buttons: mouseup is where the browser would scroll or go back a page, so both are stopped - const extra={1:"top",3:"top",4:"play"}; - view.addEventListener("mousedown",e=>{if(extra[e.button]) e.preventDefault();}); - view.addEventListener("mouseup",e=>{const p=extra[e.button]; if(p){e.preventDefault(); act(p);}}); + view.addEventListener("mousedown",e=>{if([1,3,4].includes(e.button)) e.preventDefault();}); + view.addEventListener("mouseup",e=>{ + const p=({1:"top",3:"top",4:mode==="slides"?"next":"play"})[e.button]; if(p){e.preventDefault(); act(p);} + }); document.body.appendChild(root); document.addEventListener("keydown",onKey,true); document.addEventListener("fullscreenchange",onFull); - sync(); bar.querySelector(".mxp-play").focus(); + document.addEventListener("visibilitychange",onVisible); + addEventListener("resize",onTurn); + tickTimer=setInterval(drawClock,250); + sync(); if(mode==="slides") drawSlide(); + bar.querySelector(mode==="slides"?"[data-p=next]":".mxp-play").focus(); + wake(); // it opens full screen; this runs inside the click that opened it, which the browser requires. Where the browser // does not allow it (an iPhone), it simply stays as a full-page layer. const full=root.requestFullscreen||root.webkitRequestFullscreen; @@ -179,11 +377,13 @@ function open(text){ function close(){ if(!root) return; - clearTimeout(hintTimer); + clearTimeout(hintTimer); clearInterval(tickTimer); play(false); document.removeEventListener("keydown",onKey,true); document.removeEventListener("fullscreenchange",onFull); + document.removeEventListener("visibilitychange",onVisible); removeEventListener("resize",onTurn); + lock?.release?.().catch?.(()=>{}); lock=null; if(document.fullscreenElement) document.exitFullscreen?.(); - root.remove(); root=null; back?.focus?.(); back=null; + root.remove(); root=null; deck=null; back?.focus?.(); back=null; } -window.MathlyPrompter={open,close,isOpen:()=>!!root}; +window.MathlyPrompter={open,close,isOpen:()=>!!root,parse}; })(); diff --git a/supabase/migrations/20261107130000_math_prompter_outline.sql b/supabase/migrations/20261107130000_math_prompter_outline.sql new file mode 100644 index 0000000000000000000000000000000000000000..c9483ea7a7573effb138ca1e40cd7d37889bca68 --- /dev/null +++ b/supabase/migrations/20261107130000_math_prompter_outline.sql @@ -0,0 +1,10 @@ +-- The prompter's outlines (ראשי פרקים, app/prompter.py): short topic reminders per slide that Claude writes from a +-- saved text, kept with it. Additive: one nullable column, and the AI usage log may now also say 'prompter'. +-- Rollback: alter table public.math_prompter_texts drop column outline; and restore the old feature check. +begin; +alter table public.math_prompter_texts + add column outline text check (outline is null or char_length(outline) between 1 and 20000); +alter table public.math_ai_usage drop constraint math_ai_usage_feature_check; +alter table public.math_ai_usage add constraint math_ai_usage_feature_check + check (feature in ('photo', 'grading', 'prompter')); +commit; diff --git a/tests/test_phone_browser.py b/tests/test_phone_browser.py index d4d729155a804907f5fb5f12304d2d0aa74f2c8a..60af357102c4ba44cbb5268e1f36e500280cd7fc 100644 --- a/tests/test_phone_browser.py +++ b/tests/test_phone_browser.py @@ -1255,3 +1255,68 @@ def test_prompter_from_management(phone_server): playwright.expect(page.locator(".mx-manage-sheet")).to_be_visible() # Esc closes only the prompter finally: browser.close() + + +def test_prompter_outline_from_management(phone_server): + """ראשי פרקים: Claude writes a saved text's outline once (mocked here), then it opens at once and can be edited.""" + import json + + with playwright.sync_playwright() as p: + browser = p.chromium.launch() + try: + page = browser.new_page() + page.route("https://cdn.jsdelivr.net/**", lambda route: route.abort()) + page.add_init_script('''window.supabase={createClient:()=>({auth:{ + getSession:async()=>({data:{session:{access_token:"test",user:{id:"test"}}}}), + onAuthStateChange:()=>{},signOut:async()=>{} + }})};''') + + def index(route): + response = route.fetch() + route.fulfill(response=response, body=response.text().replace( + 'supabaseUrl:""', 'supabaseUrl:"https://auth.invalid"')) + + page.route(phone_server + "/", index) + page.route("**/api/me", lambda route: route.fulfill(json={ + "email": "dev@example.com", "user_id": "test", "answer_scans": False, + "permissions": ["management.access"], "classes": []})) + page.route("**/api/math/progress", lambda route: route.fulfill(json={"progress": {}})) + page.route("**/api/classes", lambda route: route.fulfill(json={"classes": []})) + row = {"id": "aaaaaaaa-aaaa-4aaa-8aaa-000000000001", "title": "Zohar's lecture", "outline": None, + "body": "Slide 1 — Hello\n35 seconds\nGood morning.\nSlide 2 — Bye\nThank you.", + "updated_at": "2026-11-07T10:00:00Z"} + calls = [] + outline = "Slide 1 — Hello\n35 seconds\n• Good morning\n\nSlide 2 — Bye\n• Thanks" + + def make(route): + calls.append(route.request.method) + row["outline"] = outline + route.fulfill(json={"text": row}) + + def save(route): + row.update(json.loads(route.request.post_data)) + route.fulfill(json={"text": row}) + page.route("**/api/prompter/texts", lambda route: route.fulfill(json={"texts": [row]})) + page.route("**/api/prompter/texts/*/outline", make) + page.route("**/api/prompter/texts/aaaaaaaa-aaaa-4aaa-8aaa-000000000001", save) + page.goto(phone_server) + page.locator('[data-act="manage"]').click() + page.locator('[data-act="manage-prompter"]').click() + page.locator("[data-prompter-outline]").click() # no outline yet: Claude writes it + playwright.expect(page.locator(".mxp")).to_have_count(1) + playwright.expect(page.locator(".mxp-sbody p.pt")).to_have_text(["Good morning"]) + playwright.expect(page.locator(".mx-prompter-state")).to_contain_text("מוכנים ונשמרו") + page.keyboard.press("Escape") + page.locator("[data-prompter-outline]").click() # now it opens with no second call + playwright.expect(page.locator(".mxp")).to_have_count(1) + assert calls == ["POST"] + page.keyboard.press("Escape") + page.locator("[data-prompter-open]").click() # editing shows the outline and saves it + area = page.locator("#mxPrompterOutline") + playwright.expect(area).to_have_value(outline) + area.fill(outline.replace("Thanks", "Thank you all")) + page.locator('[data-act="prompter-save"]').click() + playwright.expect(page.locator(".mx-prompter-state")).to_contain_text("נשמר") + assert "Thank you all" in row["outline"] + finally: + browser.close() diff --git a/tests/test_prompter.py b/tests/test_prompter.py index f80b0918c05a69710da5d3c794b4e85b997c589d..61cded0e15ffce95cb42b4c30facbffbecbc7c52 100644 --- a/tests/test_prompter.py +++ b/tests/test_prompter.py @@ -19,6 +19,7 @@ class PrompterAuth(ScanAuth): def __init__(self): self.rows: list[dict] = [] self.missing = False + self.no_outline = False # before the outline migration def user(self, token): return {'id': token, 'email': token + '@test.invalid'} if token in (OWNER, OTHER, DEV) else None @@ -26,6 +27,8 @@ class PrompterAuth(ScanAuth): def _admin(self, path, method='GET', body=None, prefer=''): if self.missing: raise AuthUnavailable('supabase answered 404: relation does not exist') + if self.no_outline and ('outline' in path or 'outline' in (body or {})): + raise AuthUnavailable('supabase answered 400: column math_prompter_texts.outline does not exist') table, _, query = path.partition('?') assert table == '/rest/v1/math_prompter_texts' q = dict(urllib.parse.parse_qsl(query)) @@ -125,3 +128,81 @@ def test_migration_on_real_postgres(postgres_server): # noqa: F811 finally: with psycopg.connect(postgres_server.get_uri(), autocommit=True) as c: c.execute("drop database " + database + " with (force)") + + +SECTIONS = [{"part": "Part 1 — Why", "heading": "Slide 1 — From Data to Decisions", "time": "Opening · 35 seconds", + "reminders": ["Good morning", "BI + AI in daily work"]}, + {"part": "", "heading": "Slide 2 — Thank You", "time": "", "reminders": [" Use the data we have ", ""]}, + {"part": "", "heading": "", "time": "", "reminders": ["dropped: no heading"]}] + + +def test_outline_text_is_a_slide_script(): + from app.prompter import outline_text + assert outline_text(SECTIONS) == ("Part 1 — Why\nSlide 1 — From Data to Decisions\nOpening · 35 seconds\n" + "• Good morning\n• BI + AI in daily work\n\nSlide 2 — Thank You\n• Use the data we have") + + +def test_claude_writes_the_outline_and_it_is_kept(app, monkeypatch): + from app import ai_usage + from app.prompter import outline_text + seen, recorded = [], [] + app.state.prompter_outliner = lambda body: (seen.append(body) or outline_text(SECTIONS), {"model": "m"}) + monkeypatch.setattr(ai_usage, "record", lambda auth, user, feature, usage: recorded.append((user, feature))) + text = call(app, OWNER, 'POST', '/api/prompter/texts', json={'title': 't', 'body': 'Slide 1 — a\nhello'}).json()['text'] + r = call(app, OWNER, 'POST', f"/api/prompter/texts/{text['id']}/outline") + assert r.status_code == 200 and r.json()['text']['outline'].startswith("Part 1 — Why\nSlide 1") + assert seen == ['Slide 1 — a\nhello'] and recorded == [(OWNER, "prompter")] + assert call(app, DEV, 'POST', f"/api/prompter/texts/{text['id']}/outline").status_code == 404 # not theirs + assert call(app, OTHER, 'POST', f"/api/prompter/texts/{text['id']}/outline").status_code == 403 + url = f"/api/prompter/texts/{text['id']}" + # a new title keeps it; an edited outline is saved; a changed text without an outline drops it + assert call(app, OWNER, 'PUT', url, json={'title': 'new', 'body': 'Slide 1 — a\nhello'}).json()['text']['outline'] + assert call(app, OWNER, 'PUT', url, json={'title': 'new', 'body': 'Slide 1 — a\nhello', + 'outline': 'Slide 1 — a\n• mine'}).json()['text']['outline'] == 'Slide 1 — a\n• mine' + assert call(app, OWNER, 'PUT', url, json={'title': 'new', 'body': 'Slide 1 — b\nbye'}).json()['text']['outline'] is None + assert call(app, OWNER, 'PUT', url, json={'body': 'x', 'outline': 'y' * 20_001}).status_code == 413 + assert call(app, OWNER, 'PUT', url, json={'body': 'x', 'outline': ' '}).json()['text']['outline'] is None + + +def test_outline_without_claude_is_503(app, monkeypatch): + monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False) + monkeypatch.delenv("CLAUDE_API_KEY", raising=False) + text = call(app, OWNER, 'POST', '/api/prompter/texts', json={'title': 't', 'body': 'x'}).json()['text'] + assert call(app, OWNER, 'POST', f"/api/prompter/texts/{text['id']}/outline").status_code == 503 + + +def test_outline_migration_on_real_postgres(postgres_server): # noqa: F811 + psycopg = pytest.importorskip("psycopg") + from pathlib import Path + from scan_support import BOOTSTRAP + database = "pro_" + uuid.uuid4().hex + with psycopg.connect(postgres_server.get_uri(), autocommit=True) as c: + c.execute("create database " + database) + try: + with psycopg.connect(postgres_server.get_uri(database=database), autocommit=True) as c: + c.execute(BOOTSTRAP) + for name in ("20261103220000_math_ai_usage", "20261106130000_math_prompter_texts", + "20261107130000_math_prompter_outline"): + c.execute(Path(f"supabase/migrations/{name}.sql").read_text()) + c.execute("insert into auth.users values(%s)", (OWNER,)) + c.execute("set role service_role") + c.execute("insert into math_prompter_texts(user_id,title,body) values(%s,'a','b')", (OWNER,)) + c.execute("update math_prompter_texts set outline='• x'") + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("update math_prompter_texts set outline=''") + c.execute("insert into math_ai_usage(feature,model) values('prompter','m')") + with pytest.raises(psycopg.errors.CheckViolation): + c.execute("insert into math_ai_usage(feature,model) values('other','m')") + finally: + with psycopg.connect(postgres_server.get_uri(), autocommit=True) as c: + c.execute("drop database " + database + " with (force)") + + +def test_before_the_outline_migration_texts_still_work(app): + app.state.auth.no_outline = True + app.state.prompter_outliner = lambda body: ("Slide 1 — a\n• x", None) + text = call(app, OWNER, 'POST', '/api/prompter/texts', json={'title': 't', 'body': 'x'}).json()['text'] + assert 'outline' not in text + assert [t['id'] for t in call(app, OWNER, 'GET', '/api/prompter/texts').json()['texts']] == [text['id']] + assert call(app, OWNER, 'PUT', f"/api/prompter/texts/{text['id']}", json={'body': 'y'}).json()['text']['body'] == 'y' + assert call(app, OWNER, 'POST', f"/api/prompter/texts/{text['id']}/outline").status_code == 503 diff --git a/tests/test_prompter_slides_browser.py b/tests/test_prompter_slides_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..4895446c8997a51b4b15113529b9b55d06632544 --- /dev/null +++ b/tests/test_prompter_slides_browser.py @@ -0,0 +1,101 @@ +"""The prompter's slide mode (static/prompter.js): a slide script shown one slide at a time, sized for a mini iPad.""" +import pathlib + +import pytest + +playwright = pytest.importorskip("playwright.sync_api") + +JS = (pathlib.Path(__file__).parent.parent / "static" / "prompter.js").read_text() +SCRIPT = """Part 1 — Opening +Slide 1 — From Data to Decisions +Opening · 35 seconds +Good morning, everyone. +Today is about *data*. [CLICK] +Slide 2 — Why This Matters +1 minute +Before the tools, the why. // Then the questions. +Slide 3 — Thank You +15 seconds +Thank you.""" + + +def opened(p, text, size=(744, 1133)): + page = p.chromium.launch().new_page(viewport={"width": size[0], "height": size[1]}) + page.set_content("") + page.add_script_tag(content=JS) + page.evaluate("t=>window.MathlyPrompter.open(t)", text) + return page + + +def test_reads_a_slide_script(): + with playwright.sync_playwright() as p: + page = opened(p, SCRIPT) + slides = page.evaluate("t=>window.MathlyPrompter.parse(t).slides", SCRIPT) + assert [(s["num"], s["title"], s["secs"], s["label"]) for s in slides] == [ + (1, "From Data to Decisions", 35, "Opening"), (2, "Why This Matters", 60, ""), (3, "Thank You", 15, "")] + assert slides[0]["part"] == "Part 1 — Opening" + assert page.evaluate("t=>window.MathlyPrompter.parse(t).slides", "Just a text\nwith Slide 3 in it") is None + + +def test_one_slide_at_a_time_with_a_clock(): + with playwright.sync_playwright() as p: + page = opened(p, SCRIPT) + root = page.locator(".mxp") + playwright.expect(root).to_have_class("mxp slides") + playwright.expect(page.locator(".mxp-snum")).to_have_text("1 / 3") + playwright.expect(page.locator(".mxp-stitle")).to_contain_text("From Data to Decisions") + playwright.expect(page.locator(".mxp-sbody")).not_to_contain_text("35 seconds") # the timing is not read out + playwright.expect(page.locator(".mxp-sbody em")).to_have_text("data") # *data* is stressed + playwright.expect(page.locator(".mxp-sbody .mxp-cue")).to_have_text("CLICK ⏵") + playwright.expect(page.locator(".mxp-timer")).to_have_text("0:00 / 0:35") + playwright.expect(page.locator(".mxp-sfoot")).to_contain_text("Why This Matters") # the next slide + page.locator(".mxp-sbody").click() # the first tap starts the clock, stays put + playwright.expect(root).to_have_class("mxp slides playing") + playwright.expect(page.locator(".mxp-snum")).to_have_text("1 / 3") + page.keyboard.press("PageDown") # a clicker: the next slide + playwright.expect(page.locator(".mxp-snum")).to_have_text("2 / 3") + playwright.expect(page.locator(".mxp-sbody .mxp-cue.pause")).to_have_count(1) + playwright.expect(page.locator(".mxp-delta")).to_contain_text("לפני הזמן") # 35s planned, ~0s used + page.keyboard.press("PageUp") + playwright.expect(page.locator(".mxp-snum")).to_have_text("1 / 3") + page.keyboard.press("s") # S: scrolling, headings shown dimmed + playwright.expect(root).to_have_class("mxp") + playwright.expect(page.locator(".mxp-text .mxp-dir")).to_have_count(7) + playwright.expect(page.locator(".mxp-text")).to_have_text(SCRIPT) + page.keyboard.press("s") + playwright.expect(root).to_have_class("mxp slides playing") + + +def test_swipes_on_a_tablet(): + with playwright.sync_playwright() as p: + page = opened(p, SCRIPT) + page.locator(".mxp-sbody").click() # start the clock + + def swipe(dx): + box = page.locator(".mxp-sbody").bounding_box() + x, y = box["x"] + box["width"] / 2, box["y"] + 100 + page.mouse.move(x, y); page.mouse.down(); page.mouse.move(x + dx, y, steps=5); page.mouse.up() + swipe(-200) + playwright.expect(page.locator(".mxp-snum")).to_have_text("2 / 3") + swipe(200) + playwright.expect(page.locator(".mxp-snum")).to_have_text("1 / 3") + + +def test_long_notes_shrink_to_fit(): + long = "Slide 1 — Long\n40 seconds\n" + "\n".join(["A fairly long sentence that the speaker reads out loud."] * 10) \ + + "\nSlide 2 — End\nBye." + with playwright.sync_playwright() as p: + page = opened(p, long) + size = page.locator(".mxp-sbody").evaluate("e=>parseFloat(e.style.fontSize)") + assert 25 <= size < 34 + assert page.locator(".mxp-sbody").evaluate("e=>e.scrollHeight<=e.clientHeight+4") + playwright.expect(page.locator(".mxp-more")).to_be_hidden() + + +def test_outline_reminders_are_a_list(): + outline = "Part 1 — Why\nSlide 1 — From Data to Decisions\nOpening · 35 seconds\n• Good morning\n• BI + AI\n\n" \ + "Slide 2 — Thank You\n• Use the data we have" + with playwright.sync_playwright() as p: + page = opened(p, outline) + playwright.expect(page.locator(".mxp-sbody p.pt")).to_have_text(["Good morning", "BI + AI"]) + playwright.expect(page.locator(".mxp-timer")).to_have_text("0:00 / 0:35")