diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d8bee0..d566a44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,40 +3,15 @@ name: CI on: push: branches: [main] + paths: + - 'v2/**' + - '.github/workflows/ci.yml' pull_request: + paths: + - 'v2/**' + - '.github/workflows/ci.yml' jobs: - check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-node@v4 - with: - node-version: 20 - cache: npm - - - name: Install dependencies - run: npm ci - - - name: Build bundle - run: npm run build - - - name: Lint - run: npm run lint - - - name: Check formatting - run: npm run format:check - - - name: Verify committed bundle is up to date - run: git diff --exit-code -- index.html - - - name: Install Playwright browser - run: npx playwright install --with-deps chromium - - - name: Test - run: npm test - check-v2: runs-on: ubuntu-latest defaults: @@ -47,7 +22,8 @@ jobs: - uses: actions/setup-node@v4 with: - node-version: 20 + # 22: db-sql.test.ts runs the real SQL through node:sqlite (skipped on older Node). + node-version: 22 cache: npm cache-dependency-path: v2/package-lock.json @@ -62,3 +38,7 @@ jobs: - name: Build run: npm run build + + - name: Verify committed Reader template is up to date + # Shared .html files are built from this generated bundle; a stale one ships old behavior. + run: npm run build:reader && git diff --exit-code -- src/lib/generated/reader-template.ts diff --git a/.github/workflows/v1.yml b/.github/workflows/v1.yml new file mode 100644 index 0000000..8fd4744 --- /dev/null +++ b/.github/workflows/v1.yml @@ -0,0 +1,72 @@ +name: CI v1 + +on: + push: + branches: [main] + paths: + - 'src/**' + - 'scripts/**' + - 'tests/**' + - 'index.html' + - 'index.template.html' + - 'package.json' + - 'package-lock.json' + - 'playwright.config.mjs' + - 'eslint.config.mjs' + - '.github/workflows/v1.yml' + pull_request: + paths: + - 'src/**' + - 'scripts/**' + - 'tests/**' + - 'index.html' + - 'index.template.html' + - 'package.json' + - 'package-lock.json' + - 'playwright.config.mjs' + - 'eslint.config.mjs' + - '.github/workflows/v1.yml' + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Build bundle + run: npm run build + + - name: Lint + run: npm run lint + + - name: Check formatting + run: npm run format:check + + - name: Verify committed bundle is up to date + run: git diff --exit-code -- index.html + + - name: Cache Playwright browser + id: playwright-cache + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ hashFiles('package-lock.json') }} + + - name: Install Playwright browser + if: steps.playwright-cache.outputs.cache-hit != 'true' + run: npx playwright install --with-deps chromium + + - name: Install Playwright system deps + if: steps.playwright-cache.outputs.cache-hit == 'true' + run: npx playwright install-deps chromium + + - name: Test + run: npm test diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a813a2..faf1163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,83 @@ Notable changes, following [Keep a Changelog](https://keepachangelog.com/). The notebook JSON interchange format is versioned separately and migrated on import. +## [0.3.0] — 2026-10-21 + +The living handout: notebooks an LLM can draft, a teacher can trust, and a student can keep — plus a +keyboard-first Study, zoom, the Cyberpunk theme and a much larger test suite. + +- **Shared files remember progress.** A shared Reader `.html` keeps each reader's answers, ticks, + practice streaks and notes in that browser, keyed by card content so an author's later fixes + keep everyone else's progress. "Reset my progress" starts over. +- **Results for the teacher.** "My results" in the Reader summarizes progress per section and + graded answers; copy it or download it as JSON. Nothing leaves the device otherwise. +- **`problem` slot (12th).** Randomized numeric practice: params drawn on a step grid each attempt, + the typed answer checked against an expression with a tolerance, "New numbers", a worked + explanation, done after `need` correct answers. Strict answer parsing; mobile keypad friendly. +- **Guided card types.** Guided Explore (predict → explore with sliders and a chart → explain), + Worked Example (steps with self-explanation fading into practice) and Practice Set. Existing + installs receive new built-ins once through a preferences ledger; deleted ones stay deleted. Predictions with no answer key + are never marked wrong. +- **Step-by-step** slot effect in the Factory: hide a slot until the earlier tasks on its card + are done. +- **New notebook From AI.** A complete prompt for any chat AI (format, slot catalog, expression + grammar, card-scope rule, pedagogy); paste the reply, see problems with where / what / how to + fix and a copyable fix request, then create. Cards arrive as **drafts** to review; Share warns + while drafts remain. +- **Published format.** JSON Schema 2020-12 (`v2/src/lib/schema/notebook.schema.json`) and + [`docs/FORMAT.md`](docs/FORMAT.md). Rejected imports show a readable report instead of a toast. +- **Durability.** Saves are serialized and atomic (one batch per save), flushed on blur, window + close and Cmd+Q, and never written before startup loading finishes. Fixed: edits lost when + switching notebooks, the demo notebook overwriting a stored one at startup, interleaved saves + failing silently, card widths snapping back to full width after a relaunch, section resets + coming back after a restart. +- **Version history.** Automatic snapshots (at most every 10 minutes, only on change), "Save + version now", and Restore (undoable). SQLite migration v6. +- **Shared files on phones and offline.** Under 760 px the Reader starts with its panel collapsed + and cards go full width; the file makes no third-party request (the web-font import is + stripped at build, and the build fails on any external reference); a damaged file shows a + readable message instead of a blank page; the embedded payload escapes every `<`. +- **Safer sharing.** Share is refused while the notebook fails validation (the report lists + why), so students never get a broken file; Export still writes the backup and then lists what + would stop it re-importing. Progress keys are a hash of a per-install id and the notebook id, + so two authors' files never share students' progress. Imported text is made well-formed + before it reaches SQLite. +- **Examples.** `docs/examples/practice-lesson.json` (percent change) shows every new piece. +- CI runs the v2 job on Node 22 (real-SQLite tests) and fails on a stale Reader template. +- **Keyboard-first Study** — a whole study session runs from the keyboard: `j`/`k` (or the arrow + keys) move a focus ring from card to card, space or `f` flips, `1`-`9` pick an answer option, + `Enter` submits, `x` ticks the next checklist item, and `Escape` clears the focus. `?` opens a + shortcut overlay and Study carries a one-line hint under the notebook. The same bindings work + in a shared Reader file. +- **Cyberpunk (dark green) theme** — phosphor green on near-black with a fixed grid, scanlines, + neon card glow, hover lift, and mono uppercase headers. Bold, italic, inline code and + strikethrough take accent colors in Study text under this theme. +- **Syntax-highlighted code slots** — Python and JavaScript keywords, strings, numbers, + comments and callables get distinct colors via a dependency-free tokenizer; other languages + render plain. +- **Zoom** — `Cmd/Ctrl` `+`, `-`, `0` scale the whole app between 50% and 200%. +- **Three more builtin card types** — Cheatsheet, Iron Butterfly (a payoff explorer whose + breakevens and max profit and loss derive from three sliders), and Code Card, each with + accent varieties. +- **Examples** — `docs/examples/grand-tour.json` exercises every slot type in one tutorial; + `docs/examples/quant-terminal.json` rebuilds the quant-prep-terminal cockpit with chapter + dividers, tagged flashcards, cheatsheets, a lab section, and per-section service bars. +- **Styled DMG** — the disk image opens as a proper installer window with a + drag-to-Applications layout; `docs/install-macos.md` documents the build. +- **Simulation test tier** — seeded generative suites cover variable-graph resolution, + interchange round-trips, progress semantics, and expression evaluation. +- **Card type binding survives export** — a card stamped from a Factory type now carries its + `typeId` through JSON export and import, so the coverage matrix keeps its product dimension on + a round trip. A recipient without that type reads the card as untyped. +- **Design tokens** — spacing, type, radius and motion tokens with a written governance rule; + components consolidated onto them with zero visual change. +- **Fixed: Edit-in-Factory on typed cards** — the 🏭 action on a card stamped from a card type + silently did nothing instead of forking the type into a Factory bench. +- **Hardened test suite** — the SQLite persistence layer, every example notebook, the Iron + Butterfly payoff math, undo restoration of card types and Factory benches, the shortcut + overlay, Reader authoring after Remix, and every slot component are now under test; the + suite is 2718 tests across 204 files, plus real-SQLite tests of every migration. + ## [0.2.0] — 2026-07-23 NoteBuilder becomes a native macOS desktop app (`v2/`): Svelte 5 + TypeScript + Tauri 2, backed by @@ -12,8 +89,8 @@ SQLite. Rebuilds the full prototype experience on a typed engine and moves it fo card types, stamp independent copies into notebooks. - **11 slots** — text, list, code, table, image, choice, slider, text input, compute, chart, progress — composed on a 12-column grid with per-slot resize and fusing. -- **Card-scoped variables** with a topologically sorted dependency graph; cycles and missing - writers are rejected at import. +- **Card-scoped variables** with a topologically sorted dependency graph; cycles are rejected + at import and missing writers load with a warning. - **Hard Edit/Study separation** (`Cmd+Enter`); Study is the live, interactive render. - **Three state layers**: document (persists + exports), reader state (persists locally, never exports), session (transient). diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..731141d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,83 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at the maintainer's GitHub contact (@YuZh98, https://github.com/YuZh98). All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 63d3b2c..b6f2210 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,16 @@ # Contributing to NoteBuilder +## Scope + +NoteBuilder is one repo, two apps: the **v1 prototype** at the root (frozen, bug fixes only) and the +**v2 product** in `v2/` (Svelte 5 + TypeScript + Tauri 2, active development). + +In scope: v2 app quality, interchange/Reader fidelity, tests, and docs accuracy. + +Out of scope: anything that adds a network call, telemetry, or an account system (NoteBuilder is +local-first and stays that way); changes to the v1 root beyond bug fixes; features not grounded in an +open issue. + Thanks for helping. Active development happens in **`v2/`** (Svelte 5 + TypeScript + Tauri 2); the repository root is the legacy single-file prototype, kept building but not evolving. @@ -8,7 +19,7 @@ repository root is the legacy single-file prototype, kept building but not evolv ```bash cd v2 npm install -npm run dev # browser dev server (persistence no-ops; demo notebook loads) +npm run dev # browser dev server (persistence no-ops; demo notebook loads); Node 22+ npm run tauri dev # the real desktop app — needs Rust + Xcode CLT ``` @@ -18,21 +29,24 @@ Gates — keep all green before and after every change: npm test # Vitest unit suite npm run check # svelte-check, TypeScript strict npm run build # Vite production build -npm run build:reader # only when the Reader render path changes — commit the regenerated template +npm run build:reader # when the Reader render path changes — commit the regenerated template (CI fails on a stale one) ``` ## The shape of v2 -- Architecture map: Part B of [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Product spec: - [`docs/spec/v2-spec.md`](docs/spec/v2-spec.md). +- Architecture map: Part B of [`docs/CODE-MAP.md`](docs/CODE-MAP.md). - **Invariants** (don't break): variables are card-scoped, never cross a card boundary; three state layers (document persists + exports · reader state persists locally, never exports · session is transient); slot structure is sealed outside the Factory; every drag rides the one pointer engine - in `v2/src/lib/drag/` — no native HTML5 drag; no `eval` on user content, escape-first before any + in `v2/src/lib/drag/` — no native HTML5 drag outside the Factory inventory chips; no `eval` on + user content, escape-first before any `{@html}`; every document edit is undoable. - **Migrations always.** A change to the SQLite shape ships a migration in `v2/src-tauri/src/lib.rs`; a change to the JSON interchange shape bumps its schema version and ships an import migration. Old saves and old exports must still load. +- **The interchange format is published.** A change to it updates `v2/src/lib/schema/notebook.schema.json`, + `v2/src/lib/slot-catalog.ts` (for a new slot type) and `docs/FORMAT.md`; `schema-sync.test.ts` and + `ai-prompt.test.ts` name whatever is missing. - **Behavior changes are test-driven** — add a failing test, then make it pass. Verify UI and interaction changes by running the app, not by reading the diff. diff --git a/README.md b/README.md index c5150bb..f7e8bd3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # NoteBuilder [![CI](https://github.com/YuZh98/notebuilder/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/YuZh98/notebuilder/actions/workflows/ci.yml) -[![Tests](https://img.shields.io/badge/tests-1202-brightgreen)](v2/) +[![Tests](https://img.shields.io/badge/tests-2718-brightgreen)](v2/) [![Svelte 5](https://img.shields.io/badge/Svelte-5-FF3E00?logo=svelte&logoColor=white)](v2/package.json) [![Tauri 2](https://img.shields.io/badge/Tauri-2-24C8DB?logo=tauri&logoColor=white)](v2/src-tauri/) [![macOS](https://img.shields.io/badge/platform-macOS-black?logo=apple)](v2/) @@ -9,6 +9,8 @@ **Study material that does something. Build notebooks from reactive cards, drill them in Study mode, and hand them to anyone as a single offline file.** +Drag a slider, and the formula, the prose, and the chart in that card recompute together; export the notebook and those same live cards keep running inside one offline `.html` file, where nothing the reader answers ever comes back to you. + NoteBuilder is a local-first macOS desktop app. Your notebooks live in a local SQLite database. No account, no cloud, no backend. ![Study mode: a compound-interest notebook where two sliders drive computed values, live prose, and a growth chart in one card](docs/screenshots/v0.2.0/study-live.png) @@ -19,18 +21,19 @@ NoteBuilder is a local-first macOS desktop app. Your notebooks live in a local S Anyone who makes study material and wants it to be more than frozen text: -- **Students and self-learners** who want flashcards that flip, quizzes that check themselves, and a progress meter that fills as *they* finish cards. -- **Teachers and tutors** who want to send one file that works in any browser, offline, with nothing to install on the other end. +- **Students and self-learners** who want flashcards that flip, quizzes that check themselves, practice problems with fresh numbers every attempt, and a progress meter that fills as *they* finish cards. +- **Teachers and tutors** who want to send one file that works in any browser, offline, with nothing to install on the other end, that remembers each student's progress and hands back a results summary. - **Anyone explaining something quantitative.** A slider, a formula, and a chart in one card wire together and react live. Drag the slider, watch the curve move. ## Why not a document? | Problem | Static notes | NoteBuilder | | --- | --- | --- | -| Self-testing | Re-reading, highlighting | Flashcards flip, quizzes grade themselves, checklists tick | +| Self-testing | Re-reading, highlighting | Flashcards flip, quizzes grade themselves, practice problems redraw their numbers, checklists tick | | Quantitative intuition | A pasted screenshot of a plot | Slider drives formula drives chart, live, per card | | Knowing where you stand | Gut feeling | Per-reader progress meters count what you have actually finished | -| Sharing | Recipient needs your app or an account | One self-contained `.html`, opens offline in any browser | +| Sharing | Recipient needs your app or an account | One self-contained `.html`, opens offline in any browser, remembers the reader's progress | +| Authoring cost | Hours per lesson | Any chat AI drafts it from the built-in prompt; you review the drafts | | Coverage | Scroll and hope | Tag every card, read the coverage matrix | ## Quick start @@ -46,13 +49,15 @@ npm run tauri dev That is the full desktop app, with SQLite persistence and native print. `npm run tauri build` produces an app bundle. For UI work without the native shell, `npm run dev` serves the app in a browser with a demo notebook (persistence no-ops there). -First thing to try: import an example from [`docs/examples/`](docs/examples/) with the **⤒** button and hit **Study**. +To package that build as a macOS disk image and install it like any other app, follow [`docs/install-macos.md`](docs/install-macos.md). + +First thing to try: import [`grand-tour.json`](docs/examples/grand-tour.json) with the **⤒** button and hit **Study**. It is a rocket mission that puts every slot type to work in one notebook. For a short lesson built from the guided card types, import [`practice-lesson.json`](docs/examples/practice-lesson.json). The rest of the examples live in [`docs/examples/`](docs/examples/). Then **+ → From AI…** to have your favourite chat AI draft a notebook on any topic. ## How it works ### Cards are built from slots -A card is a small stack of primitives arranged on a 12-column grid: text, slider, formula, chart, choice, table, code, image, checklist, progress. Slots in the same card share variables and react to each other. Variables are strictly card-scoped; dependencies resolve by topological sort, and cycles or missing writers are caught at import. Nothing leaks across cards. +A card is a small stack of primitives arranged on a 12-column grid: text, slider, formula, chart, choice, practice problem, table, code, image, checklist, text answer, progress. Slots in the same card share variables and react to each other. Variables are strictly card-scoped; dependencies resolve by topological sort, and cycles or missing writers are caught at import. Nothing leaks across cards. ### Edit and Study are hard-separated @@ -62,29 +67,62 @@ Edit shows structure and configuration. Study *is* the rendered, interactive res *The same notebook in Edit mode: every slot becomes its configuration fields, and the sidebar holds tags, section operations, and the card-type store.* +### Have any AI draft it, then review + +**+ → From AI…** writes a complete prompt for ChatGPT, Claude, Gemini or any other chat AI: the format, every slot with an example, the formula grammar and the card-scope rule. Paste the reply back; NoteBuilder checks it (code fences and chatter are fine), lists any problems with where, what and how to fix, and gives you a fix request to paste back to the AI. Every card it creates is marked **draft** until you review it, and Share reminds you while drafts remain. No AI runs inside the app, and the format is published: [`docs/FORMAT.md`](docs/FORMAT.md). + ### The Factory stamps card types -Design a slot arrangement once, seal it as a card type, then stamp independent copies into any notebook. Stamped cards are copies, not references, so editing a notebook never mutates your library. +Design a slot arrangement once, seal it as a card type, then stamp independent copies into any notebook. Stamped cards are copies, not references, so editing a notebook never mutates your library. Built-ins include research-backed patterns: **Guided Explore** (predict, explore with sliders and a chart, then explain), **Worked Example** (steps with self-explanation, fading into practice) and **Practice Set**. ### Sharing is a file -Export a notebook as JSON for another NoteBuilder, or as a self-contained Reader `.html` that opens in any browser, offline. The recipient reads and interacts; their quiz answers and progress stay on their machine. A shared file carries only that notebook, never the rest of your library. +Export a notebook as JSON for another NoteBuilder, or as a self-contained Reader `.html` that opens in any browser, offline. The recipient reads and interacts; their answers and progress are saved in their own browser and come back when they reopen the file. **My results** gives them a summary to copy or download for you. Nothing is sent anywhere. A shared file carries only that notebook, never the rest of your library. -![A shared Reader file open in a plain browser: locked chrome with only a Remix button, quiz unanswered because reader state starts fresh](docs/screenshots/v0.2.0/reader.png) +### The two ends of a notebook -*A shared `.html` open in a plain browser: authoring chrome is gone, a single **Remix** unlocks editing, and the quiz is unanswered because the reader's state is their own.* +| ![Edit mode: the same compound-interest notebook as slot configuration fields, with the tags, section ops, and card-type store in the sidebar](docs/screenshots/v0.2.0/edit-mode.png) | ![A shared Reader file open in a plain browser: locked chrome with only a Remix button, quiz unanswered because reader state starts fresh](docs/screenshots/v0.2.0/reader.png) | +| --- | --- | +| *Edit mode: every slot becomes its configuration fields, and the sidebar holds tags, section operations, and the card-type store.* | *The shared `.html` in a plain browser: authoring chrome is gone, a single **Remix** unlocks editing, and the quiz is unanswered because the reader's state is their own.* | ### And the comforts -Full undo/redo, drag-and-drop everything (cards, slots, tags, services), tags with a coverage matrix, themes, GFM markdown with `$KaTeX$` math, native print. +Full undo/redo, version history with restore, saves that survive a crash or a Cmd+Q, drag-and-drop everything (cards, slots, tags, services), tags with a coverage matrix, themes, GFM markdown with `$KaTeX$` math, native print. A whole Study session runs from the keyboard (`j`/`k` to move, space to flip, `1`-`9` to answer, `x` to tick), in the app and in a shared file alike, with `?` listing every shortcut. ![Study mode of a regression drill: an answered quiz with its explanation, a checklist with two items struck through, and a half-full progress bar](docs/screenshots/v0.2.0/drill-practice.png) *The [`regression-drill`](docs/examples/regression-drill.json) example mid-study: the quiz has been answered and explains itself, two checklist items are done, and the notebook-wide progress meter sits at 2/4.* +### Eight themes, one picker + +Every screenshot above uses the default dark theme. Seven more ship with the app, switched from the palette button in the top bar; here are four of them on the same demo notebook. + +| ![The demo notebook in the Tomoé theme: cream stationery background, serif headings, ruled card margins](docs/screenshots/v0.2.0/theme-tomoe.png) | ![The demo notebook in the Sketch theme: graph paper background with wobbly hand-drawn card frames and marker lettering](docs/screenshots/v0.2.0/theme-sketch.png) | +| --- | --- | +| *Tomoé: stationery. Cream paper, serif headings, ruled margins on every card.* | *Sketch: graph paper, wobbly ink frames, marker lettering.* | +| ![The demo notebook in the Aurora theme: deep blue night background with glowing teal card borders and a mint chart line](docs/screenshots/v0.2.0/theme-aurora.png) | ![The demo notebook in the Cyberpunk theme: near-black background, amber wireframe cards, uppercase chrome](docs/screenshots/v0.2.0/theme-cyber.png) | +| *Aurora: fantasy night sky, cards that glow at the edges.* | *Cyberpunk: amber wireframes and uppercase everything.* | + +## Where your data lives + +One SQLite file in your own account, written by the app itself: + +```text +~/Library/Application Support/com.notebuilder.app/ +└── notebuilder.db notebooks, card types, tags, reader state, preferences +``` + +SQLite keeps its own `notebuilder.db-wal` and `notebuilder.db-shm` companion files next to it, so the folder shows three names for one database. Delete the database and NoteBuilder starts empty. Everything else NoteBuilder writes is a file you asked it to export, saved where you pointed the dialog. Run `npm run dev` in a browser instead of the desktop app and there is no database at all; the demo notebook lives only in memory. + ## Built to last -1202 tests across 87 files, TypeScript strict, svelte-check clean, CI on every push. Invariants are enforced by tests, not convention. +2718 tests across 204 files, TypeScript strict, svelte-check clean, CI on every push. Invariants are enforced by tests, not convention. + +The long-form guides: + +- [Architecture](docs/architecture.md): the v2 layer split, where your data lives at runtime, and the two build targets. +- [UI design system](docs/ui-design-system.md): the `app.css` design tokens, theming, and the rule that keeps them authoritative. +- [Notebook format](docs/FORMAT.md): the version 2 notebook JSON, slot by slot, its published JSON Schema, and the rules an AI author must follow.
Engineering deep-dive @@ -93,23 +131,24 @@ Full undo/redo, drag-and-drop everything (cards, slots, tags, services), tags wi ```text v2/src/lib/slots/ slot primitives: one Edit + one Study component per slot, one contract -v2/src/lib/drag/ a single pointer-based drag engine; no native HTML5 drag anywhere +v2/src/lib/drag/ a single pointer-based drag engine for notebook and study surfaces; the Factory inventory chips still use native HTML5 drag v2/src/lib/ variable graph, history, tags, import/export, themes, markdown v2/src-tauri/ Rust shell: SQLite (migrations in lib.rs), native print, dialogs ``` - **State layers.** Document state persists and exports; reader state (answers, ticks, progress) persists locally and never exports; session state is transient. The separation is what makes a shared file safe to open. - **Migrations always.** A persisted-shape change ships a SQLite migration; an interchange change bumps the JSON schema version and ships an import migration. Old files keep loading. +- **Atomic, serialized saves.** Every database access rides one queue; each save is a single transaction batch; nothing is written before startup loading succeeds; the real SQL and every migration are tested against SQLite. - **Security posture.** No `eval` on user content; formulas run through a small own-keys-only expression evaluator. All user text is escaped before markdown or KaTeX markup is applied. Parameterized SQL throughout. See [SECURITY.md](SECURITY.md). -- **Guard tests.** Source-level sweep tests lock invariants: no props mutation in Edit components, no native drag, Reader/App prop parity. Regressions fail loudly. +- **Guard tests.** Source-level sweep tests lock invariants: no props mutation in Edit components, no native drag outside the Factory inventory chips, Reader/App prop parity. Regressions fail loudly. -Architecture map: [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Product spec: [`docs/spec/v2-spec.md`](docs/spec/v2-spec.md). Contributing: [`CONTRIBUTING.md`](CONTRIBUTING.md). +Architecture map: [`docs/CODE-MAP.md`](docs/CODE-MAP.md). Notebook format: [`docs/FORMAT.md`](docs/FORMAT.md). Contributing: [`CONTRIBUTING.md`](CONTRIBUTING.md).
## The original prototype -The repository root holds the first NoteBuilder: a single-file web app (vanilla JS, localStorage, the whole product in one `index.html`) that proved the slot/card model and the one-file sharing story. Its Playwright suite still gates CI, but it is legacy. New work happens in [`v2/`](v2/). +The repository root holds the first NoteBuilder: a single-file web app (vanilla JS, localStorage, the whole product in one `index.html`) that proved the slot/card model and the one-file sharing story. Its Playwright suite still gates CI whenever the root app changes, but it is legacy. New work happens in [`v2/`](v2/). ## License diff --git a/SECURITY.md b/SECURITY.md index 8d66755..20b699d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,8 @@ Please do not file public issues for vulnerabilities. We aim to acknowledge with ## Threat model -NoteBuilder is local-first: there is no server, no account, and no network call at runtime. The +NoteBuilder is local-first: there is no server and no account. The only runtime network requests +are theme webfonts and remote images a notebook may embed. The desktop app (`v2/`) persists to a local SQLite database; the legacy web prototype (repository root) persists to `localStorage`. The main attack surface in both is **rendering untrusted notebook content** — an imported JSON file or a shared Reader `.html` may contain attacker-authored text and @@ -21,7 +22,8 @@ Mitigations in the code: - **Escape-first rendering.** All user text is HTML-escaped before markdown/KaTeX markup is applied and before it reaches any `{@html}` / `innerHTML` sink (`v2/src/lib/markdown.ts`). - **No remote code.** KaTeX is bundled at build time; rendered markdown links carry - `rel="noopener noreferrer"`, and notebook content cannot pull in remote assets. + `rel="noopener noreferrer"`. Notebook images may load from remote URLs, but nothing remote + executes. - **Parameterized SQL** for all database access; ids are sanitized on import. - **Slim export.** A shared file embeds only the exported notebook — never other notebooks, the card-type library, or the reader's local state. diff --git a/docs/CODE-MAP.md b/docs/CODE-MAP.md index 29e9497..399e25c 100644 --- a/docs/CODE-MAP.md +++ b/docs/CODE-MAP.md @@ -218,48 +218,81 @@ import time. v2/ src/ main.ts Svelte mount - App.svelte Root component (32KB): mode/place routing, notebook CRUD, effects + App.svelte Root component (~48KB): mode/place routing, notebook CRUD, effects app.css Global stylesheet lib/ types.ts Core type definitions (Slot, Card, Section, Notebook — incl. Notebook.cats) card-types.ts CardType, stampCard, placeType, builtinCardTypes bench.svelte.ts Factory workbench state (Svelte 5 $state rune) - session.svelte.ts Study session state (shuffle, search, archive toggle, live control values) + seal.ts Seal-modal draft: bench → CardType metadata capture + session.svelte.ts Study session state (shuffle, search, archive toggle, collapse, live values) notebook-ops.ts CRUD ops: createNotebook, addSection, addChapter, duplicateCard, etc. tags.ts The ONE tag write path: apply/remove/rename/delete/create/reorder + cats upkeep coverage-matrix.ts Matrix axes, cell matching, same 3-axis model as v1 services.ts ServiceBar: SERVICE_ORDER, svcBarItems, reorderSvc, search service-ops.ts Mutation helpers: toggleService, resetSection, flipAllSection - json-io.ts Export/import (SCHEMA_VERSION 2) + validateNotebookJSON + graph validation + json-io.ts Export/import (SCHEMA_VERSION 2) + validateNotebook / validateNotebookIssues + (structured {code, path, message}) + graph validation html-io.ts Shared-.html payload inject/extract (notebook-source script tag) - share.ts Tauri file dialog wrappers for import/export - db.ts SQLite layer (saveNotebook, loadNotebook, reader state, prefs) + share.ts Tauri file dialog wrappers for import/export; buildShareHtml (payload docId) + db.ts SQLite layer: ONE serialized queue (coalescing keys), atomic single-execute + batches (exported SQL constants), onDbError, dbIdle; notebooks, reader + state, prefs, card types, annotations, snapshots + autosave.ts Hydration-gated debounced channels (notebook / reader / factory); flush + snapshots.ts Version-history policy: contentHash, shouldAutoSnapshot, retention pruneIds + versions.ts Version keeper: when to snapshot (auto, manual, before-restore) + reader-store.ts Shared-Reader progress in localStorage: stable content keys, quota eviction + results.ts Student results summary (progress + graded score() tallies) + text form + drafts.ts AI drafts: markAllDraft, nextDraft, clear one/all (local authoring state) + rng.ts mulberry32 + step-grid draws for reproducible practice numbers + numeric-input.ts Strict parser for typed numeric answers (never evalExpr on input) + schema/ notebook.schema.json (published JSON Schema 2020-12) + schema.ts readers + slot-catalog.ts One entry per slot type for the AI kit (purpose + example; props from schema) + ai-prompt.ts buildAiPrompt: the "From AI" prompt (format, catalog, grammar, pedagogy) + import-hints.ts checkNotebookText: fence/prose-tolerant parse, own line/col, hintFor, fix request + clipboard.ts copyText with execCommand fallback + install-id.ts Per-install random id (pref install_id); shareDocId hashes it with the notebook id + well-formed.ts Replace lone UTF-16 surrogates (imports) so SQLite never stores invalid UTF-8 + reader-boot.ts Shared-file boot: extract → validate → import; a readable error page on failure db-map.ts Notebook ↔ relational row mapping variable-graph.ts Topological sort, cycle detection, scope resolution card-scope.ts Build scope from a card's slots (same invariant: card-scoped) - expr.ts Safe expression evaluator (no eval, variable whitelist) + expr.ts Safe expression evaluator (no eval, variable whitelist); parseExpr (throws) markdown.ts Markdown → HTML (inline + block) with KaTeX mdbar.ts Formatting toolbar actions verbs.ts Reveal/glow/emphasis evaluation themes.ts Theme registry toast.svelte.ts Notification state uid.ts ID generator - debounce.ts Utility + debounce.ts debounce with flush / cancel / pending annotations.ts Reader annotations (local-only) + presentation.ts Volatile presentation keys stripped from persisted reader state + demo.ts First-run seed notebook history.svelte.ts Undo/redo stacks: pushHistory/pushSnapshot/beginEdit (focus-coalesced) history-focus.ts data-history="edit" input coalescing — one undo entry per edit session + keyboard.ts Pure key dispatcher: the v1 shortcut map as a decision over a KeyCtx + study-keys.ts Study cursor: focus order, stepping, per-key reader-state effect + card-reveal.ts Scroll a just-placed card into view and flash the study ring on it + modal-inert.ts `inert` on the shell behind a modal overlay, so Tab cannot reach it + zoom.ts App zoom factor (Cmd/Ctrl +/-/0) + viewport↔zoom-space conversion + print.ts Print: native print_page on desktop, window.print() in browser + visible-cards.ts The one render order: sections/cards the Stage shows (and the cursor walks) shell.ts Shell/container styling logic slot-contract.ts SlotType interface: create, variables, evaluate, isDone, stateLayer, render* progress.ts Notebook/section/chapter progress computation card-done.ts Per-card completion logic var-colors.ts Variable key → color assignment + sim-notebook.ts Seeded notebook generator + canonical form (sim test tier) + sim-rng.ts Deterministic RNG + seed sweep for the sim suites + test-utils.ts Shared test scaffolding (pev, stubRect) - slots/ Per-slot-type modules (11 types): + slots/ Per-slot-type modules (12 types): registry.ts Slot type registry (registerSlot / getSlot / allSlots) identifiers.ts Key naming helpers text.ts + TextEdit.svelte + TextStudy.svelte slider.ts + SliderEdit.svelte + SliderStudy.svelte compute.ts + ComputeEdit.svelte + ComputeStudy.svelte (+ .test.ts) + problem.ts + ProblemEdit.svelte + ProblemStudy.svelte — randomized numeric practice chart.ts + ChartEdit.svelte + ChartStudy.svelte + plot.ts choice.ts + ChoiceEdit.svelte + ChoiceStudy.svelte (+ .test.ts) list.ts + ListEdit.svelte + ListStudy.svelte (+ .test.ts) @@ -283,6 +316,7 @@ v2/ CoverageMatrix.svelte 3-axis matrix grid (same v1 concept) ServiceBar.svelte Per-section feature/action bar SealModal.svelte Seal product: name, icon, store, varieties + ShortcutHelp.svelte Study shortcut overlay (toggled by ?) ProductDetail.svelte Product info + fork/place StoreLane.svelte Store shelf in sidebar SlotConfig.svelte Slot field editor + verb builder @@ -292,6 +326,11 @@ v2/ Toast.svelte Notifications CardNotes.svelte Reader annotations Reader.svelte Shared-.html shell — hand-mirrors the App shell (see DEBT P1 + drift guard) + ResultsModal.svelte Reader "My results": copy / download JSON + FromAiModal.svelte New notebook from AI: copy prompt → paste reply → check → create + ImportReport.svelte Import problems with where / what / fix + "Copy fix request" + DraftsBar.svelte "N drafts to review · Next · Mark all reviewed" (SideBar) + VersionsPanel.svelte Version history list, Save version now, Restore (SideBar, Tauri) drag/ Drag-and-drop engine: engine.ts Core pointer engine (startDrag, FLIP animation) @@ -334,20 +373,26 @@ CardType = { id, name, description?, verbs?, slots: SlotTemplate[], back?, accen store?, varieties? } ``` -**SQLite schema** (5 migrations in `lib.rs`): +**SQLite schema** (6 migrations in `lib.rs`; never edit an applied one): - `notebooks` (id, name, created_at, updated_at, data JSON) - `sections` (id, notebook_id FK, name, position, data JSON) - `cards` (id, section_id FK, type_id, position, data JSON) - `reader_state` (card_id, slot_id, data JSON) — local progress, never exported - `annotations` (id, card_id, kind, body, created_at) — local-only - `card_types` (id, name, data JSON, created_at) — sealed products -- `preferences` (key, value) — theme, etc. +- `preferences` (key, value) — theme, `builtin_seeded`, etc. +- `snapshots` (id, notebook_id, created_at, reason, hash, data JSON) — version history (v6); no FK, + deleted explicitly with the notebook + +`Card.draft?: boolean` is local authoring state (like `folded`): persisted in the card data blob, +never exported, never in a share payload, ignored on import. **Same invariants as v1:** - Variables are **card-scoped** (front + back share one scope, never cross card boundaries). - Study state: document (exported) · progress (persisted locally, never exported) · **session** - (`session.svelte.ts` — shuffle/search/archive-view plus `session.live`, the per-card control - values keyed by variable name; wiped on every Study entry, never persisted). + (`session.svelte.ts` — shuffle/search/archive-view/collapse plus `session.live`, the per-card + control values keyed by variable name; never persisted. Entering Study wipes shuffle and live; + search, archive view and collapse survive until the notebook changes). - A slot declares which layer its Study writes belong to via `SlotType.stateLayer` (`'progress'` default → readerState by slot id; `'session'` → `session.live` by variable name — slider is the one session-layer slot). @@ -371,17 +416,23 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): | `renderEdit` | Svelte component for Edit mode | | `renderStudy` | Svelte component for Study mode | -**Registered types** (11): `text`, `slider`, `compute`, `chart`, `choice`, `list`, `progress`, -`code`, `image`, `table`, `text-input`. +**Registered types** (12): `text`, `slider`, `compute`, `chart`, `choice`, `list`, `progress`, +`code`, `image`, `table`, `text-input`, `problem`. + +Optional `score?(props, state) → {correct, answered} | null` feeds the Reader's results export +(choice and problem implement it; a slot without an answer key returns null). ### B5. Key systems (v2) 1. **Drag engine** (`drag/engine.ts` + `kinds.ts`) — unified pointer engine with `DRAG_KINDS` registry (9 kinds: card, section, qopt, product, slot, bench, tag, svc, svcattach). Same FLIP approach as - v1, but with **no native-drag path at all** (WKWebView blocks custom dataTransfer types — see the - `text/nb-svc` sweep test). A kind's `laneSel` makes arbitrary elements drop targets: tag → card - applies, tag → `.tag-grid` reorders cats, svcattach → `.room` attaches / dustbin detaches. - Separate header-drag for matrix axis reorder. Drop handlers split by context (notebook vs factory). + v1. The pointer engine drives every notebook and study surface; the Factory inventory chips still + use native HTML5 drag (`SideFactory.svelte`). A sweep test in `svc-attach.test.ts` checks that no + component source contains the old `text/nb-svc` MIME type (WKWebView blocks custom dataTransfer + types, which is why that native path was removed). A kind's `laneSel` makes arbitrary elements drop + targets: tag → card applies, tag → `.tag-grid` reorders cats, svcattach → `.room` attaches / + dustbin detaches. Separate header-drag for matrix axis reorder. Drop handlers split by context + (notebook vs factory). 2. **Variable graph** (`variable-graph.ts`) — topological-sort evaluator. Each slot declares reads/ writes; `resolveGraph` orders by dependency and evaluates once. `findGraphIssues` does static @@ -390,26 +441,55 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): 3. **Coverage matrix** (`coverage-matrix.ts`) — same 3 axes as v1 (section/product/tag). Appears when ≥2 axes have ≥2 values. -4. **Service bar** (`services.ts` + `service-ops.ts`) — 6 services (pin, shuffle, flipAll, reset, - search, archive). Features decorate cards; actions fire once. Custom order via `svcOrder`. +4. **Service bar** (`services.ts` + `service-ops.ts`) — 7 services (pin, shuffle, flipAll, reset, + search, archive, notes). Features decorate cards; actions fire once. Custom order via `svcOrder`. 5. **JSON interchange** (`json-io.ts`) — versioned export/import with full validation including variable-graph cycle detection. Static analysis catches broken variable references before notebooks are loaded. -6. **Persistence** (`db.ts`) — SQLite via Tauri plugin-sql. `isTauri()` guards DB calls so the code - runs in tests/browser without the native layer. Notebook/section/card extras ride `data` JSON - columns (`db-map.ts`) — new optional fields need no SQL migration. +6. **Persistence** (`db.ts` + `autosave.ts`) — SQLite via Tauri plugin-sql. `isTauri()` guards DB + calls so the code runs in tests/browser without the native layer. Every read/write goes through + one serialized queue; a save is ONE `execute()` batch (`BEGIN IMMEDIATE … COMMIT`, rows via + `json_each`), so it is atomic on a pooled connection; on failure the pool is closed (rolling the + open transaction back) and the write retried once with the latest state. Nothing persists before + hydration succeeds. `flushAll()` runs on blur, hidden, window close and Cmd+Q (Rust holds the + quit until the frontend flushed). Notebook/section/card extras ride `data` JSON columns + (`db-map.ts`) — new optional fields need no SQL migration. `db-sql.test.ts` runs the real SQL and + every migration against `node:sqlite`. 7. **Tags** (`tags.ts` + `TagsPanel.svelte`) — `Notebook.cats` holds identity and order; membership lives on `card.tags`. Every mutation (including the card's comma input) goes through `tags.ts`, which keeps `cats` in sync. `pinned` is owned by the pin button and cannot be renamed. +8. **Shared Reader** (`reader-main.ts` + `Reader.svelte` + `reader-store.ts` + `results.ts`) — the + share payload `{shared, docId, notebook, theme}` is embedded (every `<`, `>`, `&` escaped as + `\u003c`…) in the committed template + (`generated/reader-template.ts`, rebuilt by `npm run build:reader`, freshness-checked in CI). + Import regenerates ids each load, so progress is keyed by a hash of each card's CONTENT (slots, + props, verbs — not width/color/tags) + slot face/index and stored in localStorage under + `notebuilder:reader:v1:` (docId = hash of install id + notebook id). "My results" + summarizes progress and `score()` tallies. Phones: under 760 px the Reader starts with its + panel collapsed and cards go full width (rules scoped to `body.nb-reader`). The build strips + remote `@import`s (no font request leaves the file) and fails on any external reference. + Share is refused while the notebook fails validation (ImportReport lists why); Export still + writes the backup, then lists what would stop it re-importing. + +9. **Bring-your-own-LLM authoring** (`schema/` + `slot-catalog.ts` + `ai-prompt.ts` + + `import-hints.ts`) — the JSON Schema is the one source the prompt kit and hints read from; the + Reader bundle must never import them (`reader-boundary.test.ts`). Notebooks created From AI arrive + with every card `draft` (`drafts.ts`, `DraftsBar.svelte`); Share warns while drafts remain. + +10. **Version history** (`snapshots.ts` + `versions.ts` + `VersionsPanel.svelte`) — automatic + snapshots after saves (≥10 min apart, only when content changed), manual "Save version now", + Restore (snapshots current first, keeps the notebook id, undoable). Retention: last 24 h up to + 50, then one per day for 30 days; manual ones kept up to 20. + ### B6. "I want to change X" → go here (v2) | Goal | Where | |---|---| -| New slot type | Implement `SlotType

` in `slots/mytype.ts` + Edit/Study `.svelte` + register in `slots/registry.ts` | +| New slot type | Implement `SlotType

` in `slots/mytype.ts` + Edit/Study `.svelte` + register in `slots/registry.ts` + `SLOT_ICONS` in `CardView.svelte` + a `$defs` entry and `if/then` branch in `schema/notebook.schema.json` + an entry in `slot-catalog.ts` (sync tests name what is missing) + `npm run build:reader` | | New verb/effect | `verbs.ts` + wire in `slots/VerbWrapper.svelte` + update `VerbConfig` in `types.ts` | | Card/section CRUD | `notebook-ops.ts` | | Factory/seal workflow | `bench.svelte.ts` + `card-types.ts` + `SealModal.svelte` | @@ -419,7 +499,12 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): | Import/export | `json-io.ts` (logic) + `share.ts` (file dialogs) + `html-io.ts` (shared .html) | | Tags | `tags.ts` (all writes) + `TagsPanel.svelte` (UI) + `drag/notebook-drop.ts` `dropTag` | | Card inspector | `CardPanel.svelte` (renders registry Edit components; writes via `updateSlotProps`) | -| Persistence/DB | `db.ts` + `db-map.ts` + migrations in `src-tauri/src/lib.rs` | +| Persistence/DB | `db.ts` (queue, SQL constants) + `db-map.ts` + `autosave.ts` + migrations in `src-tauri/src/lib.rs` (tested by `db-sql.test.ts`) | +| Shared Reader progress / results | `reader-store.ts` + `results.ts` + `Reader.svelte` (then `npm run build:reader`) | +| Interchange format / AI prompt | `schema/notebook.schema.json` + `docs/FORMAT.md` + `slot-catalog.ts` + `ai-prompt.ts` | +| Import error messages / hints | `json-io.ts` `validateNotebookIssues` (codes) + `import-hints.ts` `hintFor` | +| Built-in card types | `card-types.ts` `builtinCardTypes` (+ the `seeded_builtins` ledger: `unseededBuiltins` / `parseSeededLedger` deliver new ones to existing installs) | +| Version history | `snapshots.ts` (policy) + `versions.ts` (when) + `db.ts` snapshot SQL + `VersionsPanel.svelte` | | Themes | `themes.ts` + CSS variables in `app.css` | | Progress tracking | `progress.ts` + `card-done.ts` + `slots/progress.ts` | | Variable reactivity | `variable-graph.ts` + `card-scope.ts` + slot's `variables()`/`evaluate()` | @@ -430,8 +515,17 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): - **Card-scoped variables** — reads/writes never cross card boundaries. `findGraphIssues` enforces. - **SlotType contract** — every slot type must declare `variables()` and provide both render components. - **SQLite parameterized queries** — no string interpolation of user data in SQL. -- **Session state (`session.svelte.ts`)** is never persisted or exported — mode/notebook switches reset it. -- **`folded` is local-only** — never included in JSON export (fold state is per-reader). +- **Session state (`session.svelte.ts`)** is never persisted or exported — entering Study wipes + shuffle and live, and switching notebooks wipes all of it (`resetSession`). +- **`folded` and `draft` are local-only** — never included in JSON export or share payloads. +- **Never `INSERT OR REPLACE` a parent row** — with foreign keys on it deletes and cascades; + use `INSERT … ON CONFLICT(id) DO UPDATE`. +- **Every DB access rides the queue in `db.ts`**; multi-statement writes are one `execute()` batch. +- **Nothing persists before hydration** (`autosave.ts`); App writes check `persistOn()`. +- **Reader bundle boundary** — `json-io.ts`/the Reader never import `schema/`, `ai-prompt`, + `import-hints`, `slot-catalog` (sweep-tested); the committed Reader template is regenerated with + `npm run build:reader` whenever the Reader render path changes (CI fails on a stale one). +- **Never `evalExpr` on student input** — typed answers go through `numeric-input.ts`. - **Tauri-guard pattern** — `isTauri()` gates all native calls so lib modules run in unit tests. - **Structural immutability of placed cards** — slot add/remove only in the Factory bench; placed cards allow only content and style edits (same rule as v1). @@ -439,8 +533,11 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): (sweep-tested in `state-layer.test.ts`); every change flows through `onUpdate`/`onState` callbacks to the owner. - **One tag write path** — all `card.tags`/`Notebook.cats` mutations go through `tags.ts`. -- **No native HTML5 drag** — every gesture rides `drag/engine.ts` (sweep-tested; WKWebView breaks - custom dataTransfer MIME types). +- **Pointer engine for notebook/study, native drag in the Factory** — `drag/engine.ts` drives every + notebook and study gesture; the Factory inventory chips still use native HTML5 drag + (`SideFactory.svelte`). WKWebView blocks custom dataTransfer MIME types, so that native path can't + extend past the Factory. A sweep test in `svc-attach.test.ts` checks that no component source + contains the old `text/nb-svc` MIME type. - **Undo keeps live selections** — `restoreHistory` clears a selection only when the restored snapshot no longer contains it (D25 revised). @@ -464,11 +561,10 @@ Every slot type implements `SlotType

` (`slot-contract.ts`): docs/ CODE-MAP.md this file adr/ architecture decision records - spec/v2-spec.md v2 product spec - research/ market analysis, v1 feature inventory - examples/ sample JSON notebook + spec/ v2 product spec (local, untracked) + research/ market analysis, v1 feature inventory (local, untracked) + examples/ example notebooks DEBT.md debt ledger (local, untracked) - superpowers/plans/ task plans (local, untracked) scripts/ build.mjs v1 concatenation build @@ -478,10 +574,11 @@ scratch/ p3-gate/ … p6-gate/ visual QA screenshots (v1 vs v2 side-by-side) HANDOFF.md developer handoff notes -tests/ v1 Playwright BDD suite (~65 specs) +tests/ v1 Playwright BDD suite (66 specs, 240 tests) .github/ - workflows/ci.yml CI: build + test on push/PR + workflows/ci.yml CI: v2 check/test/build (path-filtered to v2/**) + workflows/v1.yml CI: v1 build/lint/test (path-filtered to root app paths) ISSUE_TEMPLATE/ bug/feature templates pull_request_template.md ``` diff --git a/docs/FORMAT.md b/docs/FORMAT.md new file mode 100644 index 0000000..ef2ba21 --- /dev/null +++ b/docs/FORMAT.md @@ -0,0 +1,279 @@ +# NoteBuilder notebook format (interchange JSON, version 2) + +This is the file the v2 app writes with **⤓ Backup as JSON**, reads with **⤒ import** / **+ → Import +file…**, and the shape any LLM must produce for **+ → From AI…**. A shared Reader `.html` embeds the +same document (as `{"shared": true, "notebook": }` in its ``; }); - // Inline the stylesheet, rewriting KaTeX font refs to woff2 data URIs (D23). + // Inline the stylesheet, rewriting KaTeX font refs to woff2 data URIs (D23). The authoring + // app's remote webfont @import (Google Fonts) is dropped: opening a shared file must not send a + // student's IP to a third party, and offline it only logs an error. Font stacks fall back to + // system fonts. html = html.replace(/]*\brel="stylesheet"[^>]*>/gi, (m) => { const href = m.match(/href="([^"]+)"/)?.[1]; const file = href && resolveAsset(href); if (!file) return m; - return ``; + const { css, removed } = stripRemoteImports(readFileSync(file, 'utf8')); + for (const rule of removed) console.log(`› dropped remote ${rule.slice(0, 72)}…`); + return ``; }); assertPlaceholder(html); @@ -73,22 +79,11 @@ function assertPlaceholder(html) { } } -// Fail loudly if anything would still hit the network. Script bodies are blanked first so JS/CSS -// string literals (e.g. `src="…"` inside code) never trip the scan. +// Fail loudly if anything would still hit the network: attributes, CSS url(), any CSS @import +// (including the minified `@import"https://…"` form) and any http(s) URL left in a stylesheet. +// The scan itself lives in reader-inline.mjs, where tests pin it. function assertNoExternalRefs(html) { - const scan = html.replace(/(]*>)[\s\S]*?(<\/script>)/gi, '$1$2'); - const offenders = []; - const external = (v) => v && !v.startsWith('data:') && !v.startsWith('#'); - - for (const m of scan.matchAll(/url\(\s*(["']?)([^)"']+)\1\s*\)/gi)) { - if (external(m[2].trim())) offenders.push(`url(${m[2].trim()})`); - } - for (const m of scan.matchAll(/\bsrc=(["'])([^"']*)\1/gi)) { - if (m[2].trim() && !m[2].trim().startsWith('data:')) offenders.push(`src=${m[2]}`); - } - for (const m of scan.matchAll(/\bhref=(["'])([^"']*)\1/gi)) { - if (external(m[2].trim())) offenders.push(`href=${m[2]}`); - } + const offenders = externalRefs(html); if (offenders.length) { console.error('build-reader: external references remain (must be self-contained):'); for (const o of offenders.slice(0, 10)) console.error(` ${o}`); diff --git a/v2/scripts/make-dmg-background.mjs b/v2/scripts/make-dmg-background.mjs new file mode 100644 index 0000000..70ef0c7 --- /dev/null +++ b/v2/scripts/make-dmg-background.mjs @@ -0,0 +1,100 @@ +import { deflateSync } from 'node:zlib'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const WIDTH = 660; +const HEIGHT = 400; +const ICON_ROW_Y = 170; +const APP_X = 180; +const APPLICATIONS_X = 480; + +const TOP_COLOR = [250, 250, 252]; +const BOTTOM_COLOR = [231, 234, 240]; +const ARROW_COLOR = [163, 170, 183]; + +const OUTPUT = resolve( + dirname(fileURLToPath(import.meta.url)), + '../src-tauri/dmg/background.png' +); + +const capsuleDistance = (px, py, ax, ay, bx, by, radius) => { + const dx = bx - ax; + const dy = by - ay; + const t = Math.max( + 0, + Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)) + ); + return Math.hypot(px - (ax + t * dx), py - (ay + t * dy)) - radius; +}; + +const arrowDistance = (x, y) => { + const tipX = (APP_X + APPLICATIONS_X) / 2 + 48; + const tailX = (APP_X + APPLICATIONS_X) / 2 - 48; + const stroke = 3.5; + return Math.min( + capsuleDistance(x, y, tailX, ICON_ROW_Y, tipX, ICON_ROW_Y, stroke), + capsuleDistance(x, y, tipX, ICON_ROW_Y, tipX - 22, ICON_ROW_Y - 22, stroke), + capsuleDistance(x, y, tipX, ICON_ROW_Y, tipX - 22, ICON_ROW_Y + 22, stroke) + ); +}; + +const renderPixels = () => { + const pixels = Buffer.alloc(HEIGHT * (1 + WIDTH * 3)); + for (let y = 0; y < HEIGHT; y += 1) { + const rowStart = y * (1 + WIDTH * 3); + const mix = y / (HEIGHT - 1); + const base = TOP_COLOR.map((c, i) => c + (BOTTOM_COLOR[i] - c) * mix); + for (let x = 0; x < WIDTH; x += 1) { + const coverage = Math.max( + 0, + Math.min(1, 0.5 - arrowDistance(x + 0.5, y + 0.5)) + ); + const offset = rowStart + 1 + x * 3; + for (let i = 0; i < 3; i += 1) { + pixels[offset + i] = Math.round( + base[i] + (ARROW_COLOR[i] - base[i]) * coverage + ); + } + } + } + return pixels; +}; + +const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +const crc32 = (buf) => { + let c = 0xffffffff; + for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +}; + +const chunk = (type, data) => { + const head = Buffer.alloc(8); + head.writeUInt32BE(data.length, 0); + head.write(type, 4, 'ascii'); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0); + return Buffer.concat([head, data, crc]); +}; + +const ihdr = Buffer.alloc(13); +ihdr.writeUInt32BE(WIDTH, 0); +ihdr.writeUInt32BE(HEIGHT, 4); +ihdr[8] = 8; +ihdr[9] = 2; + +const png = Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(renderPixels(), { level: 9 })), + chunk('IEND', Buffer.alloc(0)), +]); + +mkdirSync(dirname(OUTPUT), { recursive: true }); +writeFileSync(OUTPUT, png); +console.log(`wrote ${OUTPUT} (${WIDTH}x${HEIGHT}, ${png.length} bytes)`); diff --git a/v2/scripts/reader-inline.mjs b/v2/scripts/reader-inline.mjs new file mode 100644 index 0000000..9403ac8 --- /dev/null +++ b/v2/scripts/reader-inline.mjs @@ -0,0 +1,70 @@ +// @ts-check +// Pure string helpers for build-reader.mjs. No Node APIs, so src tests can import and pin them. + +/** An absolute remote target: http(s) or protocol-relative. */ +const REMOTE = String.raw`(?:https?:)?//`; + +// `@import url("…")`, `@import url('…')`, `@import url(…)`, `@import "…"` or `@import '…'` aimed at +// a remote target, plus any trailing media / supports / layer list, through its `;` (or sheet end). +const REMOTE_IMPORT_RE = new RegExp( + String.raw`@import\s*(?:url\(\s*(?:"${REMOTE}[^"]*"|'${REMOTE}[^']*'|${REMOTE}[^"')\s]*)\s*\)` + + String.raw`|"${REMOTE}[^"]*"|'${REMOTE}[^']*')[^;{}]*(?:;|$)`, + 'gi', +); + +/** + * Drop every `@import` of a remote stylesheet (e.g. the authoring app's Google Fonts import). The + * shared file must make no network request: a student's IP must not reach a third party just by + * opening it, and offline it would only log an error. Font stacks fall back to system fonts. + * @param {string} css + * @returns {{ css: string, removed: string[] }} + */ +export function stripRemoteImports(css) { + /** @type {string[]} */ + const removed = []; + const out = css.replace(REMOTE_IMPORT_RE, (rule) => { + removed.push(rule.trim()); + return ''; + }); + return { css: out, removed }; +} + +/** + * Every reference in the final HTML that would still hit the network (or the file system), as + * readable offender strings; empty when the page is self-contained. Script bodies are blanked + * first so JS string literals (e.g. `src="…"` inside code) never trip the scan; stylesheets are + * scanned in full — url(), any `@import` target, and any absolute http(s) URL left in a diff --git a/v2/src/App.test.ts b/v2/src/App.test.ts index 27b7cb5..87120fa 100644 --- a/v2/src/App.test.ts +++ b/v2/src/App.test.ts @@ -34,3 +34,28 @@ describe('App — section-service chips with a card selected', () => { expect(container.querySelector('.furn[data-card] [data-act="pin"]')).not.toBeNull(); }); }); + +describe('App — the study shortcut overlay', () => { + it('opens on ? while studying the house', async () => { + const { container } = render(App); + mode.set('study'); + await tick(); + + window.dispatchEvent(new KeyboardEvent('keydown', { key: '?' })); + await tick(); + expect(container.querySelector('.kb-modal')).not.toBeNull(); + }); + + it('closes itself when the reader leaves the house — its keys are house-only', async () => { + const { container } = render(App); + mode.set('study'); + await tick(); + window.dispatchEvent(new KeyboardEvent('keydown', { key: '?' })); + await tick(); + expect(container.querySelector('.kb-modal')).not.toBeNull(); + + place.set('factory'); + await tick(); + expect(container.querySelector('.kb-modal')).toBeNull(); + }); +}); diff --git a/v2/src/App.versions-browser.test.ts b/v2/src/App.versions-browser.test.ts new file mode 100644 index 0000000..3bc9eed --- /dev/null +++ b/v2/src/App.versions-browser.test.ts @@ -0,0 +1,18 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, cleanup } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import App from './App.svelte'; + +afterEach(() => cleanup()); + +describe('App versions — browser demo', () => { + it('shows no Versions panel: there is no storage to keep versions in', async () => { + const { container } = render(App); + await tick(); + // The notebook panel itself is there (Edit mode)… + expect(container.querySelector('#side input[placeholder="notebook name"]')).toBeTruthy(); + // …but nothing about versions. + expect(container.querySelector('.versions-panel')).toBeNull(); + expect(screen.queryByRole('button', { name: /versions/i })).toBeNull(); + }); +}); diff --git a/v2/src/App.versions.test.ts b/v2/src/App.versions.test.ts new file mode 100644 index 0000000..57f9f4d --- /dev/null +++ b/v2/src/App.versions.test.ts @@ -0,0 +1,365 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, fireEvent, waitFor, screen } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import type { Notebook } from './lib/types'; + +// App "inside Tauri" against an in-memory fake of lib/db with a snapshots table, to pin the W7 +// wiring: automatic versions ride on successful autosaves (hash-gated, rate-limited, never +// before hydration), "Save version now", and an undoable Restore that keeps the notebook id. +const h = vi.hoisted(() => ({ + notebooks: [] as Notebook[], + saves: [] as Notebook[], + snaps: [] as { id: string; nb: Notebook; reason: string; at: number }[], + n: 0, + now: 0, + failHydration: false, + hydrationGate: null as Promise | null, + confirmAnswer: true, + confirms: [] as string[], +})); + +vi.mock('./lib/db', async () => { + const { contentHash } = await import('./lib/snapshots'); + const meta = (s: (typeof h.snaps)[number]) => ({ + id: s.id, + createdAt: new Date(s.at).toISOString(), + reason: s.reason, + cardCount: s.nb.sections.reduce((k, x) => k + x.cards.length, 0), + hash: contentHash(s.nb), + }); + return { + isTauri: () => true, + onDbError: vi.fn(), + dbIdle: vi.fn(async () => {}), + listNotebooks: vi.fn(async () => { + if (h.hydrationGate) await h.hydrationGate; + if (h.failHydration) throw new Error('database is locked'); + return h.notebooks.map((n) => ({ id: n.id, name: n.name, created_at: '', updated_at: '', data: '{}' })); + }), + loadNotebook: vi.fn(async (id: string) => structuredClone(h.notebooks.find((n) => n.id === id) ?? null)), + saveNotebook: vi.fn(async (nb: Notebook) => { + h.saves.push(structuredClone(nb)); + h.notebooks = [...h.notebooks.filter((n) => n.id !== nb.id), structuredClone(nb)]; + return true; + }), + deleteNotebook: vi.fn(async () => true), + loadReaderState: vi.fn(async () => ({})), + saveReaderState: vi.fn(async () => true), + getPreference: vi.fn(async () => null), + setPreference: vi.fn(async () => true), + listCardTypes: vi.fn(async () => []), + saveCardType: vi.fn(async () => true), + deleteCardType: vi.fn(async () => true), + saveAnnotation: vi.fn(async () => true), + deleteAnnotation: vi.fn(async () => true), + loadAnnotations: vi.fn(async () => []), + saveSnapshot: vi.fn(async (nb: Notebook, reason: string, at: number = Date.now()) => { + h.snaps.push({ id: `snap${++h.n}`, nb: structuredClone(nb), reason, at }); + return true; + }), + listSnapshots: vi.fn(async (id: string) => + h.snaps + .filter((s) => s.nb.id === id) + .sort((a, b) => b.at - a.at) + .map(meta), + ), + loadSnapshot: vi.fn(async (id: string) => structuredClone(h.snaps.find((s) => s.id === id)?.nb ?? null)), + }; +}); + +vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(async () => () => {}) })); +vi.mock('@tauri-apps/api/window', () => ({ + getCurrentWindow: () => ({ onCloseRequested: vi.fn(async () => () => {}) }), +})); +vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => {}) })); +vi.mock('@tauri-apps/plugin-dialog', () => ({ + confirm: vi.fn(async (msg: string) => { + h.confirms.push(msg); + return h.confirmAnswer; + }), + open: vi.fn(async () => null), + save: vi.fn(async () => null), +})); + +import App from './App.svelte'; +import { saveSnapshot, listSnapshots } from './lib/db'; +import { mode } from './lib/stores/mode'; +import { place } from './lib/stores/place'; + +const MIN = 60_000; +const T0 = Date.parse('2026-10-18T12:00:00.000Z'); + +const nb = (id: string, name: string, texts: string[] = [`hello ${name}`]): Notebook => ({ + id, + name, + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T00:00:00Z', + cats: [], + sections: [ + { + id: `${id}_s`, + notebookId: id, + name: 'Section', + position: 0, + cards: texts.map((text, i) => ({ + id: `${id}_c${i}`, + sectionId: `${id}_s`, + position: i, + slots: [{ id: `${id}_sl${i}`, type: 'text', props: { text } }], + })), + }, + ], +}); + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const cardCount = (n: Notebook) => n.sections.reduce((k, s) => k + s.cards.length, 0); +const snapsOf = (id: string) => h.snaps.filter((s) => s.nb.id === id); +const savesOf = (id: string) => h.saves.filter((s) => s.id === id); + +async function hydrated(container: HTMLElement, text: string) { + await waitFor(() => expect(container.textContent).toContain(text)); + await tick(); + await wait(0); +} + +async function addNote(container: HTMLElement) { + const btn = [...container.querySelectorAll('button.add-card')].find((b) => b.textContent?.includes('note')); + await fireEvent.click(btn!); + await tick(); +} + +/** Add a note and wait until the debounced autosave of it has landed. */ +async function editAndAutosave(container: HTMLElement, id = 'nbA') { + const before = savesOf(id).length; + await addNote(container); + await waitFor(() => expect(savesOf(id).length).toBeGreaterThan(before), { timeout: 2000 }); + await wait(0); +} + +async function openVersions() { + await fireEvent.click(await screen.findByRole('button', { name: /versions/i })); +} + +beforeEach(() => { + h.notebooks = [nb('nbA', 'Alpha'), nb('nbB', 'Beta')]; + h.saves = []; + h.snaps = []; + h.n = 0; + h.now = T0; + h.failHydration = false; + h.hydrationGate = null; + h.confirmAnswer = true; + h.confirms = []; + vi.spyOn(Date, 'now').mockImplementation(() => h.now); + vi.mocked(saveSnapshot).mockClear(); + vi.mocked(listSnapshots).mockClear(); +}); + +afterEach(() => { + vi.mocked(Date.now).mockRestore(); + mode.set('edit'); + place.set('house'); +}); + +describe('App versions — automatic snapshots', () => { + it('edits → autosave → exactly one automatic version inside the 10-minute window', async () => { + // Its newest version (an hour old) holds exactly what is stored: opening it keeps nothing new. + h.snaps = [{ id: 'old', nb: nb('nbA', 'Alpha'), reason: 'auto', at: T0 - 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await wait(20); + expect(snapsOf('nbA')).toHaveLength(1); + + await editAndAutosave(container); + expect(snapsOf('nbA').map((s) => s.reason)).toEqual(['auto', 'auto']); + expect(cardCount(snapsOf('nbA')[1].nb)).toBe(2); + + for (let i = 0; i < 3; i++) { + h.now += 2 * MIN; // still inside the window + await editAndAutosave(container); + } + expect(snapsOf('nbA')).toHaveLength(2); + + h.now += 5 * MIN; // 11 minutes after the last version + await editAndAutosave(container); + expect(snapsOf('nbA')).toHaveLength(3); + expect(cardCount(snapsOf('nbA')[2].nb)).toBe(6); + }); + + it('a notebook with no versions yet gets one of its stored state when opened', async () => { + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await waitFor(() => expect(snapsOf('nbA')).toHaveLength(1)); + expect(snapsOf('nbA')[0].reason).toBe('auto'); + expect(cardCount(snapsOf('nbA')[0].nb)).toBe(1); + }); + + it('a stored notebook changed since its newest version is kept as it was before today’s edits', async () => { + h.snaps = [{ id: 'old', nb: nb('nbA', 'Alpha', ['yesterday morning']), reason: 'auto', at: T0 - 20 * 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await waitFor(() => expect(snapsOf('nbA')).toHaveLength(2)); + expect(snapsOf('nbA')[1].nb.sections[0].cards[0].slots[0].props.text).toBe('hello Alpha'); + await editAndAutosave(container); // inside the window now + expect(snapsOf('nbA')).toHaveLength(2); + }); + + it('nothing is listed or kept before hydration, nor after a failed one', async () => { + let release!: () => void; + h.hydrationGate = new Promise((r) => (release = r)); + h.failHydration = true; + const { container } = render(App); + await tick(); + await addNote(container); // edits the pre-hydration demo notebook + await wait(700); + expect(saveSnapshot).not.toHaveBeenCalled(); + release(); + await waitFor(() => expect(document.body.textContent).toMatch(/won’t be saved/)); + await addNote(container); + await wait(700); + expect(saveSnapshot).not.toHaveBeenCalled(); + expect(listSnapshots).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: /versions/i })).toBeNull(); + }); + + it('switching notebooks lists the other notebook’s versions', async () => { + h.snaps = [ + { id: 'a1', nb: nb('nbA', 'Alpha'), reason: 'manual', at: T0 - 60 * MIN }, + { id: 'b1', nb: nb('nbB', 'Beta'), reason: 'auto', at: T0 - 120 * MIN }, + { id: 'b2', nb: nb('nbB', 'Beta'), reason: 'manual', at: T0 - 90 * MIN }, + ]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await openVersions(); + expect(await screen.findAllByRole('button', { name: /^restore the version/i })).toHaveLength(1); + await fireEvent.click(container.querySelector('[data-act="nbmenu"]')!); + const beta = [...container.querySelectorAll('.nbitem')].find((b) => b.textContent?.includes('Beta')); + await fireEvent.click(beta!); + await hydrated(container, 'hello Beta'); + await waitFor(() => expect(screen.getAllByRole('button', { name: /^restore the version/i })).toHaveLength(2)); + }); +}); + +describe('App versions — the panel', () => { + it('“Save version now” keeps a manual version and lists it', async () => { + h.snaps = [{ id: 'old', nb: nb('nbA', 'Alpha'), reason: 'auto', at: T0 - 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await openVersions(); + expect(screen.getByRole('list', { name: /saved versions/i }).textContent).toMatch(/1 h ago/); + await addNote(container); // unsaved yet: the version is of what is on screen + await fireEvent.click(screen.getByRole('button', { name: /save version now/i })); + await waitFor(() => expect(snapsOf('nbA').map((s) => s.reason)).toEqual(['auto', 'manual'])); + expect(cardCount(snapsOf('nbA')[1].nb)).toBe(2); + await waitFor(() => expect(screen.getByRole('list', { name: /saved versions/i }).textContent).toMatch(/Saved by you/)); + expect(document.body.textContent).toMatch(/Version saved/); + }); +}); + +describe('App versions — restore', () => { + const OLD = () => nb('nbA', 'Alpha (draft)', ['old one', 'old two', 'old three']); + + async function restoreOldest(container: HTMLElement) { + await hydrated(container, 'hello Alpha'); + await openVersions(); + const buttons = await screen.findAllByRole('button', { name: /^restore the version/i }); + await fireEvent.click(buttons.at(-1)!); + } + + it('confirm → current kept as before-restore → content replaced under the same id → saved now; Undo returns', async () => { + h.snaps = [{ id: 'old', nb: OLD(), reason: 'manual', at: T0 - 3 * 24 * 60 * MIN }]; + const { container } = render(App); + await restoreOldest(container); + await waitFor(() => expect(container.textContent).toContain('old three')); + expect(h.confirms.at(-1)).toMatch(/restore/i); + + // What was on screen is kept first. + const before = snapsOf('nbA').find((s) => s.reason === 'before-restore'); + expect(before && cardCount(before.nb)).toBe(1); + expect(before!.nb.sections[0].cards[0].slots[0].props.text).toBe('hello Alpha'); + + // Saved at once (no debounce), under the same id, with the stored card ids. + await wait(20); + const saved = savesOf('nbA').at(-1)!; + expect(saved.sections[0].cards.map((c) => c.id)).toEqual(['nbA_c0', 'nbA_c1', 'nbA_c2']); + expect(saved.name).toBe('Alpha (draft)'); + expect(container.textContent).not.toContain('hello Alpha'); + expect((container.querySelector('#side input[placeholder="notebook name"]') as HTMLInputElement).value).toBe( + 'Alpha (draft)', + ); + // The notebook menu follows the restored name, like a rename. + await fireEvent.click(container.querySelector('[data-act="nbmenu"]')!); + expect([...container.querySelectorAll('.nbitem')].map((b) => b.textContent)).toEqual( + expect.arrayContaining([expect.stringContaining('Alpha (draft)')]), + ); + await fireEvent.click(container.querySelector('[data-act="nbmenu"]')!); + + await fireEvent.click(container.querySelector('button[title="Undo"]')!); + await tick(); + expect(container.textContent).toContain('hello Alpha'); + expect(container.textContent).not.toContain('old three'); + await waitFor(() => expect(cardCount(savesOf('nbA').at(-1)!)).toBe(1), { timeout: 2000 }); + expect(savesOf('nbA').at(-1)!.name).toBe('Alpha'); + // …and the menu follows the undone name too. + await fireEvent.click(container.querySelector('[data-act="nbmenu"]')!); + const names = [...container.querySelectorAll('.nbitem')].map((b) => b.textContent ?? ''); + expect(names.some((t) => t.includes('Alpha (draft)'))).toBe(false); + expect(names.some((t) => t.includes('Alpha'))).toBe(true); + }); + + it('if the current notebook cannot be kept as a version first, nothing is restored', async () => { + h.snaps = [{ id: 'old', nb: OLD(), reason: 'manual', at: T0 - 3 * 24 * 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await waitFor(() => expect(snapsOf('nbA')).toHaveLength(2)); // the baseline taken at open + vi.mocked(saveSnapshot).mockImplementationOnce(async () => false); + await openVersions(); + const buttons = await screen.findAllByRole('button', { name: /^restore the version/i }); + await fireEvent.click(buttons.at(-1)!); + await waitFor(() => expect(document.body.textContent).toMatch(/nothing was restored/)); + expect(container.textContent).toContain('hello Alpha'); + expect(container.textContent).not.toContain('old three'); + expect(savesOf('nbA')).toHaveLength(0); + expect(container.querySelector('button[title="Undo"]')!.hasAttribute('disabled')).toBe(true); + }); + + it('a cancelled restore changes nothing', async () => { + h.snaps = [{ id: 'old', nb: OLD(), reason: 'manual', at: T0 - 3 * 24 * 60 * MIN }]; + h.confirmAnswer = false; + const { container } = render(App); + await restoreOldest(container); + await wait(50); + expect(h.confirms).toHaveLength(1); + expect(container.textContent).toContain('hello Alpha'); + expect(snapsOf('nbA').map((s) => s.reason)).not.toContain('before-restore'); + expect(savesOf('nbA')).toHaveLength(0); + expect(container.querySelector('button[title="Undo"]')!.hasAttribute('disabled')).toBe(true); + }); + + it('never restores another notebook’s version into this one (its card ids would clash)', async () => { + h.snaps = [{ id: 'old', nb: OLD(), reason: 'manual', at: T0 - 3 * 24 * 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await openVersions(); + const buttons = await screen.findAllByRole('button', { name: /^restore the version/i }); + h.snaps.find((s) => s.id === 'old')!.nb = nb('nbB', 'Beta', ['beta card']); + await fireEvent.click(buttons.at(-1)!); + await waitFor(() => expect(document.body.textContent).toMatch(/no longer available/i)); + expect(container.textContent).toContain('hello Alpha'); + expect(container.textContent).not.toContain('beta card'); + expect(snapsOf('nbA').map((s) => s.reason)).not.toContain('before-restore'); + }); + + it('a version pruned meanwhile is reported, and nothing changes', async () => { + h.snaps = [{ id: 'old', nb: OLD(), reason: 'manual', at: T0 - 3 * 24 * 60 * MIN }]; + const { container } = render(App); + await hydrated(container, 'hello Alpha'); + await openVersions(); + const [restore] = await screen.findAllByRole('button', { name: /^restore the version/i }); + h.snaps = []; + await fireEvent.click(restore); + await waitFor(() => expect(document.body.textContent).toMatch(/no longer available/i)); + expect(container.textContent).toContain('hello Alpha'); + expect(snapsOf('nbA')).toHaveLength(0); + }); +}); diff --git a/v2/src/app.css b/v2/src/app.css index 2d45482..faf7301 100644 --- a/v2/src/app.css +++ b/v2/src/app.css @@ -15,6 +15,32 @@ --mono: ui-monospace, SFMono-Regular, Menlo, monospace; --font: system-ui, -apple-system, Segoe UI, Roboto, sans-serif; --glow: 0 0 0 1px rgba(110, 168, 254, 0); + + /* spacing scale (2px step — the grid the ported v1 chrome is actually built on) */ + --space-1: 2px; + --space-2: 4px; + --space-3: 6px; + --space-4: 8px; + --space-5: 10px; + --space-6: 12px; + + /* type roles */ + --fs-2xs: 10px; + --fs-xs: 11px; + --fs-sm: 12px; + --fs-md: 13px; + --fs-lg: 16px; + + /* inner-chrome radii — unlike --radius these are fixed, themes do NOT swap them */ + --radius-sm: 4px; + --radius-md: 6px; + --radius-lg: 10px; + + /* motion */ + --t-quick: 0.12s; + --t-base: 0.15s; + --t-slow: 0.35s; + --ease-out: cubic-bezier(0.2, 0.8, 0.2, 1); } body[data-theme="plain"] { --bg: #f6f7f9; @@ -158,7 +184,7 @@ body[data-theme="mono"] .furn::before { background: var(--accent); transform: scaleY(0); transform-origin: top; - transition: transform 0.35s cubic-bezier(0.2, 0.8, 0.2, 1); + transition: transform var(--t-slow) var(--ease-out); } body[data-theme="mono"] .furn:hover::before { transform: scaleY(1); @@ -429,6 +455,104 @@ body[data-theme="sketch"] .house-title { body[data-theme="sketch"] .ceview { border-radius: 8px; } +/* TERMINAL — phosphor trading-terminal look (near-black green · grid + scanlines · mono headers · neon glow) */ +body[data-theme="terminal"] { + --bg: #03100a; + --panel: #071a12; + --panel2: #061b12; + --ink: #bff7d9; + --muted: #5fa985; + --line: rgba(39, 255, 158, 0.22); + --accent: #27ff9e; + --accent2: #19e6ff; + --good: #00ffa3; + --warn: #ff2d95; + --radius: 14px; + --font: "Rajdhani", "Chakra Petch", "Avenir Next Condensed", system-ui, sans-serif; + --glow: 0 0 14px rgba(39, 255, 158, 0.35); + background: + radial-gradient(900px 600px at 22% -8%, rgba(0, 255, 163, 0.1), transparent 60%), + radial-gradient(720px 520px at 92% 108%, rgba(25, 230, 255, 0.07), transparent 60%), + repeating-linear-gradient(0deg, rgba(0, 0, 0, 0.16) 0 1px, transparent 1px 3px), + linear-gradient(rgba(57, 255, 140, 0.055) 1px, transparent 1px), + linear-gradient(90deg, rgba(57, 255, 140, 0.055) 1px, transparent 1px), + var(--bg); + background-size: + auto, + auto, + auto, + 38px 38px, + 38px 38px; + background-attachment: fixed; +} +body[data-theme="terminal"] .furn { + border: 1px solid var(--line); + background: linear-gradient(180deg, rgba(8, 28, 19, 0.92), var(--panel) 45%); + box-shadow: 0 0 14px rgba(39, 255, 158, 0.08); + transition: + border-color var(--t-base) var(--ease-out), + box-shadow var(--t-base) var(--ease-out), + transform var(--t-base) var(--ease-out); +} +body[data-theme="terminal"] .furn:hover { + border-color: var(--accent); + box-shadow: + 0 0 18px rgba(39, 255, 158, 0.28), + inset 0 0 22px rgba(39, 255, 158, 0.05); + transform: translateY(-2px); +} +body[data-theme="terminal"] .text-study b, +body[data-theme="terminal"] .text-study strong { + color: var(--accent); +} +body[data-theme="terminal"] .text-study i, +body[data-theme="terminal"] .text-study em { + color: var(--accent2); +} +body[data-theme="terminal"] .text-study code { + color: var(--good); + background: rgba(39, 255, 158, 0.08); + border: 1px solid var(--line); +} +body[data-theme="terminal"] .text-study s, +body[data-theme="terminal"] .text-study del { + color: var(--warn); +} +body[data-theme="terminal"] .house-title, +body[data-theme="terminal"] .room-title h1, +body[data-theme="terminal"] .room-title h2, +body[data-theme="terminal"] .room-title h3 { + font-family: var(--mono); + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--accent); + text-shadow: var(--glow); +} +body[data-theme="terminal"] .room-title h1::before, +body[data-theme="terminal"] .room-title h2::before, +body[data-theme="terminal"] .room-title h3::before { + content: "// "; + color: var(--muted); + text-shadow: none; +} +body[data-theme="terminal"] .btn, +body[data-theme="terminal"] .chip, +body[data-theme="terminal"] .pchip { + font-family: var(--mono); + border-radius: 999px; +} +body[data-theme="terminal"] .btn.on, +body[data-theme="terminal"] .btn.primary { + background: var(--accent); + color: var(--bg); + border-color: transparent; + box-shadow: var(--glow); +} +body[data-theme="terminal"] input:focus, +body[data-theme="terminal"] textarea:focus { + border-color: var(--accent); + outline: 1px solid var(--accent); +} * { margin: 0; @@ -1251,6 +1375,13 @@ body.side-collapsed #main { /* ---------- ported: v1 card chrome — .furn, grip/rz, bare, sel, cardrow/cardslot (styles.css) ---------- */ .furn { --cardc: var(--accent); + /* The study cursor ring, shared by the keyboard cursor and the place flash: a --bg gap and an + --ink halo either side of the accent outline that draws over them. The 3px inset repeats this + rule's own accent stripe. */ + --kring: + inset 3px 0 0 var(--cardc), /* token-exempt: the accent stripe width, kept in step with .furn */ + var(--glow), 0 0 0 var(--space-2) var(--bg), + 0 0 0 var(--space-4) color-mix(in srgb, var(--ink) 60%, transparent); flex: 0 0 calc((var(--w, 6) / 12) * 100% - 9px); background: var(--panel); border: 1px solid var(--line); @@ -1260,7 +1391,7 @@ body.side-collapsed #main { box-shadow: inset 3px 0 0 var(--cardc), var(--glow); - transition: flex-basis 0.12s ease; + transition: flex-basis var(--t-quick) ease; } .furn.dragging { transition: none; @@ -1301,6 +1432,44 @@ body[data-theme] .room.edit .furn.bare { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(110, 168, 254, 0.3); } +/* Study keyboard cursor. `.sel` is the Edit-mode selection and stays edit-only, so the cursor + carries its own two-layer ring (--kring above). The halo is what keeps the cursor apart from the + accent-coloured .done border, which the single accent ring read as in Dark and B&W. The `body` + prefix outranks the theme blocks, which restyle `.furn`'s box-shadow at a higher specificity and + would otherwise drop the halo. */ +body .furn.kfocus { + outline: var(--space-1) solid var(--accent); + outline-offset: var(--space-1); + box-shadow: var(--kring); +} +/* A card placed from the store lands at the end of its section, usually below the fold: the same + ring flashes on it so the reader sees where it arrived. */ +@keyframes kflash { + 0%, + 60% { + outline-color: var(--accent); + box-shadow: var(--kring); + } + 100% { + outline-color: transparent; + /* the card's resting shadow — token-exempt: the accent stripe width, as in .furn */ + box-shadow: + inset 3px 0 0 var(--cardc), + var(--glow); + } +} +body .furn.kflash { + outline: var(--space-1) solid var(--accent); + outline-offset: var(--space-1); + box-shadow: var(--kring); + animation: kflash calc(var(--t-slow) * 2) var(--ease-out); +} +@media (prefers-reduced-motion: reduce) { + /* The ring still appears and still clears with the class — it simply does not fade. */ + body .furn.kflash { + animation: none; + } +} .furn .grip { position: absolute; top: 6px; @@ -1310,7 +1479,7 @@ body[data-theme] .room.edit .furn.bare { font-size: 13px; user-select: none; opacity: 0; - transition: 0.15s; + transition: var(--t-base); } .furn:hover .grip { opacity: 0.8; @@ -1445,7 +1614,7 @@ body[data-theme] .room.edit .furn.bare { /* hidden row still hit-tests (opacity<1 stacks above the positioned .grip) and would swallow the grip's pointerdown, killing card drag — dead to the pointer until revealed */ pointer-events: none; - transition: 0.15s; + transition: var(--t-base); } .furn:hover .cardtools, .cardtools:focus-within { @@ -1652,7 +1821,7 @@ body[data-theme] .room.edit .furn.bare { position: relative; min-height: 46px; cursor: pointer; - transition: flex-basis 0.12s ease; + transition: flex-basis var(--t-quick) ease; } .benchslot.dragging { transition: none; @@ -1817,8 +1986,8 @@ body[data-theme] .room.edit .furn.bare { overflow: hidden; text-overflow: ellipsis; transition: - background 0.12s, - color 0.12s, + background var(--t-quick), + color var(--t-quick), transform 0.08s; } .mtx-c:hover { @@ -1991,6 +2160,102 @@ body[data-theme] .room.edit .furn.bare { top: 36px; } +/* ---------- shared Reader on phones (≤ 760px) ---------- + Reader.svelte opens with the panel collapsed below this width and marks nb-reader. + Every rule is scoped to that class: desktop widths and the authoring App keep the layout above. */ +@media (max-width: 760px) { + /* row 1: brand … My results / Remix; row 2: theme + notebook name. Never a sideways scroll. */ + body.nb-reader #top { + flex-wrap: wrap; + gap: 6px 8px; + padding: 8px 12px; + } + body.nb-reader #top .btn { + white-space: nowrap; + } + body.nb-reader #places { + order: 1; + flex: 1 1 100%; + min-width: 0; + } + body.nb-reader #places .brand-nb { + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + body.nb-reader #topright { + flex-wrap: wrap; + justify-content: flex-end; + min-width: 0; + } + /* the lesson always gets the full width; #main fills what the (wrapped) top bar leaves */ + body.nb-reader #main { + grid-template-columns: minmax(0, 1fr); + position: relative; + flex: 1 1 0; + height: auto; + min-height: 0; + } + body.nb-reader #resizer { + display: none; + } + /* an open panel overlays the lesson instead of squeezing it */ + body.nb-reader #side { + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: min(var(--sidew, 312px), 86vw); + z-index: 25; + box-shadow: 10px 0 30px rgba(0, 0, 0, 0.35); + } + body.nb-reader.side-collapsed #side { + display: none; + } + body.nb-reader #sidebump { + left: min(var(--sidew, 312px), 86vw); + width: 22px; + height: 64px; + } + body.nb-reader.side-collapsed #sidebump { + left: 0; + } + body.nb-reader #stage { + padding: 14px 12px; + } + /* the 12-column card grid collapses: every card, and every slot in it, spans the full width */ + body.nb-reader .rgwrap > .room-grid { + min-width: 0; + } + /* min-width: 0 — a flex item's min-width:auto is its min-content width, so one long code line + or URL widened its card, and through the grid every card in the section, past the screen. + Wide content now wraps (text) or scrolls inside its own slot (code, tables, display math). */ + body.nb-reader .room-grid > .furn { + flex-basis: 100%; + min-width: 0; + overflow-wrap: break-word; + } + body.nb-reader .furn .table-study, + body.nb-reader .furn .katex-display { + overflow-x: auto; + overflow-y: hidden; + } + /* the coverage matrix (≥ 42px per tag column) scrolls in its own box once it outgrows the phone */ + body.nb-reader .mtx { + overflow-x: auto; + } + body.nb-reader .cardrow > .cardslot { + flex-basis: 100%; + } + /* mobile 100vh runs under the browser's toolbar; the dynamic viewport doesn't */ + @supports (height: 100dvh) { + body.nb-reader #app { + height: 100dvh; + } + } +} + /* ---------- ported: v1 print stylesheet (styles.css @media print 2160-2183) ---------- */ @media print { #top, @@ -2008,11 +2273,14 @@ body[data-theme] .room.edit .furn.bare { .grip, .rz, .arch, - .svcbar { + .svcbar, + .kb-hint { display: none !important; } body { background: #fff; color: #000; + /* A forgotten Cmd+- must not shrink the paper: paginate at 100% whoever raised the sheet. */ + zoom: 1 !important; /* token-exempt: the identity zoom factor, not a dimension */ } } diff --git a/v2/src/index-html.test.ts b/v2/src/index-html.test.ts new file mode 100644 index 0000000..3dc2b09 --- /dev/null +++ b/v2/src/index-html.test.ts @@ -0,0 +1,15 @@ +/** + * Browser QA: the dev server logged a 404 for /favicon.ico on every load, noise that hides real + * console errors. The app page declares an empty inline icon, so the browser never asks. + */ +import { describe, it, expect } from 'vitest'; +// @ts-expect-error -- node builtin, untyped in the browser-only tsconfig (test runs in vitest/node) +import { readFileSync } from 'node:fs'; + +describe('index.html', () => { + it('declares an inline (data:) icon, so no /favicon.ico request is made', () => { + const html = readFileSync('index.html', 'utf8') as string; + const head = html.slice(0, html.indexOf('')); + expect(head).toMatch(//); + }); +}); diff --git a/v2/src/lib/ai-prompt.grammar.test.ts b/v2/src/lib/ai-prompt.grammar.test.ts new file mode 100644 index 0000000..bb3ef0f --- /dev/null +++ b/v2/src/lib/ai-prompt.grammar.test.ts @@ -0,0 +1,93 @@ +/** + * Review fix: expr.ts binds a leading minus tighter than ^ (-x^2 is (-x)^2) and has no ** + * operator. LLMs write both by habit (exp(-x^2/2) for a bell curve), and the math comes out + * silently wrong — so the prompt and FORMAT.md say so, and the From AI check warns. + */ +import { describe, it, expect } from 'vitest'; +// @ts-expect-error -- node builtin, untyped in the browser-only tsconfig (test runs in vitest/node) +import { readFileSync } from 'node:fs'; +import { buildAiPrompt, AI_EXAMPLE } from './ai-prompt'; +import { evalExpr } from './expr'; +import { checkNotebookText, lintExprPitfalls } from './import-hints'; + +function doc(slots: unknown[], back?: unknown[]): Record { + return { + version: 2, + notebook: { name: 'N', sections: [{ name: 'S', cards: [{ slots, ...(back && { back, verbs: { flip: true } }) }] }] }, + }; +} + +describe('the expression pitfalls the docs describe are real', () => { + it('a leading minus binds tighter than ^, and ** is no operator', () => { + expect(evalExpr('-x^2', { x: 3 })).toBe(9); + expect(evalExpr('-(x^2)', { x: 3 })).toBe(-9); + expect(evalExpr('exp(-x^2)', { x: 2 })).toBeCloseTo(Math.exp(4)); + expect(evalExpr('2**3', {})).not.toBe(8); + }); +}); + +describe('the prompt and FORMAT.md warn about them', () => { + const prompt = buildAiPrompt({ topic: 'Normal distribution' }); + + it('the prompt says to parenthesize a negated power and never to use **', () => { + expect(prompt).toContain('-(x^2)'); + expect(prompt).toMatch(/-x\^2 means \(-x\)\^2/); + expect(prompt).toMatch(/never \*\*/); + }); + + it('FORMAT.md says the same', () => { + const md = readFileSync('../docs/FORMAT.md', 'utf8') as string; + expect(md).toContain('-(x^2)'); + expect(md).toMatch(/not `\*\*`/); + }); +}); + +describe('lintExprPitfalls (From AI check warnings)', () => { + it('flags a negated power in a chart fn and a compute expr, on either face', () => { + const issues = lintExprPitfalls( + doc( + [ + { type: 'chart', props: { fn: 'exp(-x^2 / 2)', x0: -3, x1: 3 } }, + { type: 'compute', props: { expr: '-a^2 + 1', out: 'b' } }, + ], + [{ type: 'compute', props: { expr: 'c * -2^k', out: 'd' } }], + ), + ); + expect(issues.map((i) => i.path)).toEqual([ + 'notebook.sections[0].cards[0].slots[0].props.fn', + 'notebook.sections[0].cards[0].slots[1].props.expr', + 'notebook.sections[0].cards[0].back[0].props.expr', + ]); + for (const i of issues) { + expect(i.code).toBe('expr-pitfall'); + expect(i.hint).toContain('-(x^2)'); + } + expect(issues[0].message).toMatch(/"-x\^" raises \(-x\) to the power/); + }); + + it('flags ** as a power operator', () => { + const [issue] = lintExprPitfalls(doc([{ type: 'compute', props: { expr: 'P * (1 + r)**t', out: 'A' } }])); + expect(issue).toMatchObject({ code: 'expr-pitfall', subject: '**' }); + expect(issue.hint).toMatch(/\^/); + }); + + it('leaves correct formulas alone', () => { + const fine = ['a - x^2', '-(x^2)', 'x^-2', '(a)-x^2', '2 - 3^2', '-x * 2', 'max(-1, x)^2', 'r_1 - b^2']; + const issues = lintExprPitfalls(doc(fine.map((fn) => ({ type: 'chart', props: { fn } })))); + expect(issues).toEqual([]); + expect(lintExprPitfalls(AI_EXAMPLE)).toEqual([]); + }); + + it('ignores non-formula props and junk documents', () => { + expect(lintExprPitfalls(doc([{ type: 'text', props: { text: 'In math, $-x^2$ is negative.' } }]))).toEqual([]); + for (const junk of [null, 1, 'x', [], {}, { notebook: { sections: 'no' } }, doc([null, { type: 'chart', props: null }])]) { + expect(lintExprPitfalls(junk)).toEqual([]); + } + }); + + it('runs as a warning in checkNotebookText — the notebook still imports', () => { + const r = checkNotebookText(JSON.stringify(doc([{ type: 'chart', props: { fn: '-x^2 + 4', x0: -3, x1: 3 } }]))); + expect(r.ok).toBe(true); + expect(r.warnings.map((w) => w.code)).toContain('expr-pitfall'); + }); +}); diff --git a/v2/src/lib/ai-prompt.problem.test.ts b/v2/src/lib/ai-prompt.problem.test.ts new file mode 100644 index 0000000..e7ca43f --- /dev/null +++ b/v2/src/lib/ai-prompt.problem.test.ts @@ -0,0 +1,100 @@ +/** + * Review fix: the AI kit contradicted its own problem catalog example ("only text slots and a + * choice's q and explanation render {{name}}", while problem.prompt / explain use {{w}}) and + * never taught the problem slot's own rules — so models added sliders for params, named a param + * e or min, wrote round(x, 2), left out tol, need and explain. The prompt and the published + * schema's descriptions now say what the app actually does. + */ +import { describe, it, expect } from 'vitest'; +import { buildAiPrompt } from './ai-prompt'; +import { EXPR_BUILTINS } from './expr'; +import { SLOT_CATALOG } from './slot-catalog'; +import { NOTEBOOK_SCHEMA, slotPropsSchema } from './schema/schema'; +import { problemIssues, type ProblemProps } from './slots/problem'; + +const prompt = buildAiPrompt({ topic: 'Percentages' }); + +/** The prompt line that starts with `start` (each guidance rule is one bullet line). */ +function line(start: string): string { + const found = prompt.split('\n').find((l) => l.startsWith(start)); + expect(found, `prompt line starting with ${JSON.stringify(start)}`).toBeDefined(); + return found!; +} + +describe('the markdown / {{name}} rule names the problem fields', () => { + it('lists problem.prompt and problem.explain next to text and choice', () => { + const rule = line('- Only text slots'); + expect(rule).toMatch(/a problem's prompt and explain render markdown, \$math\$ and \{\{name\}\}/); + expect(rule).toMatch(/choice's q and explanation/); + }); + + it('agrees with the problem catalog example, which prints params with {{name}}', () => { + const ex = SLOT_CATALOG.problem.example as { prompt: string; explain: string }; + expect(ex.prompt).toMatch(/\{\{\w+\}\}/); + expect(ex.explain).toMatch(/\{\{\w+\}\}/); + }); + + it('counts a problem answer among the readers of card variables', () => { + expect(line('- Slots of the SAME card read')).toMatch(/a problem's answer/); + expect(line('- Expression grammar')).toMatch(/a problem's answer/); + }); +}); + +describe('problem slot guidance', () => { + const rule = (): string => line('- Practice problems'); + + it('says params are local to the slot and must not also get sliders', () => { + expect(rule()).toMatch(/params are local to the slot/i); + expect(rule()).toMatch(/do NOT add sliders for them/); + }); + + it('forbids built-in names as param names', () => { + for (const name of ['e', 'pi', 'min', 'max', 'sin']) expect(rule()).toMatch(new RegExp(`\\b${name}\\b`)); + expect(rule()).toMatch(/built-in/); + }); + + it('teaches one-argument round, tol for decimals, need 2–3 for drills and an explain', () => { + expect(rule()).toMatch(/round\(\) takes ONE argument/); + expect(rule()).toContain('round(x * 100) / 100'); + expect(rule()).toMatch(/\btol\b/); + expect(rule()).toMatch(/need 2–3/); + expect(rule()).toMatch(/always give explain/i); + }); + + it('the rules it states are the ones the app enforces', () => { + const base: ProblemProps = { prompt: 'p', params: [{ name: 'a', min: 1, max: 9, step: 1 }], answer: 'a', tol: 0, need: 1 }; + expect(problemIssues(base)).toEqual([]); + expect(problemIssues({ ...base, answer: 'round(a / 3, 2)' }).join(' ')).toMatch(/round/); + for (const name of ['e', 'pi', 'min', 'max', 'sin']) { + expect(problemIssues({ ...base, params: [{ name, min: 1, max: 9, step: 1 }], answer: '1' }).join(' '), name).toMatch(/reserved/); + } + }); + + it('the checklist asks for an explain and no slider standing in for a param', () => { + const check = line('- Every problem'); + expect(check).toMatch(/explain/); + expect(check).toMatch(/slider/); + }); + + it('the name rule lists every built-in the app reserves (mod included)', () => { + const names = line('- Names'); + for (const b of EXPR_BUILTINS) expect(names, b).toMatch(new RegExp(`\\b${b}\\b`)); + expect(names).toMatch(/problem param/); + }); +}); + +describe('the published schema describes who reads card variables accurately', () => { + it('the top-level description no longer limits readers to text/compute/chart, and names problem', () => { + const d = NOTEBOOK_SCHEMA.description ?? ''; + expect(d).not.toMatch(/only text\/compute\/chart/); + expect(d).toMatch(/problem/); + }); + + it('problemProps says answer, prompt and explain may read card variables while params stay local', () => { + const p = slotPropsSchema('problem')!; + expect(p.description).toMatch(/never become card variables/); + expect(p.description).toMatch(/card variables|variables of this card/); + expect(p.properties?.prompt.description).toMatch(/card variable/); + expect(p.properties?.answer.description).toMatch(/card variables/); + }); +}); diff --git a/v2/src/lib/ai-prompt.test.ts b/v2/src/lib/ai-prompt.test.ts new file mode 100644 index 0000000..d3488c0 --- /dev/null +++ b/v2/src/lib/ai-prompt.test.ts @@ -0,0 +1,160 @@ +import { describe, it, expect } from 'vitest'; +import Ajv2020 from 'ajv/dist/2020'; +import schema from './schema/notebook.schema.json'; +import { + buildAiPrompt, + compactJson, + AI_EXAMPLE, + EXAMPLE_START, + EXAMPLE_END, + EXPR_FUNCTIONS, + EXPR_CONSTANTS, +} from './ai-prompt'; +import { SLOT_CATALOG } from './slot-catalog'; +import { allSlots, getSlot } from './slots/registry'; +import { validateNotebook } from './json-io'; +import { evalExpr } from './expr'; + +const ajv = new Ajv2020({ allErrors: true, strict: true, allowUnionTypes: true }); +const schemaValid = ajv.compile(schema); + +function embeddedExample(prompt: string): unknown { + const start = prompt.indexOf(EXAMPLE_START); + const end = prompt.indexOf(EXAMPLE_END); + expect(start, 'example start marker').toBeGreaterThanOrEqual(0); + expect(end, 'example end marker').toBeGreaterThan(start); + return JSON.parse(prompt.slice(start + EXAMPLE_START.length, end)); +} + +describe('buildAiPrompt', () => { + const prompt = buildAiPrompt({ topic: 'Photosynthesis', audience: 'high-school biology students', cards: 14 }); + + it('names the topic, audience and length', () => { + expect(prompt).toContain('Photosynthesis'); + expect(prompt).toContain('high-school biology students'); + expect(prompt).toMatch(/about 14 cards/); + }); + + it('states the output contract: one JSON object, version 2, nothing else', () => { + expect(prompt).toMatch(/ONLY one JSON object/); + expect(prompt).toContain('"version": 2'); + expect(prompt).toMatch(/no code fences/i); + expect(prompt).toMatch(/double every backslash/i); + }); + + it('teaches the card-scope variable rule and the expression grammar', () => { + expect(prompt).toMatch(/variables never cross cards/i); + expect(prompt).toContain('{{name}}'); + for (const fn of EXPR_FUNCTIONS) expect(prompt).toContain(fn.name); + for (const c of EXPR_CONSTANTS) expect(prompt).toContain(c); + }); + + it('carries pedagogy guidance: retrieval practice, flashcards, guided exploration', () => { + expect(prompt).toMatch(/retrieval practice/i); + expect(prompt).toMatch(/flashcard/i); + expect(prompt).toMatch(/explanation/); + expect(prompt).toMatch(/explor/i); + }); + + it('lists every registered slot type in the catalog', () => { + for (const { type } of allSlots()) { + expect( + SLOT_CATALOG[type], + `slot type "${type}" is registered but has no SLOT_CATALOG entry in lib/slot-catalog.ts — add one (and its schema def)`, + ).toBeDefined(); + expect(prompt, `prompt catalog is missing "${type}"`).toContain(`### ${type}\n`); + } + }); + + it('embeds an example that passes validateNotebook (no errors, no warnings) and the schema', () => { + const example = embeddedExample(prompt); + expect(example).toEqual(AI_EXAMPLE); + expect(validateNotebook(example)).toEqual({ errors: [], warnings: [] }); + expect(schemaValid(example), JSON.stringify(schemaValid.errors)).toBe(true); + }); + + it('the example demonstrates the patterns the guidance asks for', () => { + const cards = AI_EXAMPLE.notebook.sections.flatMap((s) => s.cards); + const slotTypes = (c: (typeof cards)[number]) => [...c.slots, ...(c.back ?? [])].map((s) => s.type); + expect(cards.some((c) => c.verbs?.flip && c.back?.length)).toBe(true); + expect(cards.some((c) => c.slots.some((s) => s.type === 'choice' && s.props.explanation))).toBe(true); + expect(cards.some((c) => ['slider', 'compute', 'chart'].every((t) => slotTypes(c).includes(t)))).toBe(true); + expect(JSON.stringify(AI_EXAMPLE)).toContain('\\\\'); // shows a doubled LaTeX backslash + }); + + it('is deterministic and needs only a topic', () => { + expect(buildAiPrompt({ topic: 'Fractions' })).toBe(buildAiPrompt({ topic: 'Fractions' })); + const minimal = buildAiPrompt({ topic: ' Fractions ' }); + expect(minimal).toContain('Fractions'); + expect(minimal).not.toMatch(/Audience:/); + }); + + it('ignores a nonsensical card count', () => { + expect(buildAiPrompt({ topic: 'T', cards: 0 })).not.toMatch(/about 0 cards/); + expect(buildAiPrompt({ topic: 'T', cards: Number.NaN })).not.toMatch(/NaN/); + expect(buildAiPrompt({ topic: 'T', cards: 500 })).toMatch(/about 60 cards/); + }); + + it('derives the document shape and slot props from the published schema', () => { + expect(prompt).toContain('sections: Section[]'); + expect(prompt).toContain('w?: number (3–12)'); + expect(prompt).toContain('options: string[] (at least 2 items)'); + expect(prompt).toContain('props: { scope: "section" | "chapter" | "notebook"'); + // editor-only housekeeping fields stay out of the prompt + expect(prompt).not.toMatch(/^\s+- (svcW|fuseW|archived)\??:/m); + }); + + it('can append the full JSON Schema', () => { + const withSchema = buildAiPrompt({ topic: 'T', includeSchema: true }); + expect(withSchema).toContain('"$schema": "https://json-schema.org/draft/2020-12/schema"'); + expect(buildAiPrompt({ topic: 'T' })).not.toContain('draft/2020-12'); + }); +}); + +describe('compactJson', () => { + it('round-trips to the same value and keeps short values on one line', () => { + const values: unknown[] = [ + AI_EXAMPLE, + { a: [], b: {}, c: 'line\nbreak "quoted" \\ backslash', d: [1, [2, [3, { e: null }]]], f: true }, + [], + 'x', + 0, + null, + ]; + for (const v of values) expect(JSON.parse(compactJson(v))).toEqual(v); + expect(compactJson({ a: [1, 2] })).toBe('{"a":[1,2]}'); + expect(compactJson({ long: 'y'.repeat(120) })).toContain('\n'); + }); +}); + +describe('slot catalog examples', () => { + it('every catalog entry is a registered slot whose example props pass validate() and the schema', () => { + for (const [type, entry] of Object.entries(SLOT_CATALOG)) { + const st = getSlot(type); + expect(st, `catalog lists "${type}" but no such slot is registered`).toBeDefined(); + expect(st!.validate?.(entry.example) ?? [], type).toEqual([]); + const doc = { version: 2, notebook: { name: 'N', sections: [{ name: 'S', cards: [{ slots: [{ type, props: entry.example }] }] }] } }; + expect(schemaValid(doc), `${type}: ${JSON.stringify(schemaValid.errors)}`).toBe(true); + } + }); +}); + +describe('expression grammar documented in the prompt matches expr.ts', () => { + it('every documented function evaluates as described', () => { + for (const { name, sample, expect: want } of EXPR_FUNCTIONS) { + expect(evalExpr(sample, {}), `${name}: ${sample}`).toBeCloseTo(want, 9); + } + }); + + it('constants and operators behave as documented', () => { + expect(evalExpr('pi', {})).toBeCloseTo(Math.PI); + expect(evalExpr('e', {})).toBeCloseTo(Math.E); + expect(evalExpr('true', {})).toBe(true); + expect(evalExpr('2 ^ 3 ^ 2', {})).toBe(512); // right-associative + expect(evalExpr('7 // 2', {})).toBe(3); + expect(evalExpr('7 mod 4', {})).toBe(3); + expect(evalExpr('1 < 2 ? 10 : 20', {})).toBe(10); + expect(evalExpr('unknownName + 1', {})).toBe(1); // unknown names are 0 + expect(evalExpr('nosuchfn(3)', {})).toBe(0); + }); +}); diff --git a/v2/src/lib/ai-prompt.ts b/v2/src/lib/ai-prompt.ts new file mode 100644 index 0000000..369cb0b --- /dev/null +++ b/v2/src/lib/ai-prompt.ts @@ -0,0 +1,244 @@ +/** + * "From AI" prompt kit (D2c): a complete, self-contained prompt that lets any LLM write a + * valid NoteBuilder notebook. The document shape and slot props are read from the published + * schema (via slot-catalog / schema.ts), so the prompt cannot drift from the format; the + * expression grammar mirrors lib/expr.ts and is pinned by ai-prompt.test.ts. + * + * Not imported by json-io.ts — keeps the schema and this kit out of the Reader bundle. + */ +import type { NotebookJSON } from './json-io'; +import { allSlots } from './slots/registry'; +import { SLOT_CATALOG, catalogBlock } from './slot-catalog'; +import { NOTEBOOK_SCHEMA, propertyLines, schemaDef, slotPropsSchema } from './schema/schema'; + +export type AiPromptOptions = { + /** What the notebook should teach. */ + topic: string; + /** Who it is for, e.g. "first-year economics students". */ + audience?: string; + /** Rough number of cards to aim for (1–60; anything else is ignored, larger is capped). */ + cards?: number; + /** Append the full JSON Schema for models that use it (longer prompt). */ + includeSchema?: boolean; +}; + +/** Functions evalExpr understands, with a sample the tests evaluate against expr.ts. */ +export const EXPR_FUNCTIONS: ReadonlyArray<{ name: string; doc: string; sample: string; expect: number }> = [ + { name: 'sin', doc: 'sin(a)', sample: 'sin(1)', expect: Math.sin(1) }, + { name: 'cos', doc: 'cos(a)', sample: 'cos(1)', expect: Math.cos(1) }, + { name: 'tan', doc: 'tan(a)', sample: 'tan(1)', expect: Math.tan(1) }, + { name: 'exp', doc: 'exp(a)', sample: 'exp(2)', expect: Math.exp(2) }, + { name: 'log', doc: 'log(a) (natural log)', sample: 'log(10)', expect: Math.log(10) }, + { name: 'sqrt', doc: 'sqrt(a)', sample: 'sqrt(2)', expect: Math.SQRT2 }, + { name: 'abs', doc: 'abs(a)', sample: 'abs(-3)', expect: 3 }, + { name: 'sign', doc: 'sign(a)', sample: 'sign(-2)', expect: -1 }, + { name: 'round', doc: 'round(a) (to a whole number)', sample: 'round(2.6)', expect: 3 }, + { name: 'floor', doc: 'floor(a)', sample: 'floor(2.7)', expect: 2 }, + { name: 'ceil', doc: 'ceil(a)', sample: 'ceil(2.1)', expect: 3 }, + { name: 'min', doc: 'min(a, b, ...)', sample: 'min(3, 1, 2)', expect: 1 }, + { name: 'max', doc: 'max(a, b, ...)', sample: 'max(3, 1, 2)', expect: 3 }, + { name: 'pow', doc: 'pow(a, b)', sample: 'pow(2, 10)', expect: 1024 }, + { name: 'clamp', doc: 'clamp(v, lo, hi)', sample: 'clamp(15, 0, 10)', expect: 10 }, +]; +export const EXPR_CONSTANTS: readonly string[] = ['pi', 'e', 'true', 'false']; + +export const EXAMPLE_START = '--- BEGIN EXAMPLE ---\n'; +export const EXAMPLE_END = '\n--- END EXAMPLE ---'; + +/** + * The compact example embedded in every prompt. It must stay valid (ai-prompt.test.ts runs it + * through validateNotebook and the schema) and shows each pattern the guidance asks for. + */ +export const AI_EXAMPLE: NotebookJSON = { + version: 2, + notebook: { + name: 'Compound Growth', + subtitle: 'Why money (and bacteria) grow faster and faster', + cats: ['idea', 'explore', 'check'], + sections: [ + { + name: 'Growth on growth', + title: 'Growth on growth', + subtitle: 'See it, play with it, then test yourself.', + cards: [ + { + tags: ['idea'], + slots: [ + { + type: 'text', + props: { + text: '## Compound growth\nEach year the amount grows by the rate $r$ **of the current amount**:\n$$A(t) = P\\left(1 + \\frac{r}{100}\\right)^t$$', + }, + }, + ], + }, + { + tags: ['explore'], + slots: [ + { type: 'slider', props: { key: 'r', value: 7, min: 0, max: 15, step: 0.5 }, w: 6 }, + { type: 'slider', props: { key: 't', value: 10, min: 0, max: 40, step: 1 }, w: 6 }, + { type: 'compute', props: { expr: 'round(100 * (1 + r/100) ^ t)', out: 'A', note: '100 grows to' } }, + { type: 'chart', props: { fn: '100 * (1 + r/100) ^ x', x0: 0, x1: 40, label: 'value of 100 over the years' } }, + { type: 'text', props: { text: 'At **{{r}}%** for **{{t}}** years, 100 becomes **{{A}}**.' } }, + { type: 'text-input', props: { placeholder: 'Predict: if r doubles, does the doubling time halve?' } }, + ], + }, + { + tags: ['check'], + w: 6, + slots: [ + { + type: 'choice', + props: { + q: 'At 6% a year, about how long until money doubles?', + options: ['6 years', '12 years', '24 years'], + answer: [1], + explanation: + 'Rule of 72: $72 / 6 = 12$ (exactly $\\ln 2 / \\ln 1.06 \\approx 11.9$). 6 years mixes up the rate with the time; 24 years is the doubling time at 3%.', + }, + }, + ], + }, + { + tags: ['check'], + w: 6, + verbs: { flip: true }, + slots: [{ type: 'text', props: { text: '**Q.** In $A(t) = P(1 + r)^t$, what does $t$ count?' } }], + back: [{ type: 'text', props: { text: '**A.** The number of compounding periods (here, years).' } }], + }, + { + slots: [{ type: 'progress', props: { scope: 'section', label: 'Your progress' } }], + }, + ], + }, + ], + }, +}; + +/** Slot types to advertise: registered AND documented (a catalog entry and a schema def). */ +function catalogTypes(): string[] { + return allSlots() + .map((s) => s.type) + .filter((t) => SLOT_CATALOG[t] && slotPropsSchema(t)); +} + +/** + * Layout/housekeeping fields the app's own editor sets (pixel widths, lock, archive, fused + * rows). Valid in a file, but left out of the prompt so the model has less to get wrong. + */ +const AUTHOR_ONLY = { + section: ['locked', 'width', 'svcOrder', 'svcW'], + card: ['archived'], + slot: ['fuse', 'fuseW'], +} as const; + +/** + * JSON with short objects/arrays kept on one line — a compact example the model can still read. + * Equivalent to JSON.stringify(value) once whitespace is ignored. + */ +export function compactJson(value: unknown, indent = '', width = 96): string { + const flat = JSON.stringify(value); + if (flat === undefined || value === null || typeof value !== 'object' || indent.length + flat.length <= width) { + return flat ?? 'null'; + } + const inner = indent + ' '; + if (Array.isArray(value)) { + return `[\n${value.map((v) => inner + compactJson(v, inner, width)).join(',\n')}\n${indent}]`; + } + const entries = Object.entries(value as Record).filter(([, v]) => v !== undefined); + return `{\n${entries.map(([k, v]) => `${inner}${JSON.stringify(k)}: ${compactJson(v, inner, width)}`).join(',\n')}\n${indent}}`; +} + +function shapeBlock(title: string, defName: string, skip: readonly string[] = []): string { + const def = schemaDef(defName); + if (!def) return ''; + const lines = propertyLines(def, skip).map((l) => ` - ${l}`); + return [title, ...lines].join('\n'); +} + +function lengthLine(cards: number | undefined): string { + if (typeof cards === 'number' && Number.isFinite(cards) && cards >= 1) { + const n = Math.min(60, Math.round(cards)); + return `Length: about ${n} cards, grouped into sections (lessons) of 3–8 cards.`; + } + return 'Length: 8–20 cards, grouped into sections (lessons) of 3–8 cards.'; +} + +/** Build the complete prompt an author pastes into any LLM. Deterministic for a given input. */ +export function buildAiPrompt(opts: AiPromptOptions): string { + const topic = opts.topic.trim() || 'a topic of your choice'; + const audience = opts.audience?.trim(); + const types = catalogTypes(); + const fnDocs = EXPR_FUNCTIONS.map((f) => f.doc).join(', '); + + const parts: string[] = [ + 'You are an expert teacher and instructional designer. Write an interactive study notebook for the NoteBuilder app.', + '', + `Topic: ${topic}`, + ...(audience ? [`Audience: ${audience}`] : []), + lengthLine(opts.cards), + '', + '## Output contract', + '- Reply with ONLY one JSON object: no text before or after it, no code fences, no comments.', + '- Strict JSON: double-quoted keys and strings, no trailing commas, line breaks inside strings written as \\n.', + '- In JSON strings double every backslash: LaTeX is written "$\\\\frac{a}{b}$" and "$\\\\alpha$" (a single backslash corrupts the math).', + '- The top level is {"version": 2, "notebook": {...}}; "version": 2 is the number 2.', + '- Use only the fields and slot types described below. Never invent fields or slot types.', + '', + '## Document shape', + 'Top level: {"version": 2, "notebook": Notebook}', + shapeBlock('Notebook', 'notebook'), + shapeBlock('Section', 'section', AUTHOR_ONLY.section), + shapeBlock('Card', 'card', AUTHOR_ONLY.card), + shapeBlock('CardVerbs (card.verbs)', 'cardVerbs'), + shapeBlock('Slot (one block inside a card)', 'slot', AUTHOR_ONLY.slot), + shapeBlock('SlotVerbs (slot.verbs)', 'slotVerbs'), + '', + '## Slot catalog', + `Slot types: ${types.join(', ')}. Each slot is {"type": ..., "props": {...}}; "props" is always an object ({} if empty).`, + '', + ...types.map((t) => catalogBlock(t) + '\n'), + '## Variables, formulas and the card-scope rule', + '- A card is a small model. A slider writes the variable named by its key; a compute writes the variable named by its out.', + "- Slots of the SAME card read those variables: compute expr, chart fn, a problem's answer, {{name}} in markdown (text, a choice's q and explanation, a problem's prompt and explain), and verbs.reveal.key.", + '- Variables never cross cards: a slot can only read variables written by a slider or compute in its own card (the front and back of a flip card share one scope). If two cards need the same quantity, give each card its own slider.', + '- No cycles: a compute must not depend, directly or through other computes, on its own out.', + `- Names (slider keys, compute outs and problem param names): letters, digits and _, starting with a letter; case-sensitive. Do not use x (the chart axis) or a built-in function/constant name (${[...EXPR_FUNCTIONS.map((f) => f.name), ...EXPR_CONSTANTS, 'mod'].join(', ')}).`, + '- {{name}} prints a variable\'s current value. Only a plain name goes inside {{ }}, never math: compute the value first, then print it. Values print unrounded, so round in the compute: round(v * 100) / 100 keeps 2 decimals.', + "- Expression grammar (compute expr, chart fn and a problem's answer):", + ' - numbers: 3, 0.25, 1000000 (no exponent notation such as 1e6)', + ' - arithmetic: + - * /, ^ (power, right-associative; never **), % or mod (remainder), // (floor division), unary -', + ' - a leading minus binds tighter than ^: -x^2 means (-x)^2, so write -(x^2) (a bell curve is exp(-(x^2)/2))', + ' - comparison and logic: == != < <= > >= && || !, and condition ? a : b', + ` - functions: ${fnDocs}; trigonometry uses radians`, + ` - constants: ${EXPR_CONSTANTS.join(', ')}`, + ' - parentheses group; anything unknown (a misspelled variable or function) silently evaluates to 0', + '', + '## Teaching guidance', + '- One idea per card. Keep text short: a heading plus a few sentences or bullets. Use LaTeX for math.', + "- Only text slots, a choice's q and explanation, and a problem's prompt and explain render markdown, $math$ and {{name}}. Everything else (options, list items, table cells, labels, notes) is plain text: write math there with Unicode (x², √2, π, ≤).", + '- Retrieval practice: after each new idea add 1–3 choice questions with a correct answer key (0-based indexes into options) and an explanation that says why the answer is right and why the tempting wrong option is wrong. Make distractors real misconceptions.', + '- Flashcards: for definitions, formulas and key facts use a card with "verbs": {"flip": true}, the prompt in slots and the answer in back.', + "- Practice problems: for skills worth drilling with fresh numbers, use a problem slot. Its params are local to the slot: each attempt draws new values, {{name}} shows them in prompt and explain, and answer computes the expected number from them, so do NOT add sliders for them (answer may also read the card's own slider/compute variables). Param names follow the name rule above: never a built-in (e, pi, min, max, sin, …). round() takes ONE argument: round(x * 100) / 100 keeps 2 decimals, round(x, 2) is an error. For a decimal answer set tol (e.g. 0.01 for 2 decimals) and say in the prompt how to round. Use need 2–3 for drills. Always give explain: a worked solution that quotes the drawn values with {{name}}.", + '- Guided exploration: wherever a result depends on parameters, build ONE card with sliders, computes and a chart, text that quotes the live values with {{name}}, and a question (choice or text-input) asking what the learner notices or predicts.', + '- Structure: sections are lessons that build on each other; in long notebooks start each part with a {"kind": "divider", "name": ..., "cards": []} section. End each lesson with a short quiz and a progress slot.', + '- Tags: tag cards by role or concept (for example "idea", "explore", "check") and list every tag in notebook.cats.', + '- Layout: small cards (a single question or flashcard) can take "w": 6 so two sit side by side; keep explanations and models full width.', + '', + '## Checklist before you answer', + '- One JSON object with "version": 2 and nothing outside it.', + `- Every slot has "type" (one of: ${types.join(', ')}) and a "props" object.`, + '- Every choice has at least 2 options, and every answer index is less than the number of options.', + '- Every variable a card reads is written by a slider or compute in that same card, and no formula depends on itself.', + '- Every problem has an explain, its answer uses only its own params and the card\'s variables, and no param also has a slider.', + '- Every LaTeX backslash is doubled.', + '', + '## Example of a complete, valid notebook (the shape to follow; write your own content)', + EXAMPLE_START + compactJson(AI_EXAMPLE) + EXAMPLE_END, + ]; + + if (opts.includeSchema) { + parts.push('', '## Full JSON Schema (reference)', JSON.stringify(NOTEBOOK_SCHEMA, null, 2)); + } + return parts.filter((p, i, all) => !(p === '' && all[i - 1] === '')).join('\n'); +} diff --git a/v2/src/lib/annotations.test.ts b/v2/src/lib/annotations.test.ts index 6c9dd93..c211431 100644 --- a/v2/src/lib/annotations.test.ts +++ b/v2/src/lib/annotations.test.ts @@ -1,3 +1,4 @@ +// @vitest-environment node import { describe, it, expect } from 'vitest'; import { addAnnotation, @@ -134,4 +135,4 @@ describe('immutability', () => { editAnnotation(map, 'ann-1', 'Changed body'); expect(map).toEqual(original); }); -}); +}); \ No newline at end of file diff --git a/v2/src/lib/autosave.test.ts b/v2/src/lib/autosave.test.ts new file mode 100644 index 0000000..889cacb --- /dev/null +++ b/v2/src/lib/autosave.test.ts @@ -0,0 +1,214 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { createAutosave, HYDRATION_FAILED_MESSAGE, withTimeout } from './autosave'; + +describe('autosave — hydration guard', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('persists nothing before hydration succeeded', async () => { + const a = createAutosave({ wait: 100 }); + const save = vi.fn(); + const ch = a.channel('notebook', save); + ch.schedule('demo'); + vi.advanceTimersByTime(1000); + await ch.saveNow('demo-now'); + await ch.flush(); + await a.flushAll(); + expect(save).not.toHaveBeenCalled(); + expect(a.active).toBe(false); + }); + + it('a value scheduled before hydration is not replayed once hydrated', async () => { + const a = createAutosave({ wait: 100 }); + const save = vi.fn(); + const ch = a.channel('reader', save); + ch.schedule({ empty: true }); + a.markHydrated(); + vi.advanceTimersByTime(1000); + expect(save).not.toHaveBeenCalled(); + ch.schedule({ loaded: true }); + vi.advanceTimersByTime(100); + expect(save).toHaveBeenCalledTimes(1); + expect(save).toHaveBeenCalledWith({ loaded: true }); + }); + + it('hydrate() turns persistence on only when the load resolves', async () => { + const a = createAutosave({ wait: 100 }); + const save = vi.fn(); + const ch = a.channel('factory', save); + const ok = await a.hydrate(async () => { + ch.schedule('during-hydration'); + }); + expect(ok).toBe(true); + expect(a.active).toBe(true); + vi.advanceTimersByTime(200); + expect(save).not.toHaveBeenCalled(); + ch.schedule('after'); + vi.advanceTimersByTime(100); + expect(save).toHaveBeenCalledWith('after'); + }); + + it('a throwing hydration keeps persistence OFF and reports that changes will not be saved', async () => { + const onError = vi.fn(); + const a = createAutosave({ wait: 100, onError }); + const save = vi.fn(); + const ch = a.channel('notebook', save); + const ok = await a.hydrate(async () => { + throw new Error('disk on fire'); + }); + expect(ok).toBe(false); + expect(a.active).toBe(false); + expect(a.failed).toBe(true); + expect(onError).toHaveBeenCalledWith(HYDRATION_FAILED_MESSAGE, expect.any(Error)); + expect(HYDRATION_FAILED_MESSAGE).toMatch(/won.t be saved/); + ch.schedule('edit'); + vi.advanceTimersByTime(1000); + await ch.saveNow('edit'); + expect(save).not.toHaveBeenCalled(); + // A failed hydration is sticky: a stray markHydrated() cannot switch persistence back on. + a.markHydrated(); + expect(a.active).toBe(false); + }); +}); + +describe('autosave — channels', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + function hydrated(onError = vi.fn()) { + const a = createAutosave({ wait: 100, onError }); + a.markHydrated(); + return a; + } + + it('schedule debounces per channel with the latest value', () => { + const a = hydrated(); + const nb = vi.fn(); + const rs = vi.fn(); + const chNb = a.channel('notebook', nb); + const chRs = a.channel('reader', rs); + chNb.schedule(1); + chNb.schedule(2); + chRs.schedule('r'); + vi.advanceTimersByTime(100); + expect(nb).toHaveBeenCalledTimes(1); + expect(nb).toHaveBeenCalledWith(2); + expect(rs).toHaveBeenCalledWith('r'); + }); + + it('flush runs the pending save now and resolves after it completes', async () => { + const a = hydrated(); + let done = false; + const ch = a.channel('notebook', async () => { + await Promise.resolve(); + done = true; + }); + ch.schedule('x'); + await ch.flush(); + expect(done).toBe(true); + }); + + it('cancel drops the pending save', () => { + const a = hydrated(); + const save = vi.fn(); + const ch = a.channel('notebook', save); + ch.schedule('x'); + ch.cancel(); + vi.advanceTimersByTime(1000); + expect(save).not.toHaveBeenCalled(); + }); + + it('saveNow supersedes a pending scheduled value (no stale write afterwards)', async () => { + const a = hydrated(); + const save = vi.fn(); + const ch = a.channel('notebook', save); + ch.schedule('old'); + await ch.saveNow('current'); + vi.advanceTimersByTime(1000); + expect(save).toHaveBeenCalledTimes(1); + expect(save).toHaveBeenCalledWith('current'); + }); + + it('flushAll flushes every channel and waits for in-flight saves', async () => { + const a = hydrated(); + const order: string[] = []; + let release!: () => void; + const gate = new Promise((r) => (release = r)); + const slow = a.channel('slow', async (v: string) => { + await gate; + order.push(v); + }); + const fast = a.channel('fast', (v: string) => { + order.push(v); + }); + slow.schedule('slow'); + vi.advanceTimersByTime(100); // slow save starts and blocks on the gate + fast.schedule('fast'); + const all = a.flushAll(); + let settled = false; + void all.then(() => (settled = true)); + await Promise.resolve(); + await Promise.resolve(); + expect(settled).toBe(false); + release(); + await all; + expect(order.sort()).toEqual(['fast', 'slow']); + }); + + it('skips a save identical to what storage already holds (prime / last saved)', async () => { + const a = hydrated(); + const save = vi.fn(); + const ch = a.channel('notebook', save); + ch.prime({ id: 'nb', v: 1 }); + await ch.saveNow({ id: 'nb', v: 1 }); + expect(save).not.toHaveBeenCalled(); + await ch.saveNow({ id: 'nb', v: 2 }); + await ch.saveNow({ id: 'nb', v: 2 }); + expect(save).toHaveBeenCalledTimes(1); + }); + + it('a failed save (false or rejection) is retried by the next identical save', async () => { + const onError = vi.fn(); + const a = hydrated(onError); + const save = vi + .fn<(v: string) => Promise>() + .mockResolvedValueOnce(false) + .mockRejectedValueOnce(new Error('boom')) + .mockResolvedValue(true); + const ch = a.channel('notebook', save); + await ch.saveNow('x'); + await ch.saveNow('x'); + expect(onError).toHaveBeenCalledTimes(1); // the rejection is surfaced, never swallowed + await ch.saveNow('x'); + await ch.saveNow('x'); + expect(save).toHaveBeenCalledTimes(3); + }); + + it('uses a custom fingerprint when given', async () => { + const a = hydrated(); + const save = vi.fn(); + const ch = a.channel('nb', save, { fingerprint: (v: { id: string; at: number }) => v.id }); + await ch.saveNow({ id: 'a', at: 1 }); + await ch.saveNow({ id: 'a', at: 2 }); + expect(save).toHaveBeenCalledTimes(1); + }); +}); + +describe('withTimeout', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('resolves with the value when the promise settles in time', async () => { + await expect(withTimeout(Promise.resolve(5), 100)).resolves.toBe(5); + }); + + it('resolves undefined after the timeout when the promise hangs', async () => { + const p = withTimeout(new Promise(() => {}), 100); + vi.advanceTimersByTime(100); + await expect(p).resolves.toBeUndefined(); + }); + + it('never rejects, even when the promise does', async () => { + await expect(withTimeout(Promise.reject(new Error('x')), 100)).resolves.toBeUndefined(); + }); +}); diff --git a/v2/src/lib/autosave.ts b/v2/src/lib/autosave.ts new file mode 100644 index 0000000..def241c --- /dev/null +++ b/v2/src/lib/autosave.ts @@ -0,0 +1,169 @@ +import { debounce } from './debounce'; + +/** + * Autosave orchestration (D0 durability): one debounced channel per persisted value (notebook, + * reader state, factory state), all gated behind a hydration guard. NOTHING persists until the + * startup load succeeded — otherwise the pre-hydration demo notebook / empty reader state could + * overwrite what is stored. A failed hydration keeps persistence off for the whole session and + * says so, instead of silently clobbering the user's data with whatever is in memory. + */ + +export const HYDRATION_FAILED_MESSAGE = + 'Couldn’t load your saved notebooks — changes in this session won’t be saved.'; + +/** A save returns `false` (or rejects) on failure; anything else counts as success. */ +export type SaveFn = (value: T) => unknown; + +export type AutosaveChannel = { + /** Debounced: persist `value` after the quiet period. Dropped while persistence is off. */ + schedule(value: T): void; + /** Persist `value` now, superseding any pending scheduled value. Resolves when the save settled. */ + saveNow(value: T): Promise; + /** Run the pending scheduled save now (if any) and wait for every in-flight save. */ + flush(): Promise; + /** Drop the pending scheduled save. */ + cancel(): void; + /** Storage already holds `value` (just hydrated/loaded) — an identical save is skipped. */ + prime(value: T): void; +}; + +export type Autosave = { + channel(name: string, save: SaveFn, opts?: { fingerprint?: (value: T) => string }): AutosaveChannel; + /** Run the startup load; persistence turns on only if it resolves. Never rejects. */ + hydrate(load: () => Promise): Promise; + /** Turn persistence on (hydration succeeded). Ignored after a failed hydration. */ + markHydrated(): void; + /** True once hydration succeeded — the gate every persistent write checks. */ + readonly active: boolean; + /** True when hydration threw: persistence stays off for this session. */ + readonly failed: boolean; + /** Flush every channel and wait for all in-flight saves. Never rejects. */ + flushAll(): Promise; +}; + +export type AutosaveOptions = { + /** Debounce quiet period in ms (default 600). */ + wait?: number; + /** User-facing error sink (App wires a toast). Defaults to console.error. */ + onError?: (message: string, err?: unknown) => void; +}; + +export function createAutosave(opts: AutosaveOptions = {}): Autosave { + const wait = opts.wait ?? 600; + const onError = opts.onError ?? ((m: string, e?: unknown) => console.error(m, e)); + let active = false; + let failed = false; + const flushers: Array<() => Promise> = []; + + function channel( + name: string, + save: SaveFn, + copts: { fingerprint?: (value: T) => string } = {}, + ): AutosaveChannel { + const fingerprint = copts.fingerprint ?? ((v: T) => JSON.stringify(v)); + // Fingerprint of what storage holds (or is about to hold): an identical save is a no-op. + let stored: string | undefined; + const inflight = new Set>(); + + function persist(value: T): Promise { + if (!active) return Promise.resolve(); + const fp = fingerprint(value); + if (fp === stored) return Promise.resolve(); + stored = fp; + const failedSave = (err?: unknown) => { + // Forget the fingerprint so the next identical save retries instead of being skipped. + if (stored === fp) stored = undefined; + if (err !== undefined) onError(`Couldn’t save ${name} — ${errorText(err)}`, err); + }; + const p = (async () => { + try { + if ((await save(value)) === false) failedSave(); + } catch (err) { + failedSave(err); + } + })(); + inflight.add(p); + void p.finally(() => inflight.delete(p)); + return p; + } + + const debounced = debounce((value: T) => persist(value), wait); + + async function flush(): Promise { + await debounced.flush(); + await Promise.all([...inflight]); + } + + flushers.push(flush); + + return { + schedule(value) { + if (active) debounced(value); + }, + saveNow(value) { + debounced.cancel(); + return persist(value); + }, + flush, + cancel: () => debounced.cancel(), + prime(value) { + stored = fingerprint(value); + }, + }; + } + + function markHydrated(): void { + if (!failed) active = true; + } + + async function hydrate(load: () => Promise): Promise { + try { + await load(); + } catch (err) { + failed = true; + active = false; + onError(HYDRATION_FAILED_MESSAGE, err); + return false; + } + markHydrated(); + return active; + } + + async function flushAll(): Promise { + await Promise.all(flushers.map((f) => f().catch(() => {}))); + } + + return { + channel, + hydrate, + markHydrated, + get active() { + return active; + }, + get failed() { + return failed; + }, + flushAll, + }; +} + +/** Resolve with `p`'s value, or `undefined` after `ms` — never rejects. For close/quit paths. */ +export function withTimeout(p: Promise, ms: number): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => resolve(undefined), ms); + p.then( + (v) => { + clearTimeout(timer); + resolve(v); + }, + () => { + clearTimeout(timer); + resolve(undefined); + }, + ); + }); +} + +function errorText(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} diff --git a/v2/src/lib/bench.svelte.ts b/v2/src/lib/bench.svelte.ts index 50d1964..b39dc81 100644 --- a/v2/src/lib/bench.svelte.ts +++ b/v2/src/lib/bench.svelte.ts @@ -209,11 +209,14 @@ export function addBenchSlot(b: Bench, type: string, face?: 'back', at?: number) if ((face === 'back') === (factory.face === 'back')) factory.sel = idx; } +/** The per-slot effects the Factory palette toggles (`sequential` is shown as "Step-by-step"). */ +export type SlotEffect = 'reveal' | 'glow' | 'emphasis' | 'sequential'; + /** * Toggle a per-slot effect on the selected slot of the current face (v1 sverb 70-events:137). * Turning `reveal` on seeds `{key:'pick',op:'==',val:0}` unless one already exists. */ -export function setSlotVerb(idx: number, key: 'reveal' | 'glow' | 'emphasis', on: boolean): void { +export function setSlotVerb(idx: number, key: SlotEffect, on: boolean): void { const b = activeBench(); const arr = factory.face === 'back' ? (b.back ?? []) : b.slots; const slot = arr[idx]; diff --git a/v2/src/lib/bench.test.ts b/v2/src/lib/bench.test.ts index 38d30e4..6b78f5b 100644 --- a/v2/src/lib/bench.test.ts +++ b/v2/src/lib/bench.test.ts @@ -141,6 +141,8 @@ describe('benchToType', () => { expect(ct.slots[0]).not.toHaveProperty('id'); expect(ct.back![0]).not.toHaveProperty('id'); expect(ct.slots[0].props).toEqual(bench.slots[0].props); + ct.slots[0].props.text = 'mutated'; + expect(bench.slots[0].props.text).toBe('front'); expect(ct.accent).toBe(bench.accent); expect(ct.note).toBe(bench.note); expect(ct.icon).toBe(bench.icon); @@ -241,7 +243,7 @@ describe('bench slot mutators', () => { expect(factory.sel).toBe(null); }); - it('deleteBenchSlot decrements sel when a slot below the selection is removed', () => { + it('deleteBenchSlot decrements sel when a slot above the selection is removed', () => { const b = freshBench(); addBench(b); addBenchSlot(b, 'text'); @@ -251,7 +253,7 @@ describe('bench slot mutators', () => { expect(factory.sel).toBe(0); }); - it('deleteBenchSlot leaves sel unchanged when a slot above the selection is removed', () => { + it('deleteBenchSlot leaves sel unchanged when a slot below the selection is removed', () => { const b = freshBench(); addBench(b); addBenchSlot(b, 'text'); diff --git a/v2/src/lib/card-done.test.ts b/v2/src/lib/card-done.test.ts index 1432f10..44345c2 100644 --- a/v2/src/lib/card-done.test.ts +++ b/v2/src/lib/card-done.test.ts @@ -1,3 +1,4 @@ +// @vitest-environment node import { describe, it, expect } from 'vitest'; import { isCardDone, hasCompletableSlot, CARD_STATE_KEY } from './card-done'; import type { Slot } from './types'; @@ -118,4 +119,4 @@ describe('hasCompletableSlot', () => { // back is not part of the structural front-slot scan for non-flip cards expect(hasCompletableSlot({ slots: [textSlot('front')] })).toBe(false); }); -}); +}); \ No newline at end of file diff --git a/v2/src/lib/card-reveal.test.ts b/v2/src/lib/card-reveal.test.ts new file mode 100644 index 0000000..1d4f6e6 --- /dev/null +++ b/v2/src/lib/card-reveal.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { revealCard } from './card-reveal'; + +function card(id: string): HTMLElement { + const el = document.createElement('div'); + el.className = 'furn'; + el.dataset.card = id; + document.body.appendChild(el); + return el; +} + +beforeEach(() => { + vi.useFakeTimers(); + Element.prototype.scrollIntoView = vi.fn(); +}); + +afterEach(() => { + vi.useRealTimers(); + document.body.innerHTML = ''; +}); + +describe('revealCard', () => { + it('scrolls the card to the middle of the stage and flashes the ring', async () => { + const el = card('c1'); + await revealCard('c1', 500); + + expect(el.scrollIntoView).toHaveBeenCalledWith({ block: 'center' }); + expect(el.classList.contains('kflash')).toBe(true); + + vi.advanceTimersByTime(500); + expect(el.classList.contains('kflash')).toBe(false); + }); + + it('leaves every other card alone', async () => { + const other = card('c1'); + const target = card('c2'); + await revealCard('c2', 500); + + expect(other.classList.contains('kflash')).toBe(false); + expect(target.classList.contains('kflash')).toBe(true); + }); + + it('is a no-op for a card that is not on the page', async () => { + await expect(revealCard('ghost', 500)).resolves.toBeUndefined(); + }); +}); diff --git a/v2/src/lib/card-reveal.ts b/v2/src/lib/card-reveal.ts new file mode 100644 index 0000000..dd0cf63 --- /dev/null +++ b/v2/src/lib/card-reveal.ts @@ -0,0 +1,18 @@ +import { tick } from 'svelte'; + +/** How long `.kflash` stays on — the CSS animation runs 2 × --t-slow (700ms). */ +const FLASH_MS = 800; + +/** + * Scroll a card into view and flash the study ring on it. A Place from the store appends to the + * end of a section, which is routinely below the fold: without this the only feedback for the + * click is a card the reader never sees arrive. + */ +export async function revealCard(cardId: string, flashMs = FLASH_MS): Promise { + await tick(); + const el = document.querySelector(`.furn[data-card="${cardId}"]`); + if (!el) return; + el.scrollIntoView({ block: 'center' }); + el.classList.add('kflash'); + setTimeout(() => el.classList.remove('kflash'), flashMs); +} diff --git a/v2/src/lib/card-scope.test.ts b/v2/src/lib/card-scope.test.ts index 7335b9a..0a3ca09 100644 --- a/v2/src/lib/card-scope.test.ts +++ b/v2/src/lib/card-scope.test.ts @@ -1,3 +1,4 @@ +// @vitest-environment node import { describe, it, expect } from 'vitest'; import { buildCardScope } from './card-scope'; import type { Slot } from './types'; @@ -40,4 +41,4 @@ describe('buildCardScope', () => { const slots: Slot[] = [compute('c1', 'b', 'a'), compute('c2', 'a', 'b')]; expect(() => buildCardScope(slots, {})).toThrow(/Cycle detected/); }); -}); +}); \ No newline at end of file diff --git a/v2/src/lib/card-types.pedagogy.test.ts b/v2/src/lib/card-types.pedagogy.test.ts new file mode 100644 index 0000000..b3dcb8c --- /dev/null +++ b/v2/src/lib/card-types.pedagogy.test.ts @@ -0,0 +1,339 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render } from '@testing-library/svelte'; +import CardView from './components/CardView.svelte'; +import { mode } from './stores/mode'; +import { builtinCardTypes, stampCard, type CardType, type SlotTemplate, LEGACY_SEEDED_BUILTINS } from './card-types'; +import { getSlot } from './slots/registry'; +import { findGraphIssues, type GraphDecl } from './variable-graph'; +import { exportNotebook, validateNotebook } from './json-io'; +import { problemIssues, drawValues, DEFAULT_SEED, paramsOf, type ProblemProps } from './slots/problem'; +import { interp, renderMarkdown } from './markdown'; +import { isCardDone } from './card-done'; +import { buildCardScope } from './card-scope'; +import type { Card, Notebook } from './types'; + +// The three pedagogical built-ins: predict → explore → explain, a worked example that fades into +// practice, and a randomized practice set. Each must be a working lesson the moment it is placed. +const byId = (id: string): CardType => { + const ct = builtinCardTypes.find((c) => c.id === id); + expect(ct, `builtin ${id}`).toBeDefined(); + return ct!; +}; +const GUIDED = 'ct_guided'; +const WORKED = 'ct_worked'; +const PRACTICE = 'ct_practiceset'; +const NEW_IDS = [GUIDED, WORKED, PRACTICE]; + +const seq = (t: SlotTemplate) => t.verbs?.sequential === true; +const completable = (t: SlotTemplate) => getSlot(t.type)?.completable === true; + +function decls(slots: SlotTemplate[]): GraphDecl[] { + return slots.map((t, i) => { + const { reads, writes } = getSlot(t.type)!.variables(t.props); + return { id: `${i}:${t.type}`, reads: reads.map((r) => r.key), writes: writes.map((w) => w.key) }; + }); +} + +function cardVars(slots: SlotTemplate[]): Set { + return new Set(decls(slots).flatMap((d) => d.writes)); +} + +function notebookOf(types: CardType[]): Notebook { + return { + id: 'nb_p', + name: 'Pedagogy', + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + sections: [ + { id: 'sec_p', notebookId: 'nb_p', name: 'S', position: 0, cards: types.map((t, i) => stampCard(t, 'sec_p', i)) }, + ], + }; +} + +function cardProps(card: Card, state: Record> = {}) { + return { + card, + surface: 'read' as const, + selected: false, + state, + notes: [], + notesOpen: false, + onselect: vi.fn(), + onstate: vi.fn(), + onmove: vi.fn(), + ondelete: vi.fn(), + onverb: vi.fn(), + ontags: vi.fn(), + onsavetype: vi.fn(), + onupdateslot: vi.fn(), + ondeleteslot: vi.fn(), + onaddslot: vi.fn(), + progresscompletion: vi.fn(() => ({ done: 0, total: 0, pct: 0 })), + ontogglenotes: vi.fn(), + onaddnote: vi.fn(), + ondeletenote: vi.fn(), + ongrip: vi.fn(), + onresize: vi.fn(), + onfusew: vi.fn(), + onpin: vi.fn(), + onarchive: vi.fn(), + }; +} + +afterEach(() => { + mode.set('edit'); +}); + +describe('pedagogical built-ins — shared contract', () => { + it('ship in their stores with an icon, an accent and a description, as new (non-legacy) built-ins', () => { + expect(byId(GUIDED)).toMatchObject({ name: 'Guided Explore', store: 'live' }); + expect(byId(WORKED)).toMatchObject({ name: 'Worked Example', store: 'practice' }); + expect(byId(PRACTICE)).toMatchObject({ name: 'Practice Set', store: 'practice' }); + for (const id of NEW_IDS) { + expect(byId(id).icon, id).toBeTruthy(); + expect(byId(id).accent, id).toMatch(/^#[0-9a-f]{6}$/i); + expect(byId(id).description, id).toBeTruthy(); + expect(byId(id).note, id).toBeTruthy(); // "from the maker" guidance in the store + } + // Not legacy, so installs from before seeding was recorded receive them (card-types ledger). + for (const id of NEW_IDS) expect(LEGACY_SEEDED_BUILTINS).not.toContain(id); + }); + + it.each(NEW_IDS)('%s stamps into a card whose props all pass validate()', (id) => { + const card = stampCard(byId(id), 'sec_x', 0); + expect(card.typeId).toBe(id); + for (const s of card.slots) { + expect(getSlot(s.type)?.validate?.(s.props) ?? [], `${id}: ${s.type}`).toEqual([]); + } + const ids = card.slots.map((s) => s.id); + expect(new Set(ids).size).toBe(ids.length); + }); + + it.each(NEW_IDS)('%s has a clean variable graph: every read has a writer, no cycles', (id) => { + expect(findGraphIssues(decls(byId(id).slots))).toEqual([]); + }); + + it.each(NEW_IDS)('%s problem slots pass the strict card-aware check (no unknown variables)', (id) => { + const slots = byId(id).slots; + for (const t of slots.filter((s) => s.type === 'problem')) { + expect(problemIssues(t.props as ProblemProps, cardVars(slots))).toEqual([]); + } + }); + + it.each(NEW_IDS)('%s markdown and math render cleanly (no KaTeX errors, no "?" for a missing value)', (id) => { + const card = stampCard(byId(id), 'sec_x', 0); + const scope = buildCardScope(card.slots, {}); + for (const s of card.slots) { + const local = s.type === 'problem' ? { ...scope, ...drawValues(paramsOf(s.props), DEFAULT_SEED) } : scope; + const fields = ['text', 'q', 'explanation', 'prompt', 'explain'].filter((k) => typeof s.props[k] === 'string'); + for (const k of fields) { + const src = String(s.props[k]); + const html = renderMarkdown(src, local); + expect(html, `${id} ${s.type}.${k}`).not.toMatch(/katex-error|math-err|#cc0000/i); + expect(interp(src, local), `${id} ${s.type}.${k}`).not.toContain('{{'); + // Every {{name}} resolves: interp prints '?' only for a missing value. + for (const m of src.matchAll(/\{\{(\w+)\}\}/g)) expect(local[m[1]], `${id} ${s.type}.${k}: {{${m[1]}}}`).toBeDefined(); + } + } + }); + + it('exported together they import with zero errors and zero warnings', () => { + const { errors, warnings } = validateNotebook(exportNotebook(notebookOf(NEW_IDS.map(byId)))); + expect(errors).toEqual([]); + expect(warnings).toEqual([]); + }); +}); + +describe('Guided Explore — predict, explore, explain', () => { + const slots = () => byId(GUIDED).slots; + + it('opens with an ungraded prediction: a choice with no answer key and nothing completable before it', () => { + const s = slots(); + const p = s.findIndex((t) => t.type === 'choice'); + expect(p).toBeGreaterThan(0); + expect(s.slice(0, p).every((t) => t.type === 'text' && !seq(t))).toBe(true); + const props = s[p].props as { answer?: number[]; options: string[] }; + expect(props.answer ?? []).toEqual([]); + expect(props.options.length).toBeGreaterThanOrEqual(3); + // The prediction is the only completable slot, so it alone gates the simulation. + expect(s.filter(completable)).toEqual([s[p]]); + }); + + it('every slot after the prediction is step-by-step: sliders, computes, a chart, then the explanation', () => { + const s = slots(); + const p = s.findIndex((t) => t.type === 'choice'); + const after = s.slice(p + 1); + expect(after.every(seq)).toBe(true); + const types = after.map((t) => t.type); + expect(types.filter((t) => t === 'slider').length).toBeGreaterThanOrEqual(1); + expect(types).toContain('compute'); + expect(types).toContain('chart'); + expect(types.at(-1)).toBe('text'); + }); + + it('the chart reads the slider keys and the explanation quotes live computed values', () => { + const s = slots(); + const sliderKeys = s.filter((t) => t.type === 'slider').map((t) => String(t.props.key)); + const chart = s.find((t) => t.type === 'chart')!; + const chartReads = getSlot('chart')!.variables(chart.props).reads.map((r) => r.key); + expect(chartReads.some((k) => sliderKeys.includes(k))).toBe(true); + const computed = s.filter((t) => t.type === 'compute').map((t) => String(t.props.out)); + const explain = s.at(-1)!; + const reads = getSlot('text')!.variables(explain.props).reads.map((r) => r.key); + expect(reads.some((k) => computed.includes(k))).toBe(true); + expect(String(explain.props.text)).toMatch(/predict/i); + }); + + it('in Study the simulation stays hidden until the prediction is submitted, then appears', () => { + mode.set('study'); + const card = stampCard(byId(GUIDED), 'sec_g', 0); + const choice = card.slots.find((s) => s.type === 'choice')!; + + const before = render(CardView, { props: cardProps(card) }); + expect(before.container.querySelector('.choice-study')).not.toBeNull(); + expect(before.container.querySelector('.slider-study')).toBeNull(); + expect(before.container.querySelector('.chart-study')).toBeNull(); + expect(before.container.querySelector('.compute-study')).toBeNull(); + before.unmount(); + + // Picked but not yet submitted: still hidden. + const picked = render(CardView, { props: cardProps(card, { [choice.id]: { selected: [1] } }) }); + expect(picked.container.querySelector('.slider-study')).toBeNull(); + picked.unmount(); + + const after = render(CardView, { + props: cardProps(card, { [choice.id]: { selected: [1], submitted: true } }), + }); + expect(after.container.querySelectorAll('.slider-study').length).toBe( + card.slots.filter((s) => s.type === 'slider').length, + ); + expect(after.container.querySelector('.chart-study')).not.toBeNull(); + expect(after.container.querySelector('.compute-study')).not.toBeNull(); + // The explanation quotes the live values (a missing variable would render as '?'). + const texts = [...after.container.querySelectorAll('.text-study')].map((e) => e.textContent ?? ''); + const explain = texts.at(-1)!; + expect(explain).toMatch(/predict/i); + const scope = buildCardScope(card.slots, {}); + const quoted = getSlot('text')!.variables(card.slots.at(-1)!.props).reads.map((r) => r.key); + expect(quoted.length).toBeGreaterThan(0); + for (const k of quoted) expect(explain, k).toContain(String(scope[k])); + }); + + it('the simulation shows that doubling the rate more than doubles the interest (t > 1)', () => { + const card = stampCard(byId(GUIDED), 'sec_g', 0); + expect(card.slots.some((s) => s.type === 'slider' && s.props.key === 't')).toBe(true); + // At the defaults, and over a longer horizon, the ratio is above 2; with one year it is exactly 2. + expect(buildCardScope(card.slots, {}).times).toBeGreaterThan(2); + expect(buildCardScope(card.slots, { t: 30 }).times).toBeGreaterThan(buildCardScope(card.slots, {}).times as number); + expect(buildCardScope(card.slots, { t: 1 }).times).toBe(2); + }); +}); + +describe('Worked Example — self-explanation, fading into practice', () => { + const slots = () => byId(WORKED).slots; + + it('states the problem, shows step 1, then asks the student to self-explain it', () => { + const s = slots(); + expect(s[0].type).toBe('text'); + expect(s[1].type).toBe('text'); + expect(String(s[1].props.text)).toMatch(/step 1/i); + expect(s[2].type).toBe('text-input'); + expect(String(s[2].props.placeholder)).toMatch(/why is this step valid/i); + expect(s.slice(0, 3).some(seq)).toBe(false); + }); + + it('later steps and the final problem are step-by-step, so each unlocks after the self-explanation before it', () => { + const s = slots(); + expect(s.slice(3).every(seq)).toBe(true); + expect(s.slice(3).some((t) => t.type === 'text' && /step 2/i.test(String(t.props.text)))).toBe(true); + }); + + it('ends with a "Now you try" problem: randomized params, an answer formula and a worked explanation', () => { + const last = slots().at(-1)!; + expect(last.type).toBe('problem'); + const p = last.props as ProblemProps; + expect(p.prompt).toMatch(/now you try/i); + expect(p.params.length).toBeGreaterThanOrEqual(2); + expect(p.answer.trim()).not.toBe(''); + expect(p.explain?.trim()).toBeTruthy(); + }); + + it('in Study step 2 appears only once the self-explanation is written; the problem only after every explanation', () => { + mode.set('study'); + const card = stampCard(byId(WORKED), 'sec_w', 0); + const inputs = card.slots.filter((s) => s.type === 'text-input'); + expect(inputs.length).toBeGreaterThanOrEqual(2); + const step2 = (c: HTMLElement) => + [...c.querySelectorAll('.text-study')].some((e) => /step 2/i.test(e.textContent ?? '')); + + const fresh = render(CardView, { props: cardProps(card) }); + expect(step2(fresh.container)).toBe(false); + expect(fresh.container.querySelectorAll('.text-input-study')).toHaveLength(1); + expect(fresh.container.querySelector('.problem-study')).toBeNull(); + fresh.unmount(); + + const blank = render(CardView, { props: cardProps(card, { [inputs[0].id]: { value: ' ' } }) }); + expect(step2(blank.container)).toBe(false); + blank.unmount(); + + const one = render(CardView, { props: cardProps(card, { [inputs[0].id]: { value: 'same to both sides' } }) }); + expect(step2(one.container)).toBe(true); + expect(one.container.querySelector('.problem-study')).toBeNull(); + one.unmount(); + + const all = Object.fromEntries(inputs.map((s) => [s.id, { value: 'because…' }])); + const done = render(CardView, { props: cardProps(card, all) }); + expect(done.container.querySelector('.problem-study')).not.toBeNull(); + done.unmount(); + }); + + it('the card is finished only when the explanations are written and the problem is solved', () => { + const card = stampCard(byId(WORKED), 'sec_w', 0); + const inputs = card.slots.filter((s) => s.type === 'text-input'); + const prob = card.slots.find((s) => s.type === 'problem')!; + const typed = Object.fromEntries(inputs.map((s) => [s.id, { value: 'reason' }])); + expect(isCardDone(card, typed)).toBe(false); + expect(isCardDone(card, { ...typed, [prob.id]: { seed: 1, correct: 1, attempts: 1 } })).toBe(true); + }); +}); + +describe('Practice Set — randomized retrieval practice', () => { + const slots = () => byId(PRACTICE).slots; + + it('a heading, then two different problems that each need 2–3 correct answers and explain themselves', () => { + const s = slots(); + expect(s[0].type).toBe('text'); + const probs = s.filter((t) => t.type === 'problem').map((t) => t.props as ProblemProps); + expect(probs).toHaveLength(2); + for (const p of probs) { + expect(p.need).toBeGreaterThanOrEqual(2); + expect(p.need).toBeLessThanOrEqual(3); + expect(p.explain?.trim()).toBeTruthy(); + } + expect(probs[0].prompt).not.toBe(probs[1].prompt); + expect(probs[0].answer).not.toBe(probs[1].answer); + }); + + it('the two problems never show the same numbers on first draw (or the next few)', () => { + const probs = slots() + .filter((t) => t.type === 'problem') + .map((t) => t.props as ProblemProps); + for (let seed = DEFAULT_SEED; seed < DEFAULT_SEED + 5; seed++) { + const shown = probs.map((p) => interp(p.prompt, drawValues(paramsOf(p), seed))); + expect(shown[0]).not.toBe(shown[1]); + const drawn = probs.map((p) => Object.values(drawValues(paramsOf(p), seed)).join(',')); + expect(drawn[0]).not.toBe(drawn[1]); + } + }); + + it('every drawn instance has a whole-number answer, so a tolerance of 0 is fair', () => { + for (const t of slots().filter((x) => x.type === 'problem')) { + const p = t.props as ProblemProps; + for (let seed = 1; seed <= 50; seed++) { + const v = drawValues(paramsOf(p), seed); + const ans = getSlot('compute')!.evaluate!({ expr: p.answer, out: 'y' }, v).y as number; + expect(Math.abs(ans - Math.round(ans)), `${p.answer} at seed ${seed}`).toBeLessThan(1e-9); + } + } + }); +}); diff --git a/v2/src/lib/card-types.test.ts b/v2/src/lib/card-types.test.ts index a43e6e9..3fbc383 100644 --- a/v2/src/lib/card-types.test.ts +++ b/v2/src/lib/card-types.test.ts @@ -1,5 +1,6 @@ +// @vitest-environment node import { describe, it, expect } from 'vitest'; -import { stampCard, cardToType, builtinCardTypes, typePreviewCard, placeType, prodIcon, STORES, templateSlot, stampSlot } from './card-types'; +import { stampCard, cardToType, builtinCardTypes, typePreviewCard, placeType, prodIcon, STORES, templateSlot, stampSlot, LEGACY_SEEDED_BUILTINS, unseededBuiltins, parseSeededLedger } from './card-types'; import type { CardType } from './card-types'; import { getSlot } from './slots/registry'; import type { Card } from './types'; @@ -245,3 +246,47 @@ describe('slot width survives sealing and stamping (E)', () => { expect('w' in stampSlot(t)).toBe(false); }); }); + +describe('unseededBuiltins', () => { + it('returns only builtins missing from the ledger', () => { + const fresh = unseededBuiltins(LEGACY_SEEDED_BUILTINS); + expect(fresh.map((b) => b.id)).toEqual(['ct_guided', 'ct_worked', 'ct_practiceset', 'ct_cheatsheet', 'ct_ironfly', 'ct_codecard']); + }); + it('returns nothing when every builtin is in the ledger', () => { + expect(unseededBuiltins(builtinCardTypes.map((b) => b.id))).toEqual([]); + }); + it('legacy ledger covers no ids that are not real builtins', () => { + const ids = new Set(builtinCardTypes.map((b) => b.id)); + for (const id of LEGACY_SEEDED_BUILTINS) expect(ids.has(id)).toBe(true); + }); + // The ledger is history: it names what shipped before the ledger existed. Adding a new + // builtin to it would make old DBs skip seeding that builtin forever. + it('legacy ledger is exactly the pre-ledger builtin set', () => { + expect([...LEGACY_SEEDED_BUILTINS]).toEqual([ + 'ct_flashcard', 'ct_quiz', 'ct_note', 'ct_tracker', 'ct_mastery', + 'ct_sliderlab', 'ct_gaussian', 'ct_payoff', 'ct_compound', 'ct_quizcard', + ]); + }); +}); + +describe('parseSeededLedger', () => { + it('parses a well-formed ledger', () => { + expect(parseSeededLedger('["ct_flashcard","ct_quiz"]')).toEqual(['ct_flashcard', 'ct_quiz']); + }); + + it('falls back to the legacy set on garbage JSON', () => { + expect(parseSeededLedger('not json')).toEqual([...LEGACY_SEEDED_BUILTINS]); + }); + + it('falls back to the legacy set on valid JSON of the wrong shape (number)', () => { + expect(parseSeededLedger('5')).toEqual([...LEGACY_SEEDED_BUILTINS]); + }); + + it('falls back to the legacy set on valid JSON of the wrong shape (object)', () => { + expect(parseSeededLedger('{}')).toEqual([...LEGACY_SEEDED_BUILTINS]); + }); + + it('falls back to the legacy set on an array of non-strings', () => { + expect(parseSeededLedger('[1,2,3]')).toEqual([...LEGACY_SEEDED_BUILTINS]); + }); +}); \ No newline at end of file diff --git a/v2/src/lib/card-types.ts b/v2/src/lib/card-types.ts index fec8584..a3b9230 100644 --- a/v2/src/lib/card-types.ts +++ b/v2/src/lib/card-types.ts @@ -123,6 +123,38 @@ export function templateSlot(s: Slot): SlotTemplate { }; } +/** + * Builtin ids that existed before the seeded-builtins ledger was introduced. + * A DB that has card types but no ledger preference was seeded from exactly + * this set, so treating it as the ledger keeps old deletions deleted while + * still letting every later builtin seed itself on next launch. + */ +export const LEGACY_SEEDED_BUILTINS: readonly string[] = [ + 'ct_flashcard', 'ct_quiz', 'ct_note', 'ct_tracker', 'ct_mastery', + 'ct_sliderlab', 'ct_gaussian', 'ct_payoff', 'ct_compound', 'ct_quizcard', +]; + +/** Builtins absent from the seeded ledger — what a boot still needs to seed. */ +export function unseededBuiltins(seededIds: Iterable): CardType[] { + const seen = new Set(seededIds); + return builtinCardTypes.filter((b) => !seen.has(b.id)); +} + +/** + * Parse the seeded_builtins ledger preference. Garbage JSON or valid JSON of + * the wrong shape (a number, an object, an array of non-strings) falls back + * to the legacy set rather than throwing and aborting boot hydration. + */ +export function parseSeededLedger(raw: string): string[] { + try { + const parsed: unknown = JSON.parse(raw); + if (Array.isArray(parsed) && parsed.every((x) => typeof x === 'string')) return parsed; + } catch { + // garbage JSON: fall through to the legacy fallback below + } + return [...LEGACY_SEEDED_BUILTINS]; +} + export const builtinCardTypes: CardType[] = [ { id: 'ct_flashcard', name: 'Flashcard', store: 'practice', accent: '#6ea8fe', w: 6, verbs: { flip: true }, @@ -170,4 +202,94 @@ export const builtinCardTypes: CardType[] = [ slots: [{ type: 'text', props: { text: '**Q.** Var of a fair coin flip (0/1)?' } }], back: [ { type: 'choice', props: { q: 'Pick the variance:', options: ['0.25', '0.5', '1'], answer: [0], multi: false, explanation: 'Var = p(1−p) = **0.25**' } }] }, + // Predict → explore → explain: an ungraded prediction gates the simulation (every later slot is + // step-by-step, and the prediction is the card's only completable slot), so students commit to + // an idea before they see the answer, then reconcile the two. + { id: 'ct_guided', name: 'Guided Explore', store: 'live', accent: '#34e1ff', icon: '🔬', + description: 'Predict, then explore, then explain: the simulation unlocks once the student commits to a prediction.', + note: 'Keep the prediction ungraded (no answer key) and every later slot Step-by-step, so nothing shows until students commit. Swap in your own sliders, formulas and chart.', + slots: [ + { type: 'text', props: { text: '## Predict, then explore\n\nA deposit of 1000 earns interest at **r%** a year for **t** years, and the interest compounds. Make a prediction first: the simulation unlocks once you submit it.' } }, + { type: 'choice', props: { + q: '**Your prediction.** If the interest rate *doubles* (say from 4% to 8%), the interest earned over 20 years…', + options: ['…exactly doubles', '…more than doubles', '…less than doubles'], + multi: false, + explanation: 'Prediction locked in. Now test it: drag the sliders below.' } }, + { type: 'slider', props: { key: 'r', min: 1, max: 12, value: 4, step: 0.5 }, verbs: { sequential: true }, w: 6 }, + { type: 'slider', props: { key: 't', min: 1, max: 40, value: 20, step: 1 }, verbs: { sequential: true }, w: 6 }, + { type: 'compute', props: { expr: 'round(1000 * ((1 + r/100)^t - 1))', out: 'gain', note: 'interest earned at r% =' }, verbs: { sequential: true }, w: 6 }, + { type: 'compute', props: { expr: 'round(1000 * ((1 + 2*r/100)^t - 1))', out: 'gain2', note: 'interest earned at 2r% =' }, verbs: { sequential: true }, w: 6 }, + { type: 'compute', props: { expr: 'round(gain2 / gain * 100) / 100', out: 'times', note: 'doubling the rate multiplies the interest by' }, verbs: { sequential: true } }, + { type: 'chart', props: { fn: '((1 + 2*r/100)^x - 1) / ((1 + r/100)^x - 1)', x0: 1, x1: 41, xticks: 4, hover: true, label: 'interest at 2r% ÷ interest at r%, after x years' }, verbs: { sequential: true } }, + { type: 'text', props: { text: '**Explain.** At **{{r}}%** for **{{t}}** years the interest is **{{gain}}**; at double the rate it is **{{gain2}}**, which is **{{times}}×** as much. Compare that with your prediction.\n\nFor more than one year, doubling the rate *more than* doubles the interest, because each year\'s interest also earns interest. Set t = 1: with nothing to compound yet, it is exactly 2×. Why does the gap widen as t grows?' }, verbs: { sequential: true } }] }, + // Worked example with self-explanation prompts; each step unlocks once the student has explained + // the one before, and the example fades into a problem with the first step already done. + { id: 'ct_worked', name: 'Worked Example', store: 'practice', accent: '#54d6a0', icon: '📝', + description: 'A worked solution revealed step by step, with self-explanation prompts, fading into a problem to try.', + note: 'One step per text slot, each followed by a "why" box; later steps are Step-by-step, so each unlocks once the one before is explained. End with a similar problem that has the first step done.', + slots: [ + { type: 'text', props: { text: '## Worked example\n\n**Problem.** Solve $\\dfrac{x}{4} + 3 = 8$.' } }, + { type: 'text', props: { text: '**Step 1.** Subtract 3 from both sides:\n\n$$\\frac{x}{4} = 5$$' } }, + { type: 'text-input', props: { placeholder: 'Why is this step valid? Explain it in your own words to unlock step 2.' } }, + { type: 'text', props: { text: '**Step 2.** Multiply both sides by 4:\n\n$$x = 20$$\n\n**Check.** $\\frac{20}{4} + 3 = 5 + 3 = 8$ ✓' }, verbs: { sequential: true } }, + { type: 'text-input', props: { placeholder: 'Why multiply by 4, and why on both sides?' }, verbs: { sequential: true } }, + { type: 'problem', props: { + prompt: '**Now you try.** The first step is done for you.\n\nSolve $\\dfrac{x}{ {{a}} } + {{b}} = {{c}}$.\n\nStep 1: $\\dfrac{x}{ {{a}} } = {{c}} - {{b}}$. Finish it: what is $x$?', + params: [ + { name: 'a', min: 2, max: 9, step: 1 }, + { name: 'b', min: 1, max: 9, step: 1 }, + { name: 'c', min: 10, max: 20, step: 1 }], + answer: 'a * (c - b)', tol: 0, need: 1, + explain: 'Work out ${{c}} - {{b}}$, then multiply both sides by {{a}}: $x = {{a}} \\times ({{c}} - {{b}})$. Check it by substituting back.' }, + verbs: { sequential: true } }] }, + // Randomized retrieval practice: two different problem kinds, mixed, each drawing fresh numbers + // until the student has answered enough of them correctly. + { id: 'ct_practiceset', name: 'Practice Set', store: 'practice', accent: '#f0a500', icon: '🎯', + description: 'Two kinds of randomized problem, mixed: each draws fresh numbers until the student has enough right.', + note: 'Mix different kinds of problem. Give each a range for every number, an answer formula and a worked explanation; "need" sets how many correct answers finish it.', + slots: [ + { type: 'text', props: { text: '## Practice set\n\nTwo kinds of problem, mixed. Press **New numbers** for a fresh one; each problem is finished after enough correct answers.' } }, + { type: 'problem', props: { + prompt: '**1.** What is {{p}}% of {{n}}?', + params: [ + { name: 'p', min: 5, max: 95, step: 5 }, + { name: 'n', min: 20, max: 400, step: 20 }], + answer: 'p * n / 100', tol: 0, need: 3, + explain: '{{p}}% means {{p}} hundredths, so take $\\frac{ {{p}} }{100} \\times {{n}}$.' } }, + { type: 'problem', props: { + prompt: '**2.** Solve $\\dfrac{x}{ {{a}} } - {{b}} = {{c}}$. What is $x$?', + params: [ + { name: 'a', min: 2, max: 6, step: 1 }, + { name: 'b', min: 2, max: 9, step: 1 }, + { name: 'c', min: 1, max: 9, step: 1 }], + answer: 'a * (c + b)', tol: 0, need: 2, + explain: 'Add {{b}} to both sides: $\\dfrac{x}{ {{a}} } = {{c}} + {{b}}$. Then multiply both sides by {{a}}: $x = {{a}} \\times ({{c}} + {{b}})$.' } }] }, + { id: 'ct_cheatsheet', name: 'Cheatsheet', store: 'write', accent: '#27ff9e', icon: '📋', w: 6, + varieties: [{ name: 'Neon', accent: '#27ff9e' }, { name: 'Blue', accent: '#6ea8fe' }, { name: 'Amber', accent: '#f0a868' }], + slots: [ + { type: 'text', props: { text: '### Derivative Rules\n\nThe derivative is the instantaneous rate of change, the slope of the tangent.' } }, + { type: 'table', props: { rows: [ + ['RULE', 'FORMULA'], + ['Power', '`d/dx x^n = n*x^(n-1)`'], + ['Product', "`(fg)' = f'g + fg'`"], + ['Chain', "`(f(g(x)))' = f'(g(x)) * g'(x)`"]] } }, + { type: 'text', props: { text: '> **Example.** `d/dx (3x+1)^5 = 15(3x+1)^4` (chain).' } }] }, + { id: 'ct_ironfly', name: 'Iron Butterfly', store: 'live', accent: '#27ff9e', icon: '🦋', + varieties: [{ name: 'Neon', accent: '#27ff9e' }, { name: 'Amber', accent: '#f0a868' }], + slots: [ + { type: 'text', props: { text: '### Payoff explorer: iron butterfly\n\nShort a straddle at $K_0$, buy wings $W$ away, collect net credit $C$.' } }, + { type: 'slider', props: { key: 'K0', value: 100, min: 80, max: 120, step: 5 }, w: 4 }, + { type: 'slider', props: { key: 'W', value: 10, min: 5, max: 25, step: 5 }, w: 4 }, + { type: 'slider', props: { key: 'C', value: 3.5, min: 1, max: 8, step: 0.25 }, w: 4 }, + { type: 'compute', props: { expr: 'C', out: 'maxProfit', note: 'max profit' }, w: 3 }, + { type: 'compute', props: { expr: 'C - W', out: 'maxLoss', note: 'max loss' }, w: 3 }, + { type: 'compute', props: { expr: 'K0 - C', out: 'beLow', note: 'breakeven low' }, w: 3 }, + { type: 'compute', props: { expr: 'K0 + C', out: 'beHigh', note: 'breakeven high' }, w: 3 }, + { type: 'chart', props: { fn: 'C - max(K0 - x, 0) - max(x - K0, 0) + max(K0 - W - x, 0) + max(x - K0 - W, 0)', label: 'P&L at expiry vs spot', x0: 60, x1: 140, y0: -25, y1: 10, xticks: 8, yticks: 7, hover: true } }, + { type: 'text', props: { text: 'Peaks at **{{maxProfit}}**, floors at **{{maxLoss}}**, crosses zero at **{{beLow}}** and **{{beHigh}}**.' } }] }, + { id: 'ct_codecard', name: 'Code Card', store: 'write', accent: '#b388ff', icon: '⌨', w: 6, + varieties: [{ name: 'Violet', accent: '#b388ff' }, { name: 'Neon', accent: '#27ff9e' }], + slots: [ + { type: 'text', props: { text: '### Snippet\n\nSyntax-highlighted source for your own REPL.' } }, + { type: 'code', props: { lang: 'python', code: 'import numpy as np\n\ndef mc_call(s0=100, k=100, vol=0.2, t=0.25, n=100_000, seed=7):\n z = np.random.default_rng(seed).standard_normal(n)\n st = s0 * np.exp(-0.5 * vol**2 * t + vol * np.sqrt(t) * z)\n return np.maximum(st - k, 0).mean()' } }] }, ]; diff --git a/v2/src/lib/clipboard.test.ts b/v2/src/lib/clipboard.test.ts new file mode 100644 index 0000000..84f674f --- /dev/null +++ b/v2/src/lib/clipboard.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { copyText } from './clipboard'; + +function setClipboard(value: unknown) { + Object.defineProperty(navigator, 'clipboard', { value, configurable: true }); +} + +afterEach(() => { + delete (navigator as { clipboard?: unknown }).clipboard; + delete (document as { execCommand?: unknown }).execCommand; // drop the own-property stub +}); + +const leftovers = () => document.querySelectorAll('textarea').length; + +describe('copyText', () => { + it('uses the async Clipboard API when it is there', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + setClipboard({ writeText }); + document.execCommand = vi.fn(() => true); + expect(await copyText('hello')).toBe(true); + expect(writeText).toHaveBeenCalledWith('hello'); + expect(document.execCommand).not.toHaveBeenCalled(); + }); + + it('falls back to execCommand when the API refuses (file:// pages, unfocused windows)', async () => { + setClipboard({ writeText: vi.fn().mockRejectedValue(new Error('denied')) }); + let selected = ''; + document.execCommand = vi.fn(() => { + selected = document.querySelector('textarea')?.value ?? ''; + return true; + }); + expect(await copyText('fallback text')).toBe(true); + expect(document.execCommand).toHaveBeenCalledWith('copy'); + expect(selected).toBe('fallback text'); + expect(leftovers()).toBe(0); + }); + + it('reports false when neither path works, so the caller can show the text instead', async () => { + setClipboard(undefined); + document.execCommand = vi.fn(() => false); + expect(await copyText('x')).toBe(false); + expect(leftovers()).toBe(0); + }); + + it('reports false without execCommand at all', async () => { + setClipboard(undefined); + expect(await copyText('x')).toBe(false); + expect(leftovers()).toBe(0); + }); + + it('never leaves its hidden textarea behind, even when execCommand throws', async () => { + setClipboard(undefined); + document.execCommand = vi.fn(() => { + throw new Error('SecurityError'); + }); + expect(await copyText('x')).toBe(false); + expect(leftovers()).toBe(0); + }); +}); diff --git a/v2/src/lib/clipboard.ts b/v2/src/lib/clipboard.ts new file mode 100644 index 0000000..b129b92 --- /dev/null +++ b/v2/src/lib/clipboard.ts @@ -0,0 +1,33 @@ +/** + * Copy text to the clipboard: the async Clipboard API when the webview offers it, else the + * hidden-textarea + execCommand('copy') fallback. Resolves false when neither works, so the + * caller can show the text for a manual copy instead. + * + * Imports nothing: the app and the exported Reader both copy with it (reader-boundary.test.ts). + */ +export async function copyText(text: string): Promise { + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + // permission denied / not focused — try the legacy path + } + let ta: HTMLTextAreaElement | null = null; + try { + ta = document.createElement('textarea'); + ta.value = text; + ta.setAttribute('readonly', ''); + ta.style.position = 'fixed'; + ta.style.left = '-9999px'; + ta.style.opacity = '0'; + document.body.appendChild(ta); + ta.select(); + return typeof document.execCommand === 'function' && document.execCommand('copy'); + } catch { + return false; + } finally { + ta?.remove(); + } +} diff --git a/v2/src/lib/components/CardNotes.svelte b/v2/src/lib/components/CardNotes.svelte index c209177..9ca98f4 100644 --- a/v2/src/lib/components/CardNotes.svelte +++ b/v2/src/lib/components/CardNotes.svelte @@ -45,19 +45,19 @@ diff --git a/v2/src/lib/components/CardView.draft.test.ts b/v2/src/lib/components/CardView.draft.test.ts new file mode 100644 index 0000000..5a9321f --- /dev/null +++ b/v2/src/lib/components/CardView.draft.test.ts @@ -0,0 +1,105 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent, screen, cleanup } from '@testing-library/svelte'; +import CardView from './CardView.svelte'; +import { mode } from '../stores/mode'; +import type { Card } from '../types'; + +function cardOf(over: Partial = {}): Card { + return { + id: 'c1', + sectionId: 's1', + position: 0, + slots: [{ id: 'sl1', type: 'text', props: { text: 'AI wrote this' } }], + ...over, + }; +} + +function props(card: Card, over: Record = {}) { + return { + card, + surface: 'notebook' as 'bench' | 'notebook' | 'read', + selected: false, + state: {}, + notes: [], + notesOpen: false, + onselect: vi.fn(), + onstate: vi.fn(), + onmove: vi.fn(), + ondelete: vi.fn(), + onverb: vi.fn(), + ontags: vi.fn(), + onsavetype: vi.fn(), + onupdateslot: vi.fn(), + ondeleteslot: vi.fn(), + onaddslot: vi.fn(), + progresscompletion: vi.fn(() => ({ done: 0, total: 0, pct: 0 })), + ontogglenotes: vi.fn(), + onaddnote: vi.fn(), + ondeletenote: vi.fn(), + ongrip: vi.fn(), + onresize: vi.fn(), + onfusew: vi.fn(), + onreviewed: vi.fn(), + ...over, + }; +} + +const chip = (c: HTMLElement) => c.querySelector('.draft-chip'); + +afterEach(() => { + cleanup(); + mode.set('edit'); +}); + +describe('CardView — AI draft chip', () => { + it('shows a labelled Draft chip with a Reviewed button on a draft card in Edit mode', () => { + const { container } = render(CardView, { props: props(cardOf({ draft: true })) }); + expect(chip(container)).not.toBeNull(); + expect(container.querySelector('.furn')).toHaveClass('draft'); + expect(screen.getByRole('group', { name: /draft/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Mark this card reviewed' })).toBeInTheDocument(); + }); + + it('Reviewed calls onreviewed once — it neither selects nor mutates the card itself', async () => { + const card = cardOf({ draft: true }); + const p = props(card); + render(CardView, { props: p }); + await fireEvent.click(screen.getByRole('button', { name: 'Mark this card reviewed' })); + expect(p.onreviewed).toHaveBeenCalledTimes(1); + expect(p.onselect).not.toHaveBeenCalled(); + expect(card.draft).toBe(true); + }); + + it('is hidden in Study mode', () => { + mode.set('study'); + const { container } = render(CardView, { props: props(cardOf({ draft: true })) }); + expect(chip(container)).toBeNull(); + expect(container.querySelector('.furn')).not.toHaveClass('draft'); + }); + + it('is hidden when a preview forces Study', () => { + const { container } = render(CardView, { props: props(cardOf({ draft: true }), { forceMode: 'study' }) }); + expect(chip(container)).toBeNull(); + }); + + it('is hidden on a card that is not a draft', () => { + const { container } = render(CardView, { props: props(cardOf()) }); + expect(chip(container)).toBeNull(); + expect(container.querySelector('.furn')).not.toHaveClass('draft'); + }); + + it('is hidden without a review handler (the shared Reader passes none)', () => { + const { container } = render(CardView, { props: props(cardOf({ draft: true }), { onreviewed: undefined }) }); + expect(chip(container)).toBeNull(); + }); + + it('is hidden on a Factory bench', () => { + const { container } = render(CardView, { props: props(cardOf({ draft: true }), { surface: 'bench' }) }); + expect(chip(container)).toBeNull(); + }); + + it('still shows on a locked section card in Edit (read surface) so it can be reviewed', () => { + const { container } = render(CardView, { props: props(cardOf({ draft: true }), { surface: 'read' }) }); + expect(chip(container)).not.toBeNull(); + }); +}); diff --git a/v2/src/lib/components/CardView.svelte b/v2/src/lib/components/CardView.svelte index a12c990..14aac3b 100644 --- a/v2/src/lib/components/CardView.svelte +++ b/v2/src/lib/components/CardView.svelte @@ -52,6 +52,8 @@ showArch = false, onpin, onarchive, + onreviewed, + kfocus = false, }: { card: Card; surface: 'bench' | 'notebook' | 'read'; @@ -98,6 +100,13 @@ showArch?: boolean; onpin?: () => void; onarchive?: () => void; + /** + * D2d — mark this AI draft card reviewed. The host clears Card.draft undoably; without it + * (the shared Reader, previews) no draft chip renders. + */ + onreviewed?: () => void; + /** The Study keyboard cursor is on this card — draws the focus ring (`.sel` is Edit-only). */ + kfocus?: boolean; } = $props(); let newSlotType = $state('text'); @@ -109,6 +118,8 @@ const showEditSlots = $derived(surface !== 'read' && !studying); const flipped = $derived(cardState[CARD_STATE_KEY]?.flipped === true); const done = $derived(studying && isCardDone(card, cardState)); + // D2d: an unreviewed AI card is flagged while authoring only — never in Study, never on a bench. + const showDraft = $derived(card.draft === true && !studying && surface !== 'bench' && onreviewed !== undefined); // Scope failures (e.g. a cycle authored in Edit mode) must be visible, not silently empty. // Variables are card-scoped: both faces of a flip card share one scope. @@ -165,6 +176,7 @@ const SLOT_ICONS: Record = { text: '¶', list: '•', code: '‹›', table: '▦', image: '🖼', choice: '◉', slider: '⇄', 'text-input': '⌨', compute: '🟰', chart: '∿', progress: '▰', + problem: '🎲', }; const SVERB_ICONS: Record = { reveal: '👁', glow: '✦', emphasis: '❝', hint: '💡', sequential: '⏭', locked: '🔒', @@ -470,8 +482,10 @@ bind:this={furnEl} class="furn" class:sel={selected && !studying} + class:kfocus={kfocus && studying} class:bare={card.verbs?.bare} class:done + class:draft={showDraft} class:dragging={resizing} style={styleVars} data-card={card.id} @@ -495,7 +509,7 @@ {/if} @@ -595,7 +609,7 @@ {@render faceRows(card.back ?? [], false, 'back empty')} -

↻ click to flip
+
↻ click to flip
{:else if card.verbs?.flip} @@ -628,6 +642,13 @@ {/if} {/if} {/if} + {#if showDraft} +
+ Draft + +
+ {/if} @@ -638,9 +659,9 @@ border: none; color: inherit; cursor: pointer; - font-size: 12px; + font-size: var(--fs-sm); opacity: 0.5; - padding: 2px 4px; + padding: var(--space-1) var(--space-2); } .slot-del:hover { opacity: 1; @@ -652,50 +673,79 @@ background: transparent; color: inherit; border: 1px solid var(--line); - border-radius: 4px; - font-size: 11px; - padding: 2px 6px; - width: 150px; + border-radius: var(--radius-sm); + font-size: var(--fs-xs); + padding: var(--space-1) var(--space-3); + width: 150px; /* token-exempt: one-off field width sized to the tag list */ } .type-name-input { background: var(--panel); color: inherit; border: 1px solid var(--line); - border-radius: 4px; - font-size: 12px; - padding: 2px 6px; - width: 140px; + border-radius: var(--radius-sm); + font-size: var(--fs-sm); + padding: var(--space-1) var(--space-3); + width: 140px; /* token-exempt: one-off field width sized to a type name */ + } + /* D2d draft: a calm dashed halo plus a corner chip, both in the theme's secondary accent. */ + .furn.draft { + outline: 1px dashed var(--accent2); + outline-offset: 3px; + } + .draft-chip { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 6px; + margin-top: 8px; + } + .draft-tag { + font-size: 11px; + font-weight: 600; + letter-spacing: 0.02em; + color: var(--accent2); + border: 1px dashed var(--accent2); + border-radius: 999px; + padding: 1px 8px; + } + @media print { + .furn.draft { + outline: none; + } + .draft-chip { + display: none; + } } .done-badge { position: absolute; - top: 8px; - right: 12px; - font-size: 11px; + top: var(--space-4); + right: var(--space-6); + font-size: var(--fs-xs); font-weight: 600; color: var(--accent, #7c3aed); opacity: 0.8; } .scope-error { - font-size: 12px; + font-size: var(--fs-sm); color: #dc2626; - margin-bottom: 8px; + margin-bottom: var(--space-4); } /* Out of flow like the ported pin/archive buttons (app.css .furn .arch), so a card with the notes service on reserves no blank line for it. Quiet until hover or keyboard focus (D9); a card that already carries notes keeps the marker visible. */ .notes-toggle { position: absolute; - right: 9px; - bottom: 6px; + right: 9px; /* token-exempt: sits on the same edge as the app.css .furn .arch buttons */ + bottom: var(--space-3); z-index: 2; background: none; border: none; color: inherit; cursor: pointer; - font-size: 11px; + font-size: var(--fs-xs); opacity: 0; - padding: 2px 4px; - transition: opacity 0.12s ease; + padding: var(--space-1) var(--space-2); + transition: opacity var(--t-quick) ease; } .furn:hover .notes-toggle, .notes-toggle:focus-visible, @@ -706,7 +756,7 @@ .notes-toggle.open { position: static; opacity: 0.8; - padding: 4px 0 0; + padding: var(--space-2) 0 0; } .notes-toggle.has-notes { color: var(--accent, #7c3aed); @@ -720,9 +770,9 @@ .bs-head { display: flex; align-items: center; - gap: 5px; - margin: 0 0 6px; - padding-right: 12px; + gap: 5px; /* token-exempt: mirrors the v1 .benchslot .bs-head gap */ + margin: 0 0 var(--space-3); + padding-right: var(--space-6); } .bs-head .spacer { flex: 1; @@ -735,10 +785,10 @@ position: absolute; top: 0; right: 0; - width: 11px; + width: 11px; /* token-exempt: mirrors the v1 .benchslot .rz grab strip */ height: 100%; cursor: ew-resize; - border-radius: 0 10px 10px 0; + border-radius: 0 var(--radius-lg) var(--radius-lg) 0; z-index: 2; } .cardslot:hover .bs-rz, @@ -746,7 +796,7 @@ background: linear-gradient(90deg, transparent, rgba(110, 168, 254, 0.3)); } .slot { - margin-bottom: 8px; + margin-bottom: var(--space-4); } .slot:last-child { margin-bottom: 0; @@ -754,7 +804,7 @@ .slot.editing { display: flex; align-items: flex-start; - gap: 4px; + gap: var(--space-2); } .slot.editing > :global(:first-child) { flex: 1; @@ -762,26 +812,26 @@ .slot-adder { display: flex; align-items: center; - gap: 6px; - margin-top: 8px; + gap: var(--space-3); + margin-top: var(--space-4); } .slot-adder select { background: var(--panel); color: inherit; border: 1px solid var(--line); - border-radius: 4px; - font-size: 12px; - padding: 2px 6px; + border-radius: var(--radius-sm); + font-size: var(--fs-sm); + padding: var(--space-1) var(--space-3); } .slot-adder button { background: none; border: 1px dashed var(--line); - border-radius: 4px; + border-radius: var(--radius-sm); color: inherit; cursor: pointer; - font-size: 12px; + font-size: var(--fs-sm); opacity: 0.6; - padding: 4px 10px; + padding: var(--space-2) var(--space-5); } .slot-adder button:hover { opacity: 1; diff --git a/v2/src/lib/components/CoverageMatrix.svelte b/v2/src/lib/components/CoverageMatrix.svelte index caf269d..7759d93 100644 --- a/v2/src/lib/components/CoverageMatrix.svelte +++ b/v2/src/lib/components/CoverageMatrix.svelte @@ -142,7 +142,7 @@
+ + +
+{/if} + + diff --git a/v2/src/lib/components/DraftsBar.test.ts b/v2/src/lib/components/DraftsBar.test.ts new file mode 100644 index 0000000..3a20ad6 --- /dev/null +++ b/v2/src/lib/components/DraftsBar.test.ts @@ -0,0 +1,70 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent, screen, cleanup } from '@testing-library/svelte'; +import DraftsBar from './DraftsBar.svelte'; +import SideBar from './SideBar.svelte'; +import { mode } from '../stores/mode'; + +afterEach(() => { + cleanup(); + mode.set('edit'); +}); + +describe('DraftsBar', () => { + it('renders nothing when there are no drafts', () => { + const { container } = render(DraftsBar, { props: { count: 0, onnext: vi.fn(), onmarkall: vi.fn() } }); + expect(container.querySelector('.drafts-bar')).toBeNull(); + }); + + it('counts the drafts left to review (singular and plural)', async () => { + const { container, rerender } = render(DraftsBar, { props: { count: 5, onnext: vi.fn(), onmarkall: vi.fn() } }); + expect(container.querySelector('.drafts-bar')?.textContent).toMatch(/5 drafts to review/); + await rerender({ count: 1, onnext: vi.fn(), onmarkall: vi.fn() }); + expect(container.querySelector('.drafts-bar')?.textContent).toMatch(/1 draft to review/); + }); + + it('Next and Mark all reviewed call their callbacks', async () => { + const onnext = vi.fn(); + const onmarkall = vi.fn(); + render(DraftsBar, { props: { count: 2, onnext, onmarkall } }); + await fireEvent.click(screen.getByRole('button', { name: /next/i })); + expect(onnext).toHaveBeenCalledTimes(1); + await fireEvent.click(screen.getByRole('button', { name: /mark all reviewed/i })); + expect(onmarkall).toHaveBeenCalledTimes(1); + }); +}); + +describe('SideBar — drafts bar in the notebook panel', () => { + const base = { + notebookName: 'NB', + canPersist: false, + cardTypes: [], + selProd: null, + onrename: vi.fn(), + ondelete: vi.fn(), + onpickprod: vi.fn(), + onplaceprod: vi.fn(), + onclosedetail: vi.fn(), + }; + + it('shows the bar in Edit mode when drafts remain and wires both callbacks', async () => { + const ondraftnext = vi.fn(); + const ondraftsreviewed = vi.fn(); + const { container } = render(SideBar, { props: { ...base, drafts: 3, ondraftnext, ondraftsreviewed } }); + expect(container.querySelector('.drafts-bar')?.textContent).toMatch(/3 drafts to review/); + await fireEvent.click(screen.getByRole('button', { name: /next/i })); + await fireEvent.click(screen.getByRole('button', { name: /mark all reviewed/i })); + expect(ondraftnext).toHaveBeenCalledTimes(1); + expect(ondraftsreviewed).toHaveBeenCalledTimes(1); + }); + + it('has no bar when the notebook has no drafts (the default, e.g. the shared Reader)', () => { + const { container } = render(SideBar, { props: base }); + expect(container.querySelector('.drafts-bar')).toBeNull(); + }); + + it('has no bar in Study mode', () => { + mode.set('study'); + const { container } = render(SideBar, { props: { ...base, drafts: 3 } }); + expect(container.querySelector('.drafts-bar')).toBeNull(); + }); +}); diff --git a/v2/src/lib/components/Factory.svelte b/v2/src/lib/components/Factory.svelte index d741db1..1dc6772 100644 --- a/v2/src/lib/components/Factory.svelte +++ b/v2/src/lib/components/Factory.svelte @@ -16,6 +16,7 @@ fuseBenchSlot, benchFaceCard, type Bench, + type SlotEffect, } from '../bench.svelte'; import { toast } from '../toast.svelte'; import { pushGestureSnapshot } from '../drag/gesture-history'; @@ -106,7 +107,7 @@ toast('drop a slot verb onto a slot'); return; } - const key = e.dataTransfer!.getData('text/nb-sverb') as 'reveal' | 'glow' | 'emphasis'; + const key = e.dataTransfer!.getData('text/nb-sverb') as SlotEffect; pushHistory(); setSlotVerb(at, key, true); factory.sel = at; diff --git a/v2/src/lib/components/FromAiModal.svelte b/v2/src/lib/components/FromAiModal.svelte new file mode 100644 index 0000000..d364c62 --- /dev/null +++ b/v2/src/lib/components/FromAiModal.svelte @@ -0,0 +1,324 @@ + + + + + + + diff --git a/v2/src/lib/components/FromAiModal.test.ts b/v2/src/lib/components/FromAiModal.test.ts new file mode 100644 index 0000000..1919f9b --- /dev/null +++ b/v2/src/lib/components/FromAiModal.test.ts @@ -0,0 +1,247 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import FromAiModal from './FromAiModal.svelte'; +import { buildAiPrompt, AI_EXAMPLE } from '../ai-prompt'; + +function setClipboard(writeText: ((t: string) => Promise) | undefined) { + Object.defineProperty(navigator, 'clipboard', { value: writeText ? { writeText } : undefined, configurable: true }); +} + +const q = (root: ParentNode, sel: string) => root.querySelector(sel)!; +const act = (root: ParentNode, name: string) => q(root, `[data-act="${name}"]`); + +function mount() { + const onclose = vi.fn(); + const oncreate = vi.fn(); + const oncopied = vi.fn(); + const { container } = render(FromAiModal, { props: { onclose, oncreate, oncopied } }); + return { container, onclose, oncreate, oncopied }; +} + +async function paste(container: HTMLElement, text: string) { + await fireEvent.input(q(container, '[data-fa="reply"]'), { target: { value: text } }); +} + +afterEach(() => { + setClipboard(undefined); + delete (document as unknown as { execCommand?: unknown }).execCommand; + vi.restoreAllMocks(); +}); + +describe('FromAiModal — step 1: the prompt', () => { + it('is a labelled modal dialog that focuses the topic field', () => { + const { container } = mount(); + const dialog = q(container, '[role="dialog"]'); + expect(dialog.getAttribute('aria-modal')).toBe('true'); + expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)!.textContent).toMatch(/from AI/); + expect(document.activeElement).toBe(q(container, '[data-fa="topic"]')); + }); + + it('Copy prompt is disabled until there is a topic', async () => { + const { container } = mount(); + expect(act(container, 'copy-prompt').disabled).toBe(true); + await fireEvent.input(q(container, '[data-fa="topic"]'), { target: { value: ' ' } }); + expect(act(container, 'copy-prompt').disabled).toBe(true); + await fireEvent.input(q(container, '[data-fa="topic"]'), { target: { value: 'Fractions' } }); + expect(act(container, 'copy-prompt').disabled).toBe(false); + }); + + it('copies the prompt built from topic, audience and card count', async () => { + const writeText = vi.fn((_t: string) => Promise.resolve()); + setClipboard(writeText); + const { container, oncopied } = mount(); + await fireEvent.input(q(container, '[data-fa="topic"]'), { target: { value: 'Fractions' } }); + await fireEvent.input(q(container, '[data-fa="audience"]'), { target: { value: 'grade 5' } }); + await fireEvent.input(q(container, '[data-fa="cards"]'), { target: { value: '9' } }); + await fireEvent.click(act(container, 'copy-prompt')); + await tick(); + const expected = buildAiPrompt({ topic: 'Fractions', audience: 'grade 5', cards: 9 }); + expect(writeText).toHaveBeenCalledWith(expected); + expect(oncopied).toHaveBeenCalledWith('prompt', expected); + expect(act(container, 'copy-prompt').textContent).toContain('copied'); + // any change makes the copied prompt stale + await fireEvent.input(q(container, '[data-fa="audience"]'), { target: { value: 'grade 6' } }); + expect(act(container, 'copy-prompt').textContent?.trim()).toBe('Copy prompt'); + }); + + it('shows the prompt for a manual copy when the clipboard is unavailable', async () => { + setClipboard(undefined); + (document as unknown as { execCommand: () => boolean }).execCommand = () => false; + const { container } = mount(); + await fireEvent.input(q(container, '[data-fa="topic"]'), { target: { value: 'Fractions' } }); + await fireEvent.click(act(container, 'copy-prompt')); + await tick(); + await tick(); + const ta = q(container, '[data-fa="prompt"]'); + expect(ta.value).toBe(buildAiPrompt({ topic: 'Fractions', audience: '' })); + expect(container.textContent).toMatch(/Couldn't reach the clipboard/); + }); + + it('Show prompt toggles the prompt preview', async () => { + const { container } = mount(); + expect(container.querySelector('[data-fa="prompt"]')).toBeNull(); + await fireEvent.click(act(container, 'toggle-prompt')); + expect(container.querySelector('[data-fa="prompt"]')).not.toBeNull(); + expect(act(container, 'toggle-prompt').getAttribute('aria-expanded')).toBe('true'); + }); +}); + +describe('FromAiModal — step 2: check and create', () => { + it('Check and Create start disabled', () => { + const { container } = mount(); + expect(act(container, 'check').disabled).toBe(true); + expect(act(container, 'create').disabled).toBe(true); + }); + + it('a broken reply shows the report inline and keeps Create disabled', async () => { + const { container, oncreate } = mount(); + await paste(container, 'Here you go:\n```json\n{"version": 2, "notebook": {"name": "N",}}\n```'); + await fireEvent.click(act(container, 'check')); + const report = q(container, 'section.import-report.inline'); + expect(report.textContent).toMatch(/Trailing comma/); + expect(report.textContent).toContain('line 3, column'); + expect(act(container, 'create').disabled).toBe(true); + await fireEvent.click(act(container, 'create')); + expect(oncreate).not.toHaveBeenCalled(); + }); + + it('validation problems show with hints', async () => { + const { container } = mount(); + const bad = structuredClone(AI_EXAMPLE) as unknown as { notebook: { sections: { cards: { slots: { type: string }[] }[] }[] } }; + bad.notebook.sections[0].cards[0].slots[0].type = 'markdown'; + await paste(container, JSON.stringify(bad)); + await fireEvent.click(act(container, 'check')); + expect(q(container, '.import-report').textContent).toContain('Did you mean "text"?'); + expect(act(container, 'create').disabled).toBe(true); + }); + + it('a good reply shows a summary and Create hands the JSON to oncreate', async () => { + const { container, oncreate } = mount(); + await paste(container, 'Sure!\n```json\n' + JSON.stringify(AI_EXAMPLE, null, 2) + '\n```\nEnjoy.'); + await fireEvent.click(act(container, 'check')); + const summary = q(container, '[data-fa="summary"]'); + expect(summary.textContent).toContain('Compound Growth'); + expect(summary.textContent).toContain('1 section'); + expect(summary.textContent).toContain('5 cards'); + expect(summary.textContent).toContain('1 flashcard'); + expect(container.querySelector('.import-report')).toBeNull(); + expect(act(container, 'create').disabled).toBe(false); + await fireEvent.click(act(container, 'create')); + expect(oncreate).toHaveBeenCalledWith(AI_EXAMPLE); + // plain data, not a Svelte state proxy: the host may structuredClone it + expect(() => structuredClone(oncreate.mock.calls[0][0])).not.toThrow(); + }); + + it('warnings alone still allow Create and can be dismissed', async () => { + const { container, oncreate } = mount(); + const warn = structuredClone(AI_EXAMPLE) as unknown as { notebook: { sections: { cards: Record[] }[] } }; + warn.notebook.sections[0].cards[0].title = 'A card title'; + await paste(container, JSON.stringify(warn)); + await fireEvent.click(act(container, 'check')); + expect(q(container, '[data-fa="summary"]')).not.toBeNull(); + expect(q(container, '.import-report').textContent).toContain('not a NoteBuilder field'); + const close = [...q(container, '.import-report').querySelectorAll('button')].find((b) => b.textContent === 'Close')!; + await fireEvent.click(close); + expect(container.querySelector('.import-report')).toBeNull(); + await fireEvent.click(act(container, 'create')); + expect(oncreate).toHaveBeenCalledOnce(); + }); + + it('editing the reply after a check clears the stale result', async () => { + const { container } = mount(); + await paste(container, JSON.stringify(AI_EXAMPLE)); + await fireEvent.click(act(container, 'check')); + expect(act(container, 'create').disabled).toBe(false); + await paste(container, JSON.stringify(AI_EXAMPLE) + 'x'); + expect(container.querySelector('[data-fa="summary"]')).toBeNull(); + expect(act(container, 'create').disabled).toBe(true); + }); + + it('Cancel and Escape call onclose', async () => { + const { container, onclose } = mount(); + await fireEvent.click(act(container, 'cancel')); + await fireEvent.keyDown(window, { key: 'Escape' }); + expect(onclose).toHaveBeenCalledTimes(2); + }); +}); + +describe('FromAiModal — Escape never silently discards what was typed', () => { + const escape = (target: Element | Window, init: KeyboardEventInit & { keyCode?: number } = {}) => + fireEvent.keyDown(target, { key: 'Escape', ...init }); + + it('with a reply pasted, Escape asks first; a second Escape discards', async () => { + const { container, onclose } = mount(); + await paste(container, 'a long reply'); + const reply = q(container, '[data-fa="reply"]'); + await escape(reply); + expect(onclose).not.toHaveBeenCalled(); + expect(q(container, '[data-fa="discard"]').textContent).toMatch(/Discard what you typed\?/); + expect(q(container, '[data-fa="discard"]').getAttribute('role')).toBe('alert'); + await escape(reply); + expect(onclose).toHaveBeenCalledOnce(); + }); + + it('the question is scrolled into view: a second Escape never answers one that was off screen', async () => { + // jsdom has no layout, so no scrollIntoView: record which element asks to be shown. + const native = Element.prototype.scrollIntoView; + const shown: Element[] = []; + Element.prototype.scrollIntoView = function (this: Element) { + shown.push(this); + }; + try { + const { container } = mount(); + await paste(container, 'a long reply'); + await escape(q(container, '[data-fa="reply"]')); + expect(shown).toEqual([q(container, '[data-fa="discard"]')]); + } finally { + Element.prototype.scrollIntoView = native; + } + }); + + it('a held-down Escape (auto-repeat) does not answer its own question', async () => { + const { container, onclose } = mount(); + await fireEvent.input(q(container, '[data-fa="topic"]'), { target: { value: 'Fractions' } }); + await escape(window); + await escape(window, { repeat: true }); + expect(onclose).not.toHaveBeenCalled(); + expect(container.querySelector('[data-fa="discard"]')).not.toBeNull(); + }); + + it('Keep editing, or typing on, dismisses the question and keeps everything', async () => { + const { container, onclose } = mount(); + const topic = q(container, '[data-fa="topic"]'); + await fireEvent.input(topic, { target: { value: 'Fractions' } }); + topic.focus(); + await escape(topic); + await fireEvent.click(act(container, 'keep')); + expect(container.querySelector('[data-fa="discard"]')).toBeNull(); + expect(document.activeElement).toBe(topic); + await escape(topic); + await fireEvent.input(topic, { target: { value: 'Fractions!' } }); + expect(container.querySelector('[data-fa="discard"]')).toBeNull(); + // The question is asked afresh, not answered by the earlier Escape. + await escape(topic); + expect(onclose).not.toHaveBeenCalled(); + expect(topic.value).toBe('Fractions!'); + }); + + it('Discard closes', async () => { + const { container, onclose } = mount(); + await paste(container, 'reply'); + await escape(window); + await fireEvent.click(act(container, 'discard')); + expect(onclose).toHaveBeenCalledOnce(); + }); + + it('Escape during IME composition is left to the input method', async () => { + const { container, onclose } = mount(); + const topic = q(container, '[data-fa="topic"]'); + await escape(topic, { isComposing: true }); + await escape(topic, { keyCode: 229 }); + expect(onclose).not.toHaveBeenCalled(); + await fireEvent.input(topic, { target: { value: 'ぶんすう' } }); + await escape(topic, { isComposing: true }); + expect(container.querySelector('[data-fa="discard"]')).toBeNull(); + }); +}); diff --git a/v2/src/lib/components/ImportReport.fixrequest.test.ts b/v2/src/lib/components/ImportReport.fixrequest.test.ts new file mode 100644 index 0000000..f4d3041 --- /dev/null +++ b/v2/src/lib/components/ImportReport.fixrequest.test.ts @@ -0,0 +1,44 @@ +import { describe, it, expect, vi } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import ImportReport from './ImportReport.svelte'; +import type { HintedIssue } from '../import-hints'; + +// A held-back Share/Export lists problems in the open notebook: no AI wrote them, so the +// report drops its "fix request for your AI" and Close becomes the one (focused) action. +const errors: HintedIssue[] = [ + { + code: 'slot-props', + path: 'notebook.sections[1].cards[0].slots[0].props', + message: 'sections[1].cards[0].slots[0]: problem slot — parameter "e": "e" is reserved — pick another name', + subject: 'problem', + }, +]; + +describe('ImportReport fixRequest={false}', () => { + it('shows the title and every problem with its path, but no AI fix request', () => { + const { container } = render(ImportReport, { + props: { errors, title: 'Fix this problem before sharing', fixRequest: false, onclose: vi.fn() }, + }); + expect(container.querySelector('.ir-title')!.textContent).toBe('Fix this problem before sharing'); + expect(container.querySelector('.ir-where')!.textContent).toBe('section 2 › card 1 › slot 1 › props'); + expect(container.querySelector('.ir-what')!.textContent).toMatch(/"e" is reserved/); + expect(container.querySelector('[data-act="copy-fix"]')).toBeNull(); + }); + + it('focuses Close, which closes', async () => { + const onclose = vi.fn(); + const { container } = render(ImportReport, { props: { errors, fixRequest: false, onclose } }); + const close = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Close')!; + expect(document.activeElement).toBe(close); + expect(close.classList.contains('primary')).toBe(true); + await fireEvent.click(close); + expect(onclose).toHaveBeenCalledOnce(); + }); + + it('keeps the fix request by default', () => { + const { container } = render(ImportReport, { props: { errors, onclose: vi.fn() } }); + const copy = container.querySelector('[data-act="copy-fix"]'); + expect(copy).toBeTruthy(); + expect(document.activeElement).toBe(copy); + }); +}); diff --git a/v2/src/lib/components/ImportReport.svelte b/v2/src/lib/components/ImportReport.svelte new file mode 100644 index 0000000..261b30c --- /dev/null +++ b/v2/src/lib/components/ImportReport.svelte @@ -0,0 +1,206 @@ + + + { + if (!inline && e.key === 'Escape') onclose(); + }} +/> + +{#snippet issueList(list: Row[], kind: 'error' | 'warning')} +
    + {#each list as row, k (k)} +
  1. +
    {humanPath(row.where)}
    +
    {row.what}
    + {#if row.issue.excerpt} +
    {row.issue.excerpt}
    + {/if} + {#if row.hint} +
    Fix: {row.hint}
    + {/if} +
  2. + {/each} +
+{/snippet} + +{#snippet body()} +

{heading}

+ {#if errorRows.length} + {@render issueList(errorRows, 'error')} + {#if errors.length > SHOW}
…and {errors.length - SHOW} more (all are in the fix request).
{/if} + {/if} + {#if warningRows.length} +
+ {errors.length ? 'Also' : 'It will load, but'}: {warnings.length} warning{warnings.length === 1 ? '' : 's'} +
+ {@render issueList(warningRows, 'warning')} + {#if warnings.length > SHOW}
…and {warnings.length - SHOW} more.
{/if} + {/if} + {#if copyState === 'failed'} +
+
Couldn't reach the clipboard. Select this text and copy it:
+ +
+ {/if} +
+ + {#if !inline}{/if} + {#if offerFix} + + {/if} + {#if inline}{/if} +
+{/snippet} + +{#if inline} +
+ {@render body()} +
+{:else} + +{/if} + + diff --git a/v2/src/lib/components/ImportReport.test.ts b/v2/src/lib/components/ImportReport.test.ts new file mode 100644 index 0000000..65c55ca --- /dev/null +++ b/v2/src/lib/components/ImportReport.test.ts @@ -0,0 +1,133 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import ImportReport from './ImportReport.svelte'; +import { checkNotebookText, buildFixRequest, type HintedIssue } from '../import-hints'; + +function doc(slots: unknown[], card: Record = {}): string { + return JSON.stringify({ version: 2, notebook: { name: 'N', sections: [{ name: 'S', cards: [{ slots, ...card }] }] } }); +} + +function report() { + return checkNotebookText(doc([{ type: 'quiz', props: {} }, { type: 'text', props: { text: 'see {{r}}' } }], { w: 2 })); +} + +function setClipboard(writeText: ((t: string) => Promise) | undefined) { + Object.defineProperty(navigator, 'clipboard', { + value: writeText ? { writeText } : undefined, + configurable: true, + }); +} + +const button = (root: ParentNode, text: string) => + [...root.querySelectorAll('button')].find((b) => b.textContent?.includes(text)) as HTMLButtonElement | undefined; + +afterEach(() => { + setClipboard(undefined); + delete (document as unknown as { execCommand?: unknown }).execCommand; // drop the per-test stub + vi.restoreAllMocks(); +}); + +describe('ImportReport', () => { + it('lists every error and warning with location, message and fix hint', () => { + const { errors, warnings } = report(); + const { container } = render(ImportReport, { props: { errors, warnings, onclose: vi.fn() } }); + const errItems = container.querySelectorAll('.ir-list.error .ir-item'); + const warnItems = container.querySelectorAll('.ir-list.warning .ir-item'); + expect(errItems).toHaveLength(errors.length); + expect(warnItems).toHaveLength(warnings.length); + const unknown = container.querySelector('.ir-item[data-code="slot-type-unknown"]')!; + expect(unknown.querySelector('.ir-where')!.textContent).toBe('section 1 › card 1 › slot 1 › type'); + expect(unknown.querySelector('.ir-where')!.getAttribute('title')).toBe('notebook.sections[0].cards[0].slots[0].type'); + expect(unknown.querySelector('.ir-what')!.textContent).toBe('has unknown slot type: quiz'); + expect(unknown.querySelector('.ir-hint')!.textContent).toContain('Did you mean "choice"?'); + const cross = container.querySelector('.ir-item[data-code="cross-card-read"]')!; + expect(cross.textContent).toContain('variables never cross cards'); + expect(container.querySelector('.ir-title')!.textContent).toMatch(/can't be imported yet: 2 problems/); + }); + + it('shows the excerpt of a syntax error', () => { + const { errors } = checkNotebookText('{\n "a": 1,\n}'); + const { container } = render(ImportReport, { props: { errors, onclose: vi.fn() } }); + expect(container.querySelector('.ir-where')!.textContent).toBe('line 2, column 9'); + expect(container.querySelector('.ir-excerpt')!.textContent).toContain('^'); + }); + + it('copies the fix request for the AI and reports it', async () => { + const writeText = vi.fn((_t: string) => Promise.resolve()); + setClipboard(writeText); + const oncopied = vi.fn(); + const { errors, warnings } = report(); + const { container } = render(ImportReport, { props: { errors, warnings, onclose: vi.fn(), oncopied } }); + await fireEvent.click(button(container, 'Copy fix request for your AI')!); + await tick(); + const expected = buildFixRequest(errors, warnings); + expect(writeText).toHaveBeenCalledWith(expected); + expect(oncopied).toHaveBeenCalledWith(expected); + expect(button(container, 'Copied ✓')).toBeDefined(); + }); + + it('falls back to showing the text when no clipboard works', async () => { + setClipboard(undefined); + (document as unknown as { execCommand: (c: string) => boolean }).execCommand = vi.fn(() => false); + const { errors } = report(); + const { container } = render(ImportReport, { props: { errors, onclose: vi.fn() } }); + await fireEvent.click(button(container, 'Copy fix request')!); + await tick(); + await tick(); + const ta = container.querySelector('.ir-manual textarea'); + expect(ta).not.toBeNull(); + expect(ta!.value).toBe(buildFixRequest(errors)); + }); + + it('uses the legacy copy path when the Clipboard API is missing', async () => { + setClipboard(undefined); + const exec = vi.fn(() => true); + (document as unknown as { execCommand: (c: string) => boolean }).execCommand = exec; + const { errors } = report(); + const { container } = render(ImportReport, { props: { errors, onclose: vi.fn() } }); + await fireEvent.click(button(container, 'Copy fix request')!); + await tick(); + expect(exec).toHaveBeenCalledWith('copy'); + expect(button(container, 'Copied ✓')).toBeDefined(); + expect(document.querySelectorAll('textarea[readonly]').length).toBe(0); // temp textarea removed + }); + + it('Close and Escape call onclose in modal mode', async () => { + const onclose = vi.fn(); + const { container } = render(ImportReport, { props: { errors: report().errors, onclose } }); + expect(container.querySelector('[role="dialog"][aria-modal="true"]')).not.toBeNull(); + await fireEvent.click(button(container, 'Close')!); + await fireEvent.keyDown(window, { key: 'Escape' }); + expect(onclose).toHaveBeenCalledTimes(2); + }); + + it('inline mode renders no modal and ignores Escape', async () => { + const onclose = vi.fn(); + const { container } = render(ImportReport, { props: { errors: report().errors, inline: true, onclose } }); + expect(container.querySelector('.modal')).toBeNull(); + expect(container.querySelector('section.import-report.inline')).not.toBeNull(); + await fireEvent.keyDown(window, { key: 'Escape' }); + expect(onclose).not.toHaveBeenCalled(); + await fireEvent.click(button(container, 'Close')!); + expect(onclose).toHaveBeenCalledOnce(); + }); + + it('caps a very long list but keeps the count', () => { + const many: HintedIssue[] = Array.from({ length: 70 }, (_, k) => ({ + code: 'wrong-type', + path: `notebook.sections[${k}]`, + message: `sections[${k}] must be an object`, + })); + const { container } = render(ImportReport, { props: { errors: many, onclose: vi.fn() } }); + expect(container.querySelectorAll('.ir-list.error .ir-item')).toHaveLength(50); + expect(container.textContent).toContain('…and 20 more'); + }); + + it('a warnings-only report says it will still load', () => { + const { warnings } = checkNotebookText(doc([{ type: 'text', props: { text: '{{r}}' } }])); + const { container } = render(ImportReport, { props: { errors: [], warnings, onclose: vi.fn() } }); + expect(container.querySelector('.ir-title')!.textContent).toBe('1 warning'); + expect(container.textContent).toContain('It will load, but'); + }); +}); diff --git a/v2/src/lib/components/MdBar.svelte b/v2/src/lib/components/MdBar.svelte index 3be8d9a..03fc73c 100644 --- a/v2/src/lib/components/MdBar.svelte +++ b/v2/src/lib/components/MdBar.svelte @@ -1,5 +1,6 @@
@@ -142,7 +153,7 @@ {/each} {/each} -
+
Live preview
@@ -151,8 +162,16 @@
-
-
+
+
ongrip?.(ct.id, e, e.currentTarget)}> @@ -161,23 +180,25 @@
{#if ct.varieties?.length} -
+
- + {#each ct.varieties as v (v.name)} {/each}
{/if} -
+
adds to the current section
diff --git a/v2/src/lib/components/ProductDetail.test.ts b/v2/src/lib/components/ProductDetail.test.ts index 464a92d..7dc9f12 100644 --- a/v2/src/lib/components/ProductDetail.test.ts +++ b/v2/src/lib/components/ProductDetail.test.ts @@ -107,6 +107,14 @@ describe('ProductDetail', () => { expect(draft).toEqual({ '0': { text: 'edited' } }); }); + it('lays the preview stage out at the type’s own share of the room, not the whole room', () => { + const full = mount().container.querySelector('.prev-stage') as HTMLElement; + expect(full.style.width).toBe('720px'); + + const half = mount({ w: 6 }).container.querySelector('.prev-stage') as HTMLElement; + expect(half.style.width).toBe('360px'); + }); + it('close fires onclose', async () => { const { container, onclose } = mount(); await fireEvent.click([...container.querySelectorAll('button')].find((b) => b.textContent?.includes('close'))!); diff --git a/v2/src/lib/components/Reader.drafts.test.ts b/v2/src/lib/components/Reader.drafts.test.ts new file mode 100644 index 0000000..710d9b0 --- /dev/null +++ b/v2/src/lib/components/Reader.drafts.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { render, fireEvent, cleanup } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import Reader from './Reader.svelte'; +import { mode } from '../stores/mode'; +import type { Notebook } from '../types'; + +// A shared file can never carry Card.draft (export strips it, import ignores it). Even when a +// notebook handed to the Reader does, the Reader offers no review chip, before or after Remix. +function drafted(): Notebook { + return { + id: 'nb1', + name: 'Shared Deck', + createdAt: '2026-01-01', + updatedAt: '2026-01-01', + sections: [ + { + id: 's1', + notebookId: 'nb1', + name: 'S', + position: 0, + cards: [{ id: 'c1', sectionId: 's1', position: 0, draft: true, slots: [{ id: 'x', type: 'text', props: { text: 'hi' } }] }], + }, + ], + }; +} + +afterEach(() => { + cleanup(); + mode.set('edit'); + delete document.body.dataset.theme; +}); + +describe('Reader — never shows AI drafts', () => { + it('no draft chip in the shared Study view', async () => { + const { container } = render(Reader, { props: { notebook: drafted(), shared: true } }); + await tick(); + expect(container.querySelector('[data-card="c1"]')).not.toBeNull(); + expect(container.querySelector('.draft-chip')).toBeNull(); + }); + + it('no draft chip after Remix into Edit', async () => { + const { container } = render(Reader, { props: { notebook: drafted(), shared: true } }); + await fireEvent.click(container.querySelector('[data-act="remix"]') as Element); + await tick(); + const edit = [...container.querySelectorAll('#topright button')].find( + (b) => b.textContent?.trim() === 'Edit', + ) as HTMLElement; + await fireEvent.click(edit); + await tick(); + expect(container.querySelector('.cardtools')).not.toBeNull(); // really in Edit + expect(container.querySelector('.draft-chip')).toBeNull(); + expect(container.querySelector('.drafts-bar')).toBeNull(); + }); +}); diff --git a/v2/src/lib/components/Reader.narrow.test.ts b/v2/src/lib/components/Reader.narrow.test.ts new file mode 100644 index 0000000..888fe46 --- /dev/null +++ b/v2/src/lib/components/Reader.narrow.test.ts @@ -0,0 +1,142 @@ +// Phones: a shared lesson opens with the side panel closed (it holds little for a student, and +// open it left a 73px lesson column at 390px), and app.css lays the Reader out for the narrow +// screen — but only the Reader, and only below 761px, so desktop and the authoring App keep theirs. +import { describe, it, expect, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +// @ts-expect-error -- node builtin, untyped in the browser-only tsconfig (test runs in vitest/node) +import { readFileSync } from 'node:fs'; +import Reader from './Reader.svelte'; +import { mode } from '../stores/mode'; +import type { Notebook } from '../types'; + +function nb(): Notebook { + return { + id: 'nb1', + name: 'Phone Deck', + createdAt: '2026-01-01', + updatedAt: '2026-01-01', + sections: [ + { + id: 's1', + notebookId: 'nb1', + name: 'One', + position: 0, + cards: [{ id: 'c1', sectionId: 's1', position: 0, w: 6, slots: [{ id: 'x', type: 'text', props: { text: 'hi' } }] }], + }, + ], + }; +} + +const realWidth = window.innerWidth; +function viewport(width: number) { + Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width }); +} + +afterEach(() => { + viewport(realWidth); + mode.set('edit'); + document.body.className = ''; + delete document.body.dataset.theme; +}); + +describe('Reader — the side panel on narrow screens', () => { + it.each([320, 390, 760])('starts collapsed at %ipx wide', async (w) => { + viewport(w); + const { container } = render(Reader, { props: { notebook: nb(), shared: true } }); + await tick(); + expect(document.body.classList.contains('side-collapsed')).toBe(true); + expect(document.getElementById('sidebump')?.getAttribute('title')).toBe('show the panel'); + expect(container.textContent).toContain('hi'); + }); + + it.each([761, 1024, 1280])('starts open at %ipx wide (desktop unchanged)', async (w) => { + viewport(w); + render(Reader, { props: { notebook: nb(), shared: true } }); + await tick(); + expect(document.body.classList.contains('side-collapsed')).toBe(false); + expect(document.getElementById('sidebump')?.getAttribute('title')).toBe('hide the panel'); + }); + + it('the bump still opens the panel on a phone', async () => { + viewport(390); + render(Reader, { props: { notebook: nb(), shared: true } }); + await tick(); + await fireEvent.click(document.getElementById('sidebump')!); + await tick(); + expect(document.body.classList.contains('side-collapsed')).toBe(false); + }); + + it('marks the body as the Reader while mounted, and clears it on unmount', async () => { + viewport(1280); + const { unmount } = render(Reader, { props: { notebook: nb(), shared: true } }); + await tick(); + expect(document.body.classList.contains('nb-reader')).toBe(true); + unmount(); + expect(document.body.classList.contains('nb-reader')).toBe(false); + }); +}); + +describe('app.css — the narrow-screen rules', () => { + const css: string = readFileSync('src/app.css', 'utf8'); + + /** Bodies of every `@media (max-width: 760px)` block (balanced braces). */ + function narrowBlocks(): string[] { + const out: string[] = []; + const re = /@media\s*\(\s*max-width:\s*760px\s*\)\s*\{/g; + for (let m = re.exec(css); m; m = re.exec(css)) { + let depth = 1; + let i = m.index + m[0].length; + const start = i; + while (depth > 0 && i < css.length) { + if (css[i] === '{') depth++; + else if (css[i] === '}') depth--; + i++; + } + out.push(css.slice(start, i - 1)); + } + return out; + } + + /** Top-level selectors of a block body, nested at-rules (e.g. @supports) unwrapped. */ + function selectors(body: string): string[] { + const flat = body.replace(/\/\*[\s\S]*?\*\//g, '').replace(/@supports[^{]*\{([\s\S]*?\})\s*\}/g, '$1'); + return [...flat.matchAll(/([^{}]+)\{[^{}]*\}/g)].flatMap((m) => m[1].split(',').map((s) => s.trim())); + } + + it('exists, and the 760px breakpoint matches the Reader’s collapse threshold', () => { + expect(narrowBlocks().length).toBeGreaterThan(0); + }); + + it('scopes every narrow rule to the Reader (body.nb-reader), so the App never changes', () => { + const sels = narrowBlocks().flatMap(selectors); + expect(sels.length).toBeGreaterThan(5); + for (const s of sels) expect(s, s).toMatch(/^body\.nb-reader\b/); + }); + + it('collapses card and slot widths to full width and overlays the open panel', () => { + const body = narrowBlocks().join('\n'); + expect(body).toMatch(/\.room-grid\s*>\s*\.furn\s*\{[^}]*flex-basis:\s*100%/); + expect(body).toMatch(/\.cardrow\s*>\s*\.cardslot\s*\{[^}]*flex-basis:\s*100%/); + expect(body).toMatch(/#side\s*\{[^}]*position:\s*absolute/); + expect(body).toMatch(/#top\s*\{[^}]*flex-wrap:\s*wrap/); + }); + + // A flex item's default min-width:auto is its min-content width: one long code line, URL or + // wide table made its card — and, through the section grid, every card in that section — wider + // than the phone, so the lesson scrolled sideways inside #stage (which the document-level + // scrollWidth check cannot see). Cards must stay at the screen width; wide content scrolls or + // wraps inside its own slot. + it('keeps wide content (long code lines, URLs, tables, display math) from widening a card', () => { + const body = narrowBlocks().join('\n'); + expect(body).toMatch(/\.rgwrap\s*>\s*\.room-grid\s*\{[^}]*min-width:\s*0/); + expect(body).toMatch(/\.room-grid\s*>\s*\.furn\s*\{[^}]*min-width:\s*0/); + expect(body).toMatch(/\.room-grid\s*>\s*\.furn\s*\{[^}]*overflow-wrap:\s*(?:anywhere|break-word)/); + // the coverage matrix: a 80px row header plus a ≥42px column per tag outgrows a phone at + // 5 tags (320px) or 7 (390px); it scrolls inside its own box rather than moving the lesson + for (const wide of ['.table-study', '.katex-display', '.mtx']) { + const re = new RegExp(`\\${wide}[^{}]*\\{[^}]*overflow-x:\\s*auto`); + expect(body, wide).toMatch(re); + } + }); +}); diff --git a/v2/src/lib/components/Reader.progress.test.ts b/v2/src/lib/components/Reader.progress.test.ts new file mode 100644 index 0000000..fc151b2 --- /dev/null +++ b/v2/src/lib/components/Reader.progress.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import Reader from './Reader.svelte'; +import { mode } from '../stores/mode'; +import { toastState } from '../toast.svelte'; +import { exportNotebook, importNotebook, type NotebookJSON } from '../json-io'; +import { loadProgress, readerStorageKey } from '../reader-store'; +import type { Notebook } from '../types'; + +// The shared file as the author exported it; every "open" re-imports it with fresh ids. +const PAYLOAD: NotebookJSON = exportNotebook({ + id: 'nb_author', + name: 'Shared Quiz', + createdAt: '', + updatedAt: '', + sections: [ + { + id: 's', + notebookId: 'nb_author', + name: 'Basics', + position: 0, + cards: [ + { + id: 'a', + sectionId: 's', + position: 0, + slots: [{ id: 'q', type: 'choice', props: { q: 'Pick A', options: ['A', 'B'], answer: [0] } }], + }, + { + id: 'b', + sectionId: 's', + position: 1, + slots: [{ id: 't', type: 'text-input', props: { placeholder: 'your answer' } }], + }, + ], + }, + ], +}); + +const KEY = readerStorageKey('nb_author'); +const openFile = (): Notebook => importNotebook(structuredClone(PAYLOAD)); + +function mountReader(over: Record = {}) { + const notebook = openFile(); + const initialState = loadProgress(KEY, notebook); + const r = render(Reader, { + props: { notebook, shared: true, storageKey: KEY, docId: 'nb_author', initialState, ...over }, + }); + return { ...r, notebook }; +} + +const flush = () => window.dispatchEvent(new Event('pagehide')); +const stored = () => localStorage.getItem(KEY); + +async function answerChoice(container: HTMLElement) { + await fireEvent.click(container.querySelector('.choice-study button.option') as Element); + await tick(); + await fireEvent.click(container.querySelector('.choice-study button.submit') as Element); + await tick(); +} + +async function typeInto(container: HTMLElement, value: string) { + const input = container.querySelector('.text-input-study input') as HTMLInputElement; + await fireEvent.input(input, { target: { value } }); + await tick(); +} + +afterEach(() => { + localStorage.clear(); + mode.set('edit'); + vi.restoreAllMocks(); +}); + +describe('Reader — remembers a student’s progress', () => { + it('saves interactions under stable keys and restores them on the next open', async () => { + const first = mountReader(); + await answerChoice(first.container); + await typeInto(first.container, 'mitochondria'); + flush(); + expect(stored()).toContain('mitochondria'); + expect(stored()).not.toContain(first.notebook.sections[0].cards[0].id); // ids never persist + first.unmount(); + + const second = mountReader(); + await tick(); + const input = second.container.querySelector('.text-input-study input') as HTMLInputElement; + expect(input.value).toBe('mitochondria'); + expect(second.container.querySelector('.choice-study')?.getAttribute('data-verdict')).toBe('correct'); + }); + + it('loads by itself when given only a storage key — never saving empty over stored progress', async () => { + const first = mountReader(); + await typeInto(first.container, 'kept'); + flush(); + first.unmount(); + + const { container } = render(Reader, { props: { notebook: openFile(), shared: true, storageKey: KEY } }); + await tick(); + expect((container.querySelector('.text-input-study input') as HTMLInputElement).value).toBe('kept'); + flush(); + expect(stored()).toContain('kept'); + }); + + it('saves on its own debounce without waiting for pagehide', async () => { + vi.useFakeTimers(); + try { + const { container } = mountReader(); + await typeInto(container, 'debounced'); + expect(stored()).toBeNull(); + vi.advanceTimersByTime(2000); + expect(stored()).toContain('debounced'); + } finally { + vi.useRealTimers(); + } + }); + + it('flushes when the tab is hidden', async () => { + const { container } = mountReader(); + await typeInto(container, 'hidden-flush'); + const vis = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden'); + document.dispatchEvent(new Event('visibilitychange')); + vis.mockRestore(); + expect(stored()).toContain('hidden-flush'); + }); + + it('stops persisting after Remix — the document has diverged', async () => { + const { container } = mountReader(); + await typeInto(container, 'before'); + await fireEvent.click(container.querySelector('[data-act="remix"]') as Element); + await tick(); + expect(stored()).toContain('before'); // pending work was flushed first + await typeInto(container, 'after'); + flush(); + expect(stored()).toContain('before'); + expect(stored()).not.toContain('after'); + }); + + it('does not persist without a storage key (plain mount)', async () => { + const { container } = render(Reader, { props: { notebook: openFile(), shared: true } }); + await typeInto(container, 'nowhere'); + flush(); + expect(localStorage.length).toBe(0); + expect(container.querySelector('[data-note="no-storage"]')).toBeNull(); + }); + + it('shows a quiet one-line note when this browser cannot keep progress', () => { + const notebook = openFile(); + const { container } = render(Reader, { + props: { + notebook, + shared: true, + storageKey: KEY, + initialState: { readerState: {}, annotations: {}, available: false }, + }, + }); + expect(container.querySelector('[data-note="no-storage"]')?.textContent).toContain( + 'Progress isn’t saved in this browser', + ); + }); + + it('shows the note when a save fails mid-session', async () => { + const { container } = mountReader(); + expect(container.querySelector('[data-note="no-storage"]')).toBeNull(); + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('denied', 'SecurityError'); + }); + await typeInto(container, 'x'); + flush(); + await tick(); + expect(container.querySelector('[data-note="no-storage"]')).not.toBeNull(); + }); + + it('Reset my progress clears stored and in-memory progress after confirming', async () => { + const { container } = mountReader(); + await typeInto(container, 'to be cleared'); + flush(); + expect(stored()).not.toBeNull(); + + await fireEvent.click(container.querySelector('[data-act="results"]') as Element); + await tick(); + const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false); + await fireEvent.click(container.querySelector('[data-act="reset-progress"]') as Element); + await tick(); + expect(confirm).toHaveBeenCalledOnce(); + expect(stored()).not.toBeNull(); + + confirm.mockReturnValueOnce(true); + await fireEvent.click(container.querySelector('[data-act="reset-progress"]') as Element); + await tick(); + flush(); + expect(stored()).toBeNull(); + expect((container.querySelector('.text-input-study input') as HTMLInputElement).value).toBe(''); + expect(toastState.message).toContain('reset'); + }); +}); + +describe('Reader — results and credit', () => { + it('opens My results from the shared chrome, reflecting live progress', async () => { + const { container } = mountReader(); + await answerChoice(container); + const btn = container.querySelector('#topright [data-act="results"]') as HTMLElement; + expect(btn.textContent).toContain('My results'); + await fireEvent.click(btn); + await tick(); + const dialog = container.querySelector('[role="dialog"]') as HTMLElement; + expect(dialog.textContent).toContain('1 of 2 cards done'); + expect(dialog.textContent).toContain('1 of 1 answered correct'); + await fireEvent.click(dialog.querySelector('[data-act="close-results"]') as Element); + await tick(); + expect(container.querySelector('[role="dialog"]')).toBeNull(); + }); + + it('keeps the locked topbar free of author chrome', () => { + const { container } = mountReader(); + const right = container.querySelector('#topright') as HTMLElement; + expect(right.textContent).not.toContain('Edit'); + expect(right.textContent).not.toContain('Study'); + }); + + it('credits NoteBuilder with a small external link', () => { + const { container } = mountReader(); + const link = [...container.querySelectorAll('a')].find((a) => a.textContent?.includes('Made with NoteBuilder')); + expect(link).toBeDefined(); + expect(link!.getAttribute('href')).toBe('https://github.com/YuZh98/notebuilder'); + expect(link!.getAttribute('target')).toBe('_blank'); + expect(link!.getAttribute('rel')).toBe('noopener'); + }); +}); diff --git a/v2/src/lib/components/Reader.results-keys.test.ts b/v2/src/lib/components/Reader.results-keys.test.ts new file mode 100644 index 0000000..019b660 --- /dev/null +++ b/v2/src/lib/components/Reader.results-keys.test.ts @@ -0,0 +1,173 @@ +/** + * "My results" is a modal dialog: while it is open the study keys belong to it, not to the card + * the cursor was on behind it. Before, a digit or Enter pressed in the dialog bubbled to the + * Reader's window handler, answered the focused quiz card and saved that answer. + */ +import { describe, it, expect, beforeAll, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import Reader from './Reader.svelte'; +import { mode } from '../stores/mode'; +import { resetSession } from '../session.svelte'; +import { readerStorageKey } from '../reader-store'; +import type { Notebook } from '../types'; + +beforeAll(() => { + // jsdom implements no layout, so the cursor's scrollIntoView needs a stub. + Element.prototype.scrollIntoView = () => {}; +}); + +afterEach(() => { + localStorage.clear(); + mode.set('edit'); + resetSession(); +}); + +function deck(): Notebook { + return { + id: 'nb_modal', + name: 'Modal Deck', + createdAt: '2026-01-01', + updatedAt: '2026-01-01', + sections: [ + { + id: 's1', + notebookId: 'nb_modal', + name: 'Drill', + position: 0, + cards: [ + { + id: 'q', + sectionId: 's1', + position: 0, + slots: [ + { id: 'q-choice', type: 'choice', props: { q: 'pick', options: ['alpha', 'beta', 'gamma'], answer: [1] } }, + ], + }, + { + id: 'fc', + sectionId: 's1', + position: 1, + verbs: { flip: true }, + slots: [{ id: 'fc-front', type: 'text', props: { text: 'front' } }], + back: [{ id: 'fc-back', type: 'text', props: { text: 'back' } }], + }, + ], + }, + ], + }; +} + +const KEY = readerStorageKey('nb_modal'); + +async function press(key: string, target: Element | Window = window) { + await fireEvent.keyDown(target, { key, bubbles: true }); + await tick(); +} + +const focused = (container: HTMLElement) => + container.querySelector('.furn.kfocus')?.getAttribute('data-card') ?? null; +const selectedOptions = (container: HTMLElement) => + container.querySelectorAll('.furn[data-card="q"] .option.selected').length; +/** Picked, or graded after a submit: any trace of an answer on the quiz card. */ +const answerMarks = (container: HTMLElement) => + container.querySelectorAll( + '.furn[data-card="q"] .option:is(.selected, .correct, .incorrect, .missed)', + ).length; +const flipped = (container: HTMLElement) => + container.querySelector('.furn[data-card="fc"] .fc')?.classList.contains('flipped') ?? false; +const dialog = () => document.querySelector('.results-modal [role="dialog"]'); +const helpOverlay = () => document.querySelector('[aria-label="Keyboard shortcuts"]'); + +async function openResults(container: HTMLElement) { + await fireEvent.click(container.querySelector('[data-act="results"]') as Element); + await tick(); + expect(dialog()).not.toBeNull(); +} + +async function closeResults() { + await fireEvent.click(document.querySelector('[data-act="close-results"]') as Element); + await tick(); + expect(dialog()).toBeNull(); +} + +describe('Reader — the open results dialog owns the keyboard', () => { + it('digits, Enter, x, j/k and ? do nothing to the focused card behind it', async () => { + const { container } = render(Reader, { + props: { notebook: deck(), shared: true, storageKey: KEY, docId: 'nb_modal' }, + }); + await tick(); + await press('j'); + expect(focused(container)).toBe('q'); + + await openResults(container); + // Keys typed with the dialog focused (it focuses itself on open) bubble to the window too. + for (const k of ['2', 'Enter', 'x', 'j', 'k', '?']) await press(k, dialog()!); + for (const k of ['1', 'Enter', 'j', '?']) await press(k); + + expect(answerMarks(container)).toBe(0); + expect(focused(container)).toBe('q'); + expect(helpOverlay()).toBeNull(); + expect(dialog()).not.toBeNull(); + + // Nothing reached the progress layer either: no answer was saved behind the dialog. + window.dispatchEvent(new Event('pagehide')); + expect(localStorage.getItem(KEY)).toBeNull(); + + // Control: with the dialog closed, the very same key answers the card. + await closeResults(); + await press('2'); + expect(selectedOptions(container)).toBe(1); + }); + + it('Space and f do not flip the focused flashcard behind it', async () => { + const { container } = render(Reader, { props: { notebook: deck(), shared: true } }); + await tick(); + await press('j'); + await press('j'); + expect(focused(container)).toBe('fc'); + + // One key at a time: two flips would cancel out and hide a leak. + await openResults(container); + await press(' ', dialog()!); + expect(flipped(container)).toBe(false); + await press('f'); + expect(flipped(container)).toBe(false); + + await closeResults(); + await press('f'); + expect(flipped(container)).toBe(true); + }); + + it('Escape closes it even when focus has left the dialog, and touches nothing behind it', async () => { + const { container } = render(Reader, { props: { notebook: deck(), shared: true } }); + await tick(); + await press('j'); + expect(focused(container)).toBe('q'); + + await openResults(container); + // Focus can drop to with the dialog still open (the copy fallback selects, then + // removes, a hidden textarea); the dialog's own Escape handler then never sees the key. + (document.activeElement as HTMLElement | null)?.blur(); + expect(document.activeElement).toBe(document.body); + await press('Escape', document.body); + + expect(dialog()).toBeNull(); + expect(focused(container)).toBe('q'); // the cursor behind it was not cleared by that Escape + }); + + it('takes the shell behind it out of the focus order, and gives it back on close', async () => { + const { container } = render(Reader, { props: { notebook: deck(), shared: true } }); + await tick(); + const inert = () => + ['#top', '#main', '#sidebump'].map((s) => document.querySelector(s)?.hasAttribute('inert')); + expect(inert()).toEqual([false, false, false]); + + await openResults(container); + expect(inert()).toEqual([true, true, true]); + expect(document.querySelector('.results-modal')?.hasAttribute('inert')).toBe(false); + + await closeResults(); + expect(inert()).toEqual([false, false, false]); + }); +}); diff --git a/v2/src/lib/components/Reader.svelte b/v2/src/lib/components/Reader.svelte index bb2b6ce..903b798 100644 --- a/v2/src/lib/components/Reader.svelte +++ b/v2/src/lib/components/Reader.svelte @@ -11,6 +11,7 @@ import Toast from './Toast.svelte'; import Dustbin from './Dustbin.svelte'; import CoverageMatrix from './CoverageMatrix.svelte'; + import ResultsModal from './ResultsModal.svelte'; import { computeProgress, progressScopeCards, type ProgressScope } from '../progress'; import { addAnnotation, removeAnnotation, annotationsFor, type AnnotationMap } from '../annotations'; import { @@ -35,10 +36,15 @@ canRedo, type HistSnapshot, } from '../history.svelte'; - import { handleAppKey, type KeyCtx } from '../keyboard'; + import { handleAppKey, isFieldTarget, isInteractiveTarget, type KeyCtx } from '../keyboard'; + import { studyCards, stepFocus, studyKeyEffect, studySurfaces, NO_SURFACES } from '../study-keys'; + import ShortcutHelp from './ShortcutHelp.svelte'; import { installEditCoalescing } from '../history-focus'; + import { revealCard } from '../card-reveal'; + import { setAppInert } from '../modal-inert'; import { exportNotebook, importNotebook, validateNotebook, type NotebookJSON } from '../json-io'; - import { clampSideW } from '../shell'; + import { sideWidthAt } from '../shell'; + import { applyZoom, effectiveZoom, nextZoom, zoomLabel } from '../zoom'; import { addSection, addChapter, @@ -53,7 +59,7 @@ deleteSlot, reorderSectionsByValueIndex, } from '../notebook-ops'; - import { session, shuffleSection, clearShuffle } from '../session.svelte'; + import { session, sessionView, shuffleSection, clearSectionView } from '../session.svelte'; import { applyTag, removeTag, renameTag, deleteTag, tagUsage, createTag, setCardTags as setCardTagsOp } from '../tags'; import { stateLayerFor } from '../slots/registry'; import type { Scope } from '../variable-graph'; @@ -63,21 +69,48 @@ import { startEdgeResize } from '../drag/resize'; import { startPointerDrag } from '../drag/engine'; import { makeNotebookDropCallbacks } from '../drag/notebook-drop'; + import { createProgressStore, installFlushOnHide, loadProgress, type LoadedProgress } from '../reader-store'; let { notebook: initial, shared: sharedInit, initialTheme, - }: { notebook: Notebook; shared: boolean; initialTheme?: string } = $props(); - - // The document lives entirely in memory here — no db, no localStorage. A reload reopens the file. + initialState, + storageKey, + docId = '', + }: { + notebook: Notebook; + shared: boolean; + initialTheme?: string; + /** Progress restored by reader-main before mount (reader-store's synchronous load). */ + initialState?: LoadedProgress; + /** localStorage key this file's progress persists under; absent = keep nothing. */ + storageKey?: string; + /** Document identity stamped on results exports. */ + docId?: string; + } = $props(); + + // The document lives entirely in memory here — no db, and it never touches localStorage: a + // reload reopens the file. Only the reader/progress layer persists (reader-store), and only + // while the file is still the shared original — Remix or Import diverges it and stops saving. let notebook: Notebook = $state(initial); // `shared` locks the file to reading; Remix (D10) unlocks the full author chrome in-memory. let shared = $state(sharedInit); let cardTypes: CardType[] = $state([...builtinCardTypes]); - let readerState: Record>> = $state({}); - let annotations: AnnotationMap = $state({}); + // Persist only the locked original. reader-main loads before mount; loading here when it didn't + // keeps a bare storageKey from ever saving an empty state over progress already stored. + const persist = !!storageKey && sharedInit; + const boot: LoadedProgress | undefined = + initialState ?? (persist ? loadProgress(storageKey!, initial) : undefined); + let readerState: Record>> = $state(boot?.readerState ?? {}); + let annotations: AnnotationMap = $state(boot?.annotations ?? {}); + let storageOk = $state(boot?.available !== false); + let resultsOpen = $state(false); + // Keys are fixed from the pristine notebook as opened, before any in-session edit. + const progressStore = persist + ? createProgressStore({ key: storageKey!, notebook: initial, initial: boot, onStatus: (ok) => (storageOk = ok) }) + : null; let notesFor: string | null = $state(null); let galleryFor: string | null = $state(null); @@ -85,13 +118,21 @@ let openTheme = $state(false); let sideW = $state(312); - let sideCollapsed = $state(false); + // Phones open with the panel closed: it holds little for a student, and open it would squeeze + // the lesson to a sliver. Same threshold as app.css's `@media (max-width: 760px)` Reader rules, + // under which an opened panel overlays the lesson instead of narrowing it. + const NARROW_MAX_PX = 760; + let sideCollapsed = $state(typeof window !== 'undefined' && window.innerWidth <= NARROW_MAX_PX); let selSection: string | null = $state(null); let selCard: string | null = $state(null); let selProd: string | null = $state(null); let selVariety: Variety | null = $state(null); + // Study cursor + its shortcut overlay: session-transient, exactly as in the app. + let studyFocus: string | null = $state(null); + let helpOpen = $state(false); + let mtxRow: MatrixAxis | null = $state(null); let mtxCol: MatrixAxis | null = $state(null); let mtxCells: string[] = $state([]); @@ -138,17 +179,82 @@ // A shared file always opens locked into Study; Remix later unlocks the mode toggle. mode.set('study'); applyTheme(themeId); + // Scopes app.css's narrow-screen layout to the Reader; the authoring App never gets it. + document.body.classList.add('nb-reader'); // Arm in-place text edits for undo (v1 parity) — Remix unlocks editing but keeps this file's // history; without it, post-Remix text-slot edits would silently escape the undo stack. const uninstallEditCoalescing = installEditCoalescing(); window.addEventListener('keydown', handleKey); + // pagehide / tab-hidden are the last reliable moments to land a pending save. + const uninstallFlush = installFlushOnHide(() => progressStore?.flush()); return () => { window.removeEventListener('keydown', handleKey); uninstallEditCoalescing(); + uninstallFlush(); + progressStore?.flush(); delete document.body.dataset.theme; + document.body.classList.remove('nb-reader'); }; }); + // Debounced save of the reader layer (the store strips presentation and skips no-op writes). + $effect(() => { + const state = $state.snapshot(readerState) as typeof readerState; + const notes = $state.snapshot(annotations) as AnnotationMap; + if (shared) progressStore?.schedule(state, notes); + }); + + // Reading this derived is what arms the effect: a mode switch or an import drops the cursor. + const studySession = $derived(`${$mode}/${notebook.id}`); + $effect(() => { + if (studySession) { + studyFocus = null; + helpOpen = false; + } + }); + + // The overlays are modal to focus as well as to keys: without this Tab still reaches the chrome + // behind them and Enter activates whatever it lands on. + $effect(() => { + setAppInert(helpOpen || resultsOpen); + return () => setAppInert(false); + }); + + // The cards the Study grid is rendering right now, in render order — the cursor's whole world. + const studyOrderIds = $derived( + $mode === 'study' ? studyCards(notebook, (s) => sessionView(s.id), visibleCardIds) : [], + ); + + // A filter, a search, a collapse or an archive swap can pull the focused card off the page under + // the cursor; when that happens the cursor goes with it rather than acting on what nobody sees. + $effect(() => { + if (studyFocus !== null && !studyOrderIds.includes(studyFocus)) studyFocus = null; + }); + + /** The focused card — null unless the cursor is on a card the reader can actually see. */ + function focusedStudyCard(): Card | null { + if (!studyFocus || !studyOrderIds.includes(studyFocus)) return null; + return findCard(notebook, studyFocus) ?? null; + } + + function moveStudyFocus(delta: 1 | -1) { + const next = stepFocus(studyOrderIds, studyFocus, delta); + if (!next) return; + studyFocus = next; + // 'center', not 'nearest': nearest parks the card flush against the viewport edge, where the + // ring is clipped and the pinned hint sits on top of it. + document.querySelector(`.furn[data-card="${next}"]`)?.scrollIntoView({ block: 'center' }); + } + + // Card keys write through the same reader-state path as a click on the slot itself. + function applyStudyKey(key: string) { + const card = focusedStudyCard(); + if (!card) return; + const live = session.live[card.id] ?? {}; + const effect = studyKeyEffect(key, card, readerState[card.id] ?? {}, live); + if (effect) onSlotState(card, effect.slotId, effect.next); + } + function sectionCardsOf(cardId: string | null): string[] { if (!cardId) return []; for (const s of notebook.sections) { @@ -157,12 +263,20 @@ return []; } + let zoomLevel = 1; + // Reader keyboard map: the same pure dispatcher as App, in a locked-into-house context. // Mode toggle and undo/redo are meaningful only after Remix, so they gate on `!shared`. function handleKey(e: KeyboardEvent) { + // The results dialog owns the keyboard: keys pressed in it bubble here, and must not answer, + // flip or move the card the cursor was on behind it. Its own handler closes it on an Escape + // from inside; one that reaches us came from (focus left the dialog), so close it here. + if (resultsOpen) { + if (e.key === 'Escape') resultsOpen = false; + return; + } const el = e.target as HTMLElement | null; - const inField = - !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable); + const inField = isFieldTarget(el); const ctx: KeyCtx = { inField, singleLineField: false, @@ -174,6 +288,17 @@ selProd, sectionIds: notebook.sections.filter((s) => s.kind !== 'divider').map((s) => s.id), cardIdsOfSelectedSection: sectionCardsOf(selCard), + studyFocus, + // Called only for a card key on a focused card: it builds the card's scope, which + // every keystroke typed into a field would otherwise pay for. + focusedSurfaces: () => { + const card = focusedStudyCard(); + return card + ? studySurfaces(card, readerState[card.id] ?? {}, session.live[card.id] ?? {}) + : NO_SURFACES; + }, + targetInteractive: isInteractiveTarget(el), + helpOpen, }; const action = handleAppKey(e, ctx); if (!action) return; @@ -217,6 +342,29 @@ case 'blur-single-line': el?.blur(); break; + // The action preventDefaults the browser's own zoom, so this file has to replace it. + case 'zoom': + zoomLevel = nextZoom(zoomLevel, action.delta); + applyZoom(zoomLevel); + toast(zoomLabel(zoomLevel)); + break; + case 'study-focus-step': + moveStudyFocus(action.delta); + break; + case 'study-focus-clear': + studyFocus = null; + break; + case 'study-flip': + case 'study-submit': + case 'study-tick': + applyStudyKey(e.key); + break; + case 'study-choice': + applyStudyKey(String(action.digit)); + break; + case 'study-help': + helpOpen = !helpOpen; + break; } } @@ -280,6 +428,7 @@ toast(`Invalid notebook file:\n${errors.join('\n')}`, 4000); return; } + progressStore?.stop(); // a different document now — its progress isn't this file's notebook = importNotebook(json as NotebookJSON); selCard = null; selSection = null; @@ -296,10 +445,25 @@ // D10 Remix: unlock authoring in memory. Edits never touch disk — a reload reopens the original. function remix() { + // Land what the student already did, then stop: edits would drift the stable card keys. + progressStore?.stop(); shared = false; toast('Editing unlocked — changes stay in this file (a reload reopens the original)'); } + // Start over: forget this file's saved progress here and in memory (notes included). + function resetProgress() { + const ok = window.confirm( + 'Reset your progress in this notebook?\nYour answers, checkmarks and notes in this browser will be cleared.', + ); + if (!ok) return; + progressStore?.reset(); + readerState = {}; + annotations = {}; + notesFor = null; + toast('your progress was reset'); + } + function setTheme(id: ThemeId) { openTheme = false; themeId = id; @@ -318,11 +482,11 @@ e, (dx) => { if (Math.abs(dx) > 4) moved = true; - if (moved && !sideCollapsed) sideW = clampSideW(startX + dx); + if (moved && !sideCollapsed) sideW = sideWidthAt(startX + dx, effectiveZoom()); }, (mv) => { if (mv === null) sideW = startW; - else if (moved && !sideCollapsed) sideW = clampSideW(mv.clientX); + else if (moved && !sideCollapsed) sideW = sideWidthAt(mv.clientX, effectiveZoom()); else toggleSide(); }, ); @@ -462,8 +626,8 @@ toast('flipped all'); } else if (key === 'reset') { readerState = resetSectionState(section, readerState); - clearShuffle(section.id); - toast('reset — flips & answers cleared (pins and archive kept)'); + clearSectionView(section.id); + toast('reset — flips, answers & search cleared (pins and archive kept)'); } } @@ -569,8 +733,10 @@ draft[String(i)] ? { ...t, props: { ...t.props, ...draft[String(i)] } } : t, ), }; - target.cards.push(placeType(drafted, target.id, target.cards.length, variety ?? undefined)); - toast(`placed "${ct.name}"`); + const placed = placeType(drafted, target.id, target.cards.length, variety ?? undefined); + target.cards.push(placed); + toast(`placed "${ct.name}" in ${target.name}`); + void revealCard(placed.id); } function stampFromGallery(sectionId: string, ct: CardType) { @@ -648,6 +814,15 @@
{#if shared} + {#if progressStore && !storageOk} + Progress isn’t saved in this browser + {/if} + {/if} - + - + togglePinCard(card)} onarchive={() => toggleArchiveCard(section, card)} + onreviewed={void 0} + kfocus={studyFocus === card.id} /> {/snippet} @@ -770,7 +949,12 @@ {#snippet stageFooter()} {#if $mode === 'edit'} + {:else} +
⌨ j/k move · space flip · 1-9 answer · ? help
{/if} + {/snippet}
@@ -834,6 +1018,20 @@ onclick={toggleSide} >{sideCollapsed ? '›' : '‹'} +{#if resultsOpen} + (resultsOpen = false)} + onreset={shared ? resetProgress : undefined} + /> +{/if} + +{#if helpOpen} + (helpOpen = false)} /> +{/if} + @@ -841,24 +1039,24 @@ diff --git a/v2/src/lib/components/Reader.test.ts b/v2/src/lib/components/Reader.test.ts index e6ec567..5026add 100644 --- a/v2/src/lib/components/Reader.test.ts +++ b/v2/src/lib/components/Reader.test.ts @@ -29,6 +29,11 @@ afterEach(() => { delete document.body.dataset.theme; }); +const sectionNames = (c: HTMLElement) => + [...c.querySelectorAll('.room[data-section] input.section-name')].map( + (i) => i.value, + ); + async function remixToEdit(container: HTMLElement) { await fireEvent.click(container.querySelector('[data-act="remix"]') as Element); await tick(); @@ -123,26 +128,33 @@ describe('Reader — review fixes', () => { ) as HTMLElement; await fireEvent.click(addSectionBtn); await tick(); + expect(sectionNames(container)).toEqual(['name-s1', 'Section 2']); window.dispatchEvent(new KeyboardEvent('keydown', { key: 'z', metaKey: true })); await tick(); expect(toastState.message).toBe('undo'); + expect(sectionNames(container), 'the added section must be gone again').toEqual(['name-s1']); }); it('post-Remix text edits in a data-history region arm an undo step', async () => { const { container } = render(Reader, { props: { notebook: nb(), shared: true } }); await remixToEdit(container); - // A rendered author field (the section name) lives inside a data-history="edit" region. - const field = container.querySelector('[data-history="edit"]') as HTMLElement; + // A rendered author field (the notebook name) lives inside a data-history="edit" region. + const field = container.querySelector('[data-history="edit"]') as HTMLInputElement; expect(field).not.toBeNull(); + expect(field.value).toBe('Shared Deck'); + field.value = 'Renamed'; await fireEvent.input(field); + await fireEvent.change(field); await tick(); + expect(container.querySelector('.brand-nb')?.textContent).toContain('📓 Renamed'); // With installEditCoalescing wired into the Reader, the input armed history: Cmd+Z now undoes. window.dispatchEvent(new KeyboardEvent('keydown', { key: 'z', metaKey: true })); await tick(); expect(toastState.message).toBe('undo'); + expect(container.querySelector('.brand-nb')?.textContent).toContain('📓 Shared Deck'); }); it('applies an initialTheme at boot', async () => { diff --git a/v2/src/lib/components/ResultsModal.svelte b/v2/src/lib/components/ResultsModal.svelte new file mode 100644 index 0000000..563f7b5 --- /dev/null +++ b/v2/src/lib/components/ResultsModal.svelte @@ -0,0 +1,234 @@ + + + + + + diff --git a/v2/src/lib/components/ResultsModal.test.ts b/v2/src/lib/components/ResultsModal.test.ts new file mode 100644 index 0000000..b966fa9 --- /dev/null +++ b/v2/src/lib/components/ResultsModal.test.ts @@ -0,0 +1,177 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, fireEvent } from '@testing-library/svelte'; +import { tick } from 'svelte'; +import ResultsModal from './ResultsModal.svelte'; +import { copyText } from '../clipboard'; +import type { Notebook } from '../types'; + +// A pass-through spy: the dialog must copy through the shared helper, not a private copy of it. +vi.mock('../clipboard', async (importOriginal) => { + const actual = await importOriginal(); + return { copyText: vi.fn(actual.copyText) }; +}); + +function nb(): Notebook { + return { + id: 'nb_x', + name: 'Quiz: Cells', + createdAt: '', + updatedAt: '', + sections: [ + { + id: 's1', + notebookId: 'nb_x', + name: 'Cells', + position: 0, + cards: [ + { id: 'c1', sectionId: 's1', position: 0, slots: [{ id: 'q1', type: 'choice', props: { options: ['a', 'b'], answer: [0] } }] }, + { id: 'c2', sectionId: 's1', position: 1, slots: [{ id: 'q2', type: 'choice', props: { options: ['a', 'b'], answer: [1] } }] }, + ], + }, + ], + }; +} + +const state = { c1: { q1: { selected: [0], submitted: true } } }; + +function setup(extra: Record = {}) { + const onclose = vi.fn(); + const r = render(ResultsModal, { props: { notebook: nb(), readerState: state, docId: 'nb_x', onclose, ...extra } }); + return { ...r, onclose }; +} + +function setClipboard(value: unknown) { + Object.defineProperty(navigator, 'clipboard', { value, configurable: true }); +} + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + delete (navigator as { clipboard?: unknown }).clipboard; + delete (document as { execCommand?: unknown }).execCommand; // drop the own-property stub +}); + +describe('ResultsModal', () => { + it('summarises progress and graded answers', () => { + const { container } = setup(); + const text = container.textContent ?? ''; + expect(container.querySelector('[role="dialog"]')).not.toBeNull(); + expect(text).toContain('1 of 2 cards done'); + expect(text).toContain('1 of 1 answered correct'); + expect(text).toContain('Cells'); + }); + + it('shows practice tries on their own row, apart from the graded questions', () => { + const book = nb(); + book.sections[0].cards.push({ + id: 'c3', + sectionId: 's1', + position: 2, + slots: [{ id: 'p3', type: 'problem', props: { prompt: 'x', params: [], answer: '6', tol: 0, need: 1 } }], + }); + const { container } = setup({ notebook: book, readerState: { ...state, c3: { p3: { seed: 1, correct: 2, attempts: 5 } } } }); + const graded = container.querySelector('[data-results="graded"]')?.textContent ?? ''; + expect(graded).toContain('2 of 2 answered correct'); + expect(graded).toContain('3 questions'); + expect(container.querySelector('[data-results="practice"]')?.textContent).toContain('2 correct in 5 tries'); + }); + + it('has no practice row when nothing was practised', () => { + expect(setup().container.querySelector('[data-results="practice"]')).toBeNull(); + }); + + it('copies the plain-text summary, including the optional name', async () => { + const writeText = vi.fn().mockResolvedValue(undefined); + setClipboard({ writeText }); + const { container } = setup(); + const name = container.querySelector('input[data-results="name"]') as HTMLInputElement; + await fireEvent.input(name, { target: { value: 'Ada' } }); + await fireEvent.click(container.querySelector('[data-act="copy-results"]') as Element); + await tick(); + expect(writeText).toHaveBeenCalledOnce(); + const copied = writeText.mock.calls[0][0] as string; + expect(copied).toContain('Student: Ada'); + expect(copied).toContain('Quiz: Cells'); + }); + + it('copies through the shared clipboard helper', async () => { + setClipboard({ writeText: vi.fn().mockResolvedValue(undefined) }); + const { container } = setup(); + await fireEvent.click(container.querySelector('[data-act="copy-results"]') as Element); + await tick(); + expect(vi.mocked(copyText)).toHaveBeenCalledOnce(); + expect(vi.mocked(copyText).mock.calls[0][0]).toContain('Quiz: Cells'); + }); + + it('falls back to showing selectable text when the clipboard is unavailable', async () => { + setClipboard(undefined); + document.execCommand = vi.fn(() => false); + const { container } = setup(); + await fireEvent.click(container.querySelector('[data-act="copy-results"]') as Element); + await tick(); + await tick(); + const fallback = container.querySelector('textarea[data-results="text"]') as HTMLTextAreaElement; + expect(fallback).not.toBeNull(); + expect(fallback.value).toContain('Quiz: Cells'); + // the selectable text follows later edits (e.g. typing the name after a failed copy) + await fireEvent.input(container.querySelector('input[data-results="name"]') as Element, { target: { value: 'Bo' } }); + expect(fallback.value).toContain('Student: Bo'); + }); + + it('downloads a .json file via a blob — no network', async () => { + const parts: BlobPart[][] = []; + const RealBlob = globalThis.Blob; + vi.stubGlobal( + 'Blob', + class extends RealBlob { + constructor(p: BlobPart[] = [], o?: BlobPropertyBag) { + super(p, o); + parts.push(p); + } + }, + ); + URL.createObjectURL = () => 'blob:results'; + URL.revokeObjectURL = () => {}; + let downloadName = ''; + const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) { + downloadName = this.download; + }); + const fetchSpy = vi.fn(); + vi.stubGlobal('fetch', fetchSpy); + + const { container } = setup(); + await fireEvent.input(container.querySelector('input[data-results="name"]') as Element, { + target: { value: 'Ada / L' }, + }); + await fireEvent.click(container.querySelector('[data-act="download-results"]') as Element); + + expect(click).toHaveBeenCalledOnce(); + expect(fetchSpy).not.toHaveBeenCalled(); + expect(downloadName).toMatch(/\.json$/); + expect(downloadName).not.toContain('/'); + expect(downloadName).not.toContain(':'); + const json = JSON.parse(parts[0][0] as string); + expect(json.format).toBe('notebuilder-results'); + expect(json.student).toBe('Ada / L'); + expect(json.docId).toBe('nb_x'); + expect(json.graded).toEqual({ correct: 1, answered: 1, items: 2 }); + }); + + it('closes from the close button, the backdrop and Escape', async () => { + const { container, onclose } = setup(); + await fireEvent.click(container.querySelector('[data-act="close-results"]') as Element); + expect(onclose).toHaveBeenCalledTimes(1); + await fireEvent.click(container.querySelector('.results-modal') as Element); + expect(onclose).toHaveBeenCalledTimes(2); + await fireEvent.keyDown(container.querySelector('[role="dialog"]') as Element, { key: 'Escape' }); + expect(onclose).toHaveBeenCalledTimes(3); + }); + + it('offers Reset my progress only when given a handler', async () => { + expect(setup().container.querySelector('[data-act="reset-progress"]')).toBeNull(); + const onreset = vi.fn(); + const { container } = setup({ onreset }); + await fireEvent.click(container.querySelector('[data-act="reset-progress"]') as Element); + expect(onreset).toHaveBeenCalledOnce(); + }); +}); diff --git a/v2/src/lib/components/SealModal.svelte b/v2/src/lib/components/SealModal.svelte index bd5d551..ee72644 100644 --- a/v2/src/lib/components/SealModal.svelte +++ b/v2/src/lib/components/SealModal.svelte @@ -104,9 +104,9 @@