Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

feat: verified citation links and item-bank choice questions

JEM1e8f7f39aa96
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index fecff1e..d10b663 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -17,6 +17,8 @@ Follow the pipeline forward, entering at the requested stage for existing work.
books/<book>/
book.pdf, sections.json source and page map (private)
pages/chNN/text.md, *.png extracted reference material (private)
+ refs.json cited works with verified DOI/ISBN/URL (scripts/refs.py)
+ items/chNN.items.json optional choice-question bank per chapter (scripts/items.py)
style.json the agreed style every chapter anchors to (assets/templates/style.json)
chapters.md chapter map and status
chapters/chNN.md storyboard, errata, feedback
@@ -26,14 +28,16 @@ content/<book>/chNN/ narration.<lang>.json and TTS cache
tools/<book>/ tests and evidence scripts
site/<book>/ the static book (only this is delivered)
index.html, unit-art.js cover + contents, unit sketches
+ refs.js the cited works, built by scripts/refs.py
lib/engine.*, volume.*, the engine (player, cover/contents, unit headers), copied into the book by
contents.*, units.* scripts/engine.py
lib/book.css this book's engine settings and style overrides
lib/*.js, img/ the book's element library and images
chNN/index.html, audio/<lang>/ a lesson, its beat MP3s + timings.js
+ chNN/items.js built choice questions (scripts/items.py), when the chapter has a bank
```
-`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access (or Kokoro, local: `uv run --python 3.12 --with kokoro`) and Playwright browsers (`uv run --with playwright playwright install chromium firefox`). Preview: `python3 SKILL/scripts/serve.py 8765 site` (no browser caching).
+`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access (or Kokoro, local: `uv run --python 3.12 --with kokoro`) network access to api.crossref.org and openlibrary.org for references, and Playwright browsers (`uv run --with playwright playwright install chromium firefox`). Preview: `python3 SKILL/scripts/serve.py 8765 site` (no browser caching).
## Pipeline
@@ -47,10 +51,10 @@ Start with intake whenever `books/<book>/style.json` does not exist yet; reuse a
## Chapter loop
-1. **Read** this chapter's `pages/chNN/text.md`; render pages with `split_pages.py … --only chNN` when diagrams or missing text need images. Choose the ideas, examples and sections to teach.
+1. **Read** this chapter's `pages/chNN/text.md`; render pages with `split_pages.py … --only chNN` when diagrams or missing text need images. Choose the ideas, examples and sections to teach. When the chapter names other works (an author–year, a study, a book), add them to `refs.json` and run `refs.py lookup`, `verify` and `build` ([authoring.md](references/authoring.md#citations)).
2. **Beats and narration**: list beats in `chapters/chNN.md` with what each says and which word triggers which action ([authoring.md](references/authoring.md)). Write `content/<book>/chNN/narration.<lang>.json`, then `uv run --with edge-tts SKILL/scripts/tts.py content/<book>/chNN/narration.<lang>.json site/<book>/chNN/audio/<lang>` (for `"engine": "kokoro"`: `uv run --python 3.12 --with kokoro …`).
3. **Storyboard, layout first**: in the real page, place everything for one to three key moments per beat, real elements at their real sizes, no motion yet. Capture them into one sheet with `strip.py` and give each frame one line: what it says and where the eye goes. That sheet is the storyboard. Note what the chapter needs beyond the library: draw it, or add it to the image requests.
-4. **Motion**: add the motion, the camera and the questions; API and replay invariants are in [engine.md](references/engine.md).
+4. **Motion**: add the motion, the camera and the questions (choice questions may come from an item bank via `mcq()`, [authoring.md](references/authoring.md#choice-questions-from-an-item-bank)); API and replay invariants are in [engine.md](references/engine.md).
5. **Delivery pass**: watch your output in motion and judge it as a viewer would, against the storyboard; then run the checks in [review.md](references/review.md). Correct what you find, recheck, deliver; report unresolved problems.
6. **Register**: add the chapter to the contents (`units` in `Contents.book` in `index.html`), set the previous chapter's `CHAPTER.next`, update `chapters.md` and `chapters/chNN.md`. Promote new shared decisions and recurring elements to `style.json` and the library. The coordinator owns this step when using subagents.
diff --git a/.claude/skills/papermorph/assets/templates/book.html b/.claude/skills/papermorph/assets/templates/book.html
index 82a6e0d..e59a7b5 100644
--- a/.claude/skills/papermorph/assets/templates/book.html
+++ b/.claude/skills/papermorph/assets/templates/book.html
@@ -11,6 +11,7 @@
<script src="lib/units.js"></script>
<script src="lib/contents.js"></script>
<script src="unit-art.js"></script>
+<script src="refs.js"></script><!-- the book's cited works, built by the skill's scripts/refs.py -->
<link rel="expect" href="#ch01" blocking="render">
<!-- The book's own look, if it differs from the chalkboard: override the tokens of lib/contents.css here, e.g.
<style>
@@ -42,6 +43,19 @@
<span class="prog" id="prog"></span>
</header>
<div id="units"></div>
+ <p class="refs-more" id="refsMore" hidden><a href="#references"><b data-t="references">References</b><span id="refsCount"></span><i data-t="viewAll">View all →</i></a></p>
+</main>
+
+<main id="refpage" aria-labelledby="refsTitle">
+ <header class="top">
+ <a class="back" href="#contents" data-t="backToContents">← Contents</a>
+ <span class="rp-book" id="rpBook"></span>
+ </header>
+ <section class="refs" id="references">
+ <h1 id="refsTitle" tabindex="-1" data-t="references">References</h1>
+ <p class="lead" data-t="refsLead">Every work cited in the lessons.</p>
+ <ol id="refList"></ol>
+ </section>
</main>
<script>
diff --git a/.claude/skills/papermorph/assets/templates/chapter.html b/.claude/skills/papermorph/assets/templates/chapter.html
index 2c859b6..0524bb2 100644
--- a/.claude/skills/papermorph/assets/templates/chapter.html
+++ b/.claude/skills/papermorph/assets/templates/chapter.html
@@ -9,13 +9,15 @@
</head>
<body>
<script src="../lib/engine.js"></script>
+<script src="../refs.js"></script><!-- the book's sources for cite(); built by scripts/refs.py -->
+<!-- <script src="items.js"></script> choice questions for mcq(id); built by scripts/items.py from books/<book>/items/chNN.items.json -->
<script src="audio/en/timings.js"></script>
<script>
'use strict';
// A starting skeleton, not a design. Replace every beat; keep the shape: intro, lesson beats with
// quick checks between them, a summary, full-screen practice, finish. Beat ids match narration.en.json.
// <html lang> sets the interface text, language the audio folder: keep both, and the timings path above, in the book's language.
-const CHAPTER = { number: 1, title: 'CHAPTER TITLE', minutes: 8, language: 'en' }; // match the audio folder; set next once the next chapter exists
+const CHAPTER = { number: 1, title: 'CHAPTER TITLE', minutes: 8, language: 'en', refs: [] }; // match the audio folder; set next once the next chapter exists; refs: REFS keys to list on the finish card besides those drawn with cite()
/* ---------- chapter drawing helpers ---------- */
const mline = (p, parts, x, y, t0, fill = COL.chalk, size = 48, anchor = 'middle') => { const e = M(p, [].concat(parts), { x, y, size, fill, anchor, o: 0 }); show(e, t0); return e; };
diff --git a/.claude/skills/papermorph/references/authoring.md b/.claude/skills/papermorph/references/authoring.md
index da1abdb..9014482 100644
--- a/.claude/skills/papermorph/references/authoring.md
+++ b/.claude/skills/papermorph/references/authoring.md
@@ -45,7 +45,7 @@ Pick the type that lets the student act on the picture itself whenever possible
| Type | Use for |
| --- | --- |
-| `choice` | One answer from a few options, each wrong option with its own explanation |
+| `choice` / `mcq` | One answer from a few options, each wrong option with its own explanation; `mcq(id)` takes it from the chapter's item bank |
| `blanks` | Typed numbers inside an expression; fractions and mixed numbers accepted; `test` judges a whole row (answers in any order) |
| `grid` | Several items, each classified (yes/no, which category, true/false) |
| `tap` / `tapEls` / `pickEls` | Click a point on the number line / a token in an expression / any drawn object |
@@ -62,8 +62,39 @@ New types are welcome when the content calls for one; each needs keyboard play (
- Compose the question beat for its card: the picture the question is about stays visible (for example in the top 60 % with a `BAND` card below, or beside a `{x, y, w, cls: 'side'}` card); `SCREEN` for practice.
- Units in typed answers: write the unit as a word after the box (`{ box: '60' }, ' kilograms'`) so it is not set as a math variable.
+### Choice questions from an item bank
+
+A chapter's choice questions can live in a reviewed item bank, `books/<book>/items/chNN.items.json`, instead of inline in the page, so they can be linted, reviewed by a person in a sheet, and approved before release. The bank follows the JSON schema of the [mcq-item-writer](https://github.com/titulartarantula/mcq-item-writer) skill, which writes and lints items against evidence-based item-writing rules (stem with the problem, one best answer, plausible distractors, feedback on every option). Inline `choice` stays fine for a quick check written on the spot.
+
+For a bank used by a page:
+
+- **Ids** keep the book's prefixes: `c-…` for a quick check, `p-…` for practice (the finish card adds them up by prefix).
+- **The card is the screen.** Put the scenario and lead-in in `stem`; no data tables or media (draw the data in the beat and ask about it). Options stay short enough for one line on the card; three options fit a side or band card, four only on a `SCREEN`.
+- **Feedback** on every option, two or three sentences. The engine adds "Correct." / "Not quite.", so don't start with a verdict; `items.py` drops one if present.
+- **Order.** Options show as authored (no shuffle): spread the right answer's position across the chapter.
+
+Build the page's copy after every bank change, and never edit `items.js` by hand:
+
+```sh
+python3 SKILL/scripts/items.py books/<book>/items/chNN.items.json site/<book>/chNN/items.js
+```
+
+The chapter loads `<script src="items.js"></script>` right after `engine.js` and asks with `quiz(TOPR, [mcq('c-attrib')], done)` (engine.md). `items.py` refuses what a card cannot show (multiple-response items, tables, media, no single key) and warns about items not yet marked `approved`.
+
## Content rules
- Follow the agreed chapter scope and order. Verify facts, calculations and answers actually used in the finished lesson; correct or replace source errors and note them in `books/<book>/chapters/chNN.md` for the user.
- Check worked examples as the subject, not only as arithmetic (a push on someone standing on the ground is not the net force).
- Use the notation and rounding in `style.json` (`look.notation`). Record new shared decisions there.
+
+## Citations
+
+Every work named on screen (an author–year, a quoted study, a book title) can be a live link to that work. Links come from a verified list, never from memory.
+
+1. **List.** Add each cited work to `books/<book>/refs.json`, taking authors, year and full title from the source book's own reference list (`pages/*/text.md`). The key is `surname-surname-year` (`scheper-hughes-lock-1987`); `cite` is the on-screen label (`python3 SKILL/scripts/refs.py --help` lists the entry fields).
+2. **Find.** `python3 SKILL/scripts/refs.py lookup books/<book>/refs.json --write`. It accepts a Crossref DOI only when the year, first author and title all match. For books without a DOI it takes the ISBN of the edition from the cited year (Open Library), which links to its WorldCat record. Decide each `NO CONFIDENT MATCH` by hand: pick the right candidate or a trusted academic page (`url`, e.g. PubMed, JSTOR, ERIC, a university repository). If none exists, keep the citation as plain text and note it in the chapter file.
+3. **Verify.** `python3 SKILL/scripts/refs.py verify books/<book>/refs.json --write` resolves every DOI or ISBN, checks it against the entry, fills in missing metadata and stamps `verified`. Fix every `FAIL`.
+4. **Build.** `python3 SKILL/scripts/refs.py build books/<book>/refs.json site/<book>/refs.js`. Chapters and the contents page load it: the contents ends with a link to a separate References view that lists every work, and each chapter's finish card lists the sources that chapter cites.
+5. **Draw.** `cite(p, key, { x, y, size, fill, anchor, weight, o: 0 })` draws the label as an underlined link and returns it, ready for `show()`/`tw()` like `T`; `str` overrides the label (e.g. `'(1987)'` after a name drawn separately). Text drawn with `T` or written in a card that matches a work's `cite` label (or one of its `match` strings) becomes a link by itself. Clicking a citation opens the source in a new tab and pauses the lesson; faded-out links take no clicks or Tab focus. A work discussed but not drawn goes in `CHAPTER.refs` so the finish card still lists it.
+
+Draw a citation next to the text it supports rather than inside a long sentence, so the link is a separate target of at least 24 px text height.
diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.md
index 99e00c9..9b156c5 100644
--- a/.claude/skills/papermorph/references/engine.md
+++ b/.claude/skills/papermorph/references/engine.md
@@ -21,6 +21,7 @@ Many drawing helpers are mathematical because the first book was algebra. Use th
| `G(parent, {x,y,s,r,o})` | group |
| `path(parent, d, attrs, {d:0})` | path; `{d: 0}` makes it ready to be drawn on with `draw()` |
| `T(parent, str, {x,y,size,fill,font,weight,anchor,o})` | text |
+| `cite(parent, key, {str,x,y,size,fill,weight,anchor,o})` | a citation from `REFS` (`../refs.js`), drawn as an underlined link that opens the source in a new tab and listed on the finish card ([authoring.md](authoring.md#citations)) |
| `M(parent, parts, {x,y,size,fill,anchor,o,s})` | math with its baseline at y; parts are strings, `F(n,d)` fractions, `R(x, i)` roots (x may be `F(...)`, i the index), `E(exp)` exponents, `TX(tex)` LaTeX (see [LaTeX](#latex)); returns a group with `_w` (width) |
| `mathW(parts, size)` | width of math without drawing it |
| `frac(p, top, bot, x, y, t0, opts)` | built-up fraction whose top and bottom are math parts |
@@ -92,6 +93,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'
- Positions: `BAND` (bottom band, y 686–886; long content can push it past the stage, so check it), `TOPR` (top right, ≤ 470 high), `RIGHT`, `SCREEN` (full-screen practice; label `'Chapter practice N of M'`), `SORT_SCREEN`, or any `{x, y, w, cls: 'side'}`.
- `choice(options, right, why, wrongWhys[], onRight?)` — number keys.
+- `mcq(id, onRight?)` — a whole quiz entry (`{id, prompt, build: choice(...)}`) from the chapter's item bank: `quiz(TOPR, [mcq('c-attrib'), mcq('c-cause')], done)`. Needs `items.js` (built by `scripts/items.py`) loaded after `engine.js`; an unknown id throws.
- `blanks(rows)` — rows `{parts: [..., {box: '21'}, ...], why, hint?, fx?, test?}`; accepts −5, 3/4, 2 1/4, 0.75 as exact values; `{box, lowest: true}` demands lowest terms; `test(values)` judges the whole row (e.g. two factors in either order). Tab moves between boxes, Enter checks, Esc leaves a box.
- `grid(rows, cols, {multi, text})` — rows `{parts, ans: [keys], why, fx?}`, cols `[[key, label, colour?, hotkey?]]`; with `text: true` parts are rich text (math via `$m`). ↑/↓ change rows.
- `tap(values, right, why, v => wrongWhy, onRight?)` points on the number line; `tapEls(row, idx, right, …)` tokens of a `tokens` row; `pickEls([{el, box: [x,y,w,h], label}], right, …)` any drawn objects; `pickPoint(P, [x,y], why, (x,y) => wrongWhy, onRight?, test?)` grid points (arrows + Enter or click); `sorter(items, trayXY)` drag into the set diagram (keys 1–6).
diff --git a/.claude/skills/papermorph/references/review.md b/.claude/skills/papermorph/references/review.md
index 3380fc7..a0e9840 100644
--- a/.claude/skills/papermorph/references/review.md
+++ b/.claude/skills/papermorph/references/review.md
@@ -26,6 +26,12 @@ uv run --with playwright SKILL/scripts/overlap.py chNN --url http://localhost:87
`shot.py` captures open/end frames of every beat as 4-up sheets and reports console errors. Look for an empty or unrelated opening, text over drawings or clipped at the edge, a card covering what it asks about, leftovers half faded, geometry contradicting its values, shapes inside circles or curves crossing the outline (check thin geometry on the full-size `chNN_bII_T.png`, not only the sheet), text too small at half size or too much at once, and the same idea in different colours. `check_blank.py` reports openings empty for more than a second after speech starts. `overlap.py` samples every beat and lists where an arrow runs through text or two texts collide, with times, so you can look at exactly those frames.
+## Questions and citations
+
+For a chapter with an item bank, lint it with the item writer (`python3 MCQ/scripts/lint_items.py books/<book>/items/chNN.items.json`, where `MCQ` is the mcq-item-writer skill's folder) and fix every error; rebuild `items.js` after any change, then answer one bank question per card position, wrong then right, to see the answered card fit with Continue visible.
+
+For a chapter that cites works, run `python3 SKILL/scripts/refs.py verify books/<book>/refs.json` and rebuild `refs.js` after any `refs.json` change. Every author–year or work title on screen should be a link whose key is verified; look for links that are missing, unreadable or overlapping other targets, and open one per chapter to confirm it lands on the work.
+
## Smoothness
`uv run --with playwright SKILL/scripts/perf.py chNN --url …` measures frame times in Firefox, which repaints SVG on the main thread and is the slowest common browser for these pages; headless Chromium hides paint cost. Look at the worst beats and transitions; the remedies are in [engine.md](engine.md#performance-firefox).
diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.md
index fe51d82..a19c584 100644
--- a/.claude/skills/papermorph/references/site.md
+++ b/.claude/skills/papermorph/references/site.md
@@ -16,6 +16,8 @@ cp "$SKILL/assets/templates/book.html" "$BOOK_SITE/index.html"
cp "$SKILL/assets/templates/unit-art.js" "$BOOK_SITE/unit-art.js"
cp "$SKILL/assets/templates/chapter.html" "$BOOK_SITE/ch01/index.html"
cp "$SKILL/assets/templates/narration.en.json" "content/$BOOK_ID/ch01/narration.en.json"
+echo '[]' > "$BOOK_WORK/refs.json" # cited works; an empty list builds an empty refs.js
+python3 "$SKILL/scripts/refs.py" build "$BOOK_WORK/refs.json" "$BOOK_SITE/refs.js"
```
Use the pilot chapter's number in place of `ch01` when the pilot is not the first chapter. Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`). Take `voice` and `rate` for each narration file from `style.json`, and translate the template's visible UI text as needed before the pilot.
@@ -32,11 +34,12 @@ A chapter returns to its book's index. Preserve cover → contents → chapter n
## Cover and contents (`index.html`)
-One page: no hash or `#book` shows the cover, `#contents` or `#chNN` the contents; a lesson's home button returns to `#chNN`, and the card grows into the lesson frame through a view transition.
+One page: no hash or `#book` shows the cover, `#references` the reference list, `#contents` or `#chNN` the contents; a lesson's home button returns to `#chNN`, and the card grows into the lesson frame through a view transition.
- Edit the title, kicker, lede, the faint chalk phrases on the cover (a few formulas or lines from the book), and the `<title>`.
- The page's script calls `Contents.book({ start, units, hues })` (from the engine's `lib/contents.js`; the shared styles are `lib/contents.css`). `units`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order from `start` (`{ unit: 1, chapter: 1 }`; a book whose scope starts mid-way, e.g. at unit 3, chapter 9, keeps the original numbers). Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`. An optional third entry `{ unit, chapter, sample: true }` renumbers a unit and marks it as a sample, left out of the chapter count. To show different numbers than the folders, add `label` to `start` (`{ unit: 1, chapter: 9, label: 1 }` shows ch09 as 1) and set the same `CHAPTER.label` in each lesson, which its title screen and completion card show. A chapter's own third entry `{ chapter }` changes only the number on its card; `{ href, chapter }` links a card to another book's chapter, outside this book's count and progress (`href` on a unit's entry does it for the whole unit).
- `hues`: one colour per unit, cycling.
+- References: the page loads `refs.js`, and the contents ends with one link to the separate `#references` view, which lists every cited work linked to its DOI or catalogue record; a book without citations shows no link. Rebuild `refs.js` whenever `refs.json` changes ([authoring.md](authoring.md#citations)).
- A book with its own look overrides the tokens of `lib/contents.css` (`--board`, `--chalk`, `--top-bg`, …) in a `<style>` after it, as the template's comment shows; don't copy the stylesheet into the page.
## Unit sketches (`unit-art.js`)
@@ -55,7 +58,7 @@ Serve the static output over HTTP for audio playback:
python3 SKILL/scripts/serve.py 8765 site # no-store, so edits are never hidden by the browser cache
```
-Open `http://localhost:8765/<book>/`. Confirm the cover opens the contents, ready chapter links load their lessons, and lessons return to the book's contents. Deliver `site/<book>/` with its HTML, scripts, styles and audio, the preview command and entry URL, available chapter count and unresolved issues. Source PDFs, extracted pages, narration drafts and development environments are not part of the static book.
+Open `http://localhost:8765/<book>/`. Confirm the cover opens the contents, ready chapter links load their lessons, lessons return to the book's contents, and reference links open their works. Deliver `site/<book>/` with its HTML, scripts (including `refs.js`), styles and audio, the preview command and entry URL, available chapter count and unresolved issues. Source PDFs, extracted pages, narration drafts and development environments are not part of the static book.
## Languages
diff --git a/.claude/skills/papermorph/scripts/items.py b/.claude/skills/papermorph/scripts/items.py
new file mode 100644
index 0000000..e421970
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/items.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+"""Turn a chapter's mcq-item-writer bank into the items.js a chapter page loads.
+
+ python SKILL/scripts/items.py books/<book>/items/chNN.items.json site/<book>/chNN/items.js
+
+The bank is the source of truth for the chapter's choice questions: write and lint it with the
+mcq-item-writer skill, then build. The page loads items.js after engine.js and asks with
+mcq('ID') (engine.md, Questions). Lint first; this script only refuses what the engine can't show:
+
+ - multiple-response items, data tables and media (draw data in the picture and ask about it);
+ - an item without exactly one correct option.
+
+Ordered-MC items become ordinary choice questions (the engine has no partial credit). Options keep
+their authored order, since the engine doesn't shuffle, so spread key positions in the bank. The
+engine prefixes "Correct." / "Not quite.", so a leading verdict in feedback is dropped. Items that
+aren't approved yet are listed as a warning.
+"""
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+VERDICT = re.compile(r"^\s*(correct|incorrect|not quite|not correct|right|wrong|yes|no)\s*[.!:,—–-]\s*", re.I)
+
+
+def feedback(text):
+ return VERDICT.sub("", text.strip(), count=1)
+
+
+def convert(item, problems):
+ iid = item.get("id", "?")
+ fmt = item.get("format", "one-best-answer")
+ stem = item.get("stem") or {}
+ if fmt == "multiple-response":
+ problems.append(f"{iid}: multiple-response items can't be shown by choice(); rewrite as one-best-answer")
+ if stem.get("data_table"):
+ problems.append(f"{iid}: data tables aren't shown on cards; draw the data in the picture and ask about it")
+ if item.get("media"):
+ problems.append(f"{iid}: media aren't shown on cards; the picture is the item's figure")
+ opts = item.get("options") or []
+ keys = [i for i, o in enumerate(opts) if o.get("correct")]
+ if len(keys) != 1:
+ problems.append(f"{iid}: {len(keys)} correct options; choice() needs exactly one")
+ return None
+ right = keys[0]
+ prompt = " ".join(t.strip() for t in (stem.get("scenario"), stem.get("lead_in")) if t and t.strip())
+ return {
+ "prompt": prompt,
+ "opts": [[o["text"].strip()] for o in opts],
+ "right": right,
+ "why": feedback(opts[right].get("feedback", "")),
+ "no": [None if i == right else feedback(o.get("feedback", "")) for i, o in enumerate(opts)],
+ }
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ ap.add_argument("bank", type=Path, help="books/<book>/items/chNN.items.json")
+ ap.add_argument("out", type=Path, help="site/<book>/chNN/items.js")
+ a = ap.parse_args(argv)
+ try:
+ bank = json.loads(a.bank.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as e:
+ sys.exit(f"items.py: can't read {a.bank}: {e}")
+ items = [it for it in bank.get("items", []) if it.get("status") != "retired"]
+ problems, out = [], {}
+ for it in items:
+ if it.get("id") in out:
+ problems.append(f"{it['id']}: duplicate id")
+ q = convert(it, problems)
+ if q:
+ out[it["id"]] = q
+ if problems:
+ sys.exit("items.py: not built\n " + "\n ".join(problems))
+ body = json.dumps(out, ensure_ascii=False, indent=1).replace("</", "<\\/")
+ a.out.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ src = a.bank.resolve().relative_to(Path.cwd()).as_posix()
+ except ValueError:
+ src = a.bank.name
+ a.out.write_text(f"// Built by scripts/items.py from {src}; edit the bank, not this file.\n"
+ f"window.ITEMS = Object.assign(window.ITEMS || {{}}, {body});\n", encoding="utf-8", newline="\n")
+ ordered = [it["id"] for it in items if it.get("format") == "ordered-mc"]
+ drafts = [it["id"] for it in items if it.get("status") != "approved"]
+ print(f"{a.out}: {len(out)} item(s)")
+ if ordered:
+ print(f" note: ordered-MC scored right/wrong only: {', '.join(ordered)}")
+ if drafts:
+ print(f" warning: not yet approved: {', '.join(drafts)}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/papermorph/scripts/refs.py b/.claude/skills/papermorph/scripts/refs.py
new file mode 100644
index 0000000..faeff6f
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/refs.py
@@ -0,0 +1,374 @@
+#!/usr/bin/env python3
+"""Find, verify and publish a book's references as live links (Crossref DOIs first).
+
+ python refs.py lookup books/<book>/refs.json [--write] # find DOIs (Crossref) or ISBNs (Open Library)
+ python refs.py verify books/<book>/refs.json [--write] # check every link resolves to the cited work
+ python refs.py build books/<book>/refs.json site/<book>/refs.js
+
+refs.json is the book's source list, one entry per cited work (fields after "cite" help matching):
+[{"key": "scheper-hughes-lock-1987", "cite": "Scheper-Hughes & Lock (1987)",
+ "authors": ["Scheper-Hughes, Nancy", "Lock, Margaret M."], "year": 1987,
+ "title": "The mindful body", "type": "article"}, ...]
+"type" is article, book, chapter or web. Optional: container, volume, issue, pages, publisher,
+editors, edition ("4th ed."), doi, isbn, nolink (why no reliable record exists), url (a trusted academic page, used only when there is no DOI or ISBN), and
+match: other on-screen spellings of the citation (e.g. "Robert Crawford (1980)", "Cobb 1958"); the
+engine links any on-screen text equal to cite or a match string (case-insensitive).
+
+lookup searches Crossref for each entry without a doi/isbn/url and accepts a candidate only when
+the year (±1), first author's surname and title (≥ 0.85 similar) all match; anything else is
+printed for a human decision. Books that Crossref lacks are looked up in Open Library for an ISBN
+(linked to its WorldCat record). Never type a DOI from memory: add it only from these results or
+from the source's own reference list, then verify.
+
+verify resolves each DOI at Crossref (or doi.org for other registrars), compares year, author and
+title, and with --write fills missing metadata and stamps "verified". URL entries must resolve
+and sit on a trusted host. build refuses unverified entries and writes refs.js:
+window.REFS = {key: {cite, ref (APA 7 reference), url, match?}}, read by the engine and contents page.
+Set CROSSREF_MAILTO to join Crossref's polite pool (optional).
+"""
+import argparse
+import datetime
+import difflib
+import json
+import os
+import re
+import sys
+import time
+import unicodedata
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+UA = "papermorph-refs/1.0 (https://github.com/DozenTwelve/Papermorph)"
+TRUSTED = ("doi.org", "worldcat.org", "openlibrary.org", "pubmed.ncbi.nlm.nih.gov", "ncbi.nlm.nih.gov",
+ "jstor.org", "eric.ed.gov", "arxiv.org", "openalex.org", "archive.org", "loc.gov",
+ "philpapers.org", "hathitrust.org", "semanticscholar.org")
+
+
+def get(url, accept="application/json"):
+ mail = os.environ.get("CROSSREF_MAILTO")
+ if mail and "api.crossref.org" in url:
+ url += ("&" if "?" in url else "?") + "mailto=" + urllib.parse.quote(mail)
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": accept})
+ for attempt in range(3):
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ body = r.read()
+ return r.status, r.geturl(), body
+ except urllib.error.HTTPError as e:
+ if e.code in (429, 503) and attempt < 2:
+ time.sleep(2 + 3 * attempt)
+ continue
+ return e.code, url, b""
+ except (urllib.error.URLError, TimeoutError) as e:
+ if attempt < 2:
+ time.sleep(2)
+ continue
+ return 0, url, str(e).encode()
+ return 0, url, b""
+
+
+def norm(s):
+ s = unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower()
+ return re.sub(r"[^a-z0-9 ]+", " ", s).split()
+
+
+def surname(a):
+ """Family name of 'Family, Given' / 'Given Family' / Crossref author dict."""
+ if isinstance(a, dict):
+ return a.get("family") or a.get("name") or ""
+ return a.split(",")[0] if "," in a else a.split()[-1]
+
+
+def same_name(a, b):
+ return "".join(norm(a)) == "".join(norm(b))
+
+
+def title_sim(a, b):
+ lead = lambda s: " ".join(norm(re.split(r"[:?]", s or "")[0]))
+ if len(lead(a)) >= 8 and lead(a) == lead(b):
+ return 1.0 # same main title; one side omits or reorders the subtitle
+ a, b = " ".join(norm(a)), " ".join(norm(b))
+ if not a or not b:
+ return 0
+ short, long_ = sorted((a, b), key=len)
+ # A citation often gives only the main title; compare it with the start of the full title.
+ return max(difflib.SequenceMatcher(None, a, b).ratio(),
+ difflib.SequenceMatcher(None, short, long_[:len(short)]).ratio() if len(short) > 20 else 0)
+
+
+def cr_year(m):
+ for k in ("published-print", "issued", "published-online", "published"):
+ dp = (m.get(k) or {}).get("date-parts")
+ if dp and dp[0] and dp[0][0]:
+ return dp[0][0]
+ return None
+
+
+def cr_title(m):
+ t = (m.get("title") or [""])[0]
+ sub = (m.get("subtitle") or [""])
+ return f"{t}: {sub[0]}" if sub and sub[0] and sub[0].lower() not in t.lower() else t
+
+
+def match(e, m):
+ """Problems comparing entry e with Crossref record m; empty means it is the cited work."""
+ out = []
+ y = cr_year(m)
+ if e.get("year") and y and abs(int(e["year"]) - y) > 1:
+ out.append(f"year {y} ≠ {e['year']}")
+ if e.get("authors"):
+ names = [surname(a) for a in (m.get("author") or m.get("editor") or [])]
+ if names and not any(same_name(surname(e["authors"][0]), n) for n in names):
+ out.append(f"authors {names[:3]} lack {surname(e['authors'][0])}")
+ if e.get("title"):
+ s = title_sim(e["title"], cr_title(m))
+ if s < .85:
+ out.append(f"title '{cr_title(m)}' ({s:.2f})")
+ kinds = KINDS.get(e.get("type"))
+ if kinds and m.get("type") and m["type"] not in kinds:
+ out.append(f"a {m['type']}, not a {e['type']}") # e.g. a same-titled book chapter for a journal article
+ return out
+
+
+# Crossref record types that can stand for each entry type.
+KINDS = {"article": {"journal-article", "proceedings-article", "posted-content"},
+ "book": {"book", "monograph", "edited-book", "reference-book"},
+ "chapter": {"book-chapter", "book-part", "book-section", "reference-entry"}}
+
+
+def crossref_work(doi):
+ st, _, body = get("https://api.crossref.org/works/" + urllib.parse.quote(doi))
+ return json.loads(body)["message"] if st == 200 else None
+
+
+def fill(e, m):
+ """Fill missing metadata from a Crossref record."""
+ if not e.get("authors") and m.get("author"):
+ e["authors"] = [f"{a.get('family', a.get('name', ''))}, {a.get('given', '')}".strip(", ") for a in m["author"]]
+ e.setdefault("title", cr_title(m))
+ e.setdefault("year", cr_year(m))
+ typ = m.get("type", "")
+ e.setdefault("type", "book" if typ in ("book", "monograph", "edited-book") else "chapter" if typ == "book-chapter" else "article")
+ if m.get("container-title"):
+ e.setdefault("container", m["container-title"][0])
+ for k, ck in (("volume", "volume"), ("issue", "issue"), ("pages", "page"), ("publisher", "publisher")):
+ if m.get(ck):
+ e.setdefault(k, m[ck].replace("-", "–") if k == "pages" else m[ck])
+
+
+def lookup(entries, write):
+ changed = 0
+ for e in entries:
+ if e.get("doi") or e.get("isbn") or e.get("url") or e.get("nolink"):
+ continue
+ q = " ".join(str(x) for x in [*(surname(a) for a in e.get("authors", [])[:3]), e.get("year", ""), e.get("title", e.get("cite", ""))])
+ st, _, body = get("https://api.crossref.org/works?rows=5&query.bibliographic=" + urllib.parse.quote(q))
+ items = json.loads(body)["message"]["items"] if st == 200 else []
+ good = [m for m in items if not match(e, m)] if e.get("title") and e.get("authors") and e.get("year") else []
+ good.sort(key=lambda m: abs((cr_year(m) or 0) - int(e["year"]))) # the cited year's version first
+ if good:
+ m = good[0]
+ print(f"{e['key']}: doi {m['DOI']} {cr_title(m)} ({cr_year(m)})")
+ if write:
+ e["doi"] = m["DOI"].lower()
+ fill(e, m)
+ changed += 1
+ continue
+ if e.get("type") in ("book", None) and e.get("title"):
+ # The English edition from the cited year, else any English edition with an ISBN.
+ au = surname(e["authors"][0]) if e.get("authors") else ""
+ hit = None
+ for q2 in ([f"language:eng publish_year:{e['year']}"] if e.get("year") else []) + ["language:eng"]:
+ st, _, body = get("https://openlibrary.org/search.json?limit=3&fields=key,title,author_name,editions,editions.key,editions.title,"
+ "editions.isbn,editions.publish_date,editions.publishers&"
+ + urllib.parse.urlencode({"title": re.split(r"[:?]", e["title"])[0], "author": au, "q": q2}))
+ for d in (json.loads(body).get("docs", []) if st == 200 else []):
+ ed = (d.get("editions") or {}).get("docs") or [{}]
+ if (ed[0].get("isbn") and title_sim(e["title"], ed[0].get("title", d.get("title", ""))) >= .85
+ and (not au or any(same_name(au, n.split()[-1]) for n in d.get("author_name", [])))):
+ hit = ed[0]
+ break
+ if hit:
+ break
+ if hit:
+ isbn = next((i for i in hit["isbn"] if len(i) == 13), hit["isbn"][0])
+ print(f"{e['key']}: isbn {isbn} {hit['title']} ({', '.join(hit.get('publishers', [])[:1] + hit.get('publish_date', []))})"
+ + ("" if str(e.get("year")) in " ".join(hit.get("publish_date", [])) else "; edition year differs from the citation"))
+ if write:
+ e["isbn"] = isbn
+ if hit.get("publishers"):
+ e.setdefault("publisher", hit["publishers"][0])
+ changed += 1
+ continue
+ print(f"{e['key']}: NO CONFIDENT MATCH for '{q}'. Candidates:")
+ for m in items[:3]:
+ print(f" {m['DOI']} {cr_title(m)} ({cr_year(m)}) {[surname(a) for a in m.get('author', [])][:3]} ≠ {'; '.join(match(e, m))}")
+ time.sleep(.2)
+ return changed
+
+
+def verify(entries, write):
+ bad, today = 0, datetime.date.today().isoformat()
+ for e in entries:
+ problems, how = [], ""
+ if e.get("doi"):
+ e["doi"] = re.sub(r"^(https?://(dx\.)?doi\.org/|doi:)", "", e["doi"].strip(), flags=re.I).lower()
+ m = crossref_work(e["doi"])
+ if m:
+ problems, how = match(e, m), "crossref"
+ if write and not problems:
+ fill(e, m)
+ else:
+ st, _, body = get("https://doi.org/api/handles/" + urllib.parse.quote(e["doi"]))
+ ok = st == 200 and json.loads(body).get("responseCode") == 1
+ problems, how = ([] if ok else ["DOI is not registered"]), "doi.org (not in Crossref; check the landing page by hand)"
+ elif e.get("isbn"):
+ st, _, body = get(f"https://openlibrary.org/isbn/{e['isbn']}.json")
+ if st == 200:
+ rec = json.loads(body)
+ how = "openlibrary isbn"
+ if e.get("title") and title_sim(e["title"], rec.get("title", "") + " " + rec.get("subtitle", "")) < .85:
+ problems.append(f"ISBN is '{rec.get('title')}'")
+ if write and not problems and rec.get("publishers"):
+ e.setdefault("publisher", rec["publishers"][0])
+ else:
+ problems.append(f"ISBN not found in Open Library ({st})")
+ elif e.get("url"):
+ host = urllib.parse.urlparse(e["url"]).hostname or ""
+ if not any(host == t or host.endswith("." + t) for t in TRUSTED) and not re.search(r"\.(edu|gov|ac\.[a-z]{2})$", host):
+ problems.append(f"untrusted host {host}; prefer a DOI, ISBN or a TRUSTED host")
+ st, final, _ = get(e["url"], accept="text/html,*/*")
+ if not 200 <= st < 400:
+ problems.append(f"URL returned {st}")
+ how = "url"
+ elif e.get("nolink"):
+ how = "no link: " + e["nolink"] # searched; no reliable online record (thesis, magazine, talk)
+ else:
+ problems.append("no doi, isbn or url (run lookup), or set nolink to the reason none exists")
+ if problems:
+ bad += 1
+ e.pop("verified", None)
+ print(f"FAIL {e['key']}: {'; '.join(problems)}")
+ else:
+ e["verified"] = f"{today} {how}"
+ print(f"ok {e['key']}: {link(e)} [{how}]")
+ time.sleep(.2)
+ return bad
+
+
+def link(e):
+ if e.get("doi"):
+ return "https://doi.org/" + e["doi"]
+ if e.get("isbn"):
+ return "https://search.worldcat.org/isbn/" + re.sub(r"[^0-9Xx]", "", e["isbn"])
+ return e.get("url") # None for a nolink entry: listed in references, shown as plain text
+
+
+SUFFIX = re.compile(r",?\s*\b(Jr|Sr|II|III|IV)\.?\s*$", re.I)
+
+
+def split_name(a):
+ """'Family, Given[, Jr.]' or 'Given Family' -> (family, initials, suffix)."""
+ suf, a = "", a.strip()
+ m = SUFFIX.search(a)
+ if m:
+ s = m.group(1)
+ suf, a = (s.capitalize() + "." if s.lower() in ("jr", "sr") else s.upper()), a[:m.start()]
+ if "," in a:
+ fam, giv = a.split(",", 1)
+ else:
+ fam, giv = a.rsplit(" ", 1)[-1], (a.rsplit(" ", 1)[0] if " " in a else "")
+ # Ying-yi -> Y.-y.; Jean-Paul -> J.-P.
+ inits = " ".join("-".join(x[0] + "." for x in p.split("-") if x)
+ for p in re.split(r"[\s.]+", giv.strip()) if p and p[0].isalpha())
+ return fam.strip(), inits, suf
+
+
+def apa_name(a):
+ fam, inits, suf = split_name(a)
+ return ", ".join(x for x in (fam, inits, suf) if x)
+
+
+def apa_editor(a):
+ fam, inits, suf = split_name(a)
+ return " ".join(x for x in (inits, fam) if x) + (f", {suf}" if suf else "")
+
+
+def apa_authors(names):
+ n = [apa_name(a) for a in names]
+ if not n:
+ return ""
+ if len(n) == 1:
+ return n[0]
+ if len(n) <= 20:
+ return ", ".join(n[:-1]) + ", & " + n[-1]
+ return ", ".join(n[:19]) + ", … " + n[-1]
+
+
+def apa(e):
+ au = apa_authors(e.get("authors", []))
+ yr = f"({e.get('year', 'n.d.')})."
+ t = e.get("title", "").rstrip(".")
+ end = lambda s: s if s.endswith((".", "?", "!")) else s + "."
+ typ = e.get("type", "article")
+ if typ == "book":
+ parts = [au, yr, end(t + (f" ({e['edition']})" if e.get("edition") else "")), end(e["publisher"]) if e.get("publisher") else ""]
+ elif typ == "chapter":
+ eds = e.get("editors", [])
+ names = [apa_editor(x) for x in eds]
+ names = "" if not names else names[0] if len(names) == 1 else " & ".join(names) if len(names) == 2 else ", ".join(names[:-1]) + ", & " + names[-1]
+ ed = f"In {names} (Ed{'s' if len(eds) > 1 else ''}.), " if eds else "In "
+ pg = f" (pp. {e['pages']})" if e.get("pages") else ""
+ parts = [au, yr, end(t), end(f"{ed}{e.get('container', '')}{pg}"), end(e["publisher"]) if e.get("publisher") else ""]
+ elif typ == "web":
+ parts = [au, yr, end(t), end(e["container"]) if e.get("container") else ""]
+ else:
+ src = e.get("container", "")
+ if e.get("volume"):
+ src += f", {e['volume']}" + (f"({e['issue']})" if e.get("issue") else "")
+ if e.get("pages"):
+ src += f", {e['pages']}"
+ parts = [au, yr, end(t), end(src) if src else ""]
+ return " ".join(p for p in parts if p)
+
+
+def build(entries, out, allow):
+ missing = [e["key"] for e in entries if not e.get("verified")]
+ if missing and not allow:
+ sys.exit(f"Unverified: {', '.join(missing)}. Run verify --write first (or --allow-unverified for a draft).")
+ keys = [e["key"] for e in entries]
+ if len(set(keys)) != len(keys):
+ sys.exit("Duplicate keys in refs.json")
+ refs = {e["key"]: {"cite": e["cite"], "ref": apa(e), "url": link(e), **({"match": e["match"]} if e.get("match") else {})}
+ for e in entries}
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text("// Generated by the papermorph skill's scripts/refs.py from the book's refs.json. Edit that file and rebuild.\n"
+ "window.REFS = " + json.dumps(refs, ensure_ascii=False, indent=1) + ";\n", encoding="utf-8")
+ print(f"{out}: {len(refs)} references")
+
+
+def main():
+ sys.stdout.reconfigure(encoding="utf-8")
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("cmd", choices=["lookup", "verify", "build"])
+ ap.add_argument("refs", type=Path)
+ ap.add_argument("out", type=Path, nargs="?", help="build: refs.js to write")
+ ap.add_argument("--write", action="store_true", help="lookup/verify: save results into refs.json")
+ ap.add_argument("--allow-unverified", action="store_true", help="build: draft output with unverified entries")
+ a = ap.parse_args()
+ entries = json.loads(a.refs.read_text(encoding="utf-8"))
+ if a.cmd == "build":
+ if not a.out:
+ sys.exit("build needs the refs.js path")
+ return build(entries, a.out, a.allow_unverified)
+ n = lookup(entries, a.write) if a.cmd == "lookup" else verify(entries, a.write)
+ if a.write:
+ a.refs.write_text(json.dumps(entries, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
+ if a.cmd == "verify" and n:
+ sys.exit(f"{n} reference(s) failed verification")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/engine/check_i18n.py b/engine/check_i18n.py
index cee3546..ad4ad10 100644
--- a/engine/check_i18n.py
+++ b/engine/check_i18n.py
@@ -66,6 +66,8 @@ async def answer(route):
elif rest == "":
html = BASE_FILES["book"] if from_base else (TEMPLATES / "book.html").read_text(encoding="utf-8")
await route.fulfill(content_type="text/html", body=with_language(html, language))
+ elif rest.endswith("refs.js"): # the templates load the book's built reference list
+ await route.fulfill(content_type="text/javascript", body="const REFS = {};")
elif rest == "unit-art.js":
await route.fulfill(path=TEMPLATES / "unit-art.js")
elif rest.startswith("lib/") and rest[4:] in ENGINE_FILES:
diff --git a/engine/check_latex.py b/engine/check_latex.py
index d5f2998..2bc6c6b 100644
--- a/engine/check_latex.py
+++ b/engine/check_latex.py
@@ -133,6 +133,8 @@ async def answer(route):
variant, _, rest = urlparse(route.request.url).path.split("/__latex__/")[1].partition("/")
if rest == "ch01/":
await route.fulfill(content_type="text/html; charset=utf-8", body=PAGES[variant].encode("utf-8"))
+ elif rest.endswith("refs.js"): # the templates load the book's built reference list
+ await route.fulfill(content_type="text/javascript", body="const REFS = {};")
elif rest == "lib/engine.js":
if variant == "base":
await route.fulfill(content_type="text/javascript", body=BASE_ENGINE)
diff --git a/engine/check_volume.py b/engine/check_volume.py
index 0f03355..b33df71 100644
--- a/engine/check_volume.py
+++ b/engine/check_volume.py
@@ -22,6 +22,8 @@ async def template(route):
name = urlparse(route.request.url).path.split("/__volume_template__/")[1]
if name == "ch01/":
await route.fulfill(path=SKILL / "assets/templates/chapter.html")
+ elif name.endswith("refs.js"): # the templates load the book's built reference list
+ await route.fulfill(content_type="text/javascript", body="const REFS = {};")
elif name.startswith("lib/"):
await route.fulfill(path=ENGINE / Path(name).name)
elif name.endswith("timings.js"):
diff --git a/engine/contents.css b/engine/contents.css
index 3f59f10..d8f7f70 100644
--- a/engine/contents.css
+++ b/engine/contents.css
@@ -26,6 +26,8 @@ a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: 48px 16px 64px; text-align: center; overflow: hidden; }
.open #cover, body:not(.open) #contents { display: none; }
+/* #references is its own view: the full list, reached from one link at the end of the contents. */
+body:not(.refsview) #refpage, .refsview #cover, .refsview #contents { display: none; }
#cover > * { animation: rise .8s var(--ease) backwards; }
#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }
#cover .kicker { animation-delay: .9s; }
@@ -92,6 +94,26 @@ main#contents { padding-bottom: 80px; }
.ch.here:focus-visible { outline-color: var(--c); }
.ch.here { animation: here 1.8s ease-out .3s; }
@keyframes here { 0% { box-shadow: 0 0 0 0 var(--c); } 25% { box-shadow: 0 0 0 5px var(--c); } 100% { box-shadow: 0 0 0 14px transparent; } }
+/* ---------- references: every source the book cites, linked to its DOI or catalogue record ---------- */
+.refs-more { max-width: 1212px; margin: 44px auto 0; padding: 0 16px; }
+.refs-more[hidden] { display: none; }
+.refs-more a { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; padding: 16px 20px; border-radius: 16px; background: var(--panel);
+ border: 1.5px solid var(--edge); text-decoration: none; transition: border-color .3s; }
+.refs-more a:hover { border-color: var(--dim); }
+.refs-more b { font: 500 22px/1.2 var(--book); }
+.refs-more span { color: var(--dim); font-size: 15px; }
+.refs-more i { margin-left: auto; font-style: normal; color: var(--quiz); font-weight: 600; font-size: 15px; }
+#refpage { padding-bottom: 80px; }
+.top .back { display: inline-flex; align-items: center; gap: 8px; padding: 6px 4px; font-weight: 600; text-decoration: none; color: var(--quiz); border-radius: 8px; }
+.top .rp-book { margin-left: auto; font: 500 18px/1.2 var(--book); color: var(--dim); }
+.top .rp-book i { color: var(--task); }
+.refs { max-width: 1212px; margin: 32px auto 0; padding: 0 16px; }
+.refs h1 { margin: 0 0 8px; font: 500 clamp(32px, 5vw, 44px)/1.1 var(--book); view-transition-name: none; }
+.refs .lead { margin: 0 0 26px; max-width: 46em; color: var(--dim); }
+.refs ol { margin: 0; padding: 0; list-style: none; color: var(--dim); font-size: 16px; line-height: 1.5; }
+.refs li { margin: 0 0 10px; padding-left: 2em; text-indent: -2em; }
+.refs a { color: var(--chalk); text-underline-offset: 3px; overflow-wrap: anywhere; }
+.refs a:hover { color: var(--quiz); }
.stagger .top { animation: rise .6s var(--ease) backwards; }
.stagger .unit h2, .stagger .ch { animation: rise .6s var(--ease) backwards; animation-delay: calc(min(var(--i), 14) * 32ms + 80ms); }
diff --git a/engine/contents.js b/engine/contents.js
index 6b3272b..7022eb5 100644
--- a/engine/contents.js
+++ b/engine/contents.js
@@ -1,6 +1,7 @@
/* The book's cover and contents (index.html): interface text, the chapter list with reading progress, the guide,
and the cover ↔ contents ↔ lesson motion. Load it in <head>; after the markup, the page calls
- Contents.book({ units, start, hues }) with its chapter list. */
+ Contents.book({ units, start, hues }) with its chapter list. With refs.js (REFS, built by the skill's
+ scripts/refs.py) loaded first, the page also gets its References view (#references). */
'use strict';
// Observe aborted incoming transitions before the first rendering opportunity.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
@@ -15,6 +16,10 @@ const Contents = (() => {
metaUnits: { one: '{n} unit', other: '{n} units' }, metaSamples: { one: ' + {n} sample', other: ' + {n} samples' }, samples: 'Sample chapters, another look',
chapterCount: { one: '{n} chapter', other: '{n} chapters' }, finished: '{done} of {n} finished',
doneMark: '✓ Finished · ', lastMark: ' · Last opened',
+ references: 'References', viewAll: 'View all →', backToContents: '← Contents',
+ refsLead: 'Every work cited in the lessons. Each link opens the work’s DOI or library record in a new tab; works with no reliable online record are listed without a link.',
+ refsCount: { one: '{n} work cited in the lessons', other: '{n} works cited in the lessons' },
+ refsAllLinked: ', each linked to its source', refsSomeLinked: ', {n} linked to their sources',
},
ru: {
open: 'Открыть книгу', toCover: 'К обложке', resume: 'Продолжить · Глава {n}', unit: 'Раздел {n}', minutes: '{n} мин',
@@ -25,6 +30,10 @@ const Contents = (() => {
samples: 'Пробные главы в другом стиле',
chapterCount: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' }, finished: 'Пройдено {done} из {n}',
doneMark: '✓ Пройдено · ', lastMark: ' · Открыта последней',
+ references: 'Список литературы', viewAll: 'Весь список →', backToContents: '← Оглавление',
+ refsLead: 'Все работы, которые цитируются в уроках. Ссылка открывает DOI или библиотечную запись в новой вкладке; работы без надёжной записи в сети даны без ссылки.',
+ refsCount: { one: '{n} работа цитируется в уроках', few: '{n} работы цитируются в уроках', many: '{n} работ цитируются в уроках', other: '{n} работы цитируются в уроках' },
+ refsAllLinked: ', у каждой есть ссылка на источник', refsSomeLinked: ', ссылок на источник: {n}',
},
zh: {
open: '打开这本书', toCover: '返回封面', resume: '继续 · 第 {n} 章', unit: '第 {n} 单元', minutes: '{n} 分钟',
@@ -32,6 +41,9 @@ const Contents = (() => {
metaSamples: ' + {n} 个示例章', samples: '示例章,另一种风格',
chapterCount: '{n} 章', finished: '已完成 {done} / {n}',
doneMark: '✓ 已完成 · ', lastMark: ' · 上次打开',
+ references: '参考文献', viewAll: '查看全部 →', backToContents: '← 目录',
+ refsLead: '课程中引用的全部作品。每个链接会在新标签页中打开该作品的 DOI 或图书馆记录;没有可靠在线记录的作品不附链接。',
+ refsCount: '课程中引用了 {n} 部作品', refsAllLinked: ',均链接到来源', refsSomeLinked: ',其中 {n} 部链接到来源',
},
ja: {
open: '本を開く', toCover: '表紙に戻る', resume: '続きから · 第{n}章', unit: '単元 {n}', minutes: '{n}分',
@@ -39,6 +51,9 @@ const Contents = (() => {
metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
},
};
const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
@@ -54,7 +69,7 @@ const Contents = (() => {
}
const $ = id => document.getElementById(id);
const id = n => 'ch' + String(n).padStart(2, '0');
- const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];
// Fixed interface text: data-t replaces an element's first text, data-t-label its aria-label.
@@ -114,6 +129,20 @@ const Contents = (() => {
}
}
+ // The References view, from refs.js: full entries, each linked to its DOI or catalogue record. It appears as one
+ // link at the end of the contents only when the book cites something.
+ function references() {
+ const all = Object.values(typeof REFS === 'object' && REFS ? REFS : {});
+ if (!$('refList') || !all.length) return;
+ $('refList').innerHTML = all.sort((a, b) => a.ref.localeCompare(b.ref)).map(r => `<li>${esc(r.ref)}${r.url
+ ? ` <a href="${esc(r.url)}" target="_blank" rel="noopener">${esc(r.url.replace(/^https?:\/\//, ''))}</a>` : ''}</li>`).join('');
+ const linked = all.filter(r => r.url).length;
+ $('refsCount').textContent = translate('refsCount', { n: all.length }) +
+ (linked === all.length ? translate('refsAllLinked') : translate('refsSomeLinked', { n: linked }));
+ $('rpBook').innerHTML = document.querySelector('#contents .home strong')?.innerHTML || '';
+ $('refsMore').hidden = false;
+ }
+
// The guide, drawn the same way as in the lessons, in the page's chalk (ink) colour.
function lemniscate(cx, cy, a, k) {
let d = '';
@@ -134,21 +163,24 @@ const Contents = (() => {
}
}
- // The cover and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+ // The cover, the contents and the references share this page: no hash or #book shows the cover, #references the
+ // reference list, #contents or #chNN the contents.
// Lessons link back with #chNN, so the reader lands on the chapter they just left.
function views() {
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
function show(animate) {
- const open = location.hash.length > 1 && location.hash !== '#book';
+ const refs = location.hash === '#references';
+ const open = location.hash.length > 1 && location.hash !== '#book' && !refs;
const apply = () => {
document.body.classList.toggle('open', open);
+ document.body.classList.toggle('refsview', refs);
document.body.classList.toggle('stagger', animate && open);
const here = open ? $(location.hash.slice(1)) : null;
document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));
if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }
else scrollTo(0, 0);
if (animate) {
- const heading = document.querySelector(open ? '#contents .home' : '#cover h1');
+ const heading = document.querySelector(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
heading?.setAttribute('tabindex', '-1');
heading?.focus({ preventScroll: true });
}
@@ -184,6 +216,7 @@ const Contents = (() => {
function book({ units, start = { unit: 1, chapter: 1 }, hues = HUES, progressKey, ink } = {}) {
translatePage();
contents(units, start, hues, progress(progressKey ?? 'animebook:progress:' + new URL('.', location.href).pathname));
+ references();
guides(ink || getComputedStyle(document.documentElement).getPropertyValue('--chalk').trim() || '#ece8dc');
views();
}
diff --git a/engine/engine.css b/engine/engine.css
index 9b9be00..9e8e535 100644
--- a/engine/engine.css
+++ b/engine/engine.css
@@ -221,6 +221,22 @@ svg.m { display: inline-block; overflow: visible; }
@media (prefers-reduced-motion: reduce) { .card, .fb, .opt, .grid .mark, .mascot * { animation: none !important; } }
a.icon { text-decoration: none; }
+/* Citations (cite() and plain-text labels found in refs.js) and the finish card's source list open the source in a new tab. */
+a.cite { cursor: pointer; }
+a.cite text, a.cite tspan { text-decoration: underline; text-decoration-thickness: 1.5px; text-underline-offset: 5px; }
+a.cite:hover text, a.cite:hover tspan { fill: var(--quiz); }
+a.cite:focus { outline: none; }
+a.cite:focus-visible text, a.cite:focus-visible tspan { fill: var(--task); }
+a.cite:focus-visible { outline: 3px solid var(--task); outline-offset: 6px; border-radius: 4px; }
+#ui a.cite { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
+#ui a.cite:hover { color: var(--quiz); }
+.fin .srcs { margin: 26px 0 0; max-width: 1100px; font-size: 19px; line-height: 1.45; color: var(--dim); text-align: left; }
+.fin .srcs h2 { margin: 0 0 6px; font-size: 18px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.fin .srcs ol { margin: 0; padding-left: 0; list-style: none; max-height: 190px; overflow: auto; }
+.fin .srcs li { padding-left: 2em; text-indent: -2em; margin: 0 0 6px; }
+.fin .srcs a { color: var(--chalk); text-underline-offset: 3px; }
+.fin .srcs a:hover { color: var(--quiz); }
+.fin .srcs a:focus-visible { outline: 3px solid var(--task); outline-offset: 2px; }
a.btn { text-decoration: none; display: inline-block; }
/* Page-to-page motion: the contents card grows into this frame, and shrinks back on the way out. */
@view-transition { navigation: auto; }
diff --git a/engine/engine.js b/engine/engine.js
index 883103d..5c3aad3 100644
--- a/engine/engine.js
+++ b/engine/engine.js
@@ -38,7 +38,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '{n} steps left of 0',
natural: 'Natural', whole: 'Whole', integers: 'Integers', rational: 'Rational', irrational: 'Irrational', real: 'Real', integerColumn: 'Integer',
trueLabel: 'True', falseLabel: 'False',
- chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice',
+ chapterComplete: 'Chapter {n} complete', quickChecks: 'Quick checks', chapterPractice: 'Chapter practice', sources: 'Sources in this chapter', opensSource: '{label}, opens the source in a new tab',
firstTryScore: '{name}: {r} of {t} right on the first try.', notAttempted: '{name}: not attempted.',
watchAgain: 'Watch again', nextChapter: 'Next chapter',
},
@@ -74,7 +74,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: { one: '{n} шаг влево от 0', few: '{n} шага влево от 0', many: '{n} шагов влево от 0', other: '{n} шага влево от 0' },
natural: 'Натуральные', whole: 'Целые неотрицательные', integers: 'Целые', rational: 'Рациональные', irrational: 'Иррациональные', real: 'Действительные', integerColumn: 'Целые',
trueLabel: 'Верно', falseLabel: 'Неверно',
- chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе',
+ chapterComplete: 'Глава {n} пройдена', quickChecks: 'Проверь себя', chapterPractice: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
},
@@ -108,7 +108,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 左边 {n} 步',
natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
trueLabel: '对', falseLabel: '错',
- chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
watchAgain: '再看一遍', nextChapter: '下一章',
},
@@ -142,7 +142,7 @@ const TRANSLATIONS = {
stepsLeftOfZero: '0 から左へ {n}',
natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
trueLabel: '正しい', falseLabel: '誤り',
- chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
watchAgain: 'もう一度見る', nextChapter: '次の章へ',
},
@@ -298,6 +298,81 @@ function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI,
t.style.whiteSpace = 'pre';
return put(t, { x, y, o });
}
+// A citation drawn in the picture that opens its source (REFS from ../refs.js, built by scripts/refs.py) in a new tab.
+// cite(p, key, opts) takes T's options; str overrides the label (default REFS[key].cite). Returns the <a>; animate it like T.
+const CITED = new Set();
+function cite(parent, key, { str, ...opts } = {}) {
+ const r = (typeof REFS === 'object' && REFS) ? REFS[key] : null;
+ if (!r) throw new Error(`cite: no reference "${key}" in refs.js`);
+ CITED.add(key);
+ if (!r.url) return T(parent, str || r.cite, opts);
+ linkStage();
+ const a = mk('a', { class: 'cite', href: r.url, target: '_blank', rel: 'noopener', 'aria-label': translate('opensSource', { label: r.cite }) }, parent);
+ const { o = 1, x = 0, y = 0, ...rest } = opts;
+ T(a, str || r.cite, { ...rest, fill: rest.fill || COL.chalk });
+ return put(a, { x, y, o });
+}
+// Any text in the picture or a card that equals a reference's cite label or one of its match strings (case-insensitive)
+// becomes a link to the source, so chapters write citations as plain text. Watched by citeObs (set up after the player).
+let CITE_RE = null, CITE_KEY = null;
+function citeIndex() {
+ if (CITE_RE !== null) return CITE_RE;
+ CITE_KEY = new Map();
+ for (const [k, r] of Object.entries(typeof REFS === 'object' && REFS ? REFS : {}))
+ for (const s of [r.cite, ...(r.match || [])]) if (s) CITE_KEY.set(s.toLowerCase(), k);
+ const alts = [...CITE_KEY.keys()].sort((a, b) => b.length - a.length).map(s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
+ return (CITE_RE = alts.length ? new RegExp(alts.join('|'), 'gi') : false);
+}
+function autoCite(root) {
+ const re = citeIndex();
+ if (!re) return;
+ const nodes = [];
+ if (root.nodeType === 3) nodes.push(root);
+ else if (root.nodeType === 1) for (let w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT), n; (n = w.nextNode());) nodes.push(n);
+ for (const n of nodes) {
+ const host = n.parentElement;
+ if (!host || host.closest('a, button, input, script, style, kbd')) continue; // no links inside controls
+ const ms = [...n.data.matchAll(re)];
+ if (!ms.length) continue;
+ const svg = host.namespaceURI === NS, frag = document.createDocumentFragment();
+ let i = 0, made = 0;
+ for (const m of ms) {
+ const k = CITE_KEY.get(m[0].toLowerCase()), r = REFS[k];
+ CITED.add(k);
+ if (!r.url) continue; // a work with no reliable online record stays plain text but is still listed
+ frag.append(n.data.slice(i, m.index));
+ const a = svg ? mk('a', { href: r.url }) : document.createElement('a');
+ if (!svg) a.href = r.url;
+ a.setAttribute('class', 'cite');
+ a.setAttribute('target', '_blank');
+ a.setAttribute('rel', 'noopener');
+ a.setAttribute('aria-label', translate('opensSource', { label: m[0] }));
+ if (svg) mk('tspan', {}, a).textContent = m[0]; else a.textContent = m[0];
+ frag.append(a);
+ i = m.index + m[0].length;
+ made++;
+ }
+ if (!made) continue; // replacing the node unchanged would re-trigger the observer
+ if (svg) linkStage();
+ frag.append(n.data.slice(i));
+ n.replaceWith(frag);
+ }
+}
+// The stage is announced as one image; once it holds a link it becomes a group, so the link stays reachable.
+function linkStage() { document.getElementById('stage').setAttribute('role', 'group'); }
+// Links that have faded out (or sit in a faded group) must not take clicks or Tab focus.
+function syncLinks() {
+ for (const a of scene.querySelectorAll('a.cite')) {
+ let o = 1;
+ for (let e = a; e && e !== scene; e = e.parentNode) o *= +(e.getAttribute('opacity') ?? 1);
+ const on = o > .5;
+ if (on === a._on) continue;
+ a._on = on;
+ a.style.pointerEvents = on ? '' : 'none';
+ if (on) { a.removeAttribute('tabindex'); a.removeAttribute('aria-hidden'); }
+ else { a.setAttribute('tabindex', '-1'); a.setAttribute('aria-hidden', 'true'); }
+ }
+}
const ctx2d = document.createElement('canvas').getContext('2d');
function textW(str, size, italic = false) { ctx2d.font = `${italic ? 'italic ' : ''}${size}px ${MATH}`; return ctx2d.measureText(str).width; }
const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|so|up|we|my)(?![A-Za-z]))[a-z]{1,2}|(?!(?:If|In|It|Is|On|At|No|So|Or|An|As|To|By|Up)(?![A-Za-z]))[a-z]?[A-Z]{1,3}[a-z]?)(?![A-Za-z])/g; // capitals: A, PV, nRT // short lowercase runs are variables (a, x, ab), except short English words
@@ -1244,7 +1319,7 @@ function finishCard() {
: isShortcut(e, 'r') ? (restart(), true) : false;
const guide = mascotEl(240);
c.append(h('div', 'finwrap', [guide, h('p', 'kicker', translate('chapterComplete', { n: CHAPTER.label ?? CHAPTER.number })), h('p', 'prompt', CHAPTER.title),
- line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again])]));
+ line(translate('quickChecks'), sum('c-')), line(translate('chapterPractice'), sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again]), sources()].filter(Boolean)));
setTimeout(() => mood(guide, 'happy'), 400);
}
@@ -1253,6 +1328,19 @@ const $ = id => document.getElementById(id);
// The volume control (volume.js, volume.css) lives in its own files next to this one, the same in every book.
document.head.append(Object.assign(document.createElement('script'), { src: new URL('volume.js', document.currentScript.src) }));
const kbd = s => h('kbd', '', s);
+// The chapter's sources: every key passed to cite() plus CHAPTER.refs, as full references that link to the source.
+function sources() {
+ for (const m of citeObs.takeRecords()) for (const n of m.addedNodes) autoCite(n); // link text added just now (a seek to the end)
+ const keys = [...new Set([...(CHAPTER.refs || []), ...CITED])].filter(k => typeof REFS === 'object' && REFS?.[k]);
+ if (!keys.length) return null;
+ const items = keys.map(k => REFS[k]).sort((a, b) => a.ref.localeCompare(b.ref)).map(r => {
+ if (!r.url) return h('li', '', r.ref);
+ const a = h('a', '', r.url.replace(/^https?:\/\//, ''));
+ Object.assign(a, { href: r.url, target: '_blank', rel: 'noopener' });
+ return h('li', '', [r.ref + ' ', a]);
+ });
+ return h('section', 'srcs', [h('h2', '', translate('sources')), h('ol', '', items)]);
+}
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
const SCORE = {}; // question id -> first-attempt {right, total}
@@ -1391,6 +1479,13 @@ const choice = (opts, right, yes, no, onRight) => (body, api) => {
key(e) { const b = bs[+e.key - 1]; if (!b || b.disabled) return false; b.click(); return true; },
};
};
+// A choice question from the chapter's item bank: ITEMS from ./items.js, built by scripts/items.py from the
+// mcq-item-writer JSON. mcq('ID', onRight?) returns a quiz entry, so quiz(TOPR, [mcq('MB-03-01')], done) asks it.
+function mcq(id, onRight) {
+ const it = (typeof ITEMS === 'object' && ITEMS) ? ITEMS[id] : null;
+ if (!it) throw new Error(`mcq: no item "${id}" in items.js`);
+ return { id, prompt: it.prompt, build: choice(it.opts, it.right, it.why, it.no, onRight) };
+}
// The shared body of the stage tap questions: each target ring is a focusable button that answers on click or Enter,
// and ← / → move the focus between them. targets: [{ g, label, ok, wrong }], wrong() shakes and returns the explanation.
const stageTap = (api, targets, show, yes, onRight, hint) => {
@@ -1884,6 +1979,7 @@ function frame(now) {
evalTo(P.t);
if (P.t >= P.end) beatDone();
}
+ syncLinks();
ui();
requestAnimationFrame(frame);
}
@@ -1938,9 +2034,13 @@ const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
const restart = () => { for (const k in SCORE) delete SCORE[k]; hideCover(); seek(0, true); };
$('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
+ if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
});
+const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
+citeObs.observe(scene, { childList: true, subtree: true });
+citeObs.observe($('ui'), { childList: true, subtree: true });
$('bPlay').onclick = togglePlay;
$('bBack').onclick = () => { hideCover(); back1(); };
$('bRestart').onclick = restart;