Skip to content

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

feat(site): Proteus, a 37-second film where Papermorph introduces itself

yzr96ae634e2a87
diff --git a/site/proteus/ch01/audio/bgm/haydn-lark-finale.mp3 b/site/proteus/ch01/audio/bgm/haydn-lark-finale.mp3
new file mode 100644
index 0000000..2ed1aff
Binary files /dev/null and b/site/proteus/ch01/audio/bgm/haydn-lark-finale.mp3 differ
diff --git a/site/proteus/ch01/audio/en/boar.mp3 b/site/proteus/ch01/audio/en/boar.mp3
new file mode 100644
index 0000000..d2d60c3
Binary files /dev/null and b/site/proteus/ch01/audio/en/boar.mp3 differ
diff --git a/site/proteus/ch01/audio/en/dragon.mp3 b/site/proteus/ch01/audio/en/dragon.mp3
new file mode 100644
index 0000000..ff99428
Binary files /dev/null and b/site/proteus/ch01/audio/en/dragon.mp3 differ
diff --git a/site/proteus/ch01/audio/en/leopard.mp3 b/site/proteus/ch01/audio/en/leopard.mp3
new file mode 100644
index 0000000..16edb4b
Binary files /dev/null and b/site/proteus/ch01/audio/en/leopard.mp3 differ
diff --git a/site/proteus/ch01/audio/en/lion.mp3 b/site/proteus/ch01/audio/en/lion.mp3
new file mode 100644
index 0000000..18aa269
Binary files /dev/null and b/site/proteus/ch01/audio/en/lion.mp3 differ
diff --git a/site/proteus/ch01/audio/en/open.mp3 b/site/proteus/ch01/audio/en/open.mp3
new file mode 100644
index 0000000..d8b8d95
Binary files /dev/null and b/site/proteus/ch01/audio/en/open.mp3 differ
diff --git a/site/proteus/ch01/audio/en/timings.js b/site/proteus/ch01/audio/en/timings.js
new file mode 100644
index 0000000..2f9b358
--- /dev/null
+++ b/site/proteus/ch01/audio/en/timings.js
@@ -0,0 +1,128 @@
+window.TIMINGS = {
+ "open": {
+ "dur": 4.369,
+ "marks": {
+ "old": 0.4,
+ "proteus": 1.72,
+ "hands": 3.26
+ },
+ "cues": [
+ [
+ 0.0,
+ "Homer's old man of the sea, Proteus, changes shape in your hands."
+ ]
+ ]
+ },
+ "lion": {
+ "dur": 4.517,
+ "marks": {
+ "lion": 0.56,
+ "lesson": 2.44
+ },
+ "cues": [
+ [
+ 0.0,
+ "First a lion with a great mane:"
+ ],
+ [
+ 2.44,
+ "a lesson that draws itself."
+ ]
+ ]
+ },
+ "dragon": {
+ "dur": 3.643,
+ "marks": {
+ "dragon": 0.32,
+ "book": 1.66
+ },
+ "cues": [
+ [
+ 0.0,
+ "Then a dragon:"
+ ],
+ [
+ 1.66,
+ "a picture book of paper puppets."
+ ]
+ ]
+ },
+ "leopard": {
+ "dur": 2.335,
+ "marks": {
+ "leopard": 0.0,
+ "film": 1.1
+ },
+ "cues": [
+ [
+ 0.0,
+ "A leopard:"
+ ],
+ [
+ 1.1,
+ "a narrated film."
+ ]
+ ]
+ },
+ "boar": {
+ "dur": 2.988,
+ "marks": {
+ "boar": 0.0,
+ "short": 1.38
+ },
+ "cues": [
+ [
+ 0.0,
+ "A wild boar:"
+ ],
+ [
+ 1.38,
+ "a short for the phone."
+ ]
+ ]
+ },
+ "water": {
+ "dur": 2.767,
+ "marks": {
+ "water": 0.0,
+ "map": 1.22
+ },
+ "cues": [
+ [
+ 0.0,
+ "Running water:"
+ ],
+ [
+ 1.22,
+ "a map to explore."
+ ]
+ ]
+ },
+ "tree": {
+ "dur": 6.26,
+ "marks": {
+ "tree": 0.14,
+ "one": 2.82,
+ "many": 3.98,
+ "name": 5.24
+ },
+ "cues": [
+ [
+ 0.0,
+ "And a tree, where every shape stands."
+ ],
+ [
+ 2.82,
+ "One source."
+ ],
+ [
+ 3.98,
+ "Many shapes."
+ ],
+ [
+ 5.24,
+ "Papermorph."
+ ]
+ ]
+ }
+};
diff --git a/site/proteus/ch01/audio/en/tree.mp3 b/site/proteus/ch01/audio/en/tree.mp3
new file mode 100644
index 0000000..1130d85
Binary files /dev/null and b/site/proteus/ch01/audio/en/tree.mp3 differ
diff --git a/site/proteus/ch01/audio/en/water.mp3 b/site/proteus/ch01/audio/en/water.mp3
new file mode 100644
index 0000000..e8993c1
Binary files /dev/null and b/site/proteus/ch01/audio/en/water.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/growl.mp3 b/site/proteus/ch01/audio/sfx/growl.mp3
new file mode 100644
index 0000000..c31a850
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/growl.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/grunt.mp3 b/site/proteus/ch01/audio/sfx/grunt.mp3
new file mode 100644
index 0000000..5fdf1e2
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/grunt.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/hiss.mp3 b/site/proteus/ch01/audio/sfx/hiss.mp3
new file mode 100644
index 0000000..39b9580
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/hiss.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/roar.mp3 b/site/proteus/ch01/audio/sfx/roar.mp3
new file mode 100644
index 0000000..d83e1e4
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/roar.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/splash.mp3 b/site/proteus/ch01/audio/sfx/splash.mp3
new file mode 100644
index 0000000..cec8ed8
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/splash.mp3 differ
diff --git a/site/proteus/ch01/audio/sfx/whoosh.mp3 b/site/proteus/ch01/audio/sfx/whoosh.mp3
new file mode 100644
index 0000000..6c63e5e
Binary files /dev/null and b/site/proteus/ch01/audio/sfx/whoosh.mp3 differ
diff --git a/site/proteus/ch01/index.html b/site/proteus/ch01/index.html
new file mode 100644
index 0000000..09748c8
--- /dev/null
+++ b/site/proteus/ch01/index.html
@@ -0,0 +1,153 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Proteus</title>
+<link rel="stylesheet" href="../lib/engine.css">
+<link rel="expect" href="#bar" blocking="render">
+</head>
+<body>
+<!-- A documentary chapter: one beat per paragraph of the script. After engine.py has made site/<book>/lib/, copy lib/
+ found pictures; add lib/lines.js (trace.py) and img/frames.js (frames.py) when the film uses traced drawings or clips. -->
+<script src="../lib/engine.js"></script>
+<script src="../lib/film.js"></script>
+<script src="audio/en/timings.js"></script>
+<script>
+'use strict';
+// lead: false — every opening is timed by hand, so the engine never pulls a beat's first reveal earlier
+const CHAPTER = { number: 1, title: 'Proteus', minutes: 1, language: 'en', lead: false };
+
+const CX = 1130, CY = 400, KY = 690; // each shape's card, and its word under it
+
+// a card for one shape with its word, at the shape's second mark
+function shapeCard(p, name, col, word, t0, cx = CX) {
+ const g = sheet(p, cx, CY, col, t0 - .1);
+ CARDS[name](g, t0);
+ key(p, word, cx, KY, t0 + .1, { size: 72, fill: col });
+ tw(S.pro.disc, { x: cx, c_fill: col }, Math.max(0, t0 - 1.3), .9, soft); // the colour field follows the card
+ return g;
+}
+// the leopard's spots, on its body in stage coordinates; they fly off to be the film strip's holes
+const SPOTS = [[-190, -112], [-140, -128], [-95, -104], [-50, -128], [-5, -108], [40, -130], [85, -110], [130, -128], [-120, -95], [-25, -90], [65, -92], [150, -100]];
+const HOLES = SPOTS.map((_, i) => [CX - 220 + (i % 6) * 88, CY + (i < 6 ? -146 : 146)]);
+// a hand of the one who holds on (Menelaus), cut from paper, reaching from the side dir (-1 left, 1 right)
+function hand(p, x, y, dir) {
+ const g = G(p, { x: x - dir * 260, y, o: 0 });
+ const h = G(g, { s: dir < 0 ? 1 : -1 }); // drawn for the left hand; mirrored for the right
+ path(h, 'M-240 -30H-70C-40 -44 -6 -34 6 -8C16 16 12 44 -10 52C-30 58 -60 50 -80 40H-240Z', { fill: '#c98f62' });
+ path(h, 'M-74 -32C-66 -66 -30 -72 -12 -54C-20 -44 -36 -40 -50 -30Z', { fill: '#d9a275' });
+ path(h, 'M-16 -14C-6 -10 0 0 2 8M-20 10C-10 14 -4 22 -4 30M-30 32C-22 36 -18 42 -18 46', { stroke: '#a8714a', 'stroke-width': 3, fill: 'none', 'stroke-linecap': 'round' });
+ return g;
+}
+
+/* ---------- beats ----------
+ [id, title, run, extra]: id names audio/en/<id>.mp3 and its TIMINGS entry; m('mark') is the time a word is heard.
+ `pre` gives the picture seconds before the narration starts. The last frame is the first (the page), so it loops. */
+// every beat's length on screen, hold included (a little over what it needs; ?lengths shows it), so the film has one
+// clock: the start of each beat (the waves run on it) and its whole length, the loop
+const LEN = { open: 5.8, lion: 5.4, dragon: 4.3, leopard: 3.8, boar: 4.1, water: 4.2, tree: 9.3 };
+const AT0 = {}; let FILM_LEN = 0;
+for (const id in LEN) { AT0[id] = FILM_LEN; FILM_LEN += LEN[id]; }
+window.FILM_LEN = FILM_LEN;
+
+// a beat's picture: the last beat's card fades on this beat's clock (in the export too), gone before Proteus lands
+function nextPanel() {
+ if (S.panel) hide(S.panel, 0, .35);
+ return panel(.5);
+}
+
+// Proteus changes in beat `id`: the morph, a splash as he melts, and the animal's call once he has the shape
+// (the call waits for the pause after the animal is named, so it never covers a word)
+function change(id, D, from, to, t0, dur, call, vol = 1, callAt = t0 + dur) {
+ S.at0 = AT0[id];
+ morph(D, from, to, t0, dur, callAt);
+ sfx(id, t0, 'splash', .45);
+ if (call) sfx(id, callAt, call, vol);
+}
+
+const BEATS = [
+ ['open', 'Proteus', (m, D) => {
+ proteus();
+ const p = nextPanel();
+ change('open', D, 'page', 'water', .3, 1.4, null, 1, m('hands'));
+ key(p, 'Proteus', CX, CY + 20, m('proteus'), { size: 120, fill: DEEP });
+ const tg = tag(p, 'Odyssey, book IV', CX, CY + 80, m('proteus', .4), { size: 30, anchor: 'middle' });
+ tg.setAttribute('font-style', 'italic');
+ [-1, 1].forEach(dir => { const h = hand(p, 470 + dir * 130, 610, dir); tw(h, { x: 470 + dir * 130, o: 1 }, m('hands', -.3), .5, out);
+ tw(h, { x: 470 + dir * 330, o: 0 }, D - .1, .5, io); // he slips out of them
+ });
+ }, { pre: .4 }],
+ ['lion', 'A lesson', (m, D) => {
+ const p = nextPanel();
+ change('lion', D, 'water', 'lion', Math.max(0, m('lion', -.45)), .9, 'roar', .8, m('lesson', -.72));
+ shapeCard(p, 'lesson', RED, 'a lesson', m('lesson'));
+ }],
+ ['dragon', 'A picture book', (m, D) => {
+ const p = nextPanel();
+ change('dragon', D, 'lion', 'dragon', Math.max(0, m('dragon', -.3)), .9, 'hiss', .7, m('book', -.56));
+ shapeCard(p, 'book', BLUE, 'a picture book', m('book'), 470);
+ }],
+ ['leopard', 'A film', (m, D) => {
+ const p = nextPanel();
+ change('leopard', D, 'dragon', 'leopard', m('leopard', -.6), .8, 'growl', 1.4, m('film', -.62));
+ const strip = G(p, { x: 470, y: 760 });
+ shapeCard(p, 'film', PURPLE, 'a film', m('film'));
+ p.appendChild(strip); // the spots go over the card as its holes
+ clockRun(t => { // on the body, then level while they fly
+ const { x, y, r } = st(S.pro.g), k = smooth01(span01(t, m('film'), m('film', .7)));
+ put(strip, { x: x + (470 - x) * k, y: y + (760 - y) * k, r: r * (1 - k) });
+ }, D, { tail: true });
+ SPOTS.forEach(([x, y], i) => {
+ const e = G(strip, { x, y, o: 0 });
+ const r = mk('rect', { x: -11, y: -8, width: 22, height: 16, rx: 5, fill: '#3b2357' }, e);
+ show(e, m('leopard', .15), .3);
+ tw(e, { x: HOLES[i][0] - 470, y: HOLES[i][1] - 760 }, m('film', i * .03), .7, soft);
+ tw(r, { c_fill: '#f3ede0' }, m('film', .5), .3);
+ });
+ }, { pre: .6 }],
+ ['boar', 'A short', (m, D) => {
+ const p = nextPanel();
+ change('boar', D, 'leopard', 'boar', m('boar', -.5), .8, 'grunt', .9, m('short', -.44));
+ shapeCard(p, 'short', OCHRE, 'a short', m('short'), 470);
+ }, { pre: .5 }],
+ ['water', 'A map', (m, D) => {
+ const p = nextPanel();
+ change('water', D, 'boar', 'stream', m('water', -.5), .9, 'whoosh', .6, m('map', -.54));
+ shapeCard(p, 'map', TEAL, 'a map', m('map'));
+ }, { pre: .5 }],
+ ['tree', 'One source', (m, D) => {
+ const p = nextPanel();
+ const t1 = m('tree', -.5), t2 = m('name', 2.2); // into the tree, then back to the page
+ sfx('tree', t1, 'splash', .7); sfx('tree', t2, 'splash', .6);
+ S.at0 = AT0.tree; sea(D);
+ clockRun(t => t < t2 ? drawPro('stream', 'tree', smooth01(span01(t, t1, t1 + 1.1)), t, t - t1 - 1.1)
+ : drawPro('tree', 'page', smooth01(span01(t, t2, t2 + 1.2)), t), D, { tail: true });
+ S.pro.at = 'page';
+ const T0 = SHAPES.tree;
+ const shelf = [['lesson', RED, -250, -322], ['book', BLUE, -220, -492], ['film', PURPLE, 0, -684], ['short', OCHRE, 228, -547], ['map', TEAL, 252, -380]];
+ shelf.forEach(([name, col, x, y], i) => {
+ const g = sheet(p, T0.x + x, T0.y + y, col, m('tree', .9 + i * .22), { s: .3 });
+ CARDS[name](g, m('tree', 1 + i * .22));
+ tw(g, { x: SHAPES.page.x, y: SHAPES.page.y - 210, s: .1 }, t2 - .3 + i * .05, .6, io); // the shapes go back into the one source
+ hide(g, t2 - .1 + i * .05, .3);
+ });
+ [['One source.', 380, m('one')], ['Many shapes.', 490, m('many')]].forEach(([w, y, t]) => hide(key(p, w, 1250, y, t, { size: 96 }), t2, .5));
+ hide(key(p, 'Papermorph', 1250, 640, m('name'), { size: 80, fill: DEEP }), t2, .5);
+ tw(S.pro.disc, { x: 1250, c_fill: WATER }, m('one', -.6), .9, soft);
+ tw(S.pro.disc, { x: CX }, t2, 1.2, soft); // where the film starts, so it loops
+ prog(() => {}, 0, t2 + 1.25); // hold the page a moment: the film's last frame is its first
+ }],
+].map(([id, title, run, extra]) => ({ id, title, run, ...extra, minDur: LEN[id] }));
+
+/* ---------- music ----------
+ One music(file, [beat ids], gain, fade) per part of the film; window.MUSIC_UP_IN_PRE lifts it in a music-only opening. */
+window.MUSIC_UP_IN_PRE = ['open'];
+music('audio/bgm/haydn-lark-finale.mp3', BEATS.map(b => b.id), .6, 0);
+
+// the fonts must be in before words are measured
+Promise.all(['600 40px Oswald', '500 40px Oswald', 'italic 400 40px "EB Garamond"', '400 40px "EB Garamond"']
+ .map(f => document.fonts.load(f))).then(boot);
+</script>
+</body>
+</html>
diff --git a/site/proteus/img/cover.webp b/site/proteus/img/cover.webp
new file mode 100644
index 0000000..7dc7645
Binary files /dev/null and b/site/proteus/img/cover.webp differ
diff --git a/site/proteus/index.html b/site/proteus/index.html
new file mode 100644
index 0000000..84f7d86
--- /dev/null
+++ b/site/proteus/index.html
@@ -0,0 +1,74 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Proteus</title>
+<meta name="description" content="Papermorph introduces itself: Proteus, the old man of the sea, becomes a lesson, a picture book, a film, a short and a map.">
+<link rel="stylesheet" href="lib/book.css"><!-- only for --progress-key, if the book sets one -->
+<style>
+ :root { --ink: #2f2418; --soft: #6b5a46; --paper: #f3ecdc; --card: #fffaf0; --line: #e4d6bb; --accent: #2b6f8f;
+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif; --serif: "Iowan Old Style", Palatino, Georgia, serif; color-scheme: light; }
+ * { box-sizing: border-box; }
+ body { margin: 0; background: var(--paper); color: var(--ink); font: 18px/1.6 var(--ui); }
+ header { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 40px; align-items: center; max-width: 1180px; margin: 0 auto; padding: 48px 24px 24px; }
+ header img { width: 100%; height: auto; border-radius: 10px; box-shadow: 0 14px 40px #4a33182e; }
+ h1 { margin: 0 0 8px; font: 700 clamp(34px, 4.6vw, 56px)/1.05 var(--serif); }
+ .lede { font-size: 20px; color: var(--soft); }
+ main { max-width: 1000px; margin: 0 auto; padding: 8px 24px 80px; }
+ .episodes { list-style: none; padding: 0; margin: 18px 0; display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
+ .episodes a { display: flex; flex-direction: column; height: 100%; background: var(--card); border: 1px solid var(--line); border-radius: 10px;
+ overflow: hidden; color: var(--ink); text-decoration: none; transition: border-color .15s, transform .15s; }
+ .episodes a:hover, .episodes a:focus-visible { border-color: var(--accent); transform: translateY(-2px); }
+ .episodes img { display: block; width: 100%; height: auto; aspect-ratio: 16 / 9; object-fit: cover; }
+ .episodes small { margin: 12px 16px 0; color: var(--soft); font-size: 13px; font-weight: 600; letter-spacing: .03em; text-transform: uppercase; }
+ .episodes b { margin: 2px 16px 4px; font: 700 21px/1.25 var(--serif); }
+ .episodes span { margin: 0 16px 16px; color: var(--soft); font-size: 15px; line-height: 1.5; }
+ .watched small::after { content: " · ✓ watched"; color: var(--accent); }
+ .credits { margin-top: 48px; color: var(--soft); font-size: 15px; } .credits h2 { font: 700 22px/1.2 var(--serif); color: var(--ink); }
+ .credits a { color: var(--accent); }
+ @media (max-width: 760px) { header { grid-template-columns: 1fr; padding-top: 28px; } .episodes { grid-template-columns: 1fr; } }
+</style>
+</head>
+<body>
+<header>
+ <img src="img/cover.webp" width="1400" height="788" alt="A paper tree whose branches hold five small cards: a lesson, a picture book, a film, a short and a map, beside the words One source, many shapes, Papermorph.">
+ <div>
+ <h1>Proteus</h1>
+ <p class="lede">Homer’s old man of the sea changes shape in your hands, and so does a source in Papermorph: a lesson, a picture book, a film, a short, a map.</p>
+ </div>
+</header>
+<main>
+ <ul class="episodes" id="episodes"></ul>
+ <section class="credits">
+ <h2>Sources</h2>
+ <ul>
+ <li>The story: Homer, <i>The Odyssey</i>, book IV, translated by Samuel Butler (1900), <a href="https://www.gutenberg.org/ebooks/1727">Project Gutenberg</a>, public domain.</li>
+ <li>Music: Joseph Haydn, String Quartet in D major, Op. 64 No. 5 “The Lark”, finale, Musopen String Quartet, <a href="https://commons.wikimedia.org/wiki/File:Haydn_StringQuartetInDMajorOp.64_JosephHaydn-StringQuartetInDOp.645H363Lark-04-FinaleVivace.ogg">Wikimedia Commons</a>, public domain.</li>
+ <li>The lion: <a href="https://commons.wikimedia.org/wiki/File:Lion_raring-sound1TamilNadu178.ogg">a lion roaring</a>, recorded in Tamil Nadu by த*உழவன், public domain.</li>
+ <li>The leopard: <a href="https://commons.wikimedia.org/wiki/File:Yellowstone_sound_library_-_Grizzly_Bears_Roar_-_001.mp3">grizzly bears roaring</a>, Yellowstone sound library, NPS &amp; MSU Acoustic Atlas / Jennifer Jerrett, public domain.</li>
+ <li>The dragon: <a href="https://commons.wikimedia.org/wiki/File:Cat_hissing_-_Zabuhailo.wav">a cat hissing</a>, Zabuhailo (Freesound), CC0.</li>
+ <li>The boar: <a href="https://commons.wikimedia.org/wiki/File:Man_grunts_like_pig.ogg">a man grunting like a pig</a>, stilgar (PDSounds), public domain.</li>
+ <li>Pictures: cut paper drawn in code for this film. Splashes and the rush of water synthesized. Narration: ElevenLabs.</li>
+ </ul>
+ </section>
+</main>
+<script>
+'use strict';
+// One entry per finished episode, in order: its folder, title, a still (16:9) with alt text, and one line.
+const EPISODES = [
+ { ch: 'ch01', title: 'One source, many shapes', minutes: 1, still: 'img/cover.webp', alt: 'The paper tree holding five shapes.', line: 'A lion, a dragon, a leopard, a wild boar, running water: five shapes of one source, gathered on a tree.' },
+];
+// The player records finished episodes under the same key as here (engine progress(): lib/book.css --progress-key,
+// else this folder's path).
+const key = getComputedStyle(document.documentElement).getPropertyValue('--progress-key').trim().replace(/^["']|["']$/g, '')
+ || 'animebook:progress:' + new URL('.', location.href).pathname;
+let done = [];
+try { done = JSON.parse(localStorage.getItem(key) || '{}').done || []; } catch {}
+const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
+document.getElementById('episodes').innerHTML = EPISODES.map((e, i) => `<li${done.includes(+e.ch.slice(2)) ? ' class="watched"' : ''}>
+ <a href="${e.ch}/"><img src="${esc(e.still)}" alt="${esc(e.alt)}" loading="lazy">
+ <small>Episode ${i + 1} · ${e.minutes} minute${e.minutes == 1 ? "" : "s"}</small><b>${esc(e.title)}</b><span>${esc(e.line)}</span></a></li>`).join('');
+</script>
+</body>
+</html>
diff --git a/site/proteus/lib/book.css b/site/proteus/lib/book.css
new file mode 100644
index 0000000..75d6172
--- /dev/null
+++ b/site/proteus/lib/book.css
@@ -0,0 +1,14 @@
+/* The film's colours (Proteus: the landing page's paper and ink): --board is the ground, --chalk the ink on it,
+ --dim captions; --accent, and an old document's --paper, --paper-ink and --stamp, are read by film.js. Bake pictures
+ to match (prep.py and frames.py --ink is --chalk, prep.py --paper the paper). Imported by engine.css; engine.py never
+ overwrites it. */
+@import url("fonts.css");
+:root {
+ --page: #e9e1cf; --board: #f3ecdc; --panel: #fbf7ee; --edge: #d8ccb4;
+ --chalk: #26231f; --dim: #5d564c; --faint: #b9ad97;
+ --task: #b5383c; --quiz: #2b78a6; --good: #3f8a1d; --bad: #b5383c;
+ --on-fill: #fffaf0; --vignette: rgba(90, 70, 30, .10); color-scheme: light;
+ --rule: #e6dccb; --track: #e2d8c4; --track-ask: #cfdeeb;
+ --bar-edge: #e2d8c4; --hover: #ece3d1; --veil: #e9e1cf;
+ --accent: #b5383c; --paper: #fbf7ee; --paper-ink: #26231f; --stamp: #b5383c;
+}
diff --git a/site/proteus/lib/contents.css b/site/proteus/lib/contents.css
new file mode 100644
index 0000000..d8f7f70
--- /dev/null
+++ b/site/proteus/lib/contents.css
@@ -0,0 +1,137 @@
+/* The book's cover and contents (index.html): the chalkboard look, the cover, the guide, the chapter grid and the
+ page-to-page motion. A book's own <style> after this file sets its theme: the colour and font tokens below, and the
+ few rules a theme redraws (e.g. body::before for the paper). */
+:root {
+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;
+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --book: "Iowan Old Style", Palatino, Georgia, serif;
+ --ease: cubic-bezier(.2, .8, .2, 1);
+ --top-bg: rgba(22, 33, 29, .86); --top-line: #2a3b35; /* the sticky contents header */
+ --lift: rgba(0, 0, 0, .3); /* a card's shadow on hover */
+ color-scheme: dark;
+}
+* { box-sizing: border-box; }
+html { scroll-padding-top: 90px; }
+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }
+/* Chalkboard: the same grain and vignette as the lesson stage. */
+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }
+a { color: inherit; }
+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }
+
+/* ---------- cover ---------- */
+#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; }
+#cover h1 { animation-delay: 1s; }
+#cover .lede { animation-delay: 1.12s; }
+#cover .acts { animation-delay: 1.24s; }
+#cover .meta { animation-delay: 1.36s; }
+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }
+h1 i { color: var(--task); font-style: italic; }
+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }
+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }
+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;
+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }
+.btn[hidden] { display: none; }
+.btn:hover { transform: translateY(-2px); }
+.btn.go { background: var(--chalk); color: var(--board); }
+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }
+.btn.quiet:hover { border-color: var(--dim); }
+.btn svg { width: 15px; height: 15px; fill: currentColor; }
+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }
+/* Faint chalk notes around the edges of the board. */
+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }
+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;
+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }
+@keyframes chalk { to { opacity: .075; } }
+@keyframes drift { to { translate: 0 -10px; } }
+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }
+
+/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */
+.mascot { display: block; overflow: visible; }
+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }
+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }
+.mascot .joy { display: none; }
+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }
+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }
+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }
+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }
+@keyframes draw { from { stroke-dashoffset: 1; } }
+@keyframes pop { from { opacity: 0; transform: scale(.6); } }
+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }
+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }
+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }
+
+/* ---------- contents ---------- */
+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));
+ background: var(--top-bg); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid var(--top-line); }
+.home { display: flex; align-items: center; gap: 12px; text-decoration: none; border-radius: 10px; }
+.home .mascot { view-transition-name: guide; }
+.home strong { font: 500 22px/1.1 var(--book); view-transition-name: book; }
+.home strong i { color: var(--task); }
+.prog { margin-left: auto; color: var(--dim); font-size: 15px; white-space: nowrap; }
+.prog b { color: var(--good); font-weight: 600; }
+main#contents { padding-bottom: 80px; }
+.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 290px), 1fr)); gap: 12px; }
+.ch { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: 1fr auto; column-gap: 16px; row-gap: 8px; min-height: 112px;
+ padding: 16px 18px 14px 16px; border-radius: 16px; background: var(--panel); border: 1.5px solid var(--edge); border-left: 6px solid var(--c);
+ text-decoration: none; transition: transform .3s var(--ease), border-color .3s, box-shadow .3s; }
+.ch:hover { transform: translateY(-3px); border-color: var(--c); box-shadow: 0 14px 34px var(--lift); }
+.ch b { grid-row: span 2; min-width: 1.15em; font: 500 42px/1 var(--book); color: var(--c); font-variant-numeric: lining-nums tabular-nums; }
+.ch span { font-size: 18px; line-height: 1.3; }
+.ch small { color: var(--dim); font-size: 14px; }
+.ch.done small::before { content: var(--done, "✓ Finished · "); color: var(--good); font-weight: 600; }
+.ch.last small::after { content: var(--last, " · Last opened"); color: var(--quiz); }
+.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); }
+
+/* ---------- page-to-page motion ---------- */
+@view-transition { navigation: auto; }
+/* Firefox flickers through view transitions (the header blinks for several frames): it switches without one, and the
+ contents still rise in. -moz-orient exists only in Firefox. */
+@supports (-moz-orient: inline) { @view-transition { navigation: none; } }
+::view-transition-group(*) { animation-duration: .5s; animation-timing-function: var(--ease); }
+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }
+::view-transition-old(lesson) { animation-duration: .18s; }
+@media (max-width: 560px) {
+ .home strong { font-size: 18px; }
+ #contents .top { flex-wrap: wrap; gap: 8px 12px; }
+ .ch { min-height: 0; }
+ .chalk span:not(:nth-child(3), :nth-child(4), :nth-child(7)) { display: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ *, *::before, ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; transition: none !important; }
+ .chalk span { opacity: .075; }
+}
diff --git a/site/proteus/lib/contents.js b/site/proteus/lib/contents.js
new file mode 100644
index 0000000..0bacf99
--- /dev/null
+++ b/site/proteus/lib/contents.js
@@ -0,0 +1,226 @@
+/* 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. 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(() => {}));
+
+const Contents = (() => {
+ // Interface text in the page's <html lang>, as in the lessons; missing keys fall back to English.
+ // A value is a string or plural forms { one, few, many, other } chosen by vars.n.
+ const TRANSLATIONS = {
+ en: {
+ open: 'Open the book', toCover: 'Back to the cover', resume: 'Continue · Chapter {n}', unit: 'Unit {n}', minutes: '{n} min',
+ meta: '{chapters}{samples} · {units} · with sound', metaChapters: { one: '{n} chapter', other: '{n} chapters' },
+ 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} мин',
+ meta: '{chapters}{samples} · {units} · со звуком',
+ metaChapters: { one: '{n} глава', few: '{n} главы', many: '{n} глав', other: '{n} главы' },
+ metaUnits: { one: '{n} раздел', few: '{n} раздела', many: '{n} разделов', other: '{n} раздела' },
+ metaSamples: { one: ' + {n} пробная', few: ' + {n} пробные', many: ' + {n} пробных', other: ' + {n} пробной' },
+ 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} 分钟',
+ meta: '{chapters}{samples} · {units} · 有配音', metaChapters: '{n} 章', metaUnits: '{n} 个单元',
+ 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}分',
+ meta: '{chapters}{samples} · {units} · 音声つき', metaChapters: '{n}章', metaUnits: '{n}単元',
+ metaSamples: ' + サンプル{n}章', samples: 'サンプル章(別のスタイル)',
+ chapterCount: '{n}章', finished: '{n}章中 {done}章 完了',
+ doneMark: '✓ 完了 · ', lastMark: ' · 最後に開いた章',
+ references: '参考文献', viewAll: 'すべて見る →', backToContents: '← 目次',
+ refsLead: '授業で引用したすべての著作です。リンクは著作の DOI または図書館の記録を新しいタブで開きます。信頼できるオンライン記録のない著作はリンクなしで載せています。',
+ refsCount: '授業で引用した著作 {n} 件', refsAllLinked: '、すべて出典へのリンクつき', refsSomeLinked: '、うち {n} 件は出典へのリンクつき',
+ },
+ };
+ // the same lookup as translate() in engine.js (the two pages never load each other's file): keep them in step
+ const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
+ function translate(key, vars = {}) {
+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';
+ let text = TRANSLATIONS[language][key] ?? key;
+ if (typeof text === 'object') {
+ let rules;
+ try { rules = new Intl.PluralRules(language); } catch { rules = new Intl.PluralRules('en'); }
+ text = text[rules.select(vars.n)] ?? text.other;
+ }
+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);
+ }
+ const $ = id => document.getElementById(id);
+ const id = n => 'ch' + String(n).padStart(2, '0');
+ 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.
+ function translatePage() {
+ for (const element of document.querySelectorAll('[data-t]')) element.firstChild.nodeValue = translate(element.dataset.t);
+ for (const element of document.querySelectorAll('[data-t-label]')) element.setAttribute('aria-label', translate(element.dataset.tLabel));
+ document.documentElement.style.setProperty('--done', JSON.stringify(translate('doneMark')));
+ document.documentElement.style.setProperty('--last', JSON.stringify(translate('lastMark')));
+ }
+
+ // Reading progress { done: [chapter numbers], last }, written by the lessons. The engine and this page derive the
+ // same key from the book's folder; a book that predates that passes its own key.
+ function progress(key) {
+ let P = {};
+ try {
+ const saved = JSON.parse(localStorage.getItem(key) || '{}');
+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;
+ } catch {}
+ return { last: P.last, done: new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []) };
+ }
+
+ // The chapter cards, unit by unit, with progress, the header count, the cover's meta line and its resume button.
+ // A unit's optional third entry { unit, chapter, sample, href } numbers it from elsewhere in the book; a sample chapter,
+ // made to show another look, is not counted with the book's chapters, and a unit of samples has no unit number.
+ // With href, the sample lives in another book folder (its own progress): its card links there and leaves this book's
+ // numbering and progress alone. A chapter's own third entry { href, chapter } does the same for that chapter alone;
+ // without href, its chapter is only the number shown on the card.
+ // start.label is the number shown for start.chapter (folders keep the book's numbers; lessons set CHAPTER.label).
+ function contents(units, start, hues, P) {
+ let n = start.chapter - 1, total = 0, i = 0, away = 0; // i staggers the entrance, in reading order
+ const samples = new Set(), shown = k => k - start.chapter + (start.label ?? start.chapter);
+ $('units').innerHTML = units.map(([name, chs, o = {}], u) => {
+ if (o.chapter && !o.href) n = o.chapter - 1;
+ return `<section class="unit" style="--c:${hues[u % hues.length]};--i:${i++}">${Units.header(u, o.sample ? translate('samples') : translate('unit', { n: o.unit ?? u + start.unit }), name)}<div class="grid">` +
+ chs.map(([t, min, c = {}], k) => {
+ const href = c.href ?? o.href;
+ if (href) { away++; return `<a class="ch" href="${href}" style="--i:${i++}"><b>${c.chapter ?? (o.chapter ?? 1) + k}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`; }
+ n++; if (o.sample) samples.add(n); else total++;
+ const cls = 'ch' + (P.done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');
+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${c.chapter ?? shown(n)}</b><span>${esc(t)}</span><small>${translate('minutes', { n: min })}</small></a>`;
+ }).join('') + '</div></section>';
+ }).join('');
+ // A unit's sketch draws itself the first time the unit scrolls into view.
+ Units.watch();
+ const finished = [...P.done].filter(k => k >= start.chapter && k <= n && !samples.has(k)).length;
+ $('prog').innerHTML = finished ? translate('finished', { done: `<b>${finished}</b>`, n: total }) : translate('chapterCount', { n: total });
+ $('meta').textContent = translate('meta', {
+ chapters: translate('metaChapters', { n: total }),
+ samples: samples.size + away ? translate('metaSamples', { n: samples.size + away }) : '',
+ units: translate('metaUnits', { n: units.filter(x => !x[2]?.sample).length }) });
+ const last = Number.isInteger(P.last) && $(id(P.last));
+ if (last) {
+ const r = $('resume');
+ r.hidden = false;
+ r.href = last.getAttribute('href');
+ r.textContent = translate('resume', { n: last.querySelector('b').textContent });
+ }
+ }
+
+ // 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 = '';
+ for (let i = 0; i <= 96; i++) {
+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;
+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);
+ }
+ return d + 'Z';
+ }
+ function guides(ink) {
+ for (const svg of document.querySelectorAll('svg.mascot')) {
+ svg.setAttribute('viewBox', '0 0 120 84');
+ svg.setAttribute('aria-hidden', 'true');
+ const ln = `fill="none" stroke="${ink}" stroke-linecap="round" stroke-linejoin="round"`;
+ svg.innerHTML = `<g class="mbody"><path class="loop" pathLength="1" d="${lemniscate(60, 40, 52, 1.5)}" ${ln} stroke-width="6"/><g class="face">` +
+ [33, 87].map(x => `<circle class="pupil" cx="${x}" cy="40" r="6.5" fill="${ink}"/><path class="joy" d="M${x - 7} 43Q${x} 32 ${x + 7} 43" ${ln} stroke-width="4"/>`).join('') +
+ `<path d="M55 62Q60 67 65 62" ${ln} stroke-width="3.5"/></g></g>`;
+ }
+ }
+
+ // 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 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(refs ? '#refsTitle' : open ? '#contents .home' : '#cover h1');
+ heading?.setAttribute('tabindex', '-1');
+ heading?.focus({ preventScroll: true });
+ }
+ };
+ if (animate && document.startViewTransition && !reduced && !CSS.supports('-moz-orient', 'inline')) {
+ const transition = document.startViewTransition(apply);
+ // Navigation can interrupt either promise; the new view is already applied.
+ transition.ready.catch(() => {});
+ transition.finished.catch(() => {});
+ } else apply();
+ }
+ addEventListener('hashchange', () => show(true));
+ show(false);
+
+ // Between pages, the chosen card grows into the lesson frame and the frame shrinks back into its card.
+ let named = null;
+ const name = el => {
+ if (named) named.style.viewTransitionName = '';
+ named = el;
+ if (el) el.style.viewTransitionName = 'lesson';
+ };
+ document.addEventListener('click', e => { const a = e.target.closest('a[href^="ch"]'); if (a) name(a); });
+ addEventListener('pagereveal', e => {
+ const target = (location.hash.length > 1 && $(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);
+ name(e.viewTransition && target ? target : null);
+ e.viewTransition?.finished.then(() => name(null), () => name(null));
+ });
+ }
+
+ // units: [[unit title, [[chapter title, minutes], ...], { unit, chapter, sample, href }?], ...]. Chapters are numbered in
+ // order from start (a book whose scope starts mid-way keeps the original numbers in its folders, and may show them
+ // from start.label). hues: one colour per unit, cycling.
+ 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();
+ }
+
+ return { book, translate };
+})();
diff --git a/site/proteus/lib/engine.css b/site/proteus/lib/engine.css
new file mode 100644
index 0000000..bf42cc9
--- /dev/null
+++ b/site/proteus/lib/engine.css
@@ -0,0 +1,297 @@
+@import url(volume.css);
+@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
+ --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
+ color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
+}
+* { box-sizing: border-box; }
+html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
+body { color: var(--chalk); font: 26px/1.4 var(--ui); }
+button { font: inherit; color: inherit; cursor: pointer; }
+button:focus-visible, [tabindex]:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
+button[hidden] { display: none; }
+
+/* One fixed 1600×960 frame (900 stage + 60 controls), scaled to fit the window. Fixed, not absolute: a frame wider
+ than a phone would otherwise widen the phone's layout viewport, and fit() would scale to that wider width. */
+#frame { position: fixed; left: 50%; top: 50%; width: var(--sw, 1600px); height: calc(var(--sh, 900px) + 60px); transform: translate(-50%, -50%) scale(var(--k, .5));
+ border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
+#stage { position: absolute; left: 0; top: 0; width: var(--sw, 1600px); height: var(--sh, 900px); display: block;
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
+#ui { position: absolute; left: 0; top: 0; width: var(--sw, 1600px); height: var(--sh, 900px); pointer-events: none; }
+#ui > * { pointer-events: auto; }
+
+.cover { position: absolute; left: 0; top: 0; width: var(--sw, 1600px); height: var(--sh, 900px); display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
+.cover[hidden] { display: none; }
+.cover > div { display: flex; flex-direction: column; align-items: center; }
+.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
+.cover-t { margin: 0 0 44px; max-width: min(1200px, calc(var(--sw, 1600px) - 100px)); text-align: center; font: 500 64px/1.15 "Iowan Old Style", Palatino, Georgia, serif; color: var(--chalk); text-wrap: balance; }
+.cover > div > * { animation: rise .7s cubic-bezier(.2, .8, .2, 1) backwards; }
+.cover-t { animation-delay: .08s; }
+.cover .go { animation-delay: .18s; }
+.cover small { animation-delay: .26s; }
+@keyframes rise { from { opacity: 0; transform: translateY(14px); } }
+.cover .go { display: inline-flex; align-items: center; gap: 16px; padding: 20px 40px; border-radius: 999px; background: var(--chalk); color: var(--board); font-weight: 600; font-size: 32px; }
+.cover small { display: block; margin-top: 22px; font-size: 22px; text-align: center; color: var(--dim); }
+.paused-mark { position: absolute; left: 0; top: 0; width: var(--sw, 1600px); height: var(--sh, 900px); display: none; place-items: center; pointer-events: none; }
+.paused .paused-mark { display: grid; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
+
+/* Question cards inside the picture. */
+.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
+.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
+.band .mascot { grid-area: pic; }
+.band .head { grid-area: head; align-self: end; }
+.band .fb { grid-area: fb; align-self: start; }
+.band .body { grid-area: body; }
+.band .acts { grid-area: acts; }
+.side .mascot { float: right; margin: -2px -4px 6px 10px; }
+.kicker { margin: 0 0 4px; font-size: 20px; font-weight: 600; color: var(--quiz); }
+.prompt { margin: 0; font-size: 28px; line-height: 1.35; }
+.side .prompt { font-size: 24px; }
+.body:empty { display: none; }
+.side .body { margin-top: 14px; }
+.opts { display: flex; gap: 12px; flex-wrap: wrap; }
+.opt { padding: 8px 24px; border-radius: 999px; border: 2px solid var(--edge); background: transparent; color: var(--chalk); font-size: 24px; min-height: 58px; display: inline-flex; align-items: center; }
+.opt:hover:not(:disabled) { border-color: var(--dim); }
+.opt[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
+.opt.bad { border-color: var(--bad); color: var(--bad); }
+.opt:disabled { cursor: default; }
+.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
+.fb:empty { display: none; }
+.fb.ok::before { content: "✓ "; color: var(--good); font-weight: 700; }
+.fb.no::before { content: "✗ "; color: var(--bad); font-weight: 700; }
+.fb ul { margin: 6px 0 0; padding-left: 22px; }
+.side .fb { max-height: 110px; overflow: auto; font-size: 20px; }
+.acts { display: flex; gap: 12px; align-items: center; }
+.side .acts { margin-top: 16px; }
+.side .acts { flex-wrap: wrap; gap: 10px; }
+.side .btn { padding: 8px 16px; font-size: 20px; }
+.card.side { padding: 18px 22px; }
+.btn { padding: 10px 28px; border-radius: 999px; border: 0; background: var(--chalk); color: var(--board); font-weight: 600; font-size: 22px; white-space: nowrap; }
+.btn.quiet { background: transparent; color: var(--dim); border: 1.5px solid var(--edge); }
+.btn.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
+.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
+
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
+.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
+.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
+.grid.text .num { justify-content: flex-start; }
+.grid .opts { gap: 8px; }
+.grid .opt { padding: 3px 16px; min-height: 42px; font-size: 20px; }
+.grid .mark { font-weight: 700; text-align: center; }
+.grid .mark.good { color: var(--good); }
+.grid .mark.bad { color: var(--bad); }
+.grid .why { grid-column: 1 / -1; font-size: 19px; color: var(--dim); padding-left: 186px; }
+.grid.text .why { padding-left: 0; }
+.grid .why:empty { display: none; }
+
+.hit { cursor: pointer; }
+.hit .ring { fill: transparent; stroke: var(--chalk); stroke-width: 2.5; stroke-opacity: 0; }
+.hit:hover .ring, .hit:focus .ring { stroke-opacity: .7; }
+.hit.bad .ring { stroke: var(--bad); stroke-opacity: 1; }
+.hit.good .ring { stroke: var(--good); stroke-opacity: 1; stroke-width: 4; }
+/* Point and read (tapWords): hit boxes over the picture, the word beside a tapped thing, the counter and Continue.
+ A book can set --word-font for its early-reader letters. */
+.tapw .ring { stroke-width: 5; }
+#ui > .card.word { pointer-events: none; padding: 2px 36px 10px; border-left-width: 1.5px; border-radius: 30px; font: 600 96px/1.15 var(--word-font, var(--ui)); white-space: nowrap; animation: word-in .3s cubic-bezier(.3, 1.5, .6, 1); }
+@keyframes word-in { from { transform: scale(.6); opacity: 0; } }
+.card.words .acts { margin: 0; gap: 18px; }
+.card.words .count { font-size: 24px; font-weight: 600; color: var(--dim); }
+.card.words.lit .count { color: var(--good); }
+.card.words.lit .btn.go { animation: word-in .4s cubic-bezier(.3, 1.5, .6, 1); }
+.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
+
+/* Controls strip, part of the frame. */
+#bar { position: absolute; left: 0; top: var(--sh, 900px); width: var(--sw, 1600px); height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
+.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
+.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
+.icon .i-pause { display: none; }
+.is-playing .icon .i-play { display: none; }
+.is-playing .icon .i-pause { display: block; }
+.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
+.seg:hover { height: 12px; }
+.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
+.seg.ask { background: var(--track-ask); }
+.seg.ask i { background: var(--quiz); }
+.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
+/* Keep the control strip usable without scaling down its touch targets. */
+@media (max-width: 700px) {
+ #frame { top: calc(50% - 50px); overflow: visible; }
+ #bar { width: calc(var(--sw, 1600px) * var(--k)); height: auto; flex-wrap: wrap; gap: 6px; padding: 8px;
+ transform: scale(calc(1 / var(--k))); transform-origin: left top; border-radius: 0 0 12px 12px; }
+ #bar .icon { width: 36px; height: 40px; }
+ .step { display: none; }
+ #bHelp { display: none; } /* keyboard shortcuts; room for the speed button on a phone */
+ #bar .icon.speed { width: 36px; min-width: 0; padding: 0; font-size: 12px; letter-spacing: -.3px; }
+ .segs { order: 1; }
+ .segs { min-width: 80px; margin: 0; }
+ :root.full #bar { transform-origin: left bottom; border-radius: 0; }
+}
+/* Full screen: the stage fills the screen and the controls lie over its foot, out of sight until the pointer moves
+ (engine.js wake(): .awake), while paused or ended (.held) and while the pointer is on them. */
+:root.full #frame { top: 50%; height: var(--sh, 900px); border-radius: 0; box-shadow: none; }
+:root.full #bar { top: auto; bottom: 0; transition: opacity .3s; border-top: 0;
+ background: linear-gradient(transparent, color-mix(in srgb, var(--page) 85%, transparent)); }
+:root.full #frame:not(.awake):not(.held) #bar:not(:hover):not(:focus-within) { opacity: 0; pointer-events: none; }
+:root.full #frame:not(.awake):not(.held):not(:has(#bar:hover)) { cursor: none; }
+/* A touch screen has no hover to bring the controls back, and a tap that answers a question would cover the card with
+ them: there full screen keeps them, full size, under the stage (fit() leaves them room). */
+@media (pointer: coarse) {
+ :root.full #frame { top: calc(50% - 30px); overflow: visible; }
+ :root.full #frame #bar { top: var(--sh, 900px); bottom: auto; width: calc(var(--sw, 1600px) * var(--k)); height: auto; flex-wrap: wrap;
+ gap: 6px; padding: 8px; transform: scale(calc(1 / var(--k))); transform-origin: left top; background: none; opacity: 1 !important; pointer-events: auto !important; }
+ :root.full #bar .icon { width: 40px; height: 40px; }
+ :root.full .step, :root.full #bHelp { display: none; }
+ :root.full .segs { order: 1; min-width: 80px; margin: 0; }
+}
+@media (pointer: coarse) and (max-width: 700px) { :root.full #frame { top: calc(50% - 55px); } }
+
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
+.sound-note[hidden] { display: none; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
+.blanks .brow:last-child { border-bottom: 0; }
+.blanks .bline { line-height: 64px; white-space: nowrap; }
+.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
+.blanks .mark.good { color: var(--good); animation: pop .35s ease-out; }
+.blanks .mark.bad { color: var(--bad); }
+.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
+.blanks .why:empty { display: none; }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
+.box.good { border-color: var(--good); }
+.box.bad { border-color: var(--bad); }
+.box:disabled { opacity: 1; }
+kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5em; border: 1.5px solid currentColor; border-radius: 6px; font: 600 .7em/1.5 var(--ui); text-align: center; vertical-align: .12em; opacity: .6; }
+.opt kbd { margin: 0 .6em 0 0; }
+.keys { margin: 6px 0 0; font-size: 18px; color: var(--dim); }
+.keys kbd { margin: 0 .15em; }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: var(--sw, 1600px); height: var(--sh, 900px); display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
+.help[hidden] { display: none; }
+.help-box { width: min(1120px, calc(var(--sw, 1600px) - 80px)); padding: 40px 50px; border-radius: 22px; background: var(--panel); border: 1.5px solid var(--edge); }
+.help h2 { margin: 0 0 22px; font-size: 32px; font-weight: 600; }
+.help h3 { margin: 0 0 12px; font-size: 20px; font-weight: 600; color: var(--quiz); }
+.help-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 44px; }
+.help-cols:has(> [hidden]) { grid-template-columns: 1fr; }
+.help dl { margin: 0; display: grid; grid-template-columns: 150px 1fr; row-gap: 10px; font-size: 22px; }
+.help dt { text-align: right; padding-right: 18px; white-space: nowrap; }
+.help dt kbd { margin: 0 0 0 .3em; opacity: .9; }
+.help dd { margin: 0; color: var(--dim); }
+.help-close { margin: 26px 0 0; font-size: 18px; color: var(--dim); }
+.icon.txt { font-size: 20px; font-weight: 700; color: var(--dim); }
+/* Optional captions of the narration, one sentence at a time. Off by default: teaching text lives in the picture. */
+.caption { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: min(1180px, calc(var(--sw, 1600px) - 80px)); padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
+.caption[hidden] { display: none; }
+.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
+.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
+.card.side { overflow: auto; }
+svg.m { display: inline-block; overflow: visible; }
+.card b { font-weight: 700; } /* not 'bolder' (900 under a 600 prompt) */
+.card { animation: card-in .45s cubic-bezier(.2, .9, .3, 1.15); }
+.fb:not(:empty) { animation: fb-in .3s ease-out; }
+.opt.bad, .grid .mark.bad { animation: shake .4s; }
+.grid .mark.good { animation: pop .35s ease-out; }
+@keyframes card-in { from { opacity: 0; transform: translateY(24px) scale(.98); } }
+@keyframes fb-in { from { opacity: 0; transform: translateY(8px); } }
+@keyframes pop { 0% { transform: scale(.3); opacity: 0; } 70% { transform: scale(1.3); } }
+@keyframes shake { 20% { transform: translateX(-8px); } 40% { transform: translateX(8px); } 60% { transform: translateX(-5px); } 80% { transform: translateX(5px); } }
+/* Full-screen chapter practice. */
+.card.screen { height: 900px; padding: 50px 70px; border: 0; border-radius: 0; background: transparent; box-shadow: none; animation: screen-in .5s ease-out; max-height: none; overflow: visible; }
+.screen .kicker { font-size: 22px; }
+.screen .prompt { font-size: 40px; font-weight: 600; }
+.screen .body { margin-top: 30px; }
+.card.screen { display: flex; flex-direction: column; }
+.screen .head { order: 1; } .screen .body { order: 2; }
+.screen .fb { order: 3; max-width: min(1080px, calc(var(--sw, 1600px) - 140px)); margin: 26px 0 0; font-size: 24px; } /* feedback right under the answers */
+/* Practice screens: the bottom 130 px hold the buttons. Long answers scroll inside the body, so the feedback under
+ them stays in view after a wrong answer adds a 'why' line to each row. */
+.card.screen:not(.sort):not(.fin) { padding-bottom: 130px; }
+.card.screen:not(.sort):not(.fin) > .head, .card.screen:not(.sort):not(.fin) > .fb { flex: none; }
+.card.screen:not(.sort):not(.fin) > .body { flex: 0 1 auto; min-height: 0; overflow-y: auto; }
+.screen .acts { position: absolute; right: 70px; bottom: 48px; }
+.screen .grid .row { grid-template-columns: 200px minmax(0, 1fr) 40px; padding: 9px 0 9px 12px; }
+/* a long label (a system of equations) widens the label column for every row instead of running off the card's left */
+.screen .grid:not(.text) { display: grid; grid-template-columns: minmax(200px, max-content) minmax(0, 1fr) 40px; }
+.screen .grid:not(.text) > .row { grid-column: 1 / -1; grid-template-columns: subgrid; }
+.screen .grid.text .row { grid-template-columns: minmax(0, 1fr) auto 40px; }
+.screen .grid .opt { font-size: 22px; min-height: 50px; padding: 4px 20px; }
+.screen .grid .why { padding-left: 216px; font-size: 20px; }
+.screen .grid.text .why { padding-left: 0; }
+#ui > .screen.sort { pointer-events: none; }
+.screen.sort > * { pointer-events: auto; }
+.screen.sort .head { position: absolute; right: 34px; top: 40px; width: 330px; }
+.screen.sort .prompt { font-size: 28px; }
+.screen.sort .fb { position: absolute; margin: 0; left: auto; right: 34px; bottom: 116px; width: 330px; max-height: 240px; overflow: auto; font-size: 20px; }
+.screen.sort .acts { right: 34px; }
+.fin .finwrap { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; text-align: center; padding-bottom: 60px; }
+.fin .mascot { margin-bottom: 28px; }
+.fin .fb, .fin .acts { position: static; }
+.fin .fb { order: 0; margin: 0; } /* result lines, not answer feedback: keep them above the buttons */
+.fin .acts { margin-top: 30px; }
+@keyframes screen-in { from { opacity: 0; } }
+
+/* The guide: an infinity sign whose loops are its eyes. */
+.mascot { display: block; flex: none; overflow: visible; }
+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }
+.mascot .eyes { transition: transform .3s; }
+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }
+.mascot .joy, .mascot .flat { display: none; }
+.mascot.happy .pupil { display: none; }
+.mascot.happy .joy { display: inline; }
+.mascot.happy .mbody { animation: hop .55s ease-out 2, bob 3.4s ease-in-out 1.1s infinite; }
+.mascot.oops .eyes { transform: translate(-3px, 4px); }
+.mascot.oops .smile { display: none; }
+.mascot.oops .flat { display: inline; }
+.mascot.oops .mbody { animation: wobble .5s ease-in-out, bob 3.4s ease-in-out .5s infinite; }
+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }
+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }
+@keyframes hop { 40% { transform: translateY(-12px) rotate(4deg); } }
+@keyframes wobble { 25% { transform: rotate(-8deg); } 75% { transform: rotate(6deg); } }
+@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: min(1100px, calc(var(--sw, 1600px) - 100px)); 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; }
+#frame { view-transition-name: lesson; }
+::view-transition-group(lesson) { animation-duration: .5s; animation-timing-function: cubic-bezier(.2, .8, .2, 1); }
+::view-transition-old(lesson), ::view-transition-new(lesson) { height: 100%; object-fit: cover; }
+::view-transition-old(lesson) { animation-duration: .18s; }
+@media (prefers-reduced-motion: reduce) { .cover > div > * { animation: none; } ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } }
+/* The finish screen speaks the same type as the chapter cover and the contents page. */
+.fin .kicker { font-size: 20px; letter-spacing: .14em; text-transform: uppercase; }
+.fin .prompt { margin: 6px 0 14px; font: 500 56px/1.15 "Iowan Old Style", Palatino, Georgia, serif; }
+.icon.speed { width: auto; min-width: 44px; padding: 0 10px; border-radius: 22px; font-size: 16px; }
+/* An upright stage is seen at about half the scale of a wide one on the same screen: bigger caption text. */
+:root[data-stage="portrait"] .step { width: 120px; } /* the 900-wide bar keeps room for the steps */
+:root[data-stage="portrait"] .caption { font-size: 38px; bottom: 60px; }
diff --git a/site/proteus/lib/engine.js b/site/proteus/lib/engine.js
new file mode 100644
index 0000000..f36ec13
--- /dev/null
+++ b/site/proteus/lib/engine.js
@@ -0,0 +1,1923 @@
+// Papermorph lesson engine: stage, drawing, timeline, questions, player.
+// A chapter page loads this file, defines CHAPTER and BEATS, then calls boot().
+'use strict';
+// A fast follow-up navigation can abort the incoming page transition.
+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
+
+// The engine's state and helpers live in one closure. Only the names declared at the end of this file are global (the
+// API that chapters, math.js, book libraries and the scripts use), so a chapter may name its own helpers anything else
+// (clock, fit, frame, last, ui, …).
+let seeking = false; // true while seek() replays the beats before its target
+let captions = false; // the reader's captions setting (C)
+const ENGINE = (() => {
+
+/* ---------- interface language ---------- */
+// The page's <html lang> picks the interface text; CHAPTER.language picks the audio folder. Set both alike.
+// A value is a string or plural forms { one, few, many, other } chosen by vars.n. Missing keys fall back to English.
+const TRANSLATIONS = {
+ en: {
+ decimalSign: '.', stageLabel: 'Lesson animation', stageLabelTitled: 'Lesson animation: {title}',
+ shortcuts: 'Keyboard shortcuts', lesson: 'Lesson', questions: 'Questions',
+ helpPlay: 'Play or pause', helpStep: 'Previous or next step', helpStepInQuestion: 'Change step during a question', helpRestart: 'Start over',
+ helpCaptions: 'Captions on or off', helpSpeed: 'Slower or faster', helpFullScreen: 'Full screen', helpList: 'Show this list',
+ helpChoose: 'Choose an answer or a ring', helpTrueFalse: 'True or false', helpRows: 'Move between rows',
+ helpNumberLine: 'Move along the number line, or pick a number to sort', helpEnter: 'Check, then continue',
+ helpShowAnswer: 'Show the answer', helpLeaveBox: 'Leave an answer box', helpClose: 'Press {key} to close.',
+ paused: 'Paused. Press space or click to continue.',
+ soundFailed: 'Sound could not play. The lesson continues with the on-screen text.',
+ startLesson: 'Start lesson', startFilm: 'Play', aboutMinutesFilm: 'About {n} minutes, with sound.', coverKeys: 'Press {space} to start, {help} for shortcuts.', spaceKey: 'Space',
+ chapterNumber: 'Chapter {n}', aboutMinutes: 'About {n} minutes, with sound and quick checks.',
+ allChapters: 'All chapters', playLabel: 'Play or pause (space)', backLabel: 'Previous step (left arrow)', restartLabel: 'Restart lesson',
+ checksInLesson: 'Quick checks and practice are in the interactive lesson.',
+ volumeLabel: 'Adjust volume', volumeTitle: 'Volume (0 = muted)', volumeSlider: 'Volume',
+ helpLabel: 'Keyboard shortcuts (?)', speedLabel: 'Playback speed (< and >)', captionsLabel: 'Captions (C)', fullScreenLabel: 'Full screen', goToStep: 'Go to step {n}: {title}',
+ quickCheck: 'Quick check', countOf: 'question {k} of {n}', check: 'Check', showAnswer: 'Show answer', nextQuestion: 'Next question', continue: 'Continue',
+ correct: 'Correct. ', notQuite: 'Not quite. ', answerPrefix: 'Answer: ', keysPrefix: 'Keys: ',
+ hintMove: ' move, ', hintChoose: ' choose', hintChooseOrClickGrid: ' choose, or click the grid', hintMoveAlongLine: ' move along the line, ',
+ hintChooseOrClick: ' choose, or click', hintRow: ' row, ', hintTypeFraction: 'type numbers like 3/4 or −2 1/4, ', hintTypeNumber: 'type the number, ',
+ hintTypeDecimal: 'type the number, ', hintNextBox: ' next box, ', hintCheck: ' check, ', hintLeaveBox: ' leave the box',
+ hintPickNumber: ' pick a number, ', hintPickRing: ' choose its ring',
+ rowsRight: '{r} of {n} right. Fix the rows marked ✗ and check again.',
+ choicesShown: 'the correct choices are now selected.', numbersShown: 'the correct numbers are filled in.',
+ notPlacedYet: '{x} is not placed yet.',
+ realRingIsEmpty: '{x}: every real number is rational or irrational, so that space has no numbers of its own.',
+ ringsRight: '{r} of {n} in the right ring.', ringsShown: 'every number is now in its smallest ring.',
+ chipPlaced: '{x}, placed in {ring}', chipNotPlaced: '{x}, not placed', pointLabel: 'The point {v}', answerBox: 'Answer',
+ 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', 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',
+ wordsHeard: '{k} / {n}', allWordsHeard: 'You found them all!',
+ },
+ ru: {
+ decimalSign: ',', stageLabel: 'Анимация урока', stageLabelTitled: 'Анимация урока: {title}',
+ shortcuts: 'Горячие клавиши', lesson: 'Урок', questions: 'Вопросы',
+ helpPlay: 'Пуск или пауза', helpStep: 'Предыдущий или следующий шаг', helpStepInQuestion: 'Сменить шаг во время вопроса', helpRestart: 'Начать сначала',
+ helpCaptions: 'Субтитры вкл. или выкл.', helpSpeed: 'Медленнее или быстрее', helpFullScreen: 'Полноэкранный режим', helpList: 'Показать этот список',
+ helpChoose: 'Выбрать ответ или круг', helpTrueFalse: 'Верно или неверно', helpRows: 'Перейти между строками',
+ helpNumberLine: 'Двигаться по числовой прямой или выбрать число для сортировки', helpEnter: 'Проверить, затем продолжить',
+ helpShowAnswer: 'Показать ответ', helpLeaveBox: 'Выйти из поля ответа', helpClose: 'Нажмите {key}, чтобы закрыть.',
+ paused: 'Пауза. Нажмите пробел или щёлкните, чтобы продолжить.',
+ soundFailed: 'Звук не воспроизводится. Урок продолжится с текстом на экране.',
+ startLesson: 'Начать урок', startFilm: 'Смотреть', aboutMinutesFilm: { one: 'Около {n} минуты, со звуком.', few: 'Около {n} минут, со звуком.', many: 'Около {n} минут, со звуком.', other: 'Около {n} минуты, со звуком.' }, coverKeys: '{space} — начать, {help} — горячие клавиши.', spaceKey: 'Пробел',
+ chapterNumber: 'Глава {n}',
+ aboutMinutes: { one: 'Около {n} минуты, со звуком и проверками.', few: 'Около {n} минут, со звуком и проверками.',
+ many: 'Около {n} минут, со звуком и проверками.', other: 'Около {n} минуты, со звуком и проверками.' },
+ allChapters: 'Все главы', playLabel: 'Пуск или пауза (пробел)', backLabel: 'Предыдущий шаг (стрелка влево)', restartLabel: 'Начать урок заново',
+ checksInLesson: 'Проверочные вопросы и практика — в интерактивном уроке.',
+ volumeLabel: 'Настроить громкость', volumeTitle: 'Громкость (0 — без звука)', volumeSlider: 'Громкость',
+ helpLabel: 'Горячие клавиши (?)', speedLabel: 'Скорость воспроизведения (< и >)', captionsLabel: 'Субтитры (C)', fullScreenLabel: 'Полный экран', goToStep: 'Перейти к шагу {n}: {title}',
+ quickCheck: 'Проверь себя', countOf: 'вопрос {k} из {n}', check: 'Проверить', showAnswer: 'Показать ответ', nextQuestion: 'Следующий вопрос', continue: 'Продолжить',
+ correct: 'Верно. ', notQuite: 'Не совсем. ', answerPrefix: 'Ответ: ', keysPrefix: 'Клавиши: ',
+ hintMove: ' двигаться, ', hintChoose: ' выбрать', hintChooseOrClickGrid: ' выбрать или щёлкнуть по сетке', hintMoveAlongLine: ' двигаться по прямой, ',
+ hintChooseOrClick: ' выбрать или щёлкнуть', hintRow: ' строка, ', hintTypeFraction: 'вводите числа вида 3/4 или −2 1/4, ', hintTypeNumber: 'введите число, ',
+ hintTypeDecimal: 'вводите числа вида 0,75, ', hintNextBox: ' следующее поле, ', hintCheck: ' проверить, ', hintLeaveBox: ' выйти из поля',
+ hintPickNumber: ' выбрать число, ', hintPickRing: ' выбрать его круг',
+ rowsRight: 'Верно {r} из {n}. Исправьте строки с ✗ и проверьте снова.',
+ choicesShown: 'правильные варианты отмечены.', numbersShown: 'правильные числа вписаны.',
+ notPlacedYet: '{x}: ещё не размещено.',
+ realRingIsEmpty: '{x}: каждое действительное число рационально или иррационально, поэтому своих чисел у этой области нет.',
+ ringsRight: 'В нужном круге: {r} из {n}.', ringsShown: 'каждое число теперь в своём наименьшем круге.',
+ chipPlaced: '{x}, в круге «{ring}»', chipNotPlaced: '{x}, не размещено', pointLabel: 'Точка {v}', answerBox: 'Ответ',
+ 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: 'Практика по главе', sources: 'Источники этой главы', opensSource: '{label}, источник откроется в новой вкладке',
+ firstTryScore: '{name}: {r} из {t} верно с первой попытки.', notAttempted: '{name}: не выполнялось.',
+ watchAgain: 'Смотреть снова', nextChapter: 'Следующая глава',
+ wordsHeard: '{k} / {n}', allWordsHeard: 'Все найдены!',
+ },
+ zh: {
+ decimalSign: '.', stageLabel: '课程动画', stageLabelTitled: '课程动画:{title}',
+ shortcuts: '键盘快捷键', lesson: '课程', questions: '题目',
+ helpPlay: '播放或暂停', helpStep: '上一步或下一步', helpStepInQuestion: '答题时切换步骤', helpRestart: '从头开始',
+ helpCaptions: '打开或关闭字幕', helpSpeed: '减速或加速', helpFullScreen: '全屏', helpList: '显示此列表',
+ helpChoose: '选择答案或圆环', helpTrueFalse: '对或错', helpRows: '在各行之间移动',
+ helpNumberLine: '在数轴上移动,或选一个数来分类', helpEnter: '检查,然后继续',
+ helpShowAnswer: '显示答案', helpLeaveBox: '离开答题框', helpClose: '按 {key} 关闭。',
+ paused: '已暂停。按空格键或点击继续。',
+ soundFailed: '声音无法播放。课程将借助屏幕上的文字继续。',
+ startLesson: '开始上课', startFilm: '播放', aboutMinutesFilm: '约 {n} 分钟,有配音。', coverKeys: '按 {space} 开始,按 {help} 查看快捷键。', spaceKey: '空格',
+ chapterNumber: '第 {n} 章', aboutMinutes: '约 {n} 分钟,含配音和随堂小测。',
+ allChapters: '全部章节', playLabel: '播放或暂停(空格)', backLabel: '上一步(左方向键)', restartLabel: '重新开始本课',
+ checksInLesson: '小测验和练习在互动课程里。',
+ volumeLabel: '调节音量', volumeTitle: '音量(0 为静音)', volumeSlider: '音量',
+ helpLabel: '键盘快捷键(?)', speedLabel: '播放速度(< 和 >)', captionsLabel: '字幕(C)', fullScreenLabel: '全屏', goToStep: '跳到第 {n} 步:{title}',
+ quickCheck: '小测', countOf: '第 {k}/{n} 题', check: '检查', showAnswer: '显示答案', nextQuestion: '下一题', continue: '继续',
+ correct: '正确。', notQuite: '还不对。', answerPrefix: '答案:', keysPrefix: '按键:',
+ hintMove: ' 移动,', hintChoose: ' 选择', hintChooseOrClickGrid: ' 选择,或点击网格', hintMoveAlongLine: ' 沿数轴移动,',
+ hintChooseOrClick: ' 选择,或点击', hintRow: ' 换行,', hintTypeFraction: '可输入 3/4 或 −2 1/4 这样的数,', hintTypeNumber: '输入数字,',
+ hintTypeDecimal: '输入数字,', hintNextBox: ' 下一个框,', hintCheck: ' 检查,', hintLeaveBox: ' 离开答题框',
+ hintPickNumber: ' 选一个数,', hintPickRing: ' 选它所在的圆环',
+ rowsRight: '{n} 行中对了 {r} 行。改正标 ✗ 的行,再检查一次。',
+ choicesShown: '正确选项已经选上。', numbersShown: '正确的数已经填上。',
+ notPlacedYet: '{x} 还没有放好。',
+ realRingIsEmpty: '{x}:每个实数不是有理数就是无理数,所以这一块没有只属于它的数。',
+ ringsRight: '{n} 个中有 {r} 个放在了正确的圆环里。', ringsShown: '每个数现在都在它所属的最小圆环里。',
+ chipPlaced: '{x},放在「{ring}」', chipNotPlaced: '{x},未放置', pointLabel: '点 {v}', answerBox: '答案',
+ stepsLeftOfZero: '0 左边 {n} 步',
+ natural: '正整数', whole: '非负整数', integers: '整数', rational: '有理数', irrational: '无理数', real: '实数', integerColumn: '整数',
+ trueLabel: '对', falseLabel: '错',
+ chapterComplete: '第 {n} 章完成', quickChecks: '小测', chapterPractice: '本章练习', sources: '本章引用的文献', opensSource: '{label},在新标签页中打开来源',
+ firstTryScore: '{name}:第一次就答对 {r} / {t}。', notAttempted: '{name}:未作答。',
+ watchAgain: '再看一遍', nextChapter: '下一章',
+ wordsHeard: '{k} / {n}', allWordsHeard: '全都找到啦!',
+ },
+ ja: {
+ decimalSign: '.', stageLabel: '授業アニメーション', stageLabelTitled: '授業アニメーション:{title}',
+ shortcuts: 'キーボードショートカット', lesson: '授業', questions: '問題',
+ helpPlay: '再生/一時停止', helpStep: '前または次のステップ', helpStepInQuestion: '問題の途中でステップを移動', helpRestart: '最初から',
+ helpCaptions: '字幕のオン/オフ', helpSpeed: '遅く/速く', helpFullScreen: '全画面', helpList: 'この一覧を表示',
+ helpChoose: '答えまたは輪を選ぶ', helpTrueFalse: '正しい/誤り', helpRows: '行を移動',
+ helpNumberLine: '数直線上を移動、または分類する数を選ぶ', helpEnter: '答え合わせ、そして次へ',
+ helpShowAnswer: '答えを表示', helpLeaveBox: '解答欄から出る', helpClose: '{key} で閉じる。',
+ paused: '一時停止中。スペースキーかクリックで再開します。',
+ soundFailed: '音声を再生できません。画面の文字で授業を続けます。',
+ startLesson: '授業を始める', startFilm: '再生', aboutMinutesFilm: '約{n}分、音声つき。', coverKeys: '{space} で開始、{help} でショートカット一覧。', spaceKey: 'スペース',
+ chapterNumber: '第{n}章', aboutMinutes: '約{n}分、音声と確認問題つき。',
+ allChapters: 'すべての章', playLabel: '再生/一時停止(スペース)', backLabel: '前のステップ(左矢印)', restartLabel: '授業を最初から',
+ checksInLesson: '確認問題と練習はインタラクティブな授業の中にあります。',
+ volumeLabel: '音量を調整', volumeTitle: '音量(0 でミュート)', volumeSlider: '音量',
+ helpLabel: 'キーボードショートカット(?)', speedLabel: '再生速度(< と >)', captionsLabel: '字幕(C)', fullScreenLabel: '全画面', goToStep: 'ステップ {n}:{title} へ移動',
+ quickCheck: '確認問題', countOf: '問 {k}/{n}', check: '答え合わせ', showAnswer: '答えを見る', nextQuestion: '次の問題', continue: '続ける',
+ correct: '正解。', notQuite: 'おしい。', answerPrefix: '答え:', keysPrefix: 'キー:',
+ hintMove: ' 移動、', hintChoose: ' 選ぶ', hintChooseOrClickGrid: ' 選ぶ、またはマス目をクリック', hintMoveAlongLine: ' 数直線上を移動、',
+ hintChooseOrClick: ' 選ぶ、またはクリック', hintRow: ' 行、', hintTypeFraction: '3/4 や −2 1/4 のように入力、', hintTypeNumber: '数を入力、',
+ hintTypeDecimal: '数を入力、', hintNextBox: ' 次の欄、', hintCheck: ' 答え合わせ、', hintLeaveBox: ' 欄から出る',
+ hintPickNumber: ' 数を選ぶ、', hintPickRing: ' その輪を選ぶ',
+ rowsRight: '{n} 行中 {r} 行正解。✗ の行を直して、もう一度答え合わせ。',
+ choicesShown: '正しい選択肢を選びました。', numbersShown: '正しい数を入れました。',
+ notPlacedYet: '{x} はまだ置かれていません。',
+ realRingIsEmpty: '{x}:実数はどれも有理数か無理数なので、この部分だけに入る数はありません。',
+ ringsRight: '{n} 個中 {r} 個が正しい輪に入っています。', ringsShown: 'どの数も、入るいちばん小さい輪に移しました。',
+ chipPlaced: '{x}、「{ring}」に配置', chipNotPlaced: '{x}、未配置', pointLabel: '点 {v}', answerBox: '答え',
+ stepsLeftOfZero: '0 から左へ {n}',
+ natural: '自然数', whole: '0 以上の整数', integers: '整数', rational: '有理数', irrational: '無理数', real: '実数', integerColumn: '整数',
+ trueLabel: '正しい', falseLabel: '誤り',
+ chapterComplete: '第{n}章 完了', quickChecks: '確認問題', chapterPractice: '章末練習', sources: 'この章の出典', opensSource: '{label}(出典を新しいタブで開く)',
+ firstTryScore: '{name}:1 回目で {t} 問中 {r} 問正解。', notAttempted: '{name}:未挑戦。',
+ watchAgain: 'もう一度見る', nextChapter: '次の章へ',
+ wordsHeard: '{k} / {n}', allWordsHeard: 'ぜんぶ見つけたね!',
+ },
+};
+// <html data-stage="portrait"> turns the stage upright: 900 wide, 1600 tall. Landscape (1600×900) otherwise.
+const PORTRAIT = document.documentElement.dataset.stage === 'portrait';
+const SW = PORTRAIT ? 900 : 1600, SH = PORTRAIT ? 1600 : 900;
+document.documentElement.style.setProperty('--sw', SW + 'px');
+document.documentElement.style.setProperty('--sh', SH + 'px');
+const LANGUAGE = (document.documentElement.lang || 'en').toLowerCase().split('-')[0];
+const pluralRules = {};
+// Interface text in LANGUAGE: translate('chapterNumber', { n: 3 }) → 'Chapter 3'. Chapters may use it too, e.g. for practice labels.
+// contents.js has its own copy for the contents page: keep the two in step.
+function translate(key, vars = {}) {
+ const language = TRANSLATIONS[LANGUAGE]?.[key] !== undefined ? LANGUAGE : 'en';
+ let text = TRANSLATIONS[language][key] ?? key;
+ if (typeof text === 'object') {
+ try { pluralRules[language] ??= new Intl.PluralRules(language); } catch { pluralRules[language] = new Intl.PluralRules('en'); }
+ text = text[pluralRules[language].select(vars.n)] ?? text.other;
+ }
+ return text.replace(/\{(\w+)\}/g, (placeholder, name) => name in vars ? vars[name] : placeholder);
+}
+const DECIMAL_SIGN = translate('decimalSign'); // shown by num() and accepted by answer boxes
+const isLatinLetter = key => /^[a-z]$/i.test(key);
+// A letter shortcut on any keyboard layout: the typed letter, or the same physical key when the layout types a non-Latin letter.
+const isShortcut = (event, letter) => event.key.toLowerCase() === letter.toLowerCase()
+ || (isLatinLetter(letter) && !isLatinLetter(event.key) && event.code === 'Key' + letter.toUpperCase());
+// A punctuation shortcut (code 'Comma', 'Period') on a layout that types a non-Latin letter on that key.
+const isShortcutCode = (event, code) => /^\p{L}$/u.test(event.key) && !isLatinLetter(event.key) && event.code === code;
+
+document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
+ <svg id="stage" viewBox="0 0 ${SW} ${SH}" role="img" aria-label="${translate('stageLabel')}">
+ <g id="scene"></g>
+ </svg>
+ <div id="ui"></div>
+ <div class="paused-mark"><div>${translate('paused')}</div></div>
+ <div class="caption" id="caption" hidden></div>
+ <div class="help" id="help" hidden role="dialog" aria-label="${translate('shortcuts')}">
+ <div class="help-box">
+ <h2>${translate('shortcuts')}</h2>
+ <div class="help-cols">
+ <div><h3>${translate('lesson')}</h3><dl>
+ <dt><kbd>${translate('spaceKey')}</kbd></dt><dd>${translate('helpPlay')}</dd>
+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpStep')}</dd>
+ <dt><kbd>Shift</kbd><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpStepInQuestion')}</dd>
+ <dt><kbd>Home</kbd></dt><dd>${translate('helpRestart')}</dd>
+ <dt><kbd>C</kbd></dt><dd>${translate('helpCaptions')}</dd>
+ <dt><kbd>&lt;</kbd><kbd>&gt;</kbd></dt><dd>${translate('helpSpeed')}</dd>
+ <dt><kbd>F</kbd></dt><dd>${translate('helpFullScreen')}</dd>
+ <dt><kbd>?</kbd></dt><dd>${translate('helpList')}</dd>
+ </dl></div>
+ <div><h3>${translate('questions')}</h3><dl>
+ <dt><kbd>1</kbd>–<kbd>6</kbd></dt><dd>${translate('helpChoose')}</dd>
+ <dt><kbd>T</kbd><kbd>F</kbd></dt><dd>${translate('helpTrueFalse')}</dd>
+ <dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>${translate('helpRows')}</dd>
+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>${translate('helpNumberLine')}</dd>
+ <dt><kbd>Enter</kbd></dt><dd>${translate('helpEnter')}</dd>
+ <dt><kbd>S</kbd></dt><dd>${translate('helpShowAnswer')}</dd>
+ <dt><kbd>Esc</kbd></dt><dd>${translate('helpLeaveBox')}</dd>
+ </dl></div>
+ </div>
+ <p class="help-close">${translate('helpClose', { key: '<kbd>Esc</kbd>' })}</p>
+ </div>
+ </div>
+ <p class="sound-note" id="soundNote" hidden>${translate('soundFailed')}</p>
+ <button class="cover" id="cover"><div>
+ <p class="cover-k" id="coverK"></p>
+ <h1 class="cover-t" id="coverT"></h1>
+ <span class="go"><svg width="24" height="24" viewBox="0 0 18 18"><path d="M3 1.5v15l13-7.5z" fill="currentColor"/></svg><span id="coverGo">${translate('startLesson')}</span></span>
+ <small><span id="coverMeta"></span> ${translate('coverKeys', { space: `<kbd>${translate('spaceKey')}</kbd>`, help: '<kbd>?</kbd>' })}</small>
+ </div></button>
+ <div id="bar">
+ <a class="icon" id="bHome" href="../" aria-label="${translate('allChapters')}" title="${translate('allChapters')}">
+ <svg viewBox="0 0 18 18"><path d="M2 2h6v6H2zM10 2h6v6h-6zM2 10h6v6H2zM10 10h6v6h-6z"/></svg>
+ </a>
+ <button class="icon" id="bPlay" aria-label="${translate('playLabel')}">
+ <svg class="i-play" viewBox="0 0 18 18"><path d="M4 2v14l12-7z"/></svg>
+ <svg class="i-pause" viewBox="0 0 18 18"><path d="M3.5 2h4v14h-4zM10.5 2h4v14h-4z"/></svg>
+ </button>
+ <button class="icon" id="bBack" aria-label="${translate('backLabel')}">
+ <svg viewBox="0 0 18 18"><path d="M3 2h2.5v14H3zM16 2v14L6.5 9z"/></svg>
+ </button>
+ <button class="icon" id="bRestart" aria-label="${translate('restartLabel')}">
+ <svg viewBox="0 0 18 18"><path d="M9 2.5a6.5 6.5 0 1 1-6.3 8.1l2-.5A4.5 4.5 0 1 0 9 4.5V7L4.5 3.5 9 0z"/></svg>
+ </button>
+ <div class="segs" id="segs"></div>
+ <div class="step" id="stepName"></div>
+ <button class="icon txt" id="bHelp" aria-label="${translate('helpLabel')}" title="${translate('helpLabel')}">?</button>
+ <button class="icon txt speed" id="bSpeed" aria-label="${translate('speedLabel')}" title="${translate('speedLabel')}">1×</button>
+ <button class="icon cc" id="bCC" aria-pressed="false" aria-label="${translate('captionsLabel')}" title="${translate('captionsLabel')}">CC</button>
+ <button class="icon" id="bFull" aria-label="${translate('fullScreenLabel')}">
+ <svg viewBox="0 0 18 18"><path d="M1 1h6v2H3v4H1zM11 1h6v6h-2V3h-4zM1 11h2v4h4v2H1zM15 11h2v6h-6v-2h4z"/></svg>
+ </button>
+ </div>
+</div>`);
+
+// Board colour, grain and vignette are a static CSS background of #stage (engine.css). The grain is a small noise
+// texture made once here: an SVG turbulence filter behind animated content is recomputed on every frame in Firefox.
+{
+ const c = document.createElement('canvas'); c.width = c.height = 256;
+ const x = c.getContext('2d'), d = x.createImageData(256, 256);
+ for (let i = 0, s = 7; i < d.data.length; i += 4) { s = s * 16807 % 2147483647; d.data.set([235, 242, 230, 4 + s % 12], i); }
+ x.putImageData(d, 0, 0);
+ document.getElementById('stage').style.setProperty('--grain', `url(${c.toDataURL()})`);
+}
+
+/* ---------- drawing helpers ---------- */
+const NS = 'http://www.w3.org/2000/svg';
+const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
+// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
+// --progress-key for the localStorage key the cover and chapters share.
+const BOOK = getComputedStyle(document.documentElement);
+const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
+const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
+const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
+// Card positions inside the picture. BAND and the screens follow the stage; RIGHT and TOPR are placed for the wide
+// stage's number line and map and have no upright layout yet.
+const BAND = { x: 96 * SW / 1600, y: SH - 214, w: SW - 192 * SW / 1600, cls: 'band' }; // bottom band (moves up when taller than the space left)
+const RIGHT = { x: 1258, y: 546, w: 330, cls: 'side', maxH: 346 }; // right of the number map
+const TOPR = { x: 960, y: 70, w: 624, cls: 'side', maxH: 470 }; // top right, above the number line
+const SCREEN = { x: 0, y: 0, w: SW, cls: 'screen' };
+const SORT_SCREEN = { x: 0, y: 0, w: SW, cls: 'screen sort' };
+const $m = (...parts) => ({ m: parts });
+
+function mk(tag, attrs = {}, parent) {
+ const e = document.createElementNS(NS, tag);
+ for (const k in attrs) e.setAttribute(k, attrs[k]);
+ if (parent) parent.appendChild(e);
+ return e;
+}
+// Every animated element keeps a small state object; render() writes it to the DOM.
+// Keys: x y s r o (transform/opacity), d (0..1 stroke drawn), a_<attr> numeric attr, c_<attr> hex colour.
+function st(e) { return e._st || (e._st = { x: 0, y: 0, s: 1, r: 0, o: 1 }); }
+function put(e, o) { Object.assign(st(e), o); render(e); return e; }
+// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
+function render(e) {
+ const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
+ if (s.d !== undefined) {
+ e.setAttribute('stroke-dashoffset', 1 - s.d);
+ e.style.visibility = s.d < .002 ? 'hidden' : '';
+ }
+ for (const k in s) {
+ if (k.startsWith('a_')) e.setAttribute(k.slice(2), s[k]);
+ else if (k.startsWith('c_')) e.setAttribute(k.slice(2), s[k]);
+ }
+}
+function G(parent, o = {}) { return put(mk('g', {}, parent), o); }
+function path(parent, d, attrs = {}, o = {}) {
+ const p = mk('path', { d, fill: 'none', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', ...attrs }, parent);
+ if (o.d !== undefined) { p.setAttribute('pathLength', 1); p.setAttribute('stroke-dasharray', '1 1'); }
+ return put(p, o);
+}
+function T(parent, str, { x = 0, y = 0, size = 30, fill = COL.chalk, font = UI, weight = 500, anchor = 'start', o = 1 } = {}) {
+ const t = mk('text', { 'font-size': size, fill, 'font-family': font, 'font-weight': weight, 'text-anchor': anchor }, parent);
+ t.textContent = str;
+ 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
+const F = (n, d) => ({ f: [String(n), String(d)] }); // fraction
+const R = (x, i) => ({ r: x && x.f ? x : String(x), i: i && String(i) }); // root of a number or of F(n, d); i = index, e.g. 3 for a cube root
+const E = x => ({ sup: String(x) }); // exponent, raised after the part before it
+const TX = tex => ({ tex: String(tex) }); // LaTeX, drawn by MathJax; the book loads lib/mathjax.js right after this file
+const $tex = tex => $m(TX(tex)); // LaTeX inline in HTML text
+// MathJax takes this object as its configuration when lib/mathjax.js loads after the engine.
+window.MathJax ??= {
+ startup: { typeset: false }, // no page scan; formulas are converted on demand
+ svg: { fontCache: 'none', mtextInheritFont: true }, // self-contained paths; \text{} in the book's math font
+ tex: { packages: { '[-]': ['noerrors', 'noundefined'] }, // a typo stops the page, like a misspelt mark
+ formatError: (_, error) => { throw error; } },
+ options: { enableMenu: false },
+};
+const TEX_CACHE = new Map(); // TeX source -> { graphic, viewBox }; seek() redraws every earlier beat
+// A copy of the formula's MathJax drawing: units of 1/1000 em, baseline at y = 0; viewBox is [x, y, width, height].
+function texGraphic(tex) {
+ let drawn = TEX_CACHE.get(tex);
+ if (!drawn) {
+ if (!window.MathJax?.tex2svg) throw new Error(`TX('${tex}') needs lib/mathjax.js: load ../lib/mathjax.js right after engine.js`);
+ if (!document.getElementById('MJX-SVG-styles')) document.head.append(MathJax.svgStylesheet()); // draws table rules and frames
+ let svg;
+ try { svg = MathJax.tex2svg(tex, { display: false, family: MATH }).querySelector('svg'); } // family: \text{} is measured in the font it is drawn in
+ catch (error) { throw new Error(`TX('${tex}'): ${error.message}`); }
+ const graphic = mk('g');
+ graphic.append(...svg.childNodes);
+ drawn = { graphic, viewBox: svg.getAttribute('viewBox').split(' ').map(Number) };
+ TEX_CACHE.set(tex, drawn);
+ }
+ return { graphic: drawn.graphic.cloneNode(true), viewBox: drawn.viewBox };
+}
+// The part of a TeX formula marked \class{name}{...}, ready for tw/fx on c_color and o.
+// MathJax places the part with its own transform, so the tweens act on a group inside it.
+function texPart(el, name) {
+ const part = el.querySelector(`g.${CSS.escape(name)}`);
+ if (!part) throw new Error(`texPart: no \\class{${name}}{…} in this formula`);
+ if (!part._tweenGroup) {
+ const group = mk('g');
+ group.append(...part.childNodes);
+ part.append(group);
+ const color = part.closest('[color]')?.getAttribute('color'); // the formula's fill
+ put(group, /^#[\da-f]{6}$/i.test(color) ? { c_color: color } : {});
+ part._tweenGroup = group;
+ }
+ return part._tweenGroup;
+}
+const OV = x => ({ ov: String(x) }); // digits under a repeat bar: ['0.', OV('3')] is 0.333…
+// Math expression from parts: 'text' | F(n,d) | R(x) | E(exp) | OV(digits) | TX(tex). Baseline at y; anchor start/middle/end.
+// _ascent and _descent are the TeX parts' height above and below the baseline (0 without TX).
+function M(parent, parts, { x = 0, y = 0, size = 36, fill = COL.chalk, anchor = 'middle', o = 1, s = 1 } = {}) {
+ const g = G(parent, { x, y, o, s });
+ const inner = mk('g', {}, g);
+ const lw = size * .05;
+ const text = (str, tx, ty, sz) => {
+ const t = mk('text', { x: tx, y: ty, 'font-size': sz, 'font-family': MATH, fill }, inner);
+ t.style.whiteSpace = 'pre';
+ let w = 0, last = 0;
+ const run = (piece, italic) => {
+ if (!piece) return;
+ mk('tspan', italic ? { 'font-style': 'italic' } : {}, t).textContent = piece;
+ w += textW(piece, sz, italic);
+ };
+ for (const m of str.matchAll(VAR)) { run(str.slice(last, m.index), false); run(m[0], true); last = m.index + m[0].length; }
+ run(str.slice(last), false);
+ return w;
+ };
+ const rule = (x1, x2, yy) => mk('path', { d: `M${x1} ${yy}H${x2}`, stroke: fill, 'stroke-width': lw, 'stroke-linecap': 'round' }, inner);
+ let cx = 0, ascent = 0, descent = 0;
+ for (const p of parts) {
+ if (typeof p === 'string') cx += text(p, cx, 0, size);
+ else if (p.tex !== undefined) {
+ const { graphic, viewBox: [, top, w, h] } = texGraphic(p.tex), k = size / 1000; // 1000 units = 1 em = size
+ graphic.setAttribute('transform', `translate(${cx},0) scale(${k})`);
+ graphic.setAttribute('color', fill); // MathJax paints with currentColor
+ inner.append(graphic);
+ ascent = Math.max(ascent, -top * k);
+ descent = Math.max(descent, (top + h) * k);
+ cx += w * k;
+ } else if (p.f) {
+ const fs = size * .72, [n, d] = p.f, wn = textW(n, fs), wd = textW(d, fs);
+ const w = Math.max(wn, wd) + size * .2, bar = -size * .3;
+ text(n, cx + (w - wn) / 2, bar - size * .12, fs);
+ text(d, cx + (w - wd) / 2, bar + size * .62, fs);
+ rule(cx + size * .04, cx + w - size * .04, bar);
+ cx += w + size * .04;
+ } else if (p.r) {
+ const fr = typeof p.r === 'object', mid = fr ? -size * .12 : -size * .3, bot = fr ? size * .45 : size * .06, top = fr ? -size * 1.12 : -size * .82;
+ let x0 = cx + size * .04;
+ if (p.i) { const iw = textW(p.i, size * .42); text(p.i, x0, mid - size * .14, size * .42); x0 += Math.max(0, iw - size * .12); } // index in the radical's crook
+ let w;
+ if (fr) { // a fraction under the radical, laid out like F()
+ const fs = size * .72, [n, d] = p.r.f, wn = textW(n, fs), wd = textW(d, fs), bx = x0 + size * .56, bar = -size * .3;
+ w = Math.max(wn, wd) + size * .2;
+ text(n, bx + (w - wn) / 2, bar - size * .12, fs);
+ text(d, bx + (w - wd) / 2, bar + size * .62, fs);
+ mk('path', { d: `M${bx + size * .04} ${bar}H${bx + w - size * .04}`, stroke: fill, 'stroke-width': lw, 'stroke-linecap': 'round' }, inner);
+ } else { w = textW(p.r, size); text(p.r, x0 + size * .56, 0, size); }
+ mk('path', { d: `M${x0} ${mid}L${x0 + size * .1} ${mid - size * .06}L${x0 + size * .27} ${bot}L${x0 + size * .45} ${top}H${x0 + size * .56 + w + size * .06}`,
+ fill: 'none', stroke: fill, 'stroke-width': lw, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }, inner);
+ cx = x0 + size * .56 + w + size * .1;
+ } else if (p.sup !== undefined) {
+ cx += text(p.sup, cx + size * .03, -size * .45, size * .62) + size * .06;
+ } else if (p.ov !== undefined) {
+ const w = text(p.ov, cx, 0, size);
+ rule(cx + size * .04, cx + w - size * .02, -size * .8);
+ cx += w;
+ }
+ }
+ const dx = anchor === 'middle' ? -cx / 2 : anchor === 'end' ? -cx : 0;
+ inner.setAttribute('transform', `translate(${dx},0)`);
+ g._w = cx;
+ g._ascent = ascent;
+ g._descent = descent;
+ return g;
+}
+// Pill-shaped number token, centred on (x, y).
+function chip(parent, parts, color, { x = 0, y = 0, o = 1, s = 1, size = 34 } = {}) {
+ const g = G(parent, { x, y, o, s });
+ const rect = mk('rect', {}, g);
+ const m = M(g, parts, { size, y: size * .3 });
+ const w = Math.max(m._w + 36, 64);
+ let h = size * (parts.some(p => p.f) ? 1.75 : 1.45);
+ if (m._ascent) { // a TeX formula: centre it and grow the pill to fit
+ const above = Math.max(size * 1.05, m._ascent), below = Math.max(size * .45, m._descent);
+ put(m, { y: (above - below) / 2 });
+ h = Math.max(h, m._ascent + m._descent + size * .4);
+ }
+ for (const [k, v] of Object.entries({ x: -w / 2, y: -h / 2, width: w, height: h, rx: h / 2, fill: COL.board, stroke: color, 'stroke-width': 2.5 })) rect.setAttribute(k, v);
+ g._rect = rect;
+ return g;
+}
+// A row of math tokens laid out left to right. Items: string | parts array | { t, fill }.
+// Each token is centred on its own x, so it can move alone (swaps, sliding parentheses). Spacing comes from the strings.
+function tokens(parent, items, { x = 0, y = 0, size = 44, fill = COL.chalk, anchor = 'start', o = 1 } = {}) {
+ const els = items.map(it => {
+ const spec = it && it.t !== undefined ? it : { t: it };
+ return M(parent, [].concat(spec.t), { size, fill: spec.fill || fill, o });
+ });
+ return layRow(els, { x, y, size, anchor }, e => put(e, { x: e._px, y }));
+}
+// Place a row's tokens side by side. Each token keeps its planned centre in _px, so later steps
+// can be planned before earlier tweens have run.
+function layRow(els, { x, y, size, anchor }, move) {
+ const total = els.reduce((a, e) => a + e._w, 0);
+ let cx = anchor === 'middle' ? x - total / 2 : anchor === 'end' ? x - total : x;
+ for (const e of els) { e._px = cx + e._w / 2; move(e); cx += e._w; }
+ return Object.assign(els, { w: total, x, y, size, anchor });
+}
+// One simplification step: box tokens i..j, shrink them into a single result token, then close the gap.
+// Returns the new row. live = true runs on the question clock (inside ask) instead of the lesson clock.
+function collapse(row, i, j, parts, t0, { color = COL.task, fill = COL.chalk, live = false } = {}) {
+ const run = live ? fx : tw, p = row[0].parentNode, { size, y } = row;
+ const left = row[i]._px - row[i]._w / 2, right = row[j]._px + row[j]._w / 2;
+ let above = size * .95, height = size * 1.3;
+ const tall = row.slice(i, j + 1).filter(e => e._ascent); // TeX tokens may reach higher and lower than text
+ if (tall.length) {
+ above = Math.max(above, ...tall.map(e => e._ascent + 8));
+ height = above + Math.max(size * .35, ...tall.map(e => e._descent + 8));
+ }
+ const box = put(mk('rect', { rx: 10, fill: 'none', stroke: color, 'stroke-width': 3 }, p),
+ { o: 0, a_x: left - 8, a_y: y - above, a_width: right - left + 16, a_height: height });
+ run(box, { o: 1 }, t0, .3);
+ run(box, { o: 0 }, t0 + 1.2, .3);
+ const res = M(p, parts, { size, fill, o: 0, x: (left + right) / 2, y });
+ for (let k = i; k <= j; k++) run(row[k], { o: 0, s: .6 }, t0 + .8, .35);
+ run(res, { o: 1 }, t0 + .95, .35);
+ const next = [...row.slice(0, i), res, ...row.slice(j + 1)];
+ return layRow(next, row, e => run(e, { x: e._px }, t0 + 1.3, .5));
+}
+// The maths helpers (number lines, tiles, fractions, planes, the number map, sorter) are in math.js.
+// Inline math for HTML text.
+function mathEl(parts, size = 22) {
+ const svg = mk('svg', { class: 'm', 'font-weight': 400 }); // widths are measured at normal weight, so a bold prompt must not thicken the math
+ const m = M(svg, parts, { size, anchor: 'start', fill: 'currentColor' });
+ let top = size * 1.05, bottom = size * .45, h = size * 1.5;
+ if (m._ascent) { // a TeX formula may reach higher and lower than text
+ top = Math.max(top, m._ascent + size * .1);
+ bottom = Math.max(bottom, m._descent + size * .1);
+ h = top + bottom;
+ }
+ svg.setAttribute('viewBox', `0 ${-top} ${m._w + 2} ${h}`);
+ svg.setAttribute('width', m._w + 2);
+ svg.setAttribute('height', h);
+ svg.style.verticalAlign = `${-bottom}px`; // line up the math baseline with the text baseline
+ return svg;
+}
+
+
+/* ---------- timeline ---------- */
+let TW = [];
+const io = p => p < .5 ? 4 * p * p * p : 1 - (-2 * p + 2) ** 3 / 2;
+const out = p => 1 - (1 - p) ** 3;
+const back = p => 1 + 2.2 * (p - 1) ** 3 + 1.2 * (p - 1) ** 2;
+const lin = p => p;
+function tw(e, to, t0, dur = .6, ease = io) { TW.push({ e, to, t0, dur, ease }); }
+function prog(pf, t0, dur, ease = io) { TW.push({ pf, t0, dur, ease }); }
+const show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
+const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
+function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
+function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
+function mix(a, b, q) {
+ const h = c => [1, 3, 5].map(i => parseInt(c.slice(i, i + 2), 16));
+ const A = h(a), B = h(b);
+ return '#' + A.map((v, i) => Math.round(v + (B[i] - v) * q).toString(16).padStart(2, '0')).join('');
+}
+// A colour or attribute tween with no starting value in the state starts from the element's attribute.
+const fromAttr = (e, k) => k.startsWith('c_') ? e.getAttribute(k.slice(2)) : k.startsWith('a_') ? parseFloat(e.getAttribute(k.slice(2))) : undefined;
+function evalTo(t, list = TW) {
+ for (const w of list) {
+ if (w.done || t < w.t0) continue;
+ if (!w.go) { w.go = 1; if (w.e) { const s = st(w.e); w.from = {}; for (const k in w.to) w.from[k] = s[k] ?? fromAttr(w.e, k); } }
+ const p = w.dur ? Math.min(1, (t - w.t0) / w.dur) : 1, q = w.ease(p);
+ if (w.e) {
+ const s = st(w.e);
+ for (const k in w.to) s[k] = k.startsWith('c_') ? mix(w.from[k], w.to[k], q) : w.from[k] + (w.to[k] - w.from[k]) * q;
+ render(w.e);
+ } else w.pf(q);
+ if (p >= 1) w.done = 1;
+ }
+}
+
+/* ---------- world clock and camera ---------- */
+const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
+// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject. f also gets the run's end
+// (for a tail, the beat's real end), so a move can land on it, as a whip at the end of a beat does. Under music that
+// end is where the beat really leaves, up to HOLD early (P.back, see frameStep), so the move is still seen landing.
+// A tail's own D does not lengthen the beat: it runs to the end whatever it is (so D + HOLD adds no second hold).
+const clockRun = (f, D, { tail = false } = {}) => { const w = { t0: 0, dur: D, ease: lin, tail }; f(0, D); w.pf = q => f(q * w.dur, w.tail ? w.dur - P.back : w.dur); TW.push(w); };
+// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
+// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
+// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
+// function of t (follow). Unspecified keys keep following the earlier moves. dur 0 is a hard cut.
+let camN = 0;
+function camera(p, D, { box, x = SW / 2, y = SH / 2, z, r = 0, bg = COL.board } = {}) {
+ const [bx, by, bw, bh] = box || [0, 0, SW, SH];
+ const el = G(p, { x: bx + bw / 2, y: by + bh / 2 });
+ let hold = el;
+ if (box) {
+ const id = 'cam' + (++camN);
+ mk('rect', { x: -bw / 2, y: -bh / 2, width: bw, height: bh, rx: 18 }, mk('clipPath', { id }, mk('defs', {}, el)));
+ hold = G(el); hold.setAttribute('clip-path', `url(#${id})`);
+ mk('rect', { x: -bw / 2, y: -bh / 2, width: bw, height: bh, fill: bg }, hold);
+ }
+ const view = mk('g', {}, hold), world = G(view);
+ if (box) mk('rect', { x: -bw / 2, y: -bh / 2, width: bw, height: bh, rx: 18, fill: 'none', stroke: COL.faint, 'stroke-width': 2 }, el);
+ const v0 = { x, y, z: z ?? (box ? Math.min(bw / SW, bh / SH) : 1), r };
+ const ops = [], shakes = [], layers = [];
+ const val = (v, t) => typeof v === 'function' ? v(t) : v;
+ // The view at time t after the first n moves; each move remembers the view it starts from.
+ function at(t, n = ops.length) {
+ const s = { ...v0 };
+ for (let i = 0; i < n && ops[i].t0 <= t; i++) {
+ const o = ops[i], a = o.from || (o.from = at(o.t0, i));
+ const q = o.dur ? o.ease(Math.min(1, (t - o.t0) / o.dur)) : 1, b = {};
+ for (const k in o.v) b[k] = val(o.v[k], t);
+ if ('z' in b) s.z = a.z * (b.z / a.z) ** q; // even zoom speed
+ // While zooming, x/y move so that one world point stays put on screen (when start and end allow it).
+ const u = 'z' in b && Math.abs(b.z - a.z) > 1e-6 * a.z ? (1 / s.z - 1 / a.z) / (1 / b.z - 1 / a.z) : q;
+ for (const k of ['x', 'y']) if (k in b) s[k] = a[k] + (b[k] - a[k]) * u;
+ if ('r' in b) s.r = a.r + (b.r - a.r) * q;
+ }
+ return s;
+ }
+ function apply(t) {
+ const s = at(t);
+ let sx = 0, sy = 0;
+ for (const k of shakes) if (t > k.t0 && t < k.t0 + k.dur) {
+ const e = k.amp * Math.min(1, (t - k.t0) / .3, (k.t0 + k.dur - t) / .3), w = 2 * Math.PI * k.hz * t;
+ sx += e * (Math.sin(w) + .5 * Math.sin(2.3 * w + 1)) / 1.5; sy += e * (Math.sin(1.7 * w + 2) + .5 * Math.sin(3.1 * w)) / 1.5;
+ }
+ const tf = `translate(${sx} ${sy}) rotate(${-s.r}) scale(${s.z}) translate(${-s.x} ${-s.y})`;
+ if (tf !== view._tf) view.setAttribute('transform', view._tf = tf);
+ const dx = s.x - v0.x, dy = s.y - v0.y;
+ for (const L of layers) put(L.g, { x: L.wrap ? dx - ((L.k * dx) % L.wrap + L.wrap) % L.wrap : (1 - L.k) * dx, y: (1 - L.k) * dy });
+ }
+ const cam = { el, world, at,
+ to(v, t0, dur = 1, ease = soft) { ops.push({ v, t0, dur, ease }); ops.sort((a, b) => a.t0 - b.t0); ops.forEach(o => delete o.from); return cam; },
+ cut: (v, t0) => cam.to(v, t0, 0),
+ shake(amp, t0, dur, hz = 7) { shakes.push({ amp, t0, dur, hz }); return cam; },
+ // Parallax layer: k < 1 is far (moves slower than the camera), k > 1 near. With wrap = W the layer's content
+ // repeats every W world px: draw one period plus the widest view, and the layer never runs out.
+ layer(k = 1, wrap) { const g = G(world); layers.push({ g, k, wrap }); return g; },
+ // Screen position of a world point at time t (k = 1 layers, no shake): for labels that track an object.
+ screen(wx, wy, t) {
+ const s = at(t), a = -s.r * Math.PI / 180, ux = (wx - s.x) * s.z, uy = (wy - s.y) * s.z;
+ return [bx + bw / 2 + ux * Math.cos(a) - uy * Math.sin(a), by + bh / 2 + ux * Math.sin(a) + uy * Math.cos(a)];
+ },
+ // Put a screen-space label (text, anchor middle, outside the camera) over world point (wx, wy) at time t, kept
+ // inside the frame or box by margin m; it fades out once the point itself leaves. Fade it in with a wrapper group.
+ track(el, wx, wy, t, m = 24) {
+ const [sx, sy] = cam.screen(wx, wy, t), str = el.textContent;
+ if (el._tw?.[0] !== str) el._tw = [str, el.getComputedTextLength() / 2];
+ const h = el._tw[1], away = Math.max(bx - sx, sx - bx - bw, 0);
+ put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
+ },
+ };
+ clockRun(apply, D, { tail: 'follow' });
+ return cam;
+}
+
+/* ---------- scene ---------- */
+const scene = document.getElementById('scene');
+const S = {};
+const AXIS = { o: SW / 2, u: 120 }; // number line: x of 0, pixels per unit; a chapter may change it
+const X = v => AXIS.o + AXIS.u * v, Y0 = 610;
+const num = v => (v < 0 ? '−' : '') + String(Math.abs(v)).replace('.', DECIMAL_SIGN);
+function reset() {
+ scene.replaceChildren();
+ for (const k in S) delete S[k];
+ Object.assign(S, { dots: {}, tick: {}, rows: [], chips: [], samples: [], list: G(scene), line: G(scene), venn: G(scene) });
+}
+function tick(v) {
+ const g = G(S.line, { o: 0 });
+ path(g, `M${X(v)} ${Y0 - 11}V${Y0 + 11}`, { stroke: COL.dim, 'stroke-width': 2.5 });
+ T(g, num(v), { x: X(v), y: Y0 + 50, size: 30, fill: COL.dim, font: MATH, anchor: 'middle' });
+ return (S.tick[v] = g);
+}
+function dot(key, v, r = 9, name = v) {
+ const g = G(S.line, { x: X(v), y: Y0, s: 0, o: 0 });
+ mk('circle', { r, fill: COL[key], stroke: COL.board, 'stroke-width': 2 }, g);
+ return (S.dots[name] = g);
+}
+const arrow = (x, dir) => `M${x - 15 * dir} ${Y0 - 10}L${x} ${Y0}L${x - 15 * dir} ${Y0 + 10}`;
+function panel(t0) {
+ if (t0 < .5) S.cleared = true; // the old panel fades, or this is the first panel after the title
+ const old = S.panel;
+ if (old && t0 < .5) retire(old);
+ else if (old) { // a panel change later in the beat stays on the beat clock
+ hide(old, t0, .4);
+ prog(q => { if (q === 1) old.style.display = 'none'; }, t0 + .4, 0, lin);
+ }
+ return (S.panel = G(scene));
+}
+// Take a beat's old picture away on wall time: a 150 ms fade, then out of rendering. On the beat clock the fade would
+// wait for the new clip's audio to start (a few hundred ms in Firefox) with the old, frozen scene still showing.
+// While seeking, the pictures passed on the way were never seen: they go at once.
+// It then leaves the page: a long film otherwise keeps every earlier beat's picture (a documentary's maps: megabytes).
+function retire(e) {
+ if (seeking) { e.remove(); return; }
+ e.style.transition = 'opacity .15s linear';
+ e.style.opacity = '0';
+ setTimeout(() => e.remove(), 160);
+}
+function header(p, str, t0, x = 1000, y = 170) {
+ const h = T(p, str, { x, y, size: 30, fill: COL.dim, weight: 600, o: 0 });
+ show(h, t0);
+ return h;
+}
+
+/* ---------- question effects: run on wall time, independent of the lesson clock ---------- */
+let FX = [], clock = 0;
+function fx(e, to, delay = 0, dur = .5, ease = io) { FX.push({ e, to, t0: clock + delay, dur, ease }); }
+function fxp(pf, delay, dur, ease = io) { FX.push({ pf, t0: clock + delay, dur, ease }); }
+function finishFx() { FX.sort((a, b) => a.t0 - b.t0); evalTo(Infinity, FX); FX = []; }
+const pulseFx = (e, k = 1.8) => { if (!e) return; fx(e, { s: k }, 0, .22, out); fx(e, { s: 1 }, .22, .45); };
+const shakeFx = e => { if (!e) return; const x0 = st(e).x; fxp(q => put(e, { x: x0 + Math.sin(q * Math.PI * 6) * (1 - q) * 12 }), 0, .55, lin); };
+function floatText(str, x, y, colr) {
+ const t = T(S.q || qlayer(), str, { x, y: y + 14, size: 24, fill: colr, anchor: 'middle', weight: 600, o: 0 });
+ fx(t, { o: 1, y }, 0, .5, out);
+}
+
+/* ---------- shared answer columns ---------- */
+const TF = [['t', translate('trueLabel'), null, 'T'], ['f', translate('falseLabel'), null, 'F']];
+function finishCard() {
+ const c = card(SCREEN, 'fin');
+ const sum = pre => Object.entries(SCORE).filter(([k]) => k.startsWith(pre)).reduce((a, [, v]) => [a[0] + v.right, a[1] + v.total], [0, 0]);
+ const line = (name, [r, t]) => h('p', 'fb', t ? translate('firstTryScore', { name, r, t }) : translate('notAttempted', { name }));
+ progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ const home = h('a', 'btn quiet', translate('allChapters'));
+ home.href = $('bHome').href;
+ const again = h('button', 'btn' + (CHAPTER.next ? ' quiet' : ' go'), [translate('watchAgain'), kbd(CHAPTER.next ? 'R' : 'Enter')]);
+ again.onclick = restart;
+ const next = CHAPTER.next && h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
+ if (next) next.onclick = () => { location.href = CHAPTER.next; };
+ P.keys = e => e.key === 'Enter' ? ((next ? next.onclick() : restart()), true)
+ : 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]), sources()].filter(Boolean)));
+ setTimeout(() => mood(guide, 'happy'), 400);
+}
+
+/* ---------- in-picture cards ---------- */
+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 SCORE = {}; // question id -> first-attempt {right, total}
+
+function h(tag, cls, kids = []) {
+ const e = document.createElement(tag);
+ if (cls) e.className = cls;
+ for (const k of [].concat(kids)) e.append(k);
+ return e;
+}
+// Rich text: strings, DOM nodes, or $m(...) inline math.
+function rich(parts, size = 28) {
+ const s = document.createElement('span');
+ for (const p of [].concat(parts)) s.append(typeof p === 'string' || p instanceof Node ? p : mathEl(p.m, size));
+ return s;
+}
+// A card at pos; a band card keeps its bottom on the stage: when its content grows (a long question, feedback),
+// it moves up rather than running under the player bar.
+function card(pos, cls) {
+ const c = h('div', `card ${pos.cls} ${cls}`);
+ Object.assign(c.style, { left: pos.x + 'px', top: pos.y + 'px', width: pos.w + 'px' });
+ if (pos.maxH) c.style.maxHeight = pos.maxH + 'px';
+ $('ui').append(c);
+ if (pos.cls === 'band') {
+ const fit = () => { c.style.top = Math.max(16, Math.min(pos.y, SH - 16 - c.offsetHeight)) + 'px'; };
+ const ro = new ResizeObserver(fit);
+ ro.observe(c); fit();
+ P.cleanup.push(() => ro.disconnect());
+ }
+ return c;
+}
+// The guide: an infinity sign whose two loops are its eyes. Drawn in SVG so it can blink, hop and wobble.
+function lemniscate(cx, cy, a, k) {
+ let d = '';
+ for (let i = 0; i <= 96; i++) {
+ const t = i / 96 * 2 * Math.PI, sn = Math.sin(t), q = 1 + sn * sn;
+ d += (i ? 'L' : 'M') + (cx + a * Math.cos(t) / q).toFixed(1) + ' ' + (cy + k * a * sn * Math.cos(t) / q).toFixed(1);
+ }
+ return d + 'Z';
+}
+function mascotEl(size = 100) {
+ const svg = mk('svg', { class: 'mascot', viewBox: '0 0 120 84', width: size, height: size * .7, 'aria-hidden': 'true' });
+ const body = mk('g', { class: 'mbody' }, svg);
+ const line = { fill: 'none', stroke: COL.chalk, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' };
+ mk('path', { d: lemniscate(60, 40, 52, 1.5), ...line, 'stroke-width': 6 }, body);
+ const eyes = mk('g', { class: 'eyes' }, body);
+ for (const x of [33, 87]) {
+ mk('circle', { class: 'pupil', cx: x, cy: 40, r: 6.5, fill: COL.chalk }, eyes);
+ mk('path', { class: 'joy', d: `M${x - 7} 43Q${x} 32 ${x + 7} 43`, ...line, 'stroke-width': 4 }, body);
+ }
+ mk('path', { class: 'smile', d: 'M55 62Q60 67 65 62', ...line, 'stroke-width': 3.5 }, body);
+ mk('path', { class: 'flat', d: 'M55 64H65', ...line, 'stroke-width': 3.5 }, body);
+ return svg;
+}
+function mood(el, m) {
+ el.classList.remove('happy', 'oops');
+ void el.getBoundingClientRect(); // restart the CSS animation
+ if (m) el.classList.add(m);
+}
+// A sequence of questions in one card. Each question: { id, prompt, build(body, api) -> { check?, reveal, lock? } }.
+function quiz(pos, qs, done, label = translate('quickCheck')) {
+ const c = card(pos, 'quiz');
+ let k = 0;
+ const show = () => {
+ const q = qs[k];
+ let first = true, resolved = false;
+ const fb = h('div', 'fb'), body = h('div', 'body'), acts = h('div', 'acts');
+ fb.setAttribute('role', 'status'); // screen readers announce right or wrong
+ const bCheck = h('button', 'btn', [translate('check'), kbd('Enter')]), bShow = h('button', 'btn quiet', [translate('showAnswer'), kbd('S')]);
+ const bNext = h('button', 'btn go', [k < qs.length - 1 ? translate('nextQuestion') : translate('continue'), kbd('Enter')]);
+ bShow.hidden = bNext.hidden = true;
+ const guide = pos.cls === 'band' || pos.cls === 'side' ? mascotEl(pos.cls === 'band' ? 108 : 70) : null;
+ const say = (cls, parts) => { fb.className = 'fb ' + cls; fb.replaceChildren(rich(parts, 24)); fb.style.animation = 'none'; void fb.offsetWidth; fb.style.animation = ''; };
+ const resolve = () => {
+ resolved = true;
+ bCheck.hidden = bShow.hidden = true;
+ ctl.lock?.();
+ bNext.hidden = false;
+ bNext.focus({ preventScroll: true });
+ };
+ const api = {
+ grade(ok, msg, score) {
+ if (resolved) return;
+ if (first) { if (!Object.hasOwn(SCORE, q.id)) SCORE[q.id] = score || { right: +ok, total: 1 }; first = false; }
+ say(ok ? 'ok' : 'no', [ok ? translate('correct') : translate('notQuite'), ...[].concat(msg || [])]);
+ if (guide) {
+ mood(guide, ok ? 'happy' : 'oops');
+ if (!ok) setTimeout(() => { if (guide.classList.contains('oops')) mood(guide, null); }, 1600);
+ }
+ if (ok) resolve(); else bShow.hidden = false;
+ },
+ };
+ const ctl = q.build(body, api);
+ if (ctl.check) { bCheck.onclick = () => ctl.check(); acts.append(bCheck); }
+ acts.append(bShow, bNext);
+ bShow.onclick = () => { say('', [translate('answerPrefix'), ...[].concat(ctl.reveal())]); resolve(); };
+ bNext.onclick = () => { if (k < qs.length - 1) { k++; show(); } else done(); };
+ P.keys = e => {
+ if (e.key === 'Enter' && resolved) { bNext.click(); return true; }
+ if (!resolved && ctl.key?.(e)) return true;
+ if (e.key === 'Enter' && !resolved && ctl.check) { bCheck.click(); return true; }
+ if (isShortcut(e, 's') && !bShow.hidden) { bShow.click(); return true; }
+ return false;
+ };
+ const kick = label + (qs.length > 1 ? ' · ' + translate('countOf', { k: k + 1, n: qs.length }) : '');
+ const head = h('div', 'head', [h('p', 'kicker', kick), h('p', 'prompt', [rich(q.prompt, pos.cls.startsWith('screen') ? 38 : 28)])]); // match the prompt's type size
+ if (ctl.hint) head.append(h('p', 'keys', [translate('keysPrefix'), ...ctl.hint]));
+ c.replaceChildren(...(guide ? [guide] : []), head, fb, body, acts);
+ };
+ show();
+}
+function qlayer() {
+ S.q?.remove();
+ S.q = G(scene);
+ S.q.classList.add('qlayer');
+ return S.q;
+}
+const keyAct = (el, fn) => el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); fn(); } });
+
+/* ---------- question builders ---------- */
+// Single answer from buttons; each wrong option has its own explanation.
+const choice = (opts, right, yes, no, onRight) => (body, api) => {
+ const row = h('div', 'opts');
+ const bs = opts.map((o, i) => {
+ const b = h('button', 'opt', [kbd(String(i + 1)), rich(o, 32)]);
+ b.onclick = () => {
+ if (i === right) { b.classList.add('good'); onRight?.(); api.grade(true, yes); }
+ else { b.classList.add('bad'); b.disabled = true; api.grade(false, no[i]); }
+ };
+ row.append(b);
+ return b;
+ });
+ body.append(row);
+ return {
+ reveal() { bs[right].classList.add('good'); onRight?.(); return yes; },
+ lock() { bs.forEach(b => { b.disabled = true; }); },
+ 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) };
+}
+// Stage targets the reader taps: each g turns into a focusable button named by its label that acts on a click, Enter or
+// Space. Returns key(e) for P.keys: ← / → move the focus between them (from the one focused, if any).
+function tappable(items) { // [{ g, label, act }]
+ for (const { g, label, act } of items) {
+ g.classList.add('hit');
+ g.setAttribute('tabindex', 0);
+ g.setAttribute('role', 'button');
+ g.setAttribute('aria-label', label);
+ g.addEventListener('click', act);
+ keyAct(g, act);
+ }
+ let cur = -1;
+ return e => {
+ const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (!d || !items.length) return false;
+ const on = items.findIndex(it => it.g === document.activeElement);
+ if (on >= 0) cur = on;
+ cur = cur < 0 ? (d > 0 ? 0 : items.length - 1) : (cur + d + items.length) % items.length;
+ items[cur].g.focus();
+ return true;
+ };
+}
+// The shared body of the stage tap questions: each target ring answers on click or Enter (tappable), wrong() shakes
+// and returns the explanation. targets: [{ g, label, ok, wrong }].
+const stageTap = (api, targets, show, yes, onRight, hint) => {
+ let locked = false;
+ const move = tappable(targets.map(({ g, label, ok, wrong }) => ({ g, label, act: () => {
+ if (locked) return;
+ if (ok) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }
+ else { g.classList.add('bad'); api.grade(false, wrong()); }
+ } })));
+ return {
+ reveal() { targets[show].g.classList.add('good'); onRight?.(); return yes; },
+ lock() { locked = true; },
+ hint,
+ key: e => !locked && move(e),
+ };
+};
+// Tap a point on the stage number line.
+const tap = (values, right, yes, no, onRight) => (body, api) => {
+ const L = qlayer();
+ const targets = values.map(v => {
+ const g = G(L, { x: X(v), y: Y0 });
+ mk('circle', { r: 30, class: 'ring' }, g);
+ return { g, label: translate('pointLabel', { v: num(v) }), ok: v === right, wrong: () => { shakeFx(S.dots[v]); return no(v); } };
+ });
+ return stageTap(api, targets, values.lastIndexOf(right), yes, onRight,
+ [kbd('←'), kbd('→'), translate('hintMoveAlongLine'), kbd('Enter'), translate('hintChoose')]);
+};
+// Tap one token of a stage token row, e.g. the operation to do first. idx: tappable token indexes.
+const tapEls = (row, idx, right, yes, no, onRight) => (body, api) => {
+ const L = qlayer();
+ const targets = idx.map(i => {
+ const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });
+ mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);
+ return { g, label: e.textContent.trim(), ok: i === right, wrong: () => { shakeFx(e); return no(i); } };
+ });
+ return stageTap(api, targets, idx.indexOf(right), yes, onRight,
+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChoose')]);
+};
+// Click one of several stage objects (table cells, bars, small graphs). items: [{ el, box: [x, y, w, h], label }].
+const pickEls = (items, right, yes, no, onRight) => (body, api) => {
+ const L = qlayer();
+ const targets = items.map((it, i) => {
+ const [x, y, w, hh] = it.box, g = G(L);
+ mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);
+ return { g, label: it.label, ok: i === right, wrong: () => { shakeFx(it.el); return no(i); } };
+ });
+ return stageTap(api, targets, right, yes, onRight,
+ [kbd('←'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClick')]);
+};
+/* ---------- point and read ---------- */
+// A picture book's point-and-read moment, for young children learning words: a film's ask beat (CHAPTER.film),
+// ask: done => tapWords(THINGS, done) THINGS = [{ g, word: 'basket', clip: 'w-basket', side: 'below' }]
+// which the scene fills as it builds the picture; g is what the reader taps (a puppet, a prop, or a transparent shape
+// over part of a baked set), clip names audio/<lang>/<clip>.mp3, 'w-' + the word by default, and side puts the word
+// 'above', 'below', 'left' or 'right' of its thing (kept on the stage); without it the word goes above, or wherever fits. Once the narration is
+// over (P.waiting) every thing turns tappable: a tap hops it, shows its word in large letters beside it and says it, on
+// wall time at the player volume with the music ducked under it; tapping again says it again. A counter and Continue
+// (Enter) wait in the corner; Continue lights up once every thing has been heard. Seeking or replaying clears it all.
+// While the page waits, the scene's continuous motion (stopClock, clockRun with tail: true) runs on past the beat's
+// end on wall time, so puppets posed as a function of time keep breathing and blinking.
+// The video (export.py) cannot tap: P.tapDemo.at(s) shows the words one by one, DEMO_STEP s apart, while it holds.
+const TAP_MIN = 120, DEMO_STEP = 2; // TAP_MIN: the smallest hit box in stage px, a child's finger on a phone
+const SIDES = { above: 0, below: 1, right: 2, left: 3 }; // where a word goes, in the order tried
+const wordClip = word => 'w-' + word.toLowerCase().trim().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '');
+function tapWords(things, done) {
+ const gen = P.gen, stage = $('stage'), lang = CHAPTER.language || 'en';
+ if (!CHAPTER.film) console.warn('tapWords: CHAPTER.film is not true, so the chapter plays as a lesson: no music or effects');
+ const list = things.filter(t => {
+ const why = !t.word ? 'has no word' : !(t.g instanceof SVGGraphicsElement && stage.contains(t.g)) ? 'is not an element on the stage' : '';
+ if (why) console.warn(`tapWords: ${t.word ? `"${t.word}"` : 'a thing'} ${why}: left out`);
+ return !why;
+ }).map(t => {
+ const clip = t.clip || wordClip(t.word), a = new Audio(`audio/${lang}/${clip}.mp3`);
+ a.preload = 'auto';
+ a.onerror = () => console.warn(`tapWords: "${t.word}" has no clip at audio/${lang}/${clip}.mp3`);
+ if (t.side && !Object.hasOwn(SIDES, t.side)) console.warn(`tapWords: "${t.word}" has side "${t.side}": use above, below, left or right; its word goes where it fits`);
+ return { g: t.g, word: t.word, clip, a, side: Object.hasOwn(SIDES, t.side ?? '') ? t.side : null, heard: false };
+ });
+ const L = mk('g', { class: 'tapw' }, stage); // the hit boxes, over the whole picture
+ let on = false, alive = true, finished = false, word = null, shown = -1, bar, count, go;
+ // a thing's box in stage px (its picture may move: puppets idle), and its hit box, at least TAP_MIN square
+ const box = t => {
+ const s = stage.getBoundingClientRect(), r = t.g.getBoundingClientRect(), kx = SW / s.width, ky = SH / s.height;
+ return { x: (r.left - s.left) * kx, y: (r.top - s.top) * ky, w: r.width * kx, h: r.height * ky };
+ };
+ const place = () => {
+ for (const t of list) {
+ const b = box(t), w = Math.max(TAP_MIN, b.w), hh = Math.max(TAP_MIN, b.h);
+ for (const [k, v] of Object.entries({ x: b.x + (b.w - w) / 2, y: b.y + (b.h - hh) / 2, width: w, height: hh })) t.ring.setAttribute(k, v.toFixed(1));
+ }
+ };
+ const finish = () => { if (finished || P.gen !== gen) return; finished = true; done(); };
+ const idle = s => { for (const w of TW) if (w.tail === true && w.dur) w.pf(1 + s / w.dur); }; // s seconds past the end
+ let since = 0;
+ const tapIt = (k, quiet) => {
+ const t = list[k];
+ shown = k;
+ t.heard = true;
+ const n = list.filter(x => x.heard).length, all = n === list.length;
+ count.textContent = all ? translate('allWordsHeard') : translate('wordsHeard', { k: n, n: list.length });
+ if (all && !go.classList.contains('go')) { go.className = 'btn go'; bar.classList.add('lit'); }
+ // the word beside the thing: on its side, or above it, else below, right or left, wherever it fits on the stage
+ // (slid along that side to stay on it)
+ word?.remove();
+ word = h('div', 'card word', t.word);
+ word.setAttribute('aria-hidden', 'true'); // the thing's own label already says the word
+ $('ui').append(word);
+ // gap: clear of the thing's hop; m: the stage's margin
+ const b = box(t), w = word.offsetWidth, hh = word.offsetHeight, gap = 30, m = 16, cx = b.x + (b.w - w) / 2, cy = b.y + (b.h - hh) / 2;
+ const spots = [[cx, b.y - hh - gap], [cx, b.y + b.h + gap], [b.x + b.w + gap, cy], [b.x - w - gap, cy]];
+ const [x, y] = t.side ? spots[SIDES[t.side]] : spots.find(([x, y], k) => k < 2 ? y >= m && y + hh <= SH - m : x >= m && x + w <= SW - m) || spots[0];
+ Object.assign(word.style, { left: Math.max(m, Math.min(SW - m - w, x)) + 'px', top: Math.max(m, Math.min(SH - m - hh, y)) + 'px' });
+ if (quiet) { word.style.animation = go.style.animation = 'none'; return; } // a video's frame shows it at rest
+ for (const x of list) if (x !== t) x.a.pause();
+ t.a.currentTime = 0;
+ t.a.volume = +($('volume')?.value ?? 1);
+ t.a.play().catch(() => {});
+ SND.word = t.a; // soundTick ducks the music under it
+ // the hop is the CSS translate property, which adds to the transform the scene sets (a prop posed every frame keeps its place)
+ t.g.animate([{ translate: '0 0' }, { translate: '0 -18px', offset: .3 }, { translate: '0 0' }], { duration: 450, easing: 'ease-out' });
+ t.ring.animate([{ strokeOpacity: 1 }, { strokeOpacity: 0 }], { duration: 700, easing: 'ease-out' });
+ };
+ const enable = () => {
+ on = true;
+ since = performance.now();
+ linkStage(); // the stage is no longer one picture to a screen reader: the things are its buttons
+ const at = new Map(list.map(t => [t, box(t)]));
+ for (const [t, b] of at) if (b.x + b.w <= 0 || b.x >= SW || b.y + b.h <= 0 || b.y >= SH || !b.w || !b.h) console.warn(`tapWords: "${t.word}" is not in the picture`);
+ // smaller boxes on top, so a thing standing in front of a bigger one can still be tapped
+ for (const t of [...list].sort((a, c) => at.get(c).w * at.get(c).h - at.get(a).w * at.get(a).h)) { t.hit = G(L); t.ring = mk('rect', { class: 'ring', rx: 22 }, t.hit); }
+ place();
+ // the arrows go through the things from left to right
+ const order = [...list].sort((a, c) => at.get(a).x + at.get(a).w / 2 - at.get(c).x - at.get(c).w / 2);
+ const move = tappable(order.map(t => ({ g: t.hit, label: t.word, act: () => { if (alive) tapIt(list.indexOf(t)); } })));
+ P.keys = e => e.key === 'Enter' ? (finish(), true) : move(e);
+ bar = card({ x: 0, y: SH - 130, w: 0, cls: 'side' }, 'words');
+ Object.assign(bar.style, { left: 'auto', right: '40px', width: 'auto' });
+ count = h('span', 'count', translate('wordsHeard', { k: 0, n: list.length }));
+ count.setAttribute('role', 'status');
+ go = h('button', 'btn quiet', [translate('continue'), kbd('Enter')]);
+ go.onclick = finish;
+ bar.append(h('div', 'acts', [count, go]));
+ // a thing whose box is covered where a finger lands (a card, a layer over the stage) cannot be tapped: once the
+ // counter's card has come in, try each box's middle and four points around it, and name what covers it
+ setTimeout(() => { if (alive) for (const t of list) {
+ const r = t.ring.getBoundingClientRect(), pts = [[.5, .5], [.3, .3], [.7, .3], [.3, .7], [.7, .7]];
+ const tops = pts.map(([u, v]) => document.elementFromPoint(r.left + u * r.width, r.top + v * r.height));
+ if (!tops.some(e => t.hit.contains(e))) {
+ const e = tops[0], cls = e?.getAttribute('class')?.split(' ')[0];
+ const what = !e ? 'it is off screen' : e.closest('.hit') ? `"${e.closest('.hit').getAttribute('aria-label')}" covers it`
+ : `<${e.tagName.toLowerCase()}${e.id ? '#' + e.id : cls ? '.' + cls : ''}> covers it`;
+ console.warn(`tapWords: "${t.word}" cannot be tapped: ${what}`);
+ }
+ } }, 600);
+ };
+ const cleanup = () => {
+ alive = false;
+ L.remove();
+ for (const t of list) { t.a.onerror = null; t.a.pause(); t.a.removeAttribute('src'); t.a.load(); if (SND.word === t.a) SND.word = null; }
+ if (P.tapDemo?.gen === gen) delete P.tapDemo;
+ };
+ P.cleanup.push(cleanup);
+ P.tapDemo = { gen, clips: list.map(t => t.clip), step: DEMO_STEP, at(s) { if (!on) enable(); idle(s); const k = Math.min(list.length - 1, Math.floor(s / DEMO_STEP)); if (k >= 0 && k !== shown) { list.slice(0, k).forEach(t => { t.heard = true; }); tapIt(k, true); } } };
+ const tick = () => {
+ if (!alive) return;
+ if (P.gen !== gen) { cleanup(); return; } // a seek away, or the beat replayed
+ if (P.waiting && !on) enable();
+ if (on && P.waiting) idle((performance.now() - since) / 1000);
+ if (on) place();
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+}
+// Rows of toggles. items: { parts, ans: [keys], why }. parts are math parts (strings, F, R) unless text: true,
+// where they are rich text (strings and $m(...)). cols: [[key, label, colour?, shortcut?]]. multi: several per row.
+const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) => {
+ const wrap = h('div', 'grid' + (text ? ' text' : ''));
+ const hot = cols.map((c, j) => c[3] || String(j + 1));
+ let cur = 0, locked = false;
+ const rows = items.map((it, ri) => {
+ const opts = h('div', 'opts'), mark = h('div', 'mark'), why = h('div', 'why');
+ const bs = cols.map(([key, lab, colr], j) => {
+ const b = h('button', 'opt', [kbd(hot[j]), lab]);
+ if (colr) b.style.setProperty('--c', colr);
+ b.setAttribute('aria-pressed', 'false');
+ b.onclick = () => {
+ const on = b.getAttribute('aria-pressed') !== 'true';
+ if (!multi) bs.forEach(x => x.setAttribute('aria-pressed', 'false'));
+ b.setAttribute('aria-pressed', String(on));
+ };
+ opts.append(b);
+ return b;
+ });
+ const el = h('div', 'row', [h('div', 'num', [text ? rich(it.parts, 26) : mathEl(it.parts, 32)]), opts, mark, why]);
+ el.addEventListener('click', () => { cur = ri; showCur(); });
+ wrap.append(el);
+ const picked = () => cols.filter((c, i) => bs[i].getAttribute('aria-pressed') === 'true').map(c => c[0]);
+ return { it, bs, mark, why, picked, el, played: false };
+ });
+ const single = rows.length === 1;
+ const showCur = () => rows.forEach((r, i) => {
+ const on = !single && !locked && i === cur;
+ r.el.classList.toggle('cur', on);
+ if (on && r.el.isConnected) r.el.scrollIntoView({ block: 'nearest' }); // a long practice list scrolls
+ });
+ showCur();
+ body.append(wrap);
+ const judge = r => {
+ const p = r.picked(), ok = p.length === r.it.ans.length && r.it.ans.every(k => p.includes(k));
+ r.mark.className = 'mark ' + (ok ? 'good' : 'bad');
+ r.mark.textContent = ok ? '✓' : '✗';
+ r.why.replaceChildren(ok || single ? '' : rich(r.it.why, 20));
+ if (ok && !r.played) { r.played = true; r.it.fx?.(); }
+ return ok;
+ };
+ return {
+ check() {
+ const right = rows.filter(judge).length;
+ const all = right === rows.length;
+ api.grade(all, single ? rows[0].it.why : all ? [] : [translate('rowsRight', { r: right, n: rows.length })], { right, total: rows.length });
+ },
+ reveal() {
+ for (const r of rows) {
+ r.bs.forEach((b, i) => b.setAttribute('aria-pressed', String(r.it.ans.includes(cols[i][0]))));
+ judge(r);
+ if (!single) r.why.replaceChildren(rich(r.it.why, 20));
+ }
+ return single ? rows[0].it.why : translate('choicesShown');
+ },
+ lock() { locked = true; showCur(); rows.forEach(r => r.bs.forEach(b => { b.disabled = true; })); },
+ hint: [...(single ? [] : [kbd('↑'), kbd('↓'), translate('hintRow')]), ...(/\d/.test(hot[0]) ? [kbd(hot[0]), '–', kbd(hot[hot.length - 1])] : hot.map(kbd)), translate('hintChoose')],
+ key(e) {
+ if (locked) return false;
+ if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && !single) {
+ cur = (cur + (e.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length;
+ showCur();
+ return true;
+ }
+ const j = hot.findIndex(x => isShortcut(e, x));
+ if (j < 0) return false;
+ rows[cur].bs[j].click();
+ if (!multi && cur < rows.length - 1) { cur++; showCur(); }
+ return true;
+ },
+ };
+};
+// Exact value of a typed answer: integer, decimal, fraction a/b or mixed number "w a/b"; returns [num, den] or null.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+function rat(str) {
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
+ if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
+ let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
+ if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
+ m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);
+ if (m && Number(m[4]) > 0) { const d = Number(m[4]), n = (m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
+ return null;
+}
+const gcd = (a, b) => { a = Math.abs(a); b = Math.abs(b); while (b) [a, b] = [b, a % b]; return a; };
+const lowest = ([n, d]) => gcd(n, d) === 1;
+// Fill-in boxes inside math. rows: [{ parts: [math parts and { box: '21' }], why, hint?, fx? }].
+// test(values), when given, judges the whole row from the typed numbers (e.g. a factor pair in either order); the boxes' answers are still what Show answer fills in.
+// Answers are exact numbers: "−5", "-5", "0.5", "3/4" and "2 1/4" all work, and equal values match ("6/8" = "3/4")
+// unless the box has lowest: true. hint is shown after a wrong try, why after a right one.
+const blanks = rowsIn => (body, api) => {
+ const all = [];
+ const rows = rowsIn.map(it => {
+ const line = h('div', 'bline'), mark = h('span', 'mark'), why = h('div', 'why');
+ let run = [];
+ const flush = () => { if (run.length) line.append(mathEl(run, 34)); run = []; };
+ const boxes = [];
+ for (const p of it.parts) {
+ if (p && p.box !== undefined) {
+ flush();
+ const b = h('input', 'box');
+ Object.assign(b, { type: 'text', inputMode: 'decimal', autocomplete: 'off', spellcheck: false });
+ b.setAttribute('aria-label', translate('answerBox'));
+ b.dataset.ans = p.box;
+ if (p.lowest) b.dataset.lowest = '1';
+ b.style.width = `${Math.max(2, String(p.box).length) + 2}ch`;
+ line.append(b);
+ boxes.push(b);
+ all.push(b);
+ } else run.push(p);
+ }
+ flush();
+ line.append(mark);
+ body.append(h('div', 'brow', [line, why]));
+ return { it, boxes, mark, why, played: false };
+ });
+ body.classList.add('blanks');
+ const single = rows.length === 1;
+ const judge = r => {
+ let ok = true;
+ if (r.it.test) { // the row is judged as a whole, e.g. two factors in either order
+ const vals = r.boxes.map(b => rat(b.value));
+ ok = vals.every(Boolean) && !!r.it.test(vals.map(([n, d]) => n / d));
+ r.boxes.forEach(b => { b.classList.toggle('good', ok); b.classList.toggle('bad', !ok); });
+ } else for (const b of r.boxes) {
+ const want = rat(b.dataset.ans), got = rat(b.value);
+ const good = !!got && !!want && BigInt(got[0]) * BigInt(want[1]) === BigInt(want[0]) * BigInt(got[1]) && (!b.dataset.lowest || lowest(got));
+ b.classList.toggle('good', good);
+ b.classList.toggle('bad', !good);
+ ok = ok && good;
+ }
+ r.mark.className = 'mark ' + (ok ? 'good' : 'bad');
+ r.mark.textContent = ok ? '✓' : '✗';
+ r.why.replaceChildren(ok || single ? '' : rich(r.it.hint ?? r.it.why, 20));
+ if (ok && !r.played) { r.played = true; r.it.fx?.(); }
+ return ok;
+ };
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
+ return {
+ check() {
+ const right = rows.filter(judge).length, done = right === rows.length;
+ const msg = single ? (done ? rows[0].it.why : rows[0].it.hint ?? rows[0].it.why)
+ : done ? [] : [translate('rowsRight', { r: right, n: rows.length })];
+ api.grade(done, msg, { right, total: rows.length });
+ },
+ reveal() {
+ for (const r of rows) {
+ r.boxes.forEach(b => { b.value = b.dataset.ans.replace('-', '−'); }); // shown exactly as authored
+ judge(r);
+ if (!single) r.why.replaceChildren(rich(r.it.why, 20));
+ }
+ return single ? rows[0].it.why : translate('numbersShown');
+ },
+ lock() { all.forEach(b => { b.disabled = true; }); },
+ hint: [translate(all.some(b => b.dataset.ans.includes('/')) ? 'hintTypeFraction' : all.some(b => /[.,]/.test(b.dataset.ans)) ? 'hintTypeDecimal' : 'hintTypeNumber'),
+ kbd('Tab'), translate('hintNextBox'), kbd('Enter'), translate('hintCheck'), kbd('Esc'), translate('hintLeaveBox')],
+ };
+};
+
+/* ---------- sound effects and music ----------
+ sfx(beat, at, name, vol, bed): play audio/sfx/<name>.mp3 when the clock of beat `beat` passes `at` in normal playback
+ (a seek past it fires nothing), at half volume (vol 2 is full). A long ambience is listed in SFX_BED with its length
+ (SFX_BED.birds = 10): a seek into it joins it part-way. A beat function runs again at every seek; an effect is listed once.
+ An effect still loading when it is due plays late, joined part-way, for up to a second (or its bed).
+ music(file, beats, gain, fade): a looping track under the listed beats (all of them by default). Its place is the
+ length of its earlier beats plus the clock. It ducks to 30 % under the whole beat, or 70 % in the music-only lead-in
+ (`pre`) of the beats in window.MUSIC_UP_IN_PRE (true: every beat). It crossfades over `fade` s (0: a cut), and
+ window.MUSIC_OFF = { beat: t => true } fades it out for a moment.
+ export.py reads SFX, BGM and these settings, and mixes the film by the same rules.
+ Films only (a chapter without questions): effects and music go through one Web Audio graph, so ducks, fades and the
+ volume slider reach them on phones too (iOS ignores an element's .volume). A pause holds them; a seek stops the effects.
+ When a clip loading or buffering holds the film's clock, the music runs on and then eases back (5 % slower or faster),
+ or jumps back once if it is more than a second out. */
+const SND = { sfx: [], bed: {}, bgm: [], len: [], on: [], wait: [], buf: {}, ctx: null, out: null, last: { i: -1, t: 0 }, duck: .3 };
+const everyBeat = () => { try { return BEATS.map(b => b.id); } catch { return undefined; } }; // undefined until BEATS is defined
+// window properties, not declarations: a book with its own older sfx() or BGM declares them over these
+Object.assign(window, { SFX: SND.sfx, SFX_BED: SND.bed, BGM: SND.bgm,
+ sfx(beat, at, name, vol = 1, bed = SND.bed[name] || 0) {
+ const e = SND.sfx.find(x => x.beat === beat && x.at === at && x.name === name);
+ if (e) Object.assign(e, { vol, bed }); else SND.sfx.push({ beat, at, name, vol, bed });
+ sfxLoad(name);
+ },
+ // without beats, every beat: boot() fills them in when music() comes before BEATS
+ music(file, beats = everyBeat(), gain = 1, fade = .8) {
+ const m = { n: file, beats, gain, fade, v: 0, a: Object.assign(new Audio(file), { preload: 'auto', loop: true, volume: 0 }) };
+ SND.bgm.push(m);
+ if (SND.ctx) bgmWire(m);
+ },
+});
+// An effect is fetched and decoded at once, before the first click builds the sound graph: decoding needs no running
+// context (an AudioBuffer plays in any), so an effect due in the first second after Play, or after an early seek, is
+// ready instead of dropped on a slow line.
+let DECODER = null;
+function sfxLoad(name) {
+ const s = SND.buf[name] ??= { data: fetch(`audio/sfx/${name}.mp3`).then(r => r.ok ? r.arrayBuffer() : null).catch(() => null) };
+ const ctx = SND.ctx || (window.OfflineAudioContext && (DECODER ??= new OfflineAudioContext(2, 1, 44100)));
+ if (ctx && !s.decoded) s.decoded = s.data.then(d => d && ctx.decodeAudioData(d)).then(b => { s.b = b; }, () => {});
+}
+function sfxPlay(e, late) {
+ const ctx = SND.ctx, src = ctx.createBufferSource(), g = ctx.createGain();
+ src.buffer = SND.buf[e.name].b; src._sfx = e.name; g.gain.value = src._vol = .5 * e.vol;
+ src.playbackRate.value = P.rate;
+ src.connect(g).connect(SND.out);
+ src.start(0, late && !e.bed ? 0 : Math.max(0, P.t - e.at)); // a late one-shot starts from its attack
+ SND.on.push(src);
+ src.onended = () => { const k = SND.on.indexOf(src); if (k >= 0) SND.on.splice(k, 1); };
+}
+function bgmWire(m) {
+ m.g = SND.ctx.createGain();
+ SND.ctx.createMediaElementSource(m.a).connect(m.g).connect(SND.out);
+ m.a.volume = 1;
+}
+// A browser starts sound only after a click or a key: the first one builds the graph (films only) and readies the music.
+function soundUnlock() {
+ if (typeof BEATS === 'undefined') return; // the chapter's script has not run yet
+ if (!SND.ctx && window.AudioContext && (!BEATS.some(b => b.ask) || CHAPTER.film)) { // a film with a question (CHAPTER.film) keeps its sound
+ if (navigator.audioSession) navigator.audioSession.type = 'playback'; // iOS: the silent switch must not mute the film
+ SND.ctx = new AudioContext();
+ SND.out = SND.ctx.createGain();
+ SND.out.connect(SND.ctx.destination);
+ for (const n in SND.buf) sfxLoad(n);
+ for (const m of SND.bgm) bgmWire(m);
+ }
+ if (SND.ctx && SND.ctx.state !== 'running' && SND.ctx.state !== 'closed') SND.ctx.resume().catch(() => {}); // also iOS 'interrupted'
+ for (const m of SND.bgm) if (!m.blessed) { // iOS lets an element play later only if it once played inside a click
+ m.blessed = true; m.a.muted = true;
+ m.a.play().then(() => { if (!m.cur) m.a.pause(); m.a.muted = false; }, () => { m.a.muted = false; m.blessed = false; });
+ }
+}
+// a touch activates the page on touchend or click, not on pointerdown
+for (const type of ['pointerdown', 'touchend', 'click', 'keydown']) addEventListener(type, soundUnlock, true);
+// Safari (and every iOS browser) stops a media element for .3-.6 s at each playbackRate change, so easing the music
+// back would only push it further out: there it keeps the film's rate and seeks instead.
+const RATE_STALLS = /AppleWebKit/.test(navigator.userAgent) && !/Chrome\/|Android/.test(navigator.userAgent);
+function soundTick(dt) {
+ const id = BEATS[P.i]?.id, pre = BEATS[P.i]?.pre || 0, on = P.started && P.playing && !P.waiting && !P.done, L = SND.last;
+ // a film waiting for the reader (CHAPTER.film, a question beat after its narration): the music plays on, louder
+ const wait = P.started && P.playing && P.waiting && !P.done && !!CHAPTER.film;
+ const held = P.started && !P.playing && !P.done, ctx = SND.ctx;
+ if (ctx?.state === 'running' && held) ctx.suspend();
+ else if (ctx && ctx.state !== 'running' && ctx.state !== 'closed' && !held) ctx.resume().catch(() => {});
+ // the clock ran on (or stood still, paused) in the same beat; anything else is a seek, a replay or the next beat
+ const same = L.i === P.i && P.t >= L.t && P.t - Math.max(0, L.t) < Math.max(.5, dt * P.rate + .25);
+ if (!same) { while (SND.on.length) SND.on.pop().stop(); SND.wait = []; }
+ // a beat that has just begun fires its effects from 0 on; a seek fires nothing it skipped, but joins a bed
+ const from = same ? L.t : P.t < .25 ? -1 : P.t, seeked = !same || L.pend;
+ if (on && ctx) {
+ for (const e of SND.sfx) {
+ if (e.beat !== id || !(e.at > from && e.at <= P.t || seeked && e.bed && e.at < P.t && P.t < e.at + e.bed)) continue;
+ if (SND.buf[e.name]?.b) sfxPlay(e); else SND.wait.push(e);
+ }
+ SND.wait = SND.wait.filter(e => P.t - e.at < (e.bed || 1) && !(SND.buf[e.name]?.b && (sfxPlay(e, true), true)));
+ for (const s of SND.on) if (s.playbackRate.value !== P.rate) s.playbackRate.value = P.rate;
+ }
+ SND.last = { i: P.i, t: on ? P.t : from, pend: !on && (!same || !!L.pend) };
+ const vol = +($('volume')?.value ?? 1), up = window.MUSIC_UP_IN_PRE;
+ if (SND.out) SND.out.gain.value = vol;
+ if (!SND.bgm.length || BEATS.some(b => b.ask) && !CHAPTER.film) return; // a lesson with questions plays no music
+ // the film's clock moved this frame (a clip loading or buffering holds it), or jumped (a seek, a replay)
+ const runs = on && same && P.t > L.t, jump = !same && !(L.i === P.i - 1 && P.t < .5);
+ // a word the reader tapped (tapWords) ducks the music at once, as the narration does
+ const saying = !!SND.word && !SND.word.paused && !SND.word.ended;
+ if (!held) SND.duck += Math.max(-dt * (saying ? 4 : 1), Math.min(dt, (wait && !saying || P.t < pre && (up === true || up?.includes?.(id)) ? .7 : .3) - SND.duck));
+ for (const m of SND.bgm) {
+ const k = m.beats.indexOf(id), current = (on || wait) && k >= 0 && !window.MUSIC_OFF?.[id]?.(P.t);
+ if (jump) m.off = 0; // a seek or a replay puts every track back where the film's own timing says
+ if (wait && current) m.off = (m.off || 0) + dt * P.rate; // the time it ran on while the reader decided
+ m.cur = current;
+ if (!held) m.v = m.fade > 0 ? Math.max(0, Math.min(1, m.v + (current ? 1 : -1) * dt / m.fade)) : +current;
+ const g = m.v * m.gain * SND.duck;
+ if (m.g) m.g.gain.value = g; else m.a.volume = Math.min(1, g * vol);
+ if (current) {
+ // where the film is: the beats before this one in the track as they really ran (P.end), plus now
+ const dur = m.a.duration || Infinity;
+ const want = (m.beats.slice(0, k).reduce((s, b) => s + (SND.len[BEATS.findIndex(x => x.id === b)] || 0), 0) + P.t + (m.off || 0)) % dur;
+ let d = m.a.currentTime - want;
+ if (d > dur / 2) d -= dur; else if (d < -dur / 2) d += dur;
+ // a start, a jump, or more than a second out once the clock runs again: seek. Less: ease back while the clock runs,
+ // from .25 s out until .05 s
+ const ok = runs && !m.a.seeking;
+ // (once more after a jump: the element plays on while it seeks)
+ // Where a rate change stalls, starting and seeking stall too: once a second the music's lag is learnt (m.lead),
+ // seeks aim that far ahead, and a quarter second out is then worth a seek.
+ let far = m.settle ? .25 : 1;
+ m.sought ??= clock;
+ if (RATE_STALLS && ok && clock - m.sought > 1) {
+ m.sought = clock; m.lead = Math.max(0, Math.min(.6, (m.lead || 0) - d)); far = .25;
+ }
+ if (m.a.paused || jump && Math.abs(d) > .05 || ok && Math.abs(d) > far) {
+ m.a.currentTime = (want + (RATE_STALLS && m.lead || 0)) % dur; d = 0; m.settle = !ok; m.sought = clock;
+ } else if (ok) m.settle = false;
+ if (Math.abs(d) > .25) m.fix = true; else if (Math.abs(d) < .05) m.fix = false;
+ // a frame where the clock stood still keeps the rate it had
+ const rate = !m.fix || RATE_STALLS ? P.rate : ok ? P.rate * (1 - Math.sign(d) * .05) : m.a.playbackRate;
+ if (Math.abs(m.a.playbackRate - rate) > .001) m.a.playbackRate = rate;
+ if (m.a.paused) m.a.play().catch(() => {});
+ } else {
+ if (m.a.playbackRate !== P.rate) m.a.playbackRate = P.rate;
+ if (m.v === 0 && !m.a.paused) m.a.pause();
+ }
+ }
+ if (!on && !wait && !P.done) for (const m of SND.bgm) m.a.pause();
+}
+
+/* ---------- player ---------- */
+const P = { i: 0, t: 0, end: 1, back: 0, playing: false, waiting: false, done: false, started: false, audio: null, afail: false, stall: 0, cleanup: [], rate: 1, nextClip: null };
+function runBeat(i) {
+ TW = [];
+ const b = BEATS[i], tm = TIMINGS[b.id], pre = b.pre || 0; // pre: seconds of picture before the narration starts
+ const m = (k, off = 0) => {
+ if (!(k in tm.marks)) throw new Error(`${b.id}: missing mark ${k}`);
+ return pre + tm.marks[k] + off;
+ };
+ S.cleared = false;
+ b.run(m, pre + tm.dur);
+ if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)
+ TW.sort((a, c) => a.t0 - c.t0);
+ // runs that last to the end anyway (tails, follow cameras) do not set it: only the narration and the other tweens do,
+ // and minDur, the least the whole beat lasts (two mirrored beats run the same seconds)
+ const end = Math.max(Math.max(pre + tm.dur, ...TW.filter(w => !w.tail).map(w => w.t0 + w.dur)) + HOLD, b.minDur || 0);
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return SND.len[i] = end; // the music places itself by how long each beat really runs
+}
+const HOLD = .6;
+// A beat that clears the picture must not leave it empty while the narration has started.
+// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
+// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
+const LEAD_AT = .4, LEAD_MAX = .8, LEAD_GROUP = 1.2;
+function leadIn() {
+ const reveals = TW.filter(w => {
+ if (!w.e) return false;
+ const s = st(w.e), to = w.to;
+ return (to.o > 0 && s.o === 0) || (to.s > 0 && s.s === 0) || (to.d > 0 && (s.d ?? 1) === 0);
+ });
+ if (!reveals.length) return;
+ const first = Math.min(...reveals.map(w => w.t0));
+ if (first <= LEAD_MAX) return;
+ for (const w of TW) if (w.t0 >= first && w.t0 < first + LEAD_GROUP) w.t0 -= first - LEAD_AT;
+}
+function stopAudio() {
+ const a = P.audio;
+ if (!a) return;
+ a.onerror = null; a.pause(); a.removeAttribute('src'); a.load();
+ P.audio = null;
+}
+function clearCards() {
+ $('ui').replaceChildren();
+ P.cleanup.forEach(f => f());
+ P.cleanup = [];
+ finishFx();
+ P.keys = null;
+ S.q?.remove();
+ delete S.q;
+}
+// Rebuild the scene from scratch and fast-forward every earlier beat, so any step starts from its exact picture.
+function seek(i, play = P.playing) {
+ stopAudio(); clearCards(); reset();
+ seeking = true;
+ try {
+ for (let k = 0; k < i; k++) { runBeat(k); evalTo(Infinity); }
+ start(i, play);
+ } finally { seeking = false; }
+}
+// Jump to a point inside beat i (frac of its narration); question beats always start at their beginning.
+function seekInto(i, frac) {
+ seek(i, true);
+ const pre = BEATS[i].pre || 0, t = BEATS[i].ask && !CHAPTER.film ? 0 : frac * (pre + TIMINGS[BEATS[i].id].dur); // a film's question beats seek like any other
+ if (t < .3) return;
+ P.t = t;
+ evalTo(t);
+ if (P.audio) P.audio.currentTime = Math.max(0, t - pre);
+}
+function start(i, play) {
+ stopAudio(); clearCards();
+ // P.gen counts starts: a done() kept from an earlier start of this same beat (a step replayed) no longer counts
+ const gen = P.gen = (P.gen || 0) + 1;
+ Object.assign(P, { i, t: 0, waiting: false, done: false, afail: false, stall: 0, lost: 0, back: 0 });
+ P.end = runBeat(i);
+ evalTo(0);
+ const a = P.audio = beatClip(i, true);
+ if (a) { // a beat with no narration ({ dur }) has no clip: wall time drives its clock
+ a.volume = +($('volume')?.value ?? 1);
+ a.playbackRate = P.rate;
+ // An aborted or superseded load (fast stepping, a reload) is not a failure: only a real error for the current clip
+ // shows the note, and the note goes away as soon as a clip plays.
+ a.onerror = () => { if (P.audio === a && a.error && a.error.code !== MediaError.MEDIA_ERR_ABORTED) soundFailed(); };
+ a.onplaying = () => {
+ if (P.audio !== a) return;
+ $('soundNote').hidden = true;
+ if (P.afail) { P.afail = false; a.currentTime = Math.max(0, P.t - (BEATS[P.i].pre || 0)); } // sound came back late: rejoin the picture where it is
+ };
+ }
+ const b = BEATS[i];
+ if (b.ask) b.ask(() => {
+ if (P.gen !== gen || P.done) return;
+ evalTo(Infinity);
+ if (i + 1 < BEATS.length) start(i + 1, true);
+ else { P.done = true; setPlaying(false); filmDone(); }
+ });
+ setPlaying(play);
+ if (i + 1 < BEATS.length) beatClip(i + 1);
+}
+// The next beat's clip starts loading while this one plays, so a slow connection does not stall between beats.
+function beatClip(i, take) {
+ if (TIMINGS[BEATS[i].id]?.silent) return null;
+ // the clip's length rides on the URL: regenerated narration gets a new address, so a browser cache cannot pair new
+ // timings with an old clip
+ const src = `audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3?v=${TIMINGS[BEATS[i].id]?.dur ?? ''}`;
+ let a = P.nextClip?._src === src ? P.nextClip : null;
+ if (!a) {
+ if (P.nextClip && P.nextClip !== P.audio) { P.nextClip.removeAttribute('src'); P.nextClip.load(); } // abandon a stale preload
+ a = Object.assign(new Audio(src), { preload: 'auto', _src: src });
+ }
+ P.nextClip = take ? null : a;
+ return a;
+}
+// Playback speed: the audio clock drives the picture, so changing the clip's rate keeps them together.
+const SPEEDS = [.75, 1, 1.25, 1.5];
+function setSpeed(r) {
+ P.rate = r;
+ $('bSpeed').textContent = r + '×';
+ if (P.audio) P.audio.playbackRate = r;
+ try { localStorage.setItem('speed', String(r)); } catch {}
+}
+const stepSpeed = d => setSpeed(SPEEDS[Math.max(0, Math.min(SPEEDS.length - 1, SPEEDS.indexOf(P.rate) + d))]);
+function soundFailed() { P.afail = true; $('soundNote').hidden = false; }
+function setPlaying(v) {
+ P.playing = v;
+ const a = P.audio;
+ if (!a) return;
+ const lead = v && P.t < (BEATS[P.i]?.pre || 0);
+ if (v && !P.waiting && !a.ended && !P.afail && !lead) a.play().catch(e => { if (P.audio === a && e.name === 'NotAllowedError') soundFailed(); });
+ else if (lead && !a._unlocked) { // the clip starts later, outside this click: play it silently now so the browser allows that
+ a._unlocked = true; a.muted = true;
+ a.play().then(() => { if (P.t < (BEATS[P.i].pre || 0)) { a.pause(); a.currentTime = 0; } a.muted = false; }, () => { a.muted = false; });
+ } else a.pause();
+}
+function beatDone() {
+ // Steps finish; continuous motion (tails) stays where the clock is: a beat under music ends up to HOLD early, and
+ // jumping its tails to their end would move them a few px on the last frame
+ evalTo(Infinity, TW.filter(w => !w.tail));
+ const b = BEATS[P.i];
+ if (b.ask) P.waiting = true;
+ else if (P.i < BEATS.length - 1) start(P.i + 1, true);
+ else { P.done = true; setPlaying(false); filmDone(); }
+}
+// A chapter that ends on its last frame, with no closing card of questions (a picture book), is finished there: it
+// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
+function filmDone() {
+ progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
+ if (!CHAPTER.next) return;
+ const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
+ next.onclick = go;
+ const c = card({ x: 0, y: SH - 130, w: 0, cls: 'side' }, 'next');
+ Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
+ c.append(h('div', 'acts', [next]));
+}
+let last = performance.now();
+function frame(now) {
+ frameStep(now, .1);
+ requestAnimationFrame(frame);
+}
+function frameStep(now, most) {
+ const raw = Math.max(0, now - last) / 1000, dt = Math.min(most, raw);
+ last = now;
+ clock += dt;
+ if (FX.length) { evalTo(clock, FX); FX = FX.filter(w => !w.done); }
+ if (P.playing && !P.waiting && !P.done) {
+ const a = P.audio, t0 = P.t;
+ // While the clip plays, its clock drives the picture; before it starts or after it ends, wall time does.
+ const pre = BEATS[P.i].pre || 0;
+ if (a && P.t < pre) { // the picture's lead before the narration, on wall time; then the clip starts
+ P.t += dt * P.rate;
+ if (P.t >= pre && !P.afail) { a.muted = false; a.currentTime = P.t - pre; a.play().catch(e => { if (P.audio === a && e.name === 'NotAllowedError') soundFailed(); }); }
+ } else if (a && !P.afail && !a.ended) {
+ if (a.currentTime > 0) { P.t = Math.max(P.t, pre + a.currentTime); P.stall = 0; }
+ else if ((P.stall += dt) > (a.readyState < 2 ? 8 : 15)) soundFailed(); // nothing to play after 8 s, or stuck for 15
+ } else P.t += dt * P.rate;
+ // P.lost: how long the clock stood still while the film played (a clip getting going, buffering). Music runs on
+ // through it, so a beat under music gives that time back from its closing hold: each beat then lasts as long in
+ // real time as on the music's timeline, and the music stays with the picture instead of drifting ahead beat by beat.
+ P.lost += raw * P.rate - (P.t - t0); // real time: a long frame moves the music by all of it
+ const back = P.back = SND.bgm.some(m => m.beats.includes(BEATS[P.i].id)) ? Math.max(0, Math.min(HOLD, P.lost)) : 0;
+ evalTo(P.t);
+ if (P.t >= P.end - back) beatDone();
+ }
+ soundTick(dt);
+ syncLinks();
+ ui();
+}
+let segs = [];
+function buildSegs() {
+ segs = BEATS.map((b, i) => {
+ const s = h('button', 'seg' + (b.ask ? ' ask' : ''), [h('i')]);
+ s.style.flex = TIMINGS[b.id].dur + (b.ask ? 12 : 0);
+ s.title = b.title;
+ s.setAttribute('aria-label', translate('goToStep', { n: i + 1, title: b.title }));
+ // A click lands at that point of the step; keyboard activation (no pointer position) starts the step.
+ s.onclick = e => {
+ const r = s.getBoundingClientRect();
+ hideCover(); seekInto(i, e.detail ? (e.clientX - r.left) / r.width : 0);
+ };
+ $('segs').append(s);
+ return s.firstChild;
+ });
+}
+// ui() runs on every frame, paused or not: it writes only what changed, so an idle lesson does no layout work.
+let stepText = '';
+const setWidth = (f, w) => { if (f._w !== w) { f._w = w; f.style.width = w + '%'; } };
+function ui() {
+ segs.forEach((f, k) => setWidth(f, k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)));
+ const fr = $('frame');
+ fr.classList.toggle('is-playing', P.playing && !P.done && !P.waiting);
+ fr.classList.toggle('held', P.started && (!P.playing || P.done)); // paused or ended: full screen keeps the controls
+ fr.classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);
+ const step = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;
+ if (step !== stepText) { stepText = step; $('stepName').textContent = step; }
+ const b = BEATS[P.i];
+ let text = '';
+ // a question's caption shows while its narration plays, clear of the cards; a full-screen card already shows the
+ // question, so it has none
+ const asking = !!b.ask;
+ if (P.started && !P.done && !(asking && (P.waiting || $('ui').querySelector('.card.screen')))) {
+ // a cue is [start, line], [start, line, end] or [start, line, end, 1]: with an end, the caption clears once its
+ // words are over; a 1 marks a line in another language, whose subtitle shows even with captions off (as does every
+ // cue of a beat whose timings say forced: true, from tts.py or eleven.py)
+ // the last line without an end clears a second after the narration, so it does not sit on a closing title
+ const cues = TIMINGS[b.id].cues;
+ for (const [k, [t, line, end = k === cues.length - 1 ? TIMINGS[b.id].dur + 1 : null, forced]] of cues.entries()) {
+ if (t + (b.pre || 0) > P.t + .05) break;
+ text = (captions || forced || TIMINGS[b.id].forced) && !(end != null && P.t > end + (b.pre || 0)) ? line : '';
+ }
+ }
+ if (text !== capText) { capText = text; $('caption').textContent = text; $('caption').hidden = !text; }
+ if (text) placeCaption(asking);
+}
+// Above a bottom band, or centred left of a card in the bottom right; elsewhere the caption keeps its place.
+let capAt = '';
+function placeCaption(asking) {
+ const c = asking ? $('ui').querySelector('.card.band, .card.side') : null;
+ let at = '';
+ if (c?.classList.contains('band')) at = `${SH + 60 - c.offsetTop + 12}||`;
+ else if (c && c.offsetLeft > 800 && c.offsetTop + c.offsetHeight > 700) at = `|${c.offsetLeft / 2}|${c.offsetLeft - 60}`;
+ if (at === capAt) return;
+ capAt = at;
+ const [bottom, left, width] = at.split('|'), s = $('caption').style;
+ Object.assign(s, { bottom: bottom && bottom + 'px', left: left && left + 'px', maxWidth: width && width + 'px' });
+}
+let capText = '';
+try { captions = localStorage.getItem('captions') === '1'; } catch {}
+function setCaptions(on, save = true) {
+ captions = on;
+ $('bCC').setAttribute('aria-pressed', String(on));
+ if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
+}
+setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
+function togglePlay() {
+ if (!P.started) { turnPhone(); hideCover(); return setPlaying(true); }
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
+ setPlaying(!P.playing);
+}
+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 && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
+});
+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;
+$('bCC').onclick = () => setCaptions(!captions);
+$('bSpeed').onclick = () => setSpeed(SPEEDS[(SPEEDS.indexOf(P.rate) + 1) % SPEEDS.length]);
+try { const r = +localStorage.getItem('speed'); if (SPEEDS.includes(r)) setSpeed(r); } catch {}
+$('bFull').onclick = () => toggleFull();
+// Full screen also turns the screen to the stage's orientation where the browser allows it (Android browsers lock
+// orientation only in full screen; iOS has no lock, so there the reader turns the phone). On a phone held across the
+// stage's orientation, starting the lesson goes full screen the same way, since the stage would otherwise be a strip.
+function goFull() {
+ return document.documentElement.requestFullscreen?.({ navigationUI: 'hide' })
+ .then(() => screen.orientation?.lock?.(PORTRAIT ? 'portrait' : 'landscape')).catch(() => {});
+}
+function turnPhone() {
+ const phone = matchMedia('(pointer: coarse)').matches && Math.min(screen.width, screen.height) <= 600;
+ if (phone && !document.fullscreenElement && (innerHeight > innerWidth) !== PORTRAIT) goFull();
+}
+const toggleFull = () => document.fullscreenElement ? document.exitFullscreen() : goFull();
+// In full screen the stage fills the screen and the controls lie over its foot: they show while the pointer moves (a
+// tap on a phone) or a key is pressed, for 2.5 s after, while paused and while the pointer is on them.
+document.addEventListener('fullscreenchange', () => {
+ document.documentElement.classList.toggle('full', !!document.fullscreenElement);
+ fit(); wake();
+ if (!document.fullscreenElement) try { screen.orientation?.unlock?.(); } catch {}
+});
+let wakeT = 0;
+function wake() { $('frame').classList.add('awake'); clearTimeout(wakeT); wakeT = setTimeout(() => $('frame').classList.remove('awake'), 2500); }
+for (const type of ['pointermove', 'pointerdown', 'keydown']) addEventListener(type, wake, true);
+let helpResume = false;
+function toggleHelp() {
+ const open = $('help').hidden;
+ $('help').hidden = !open;
+ if (open) { helpResume = P.playing; if (P.playing) setPlaying(false); }
+ else if (helpResume) setPlaying(true);
+}
+// Review notes, only with ?review in the URL: N pauses and asks for a note on this moment, Shift+N copies every
+// note of the chapter (one line each, with the ?beat=N&t=S that reopens it) and offers to clear them.
+const REVIEW = new URLSearchParams(location.search).has('review');
+const REVIEW_KEY = 'papermorph:review:' + location.pathname;
+const reviewNotes = () => { try { return JSON.parse(localStorage.getItem(REVIEW_KEY) || '[]'); } catch { return []; } };
+function reviewNote() {
+ if (P.playing) setPlaying(false);
+ const at = `?beat=${P.i}&t=${P.t.toFixed(1)}`, note = prompt(`Note at ${BEATS[P.i].id} ${at}`);
+ if (!note) return;
+ try { localStorage.setItem(REVIEW_KEY, JSON.stringify([...reviewNotes(), `ch${String(CHAPTER.number).padStart(2, '0')} ${at} (${BEATS[P.i].id}): ${note}`])); } catch {}
+}
+function reviewCopy() {
+ const notes = reviewNotes(), text = notes.join('\n');
+ console.log(text);
+ navigator.clipboard?.writeText(text).catch(() => {});
+ if (confirm(`${notes.length} notes copied (also in the console). Clear them?`)) try { localStorage.removeItem(REVIEW_KEY); } catch {}
+}
+// Every action has a key. A question's own keys (P.keys) come first; Shift reaches the player during a question.
+document.addEventListener('keydown', e => {
+ if (e.altKey || e.metaKey || e.ctrlKey) return;
+ const k = e.key;
+ if (!$('help').hidden) { if (k === 'Escape' || k === '?') { e.preventDefault(); toggleHelp(); } return; }
+ if (e.target.matches?.('input')) { // Keep native input keys; only answer boxes use Enter to check.
+ if (k === 'Enter' && e.target.type !== 'range' && P.keys) { e.preventDefault(); P.keys(e); }
+ else if (k === 'Escape') e.target.blur();
+ return;
+ }
+ if (k === '?') { e.preventDefault(); toggleHelp(); return; }
+ if (REVIEW && isShortcut(e, 'n')) { e.preventDefault(); e.shiftKey ? reviewCopy() : reviewNote(); return; }
+ if ((k === 'Enter' || k === ' ') && e.target.closest?.('button, [tabindex], a')) return; // a Tab-focused control acts itself
+ if (!P.started) { if (k === ' ' || k === 'Enter') { e.preventDefault(); togglePlay(); } return; }
+ if (P.keys && !e.shiftKey && P.keys(e)) { e.preventDefault(); return; }
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
+ let used = true;
+ if (k === ' ') togglePlay();
+ else if (k === 'ArrowLeft' && free) back1();
+ else if (k === 'ArrowRight' && free) { if (P.i < BEATS.length - 1) seek(P.i + 1); }
+ else if (k === 'Home') restart();
+ else if (isShortcut(e, 'c')) setCaptions(!captions);
+ else if (k === '<' || k === ',' || isShortcutCode(e, 'Comma')) stepSpeed(-1);
+ else if (k === '>' || k === '.' || isShortcutCode(e, 'Period')) stepSpeed(1);
+ else if (isShortcut(e, 'f')) toggleFull();
+ else used = false;
+ if (used) e.preventDefault();
+});
+// Mouse clicks should not leave focus on a control, so Enter and Space keep meaning "check" and "play".
+$('frame').addEventListener('mousedown', e => { if (e.target.closest('button, [tabindex]')) e.preventDefault(); });
+$('bHelp').onclick = toggleHelp;
+// full screen: the stage alone, except that a touch screen keeps the controls under it (engine.css)
+const fit = () => document.documentElement.style.setProperty('--k', document.fullscreenElement
+ ? Math.min(innerWidth / SW, (innerHeight - (matchMedia('(pointer: coarse)').matches ? innerWidth <= 700 ? 110 : 60 : 0)) / SH)
+ : Math.min(innerWidth / (SW + 40), (innerHeight - (innerWidth <= 700 ? 120 : 0)) / (SH + 100)));
+addEventListener('resize', fit);
+fit();
+
+// Start the lesson once the chapter page has defined CHAPTER and BEATS.
+// ?beat=N&t=S opens a paused frame, for reviewing a single moment.
+function boot() {
+ // a beat with no narration: { dur } in its fourth slot stands in for its clip and its TIMINGS entry
+ window.TIMINGS ??= {};
+ for (const b of BEATS) if (!TIMINGS[b.id] && b.dur != null) TIMINGS[b.id] = { dur: b.dur, marks: {}, cues: [], silent: true };
+ for (const m of SND.bgm) { // music() above BEATS plays under every beat
+ m.beats ??= BEATS.map(b => b.id);
+ const lost = m.beats.filter(id => !BEATS.some(b => b.id === id));
+ if (lost.length) console.warn(`music('${m.n}'): no beat ${lost.join(', ')} in BEATS`);
+ }
+ $('coverK').textContent = translate('chapterNumber', { n: CHAPTER.label ?? CHAPTER.number });
+ $('coverT').textContent = CHAPTER.title;
+ $('bHome').href = `../#ch${String(CHAPTER.number).padStart(2, '0')}`;
+ progress(p => { p.last = CHAPTER.number; });
+ document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
+ const film = !!CHAPTER.film || !BEATS.some(b => b.ask); // a picture book or a film: no "lesson" or "quick checks" on its cover
+ if (film) $('coverGo').textContent = translate('startFilm');
+ if (film && (!BEATS.some(b => b.ask) || CHAPTER.questionKeys === false)) { // nothing to answer with keys (or its own controls): the help lists no question keys and needs no column titles
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
+ $('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
+ buildSegs();
+ const qs = new URLSearchParams(location.search);
+ if (qs.has('lengths')) { // each beat's voice against its length on screen: a tween or a run past the voice lengthens it
+ reset(); seeking = true;
+ try { for (let k = 0; k < BEATS.length; k++) { runBeat(k); evalTo(Infinity); } } finally { seeking = false; }
+ console.log(`?lengths: beat, voice (pre + clip), on screen (hold included), and the time past voice + ${HOLD} s hold\n` + BEATS.map((b, i) => {
+ const v = (b.pre || 0) + TIMINGS[b.id].dur, over = SND.len[i] - HOLD - v;
+ return `${b.id.padEnd(16)} ${v.toFixed(2).padStart(6)} ${SND.len[i].toFixed(2).padStart(6)}${over > .005 ? ` +${over.toFixed(2)}` : ''}`;
+ }).join('\n'));
+ }
+ if (qs.has('beat')) {
+ $('cover').hidden = true;
+ seek(Math.max(0, Math.min(BEATS.length - 1, qs.get('beat') | 0)), false);
+ P.t = +(qs.get('t') || 0);
+ evalTo(P.t);
+ if (P.audio) P.audio.currentTime = Math.max(0, P.t - (BEATS[P.i].pre || 0));
+ } else seek(0, false);
+ requestAnimationFrame(frame);
+ // A hidden tab gets no animation frames: a timer keeps the film going, so a beat that ends there still starts the next
+ // one (a tab playing sound keeps its timers). Its ticks come late, so they may move the clock further at once.
+ setInterval(() => { if (document.hidden) frameStep(performance.now(), 1.5); }, 250);
+}
+return { TRANSLATIONS, PORTRAIT, SW, SH, LANGUAGE, translate, DECIMAL_SIGN, isShortcut, NS, UI, BOOK, bookSetting,
+ COL, MATH, NAME, BAND, RIGHT, TOPR, SCREEN, SORT_SCREEN, $m, mk, st, put, render, G, path, T, cite, ctx2d, textW, F,
+ R, E, TX, $tex, texGraphic, texPart, OV, M, chip, tokens, layRow, collapse, mathEl, io, out, back, lin, tw, prog,
+ show, hide, draw, pop, pulse, stream, mix, evalTo, soft, clockRun, camera, scene, S, AXIS, X, Y0, num, reset, tick,
+ dot, arrow, panel, retire, header, fx, fxp, finishFx, pulseFx, shakeFx, floatText, TF, $, kbd, sources, uiW, SCORE,
+ h, rich, card, mascotEl, quiz, qlayer, keyAct, choice, mcq, tap, tapEls, pickEls, tapWords, grid, rat, gcd, lowest, blanks,
+ SND, P, HOLD, clearCards, seek, seekInto, start, setSpeed, setPlaying, setCaptions, hideCover, restart, boot,
+ finishCard };
+})();
+
+// The API, one global each: lint.py reads these declarations, and a chapter that declares one of them again stops
+// with an error, as before.
+const TRANSLATIONS = ENGINE.TRANSLATIONS, PORTRAIT = ENGINE.PORTRAIT, SW = ENGINE.SW, SH = ENGINE.SH,
+ LANGUAGE = ENGINE.LANGUAGE, translate = ENGINE.translate, DECIMAL_SIGN = ENGINE.DECIMAL_SIGN,
+ isShortcut = ENGINE.isShortcut, NS = ENGINE.NS, UI = ENGINE.UI, BOOK = ENGINE.BOOK,
+ bookSetting = ENGINE.bookSetting, COL = ENGINE.COL, MATH = ENGINE.MATH, NAME = ENGINE.NAME, BAND = ENGINE.BAND,
+ RIGHT = ENGINE.RIGHT, TOPR = ENGINE.TOPR, SCREEN = ENGINE.SCREEN, SORT_SCREEN = ENGINE.SORT_SCREEN, $m = ENGINE.$m,
+ mk = ENGINE.mk, st = ENGINE.st, put = ENGINE.put, render = ENGINE.render, G = ENGINE.G, path = ENGINE.path,
+ T = ENGINE.T, cite = ENGINE.cite, ctx2d = ENGINE.ctx2d, textW = ENGINE.textW, F = ENGINE.F, R = ENGINE.R,
+ E = ENGINE.E, TX = ENGINE.TX, $tex = ENGINE.$tex, texGraphic = ENGINE.texGraphic, texPart = ENGINE.texPart,
+ OV = ENGINE.OV, M = ENGINE.M, chip = ENGINE.chip, tokens = ENGINE.tokens, layRow = ENGINE.layRow,
+ collapse = ENGINE.collapse, mathEl = ENGINE.mathEl, io = ENGINE.io, out = ENGINE.out, back = ENGINE.back,
+ lin = ENGINE.lin, tw = ENGINE.tw, prog = ENGINE.prog, show = ENGINE.show, hide = ENGINE.hide, draw = ENGINE.draw,
+ pop = ENGINE.pop, pulse = ENGINE.pulse, stream = ENGINE.stream, mix = ENGINE.mix, evalTo = ENGINE.evalTo,
+ soft = ENGINE.soft, clockRun = ENGINE.clockRun, camera = ENGINE.camera, scene = ENGINE.scene, S = ENGINE.S,
+ AXIS = ENGINE.AXIS, X = ENGINE.X, Y0 = ENGINE.Y0, num = ENGINE.num, reset = ENGINE.reset, tick = ENGINE.tick,
+ dot = ENGINE.dot, arrow = ENGINE.arrow, panel = ENGINE.panel, retire = ENGINE.retire, header = ENGINE.header,
+ fx = ENGINE.fx, fxp = ENGINE.fxp, finishFx = ENGINE.finishFx, pulseFx = ENGINE.pulseFx, shakeFx = ENGINE.shakeFx,
+ floatText = ENGINE.floatText, TF = ENGINE.TF, $ = ENGINE.$, kbd = ENGINE.kbd, sources = ENGINE.sources,
+ uiW = ENGINE.uiW, SCORE = ENGINE.SCORE, h = ENGINE.h, rich = ENGINE.rich, card = ENGINE.card,
+ mascotEl = ENGINE.mascotEl, quiz = ENGINE.quiz, qlayer = ENGINE.qlayer, keyAct = ENGINE.keyAct,
+ choice = ENGINE.choice, mcq = ENGINE.mcq, tap = ENGINE.tap, tapEls = ENGINE.tapEls, pickEls = ENGINE.pickEls,
+ tapWords = ENGINE.tapWords, grid = ENGINE.grid, rat = ENGINE.rat, gcd = ENGINE.gcd, lowest = ENGINE.lowest, blanks = ENGINE.blanks,
+ SND = ENGINE.SND, P = ENGINE.P, HOLD = ENGINE.HOLD, clearCards = ENGINE.clearCards, seek = ENGINE.seek,
+ seekInto = ENGINE.seekInto, start = ENGINE.start, setSpeed = ENGINE.setSpeed, setPlaying = ENGINE.setPlaying,
+ setCaptions = ENGINE.setCaptions, hideCover = ENGINE.hideCover, restart = ENGINE.restart, boot = ENGINE.boot;
+// Hooks: scorm-bridge.js wraps these two, and the engine calls progress() through this global.
+let finishCard = ENGINE.finishCard;
+// Per-book progress shared with the cover/contents at the parent URL folder.
+const BOOK_PROGRESS_KEY = bookSetting('--progress-key') || 'animebook:progress:' + new URL('../', location.href).pathname;
+function progress(f) {
+ try {
+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');
+ const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
+ p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];
+ f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));
+ } catch {}
+}
diff --git a/site/proteus/lib/film.js b/site/proteus/lib/film.js
new file mode 100644
index 0000000..f791ac9
--- /dev/null
+++ b/site/proteus/lib/film.js
@@ -0,0 +1,494 @@
+/* film.js — the documentary kit: found pictures, line drawings, words and maps on the engine's beat clock.
+ This is the book's own copy: its look is set in lib/book.css (colours) and lib/fonts.css; add the film's recurring
+ pieces at the end. Every helper is a pure function of the beat clock, so pause, seek, ?beat=N&t=S and export.py agree.
+ Pictures are img/<name>.webp with their sizes in ART (img/art.js, from prep.py); traced drawings are LINES (lib/lines.js,
+ from trace.py); clips are FRAMES (img/frames.js, from frames.py). The fonts must be loaded before boot(): words are
+ measured on a canvas (chapter.html does this). */
+'use strict';
+/* ---------- the look ---------- */
+const KEY = '"Oswald", "Arial Narrow", sans-serif', SER = '"EB Garamond", Georgia, serif'; // titles and key words; quotes and captions
+// colours from lib/book.css (read by the engine into COL, or with bookSetting): ink on the ground, the accent, captions,
+// a document's paper, ink on paper, a document's heading
+const CREAM = COL.chalk, SOFT = COL.dim, HOT = bookSetting('--accent') || '#f08a4b', PAPER = bookSetting('--paper') || CREAM,
+ INK = bookSetting('--paper-ink') || '#3a2a24', STAMP = bookSetting('--stamp') || '#7a1a20';
+
+// a picture from img/: centred on (x, y), h or w in stage px; `at` makes it enter (from offset dx, dy) at that time
+function pic(p, name, { x = 800, y = 450, h = 600, w, r = 0, s = 1, at, from = [0, 40], dur = .9, o = 1, back = false } = {}) {
+ const sz = ART[name];
+ const g = G(p, at === undefined ? { x, y, r, s, o } : { x: x + from[0], y: y + from[1], r, s, o: 0 });
+ const k = w ? w / sz[0] : h / sz[1], W = sz[0] * k, H = sz[1] * k;
+ if (back) mk('rect', { x: -W / 2 + 4, y: -H / 2 + 4, width: W - 8, height: H - 8, fill: COL.board }, g); // a solid line drawing (a door)
+ mk('image', { href: `../img/${name}.webp`, x: -W / 2, y: -H / 2, width: W, height: H }, g);
+ g._w = W; g._h = H; g._x = x; g._y = y;
+ if (at !== undefined) tw(g, { x, y, o }, at, dur, out);
+ return g;
+}
+const leave = (g, t0, dx = 0, dy = 0, dur = .7) => tw(g, { x: g._x + dx, y: g._y + dy, o: 0 }, t0, dur, io);
+const push = (g, t0, t1, s1 = 1.06, dx = 0, dy = 0) => tw(g, { s: s1, x: g._x + dx, y: g._y + dy }, t0, t1 - t0, lin); // slow Ken Burns
+// one picture turning into another in place (a figure changing era)
+const dissolve = (a, b, t0, dur = 1.2) => { hide(a, t0, dur, lin); show(b, t0, dur, lin); };
+
+// a line drawing traced into strokes (LINES[name] from trace.py): drawn on stroke by stroke over `draw` s, or shown whole
+function traced(p, name, { x = 800, y = 450, h = 600, at = 0, draw: dd = 0, o = 1, flip = false } = {}) {
+ const L = LINES[name], [x0, y0, x1, y1] = L.box, k = h / (y1 - y0);
+ const g = G(p, { x, y, o: dd ? 1 : 0 });
+ const inner = mk('g', { transform: `scale(${flip ? -k : k},${k}) translate(${-(x0 + x1) / 2},${-(y0 + y1) / 2})` }, g);
+ const total = L.l.reduce((a, b) => a + b, 0);
+ let acc = 0;
+ L.p.forEach((d, i) => {
+ const e = path(inner, d, { stroke: CREAM, 'stroke-width': 2.4 / k }, dd ? { d: 0 } : {});
+ if (dd) { draw(e, at + dd * acc / total, Math.max(.04, dd * L.l[i] / total), lin); acc += L.l[i]; }
+ });
+ if (!dd) tw(g, { o }, at, .6);
+ g._x = x; g._y = y; g._h = h;
+ return g;
+}
+// words in a font measured on a canvas (fonts are loaded before boot)
+const CTX = document.createElement('canvas').getContext('2d');
+const wid = (str, size, font, style = '', weight = 400) => { CTX.font = `${style} ${weight} ${size}px ${font}`; return CTX.measureText(str).width; };
+
+// big condensed word(s)
+function key(p, str, x, y, t0, { size = 96, fill = CREAM, anchor = 'middle', from = 24, o = 1 } = {}) {
+ const e = T(p, str.toUpperCase(), { x, y: y + from, size, fill, font: KEY, weight: 600, anchor, o: 0 });
+ e.setAttribute('letter-spacing', '.02em');
+ e._w = wid(str.toUpperCase(), size, KEY, '', 600) * 1.02;
+ tw(e, { y, o }, t0, .55, out);
+ return e;
+}
+// a line struck through a key word (the word's own width)
+function strike(p, e, x, y, t0, size, anchor = 'middle') {
+ const x0 = anchor === 'middle' ? x - e._w / 2 : anchor === 'end' ? x - e._w : x;
+ return line(p, `M${x0 - 16} ${y - size * .32}H${x0 + e._w + 16}`, t0, .4, Math.max(5, size / 12), { stroke: HOT });
+}
+// serif lines typed word by word between t0 and t1 (Chinese, Japanese and Korean characters one by one)
+const CJK = /[⺀-鿿가-힯豈-﫿＀-￯]|[^⺀-鿿가-힯豈-﫿＀-￯]+/g;
+function say(p, lines, x, y, t0, t1, { size = 44, fill = CREAM, italic = true, anchor = 'start', lh = 1.3, weight = 400 } = {}) {
+ const g = G(p, {}), style = italic ? 'italic' : '', words = [];
+ const sp = wid(' ', size, SER, style, weight);
+ lines.forEach((ln, i) => {
+ const W = wid(ln, size, SER, style, weight);
+ let cx = anchor === 'middle' ? x - W / 2 : anchor === 'end' ? x - W : x;
+ ln.split(' ').forEach(word => (word.match(CJK) || ['']).forEach((w, j, ws) => {
+ const e = T(g, w, { x: cx, y: y + i * size * lh, size, fill, font: SER, weight, o: 0 });
+ if (italic) e.setAttribute('font-style', 'italic');
+ words.push(e); cx += wid(w, size, SER, style, weight) + (j === ws.length - 1 ? sp : 0);
+ }));
+ });
+ const chars = words.map(e => e.textContent.length + 1), all = chars.reduce((a, b) => a + b, 0);
+ let acc = 0;
+ words.forEach((e, i) => { show(e, t1 === t0 ? t0 : t0 + (t1 - t0) * acc / all, .25, lin); acc += chars[i]; });
+ return g;
+}
+// a small caption under a picture (a credit or a name tag)
+function tag(p, str, x, y, t0, { size = 24, anchor = 'start', fill = SOFT } = {}) {
+ const e = T(p, str, { x, y, size, fill, font: SER, anchor, o: 0 });
+ e.setAttribute('font-style', 'italic');
+ show(e, t0, .5);
+ return e;
+}
+// the era at the top left, like a chapter opener: the year in italic, a hairline, the place or topic in spaced capitals
+function dateChip(p, year, topic, t0 = .2) {
+ const g = G(p, { x: 80, y: 112, o: 0 });
+ T(g, year, { size: 72, font: SER, weight: 400, fill: HOT }).setAttribute('font-style', 'italic');
+ const tw_ = wid(topic.toUpperCase(), 26, SER) * 1.3 + 8; // letter-spacing .28em widens the caps by about 30 %
+ const rule = path(g, `M3 22H${Math.max(220, tw_)}`, { stroke: CREAM, 'stroke-width': 1.4, opacity: .7 }, { d: 0 });
+ T(g, topic.toUpperCase(), { x: 3, y: 58, size: 26, font: SER, weight: 400, fill: CREAM }).setAttribute('letter-spacing', '.28em');
+ tw(g, { o: 1 }, t0, .6); draw(rule, t0 + .2, .6);
+ return g;
+}
+// cream line, drawn on
+const line = (p, d, t0, dur = .8, w = 3, extra = {}) => { const e = path(p, d, { stroke: CREAM, 'stroke-width': w, ...extra }, { d: 0 }); draw(e, t0, dur); return e; };
+// wavy water lines that flow forever (pure function of the beat clock); amp may be a function of t
+function water(p, y0, D, { rows = 3, amp = 8, len = 1700, x0 = -50, gap = 26, o = .75 } = {}) {
+ const g = G(p, { o: 0 }); tw(g, { o }, 0, .6);
+ const ps = [...Array(rows)].map((_, i) => path(g, '', { stroke: CREAM, 'stroke-width': 2.2, opacity: 1 - i * .25 }));
+ clockRun(t => { const a = typeof amp === 'function' ? amp(t) : amp; ps.forEach((e, i) => {
+ let d = ''; for (let x = 0; x <= len; x += 20) d += `${x ? 'L' : 'M'}${x0 + x} ${(y0 + i * gap * (a / 8) ** .5 + a * Math.sin(x / 70 + t * 1.6 + i)).toFixed(1)}`;
+ e.setAttribute('d', d);
+ }); }, D, { tail: true });
+ return g;
+}
+// something that bobs on the water (a boat); x may follow a function of t
+const bob = (g, D, a = 6, xf) => clockRun(t => put(g, { y: g._y + a * Math.sin(t * 1.6), r: 1.5 * Math.sin(t * 1.1), ...(xf ? { x: xf(t) } : {}) }), D, { tail: true });
+const span01 = (t, a, b) => Math.min(1, Math.max(0, (t - a) / (b - a)));
+const smooth01 = q => q * q * (3 - 2 * q);
+// a speech balloon, cream outline, its tail to (tx, ty)
+function balloon(p, x, y, w, h, tx, ty, t0) {
+ const bx = Math.min(Math.max(tx, x + 60), x + w - 100);
+ const d = `M${x + 30} ${y}H${x + w - 30}Q${x + w} ${y} ${x + w} ${y + 30}V${y + h - 30}Q${x + w} ${y + h} ${x + w - 30} ${y + h}H${bx + 40}L${tx} ${ty}L${bx} ${y + h}H${x + 30}Q${x} ${y + h} ${x} ${y + h - 30}V${y + 30}Q${x} ${y} ${x + 30} ${y}Z`;
+ return line(p, d, t0, .7, 3);
+}
+// a field of dots: positions from a fixed seed so every replay is the same
+function rng(seed) { return () => (seed = (seed * 16807) % 2147483647) / 2147483647; }
+function dots(p, n, box, r, seed, fill = CREAM) {
+ const R = rng(seed), g = G(p, {});
+ return { g, el: [...Array(n)].map(() => mk('circle', { cx: box[0] + R() * box[2], cy: box[1] + R() * box[3], r, fill }, g)).map(e => put(e, { o: 0 })) };
+}
+// close-ups inside a print as their words are spoken: shots [[mark, fx, fy, label, zoom]], fx/fy the point in the picture
+// (0..1 of the picture inside its border); the view never leaves the picture; a band names each one; back to the whole after
+function closeups(p, g, name, shots, m, tBack, home) {
+ const [W, H] = ART[name], k = g._w / W, iw = (W - 112) * k, ih = (H - 112) * k; // a print's picture sits 56 px in
+ const clamp = (v, lim) => Math.max(-lim, Math.min(lim, v));
+ shots.forEach(([mark, fx, fy, label, Z = 3], i) => {
+ const dx = clamp((fx - .5) * iw, iw / 2 - 800 / Z), dy = clamp((fy - .5) * ih, ih / 2 - 450 / Z), t0 = m(mark) - .15;
+ tw(g, { s: Z, x: 800 - Z * dx, y: 450 - Z * dy, r: 0 }, t0, .35, out);
+ const l = G(p, { x: 800, y: fy > .7 ? 130 : 820, o: 0 }), lw = wid(label.toUpperCase(), 72, KEY, '', 600) + 70; // clear of a low subject
+ mk('rect', { x: -lw / 2, y: -68, width: lw, height: 92, fill: COL.board }, l);
+ T(l, label.toUpperCase(), { y: 0, size: 72, font: KEY, weight: 600, fill: CREAM, anchor: 'middle' });
+ show(l, t0, .12);
+ hide(l, i < shots.length - 1 ? m(shots[i + 1][0]) - .15 : tBack, .15);
+ });
+ if (home) tw(g, { s: 1, ...home }, tBack, .8, soft); // no home: stay on the last close-up
+}
+// a generated clip as cream-line frames on one sprite sheet (frames.py), played on the beat clock from t0:
+// the frame is a pure function of the time, so pausing, seeking and the export all show the same picture
+function anim(p, name, { x = 800, y = 450, size = 600, at = 0, t0 = at, D, o = 1 } = {}) {
+ const F = FRAMES[name], rows = Math.ceil(F.n / F.cols);
+ const g = G(p, { x, y, o: 0 });
+ const v = mk('svg', { x: -size / 2, y: -size / 2, width: size, height: size, viewBox: `0 0 ${F.fw} ${F.fh}` }, g);
+ mk('image', { href: `../img/${name}-sheet.webp`, width: F.cols * F.fw, height: rows * F.fh }, v);
+ let last = -1;
+ clockRun(t => {
+ const f = Math.max(0, Math.min(F.n - 1, Math.floor((t - t0) * F.fps)));
+ if (f !== last) { last = f; v.setAttribute('viewBox', `${(f % F.cols) * F.fw} ${Math.floor(f / F.cols) * F.fh} ${F.fw} ${F.fh}`); }
+ }, D, { tail: true });
+ tw(g, { o }, at, .8);
+ return g;
+}
+// an old document: paper, lines of ink, a label
+function doc(p, label, x, y, r, t0, seed) {
+ const R = rng(seed), g = G(p, { x: x - 700, y, r, o: 0 });
+ mk('rect', { x: -150, y: -200, width: 300, height: 400, fill: PAPER, stroke: '#cdbfa6' }, g);
+ for (let i = 0; i < 13; i++) {
+ const yy = -130 + i * 24, ww = 160 + R() * 70;
+ path(g, `M-118 ${yy}q${ww / 4} ${-3 + R() * 6} ${ww / 2} 0t${ww / 2} 0`, { stroke: INK, 'stroke-width': 2, opacity: .7 });
+ }
+ T(g, label.toUpperCase(), { y: -160, size: 22, font: KEY, weight: 600, fill: STAMP, anchor: 'middle' }).setAttribute('letter-spacing', '.06em');
+ tw(g, { x, o: 1 }, t0, .8, out);
+ g._x = x; g._y = y;
+ return g;
+}
+// a point moving along a polyline [[x, y], …] as q goes 0..1
+function along(pts, q) {
+ const seg = pts.slice(1).map((b, i) => Math.hypot(b[0] - pts[i][0], b[1] - pts[i][1])), L = seg.reduce((a, b) => a + b, 0);
+ let d = q * L, i = 0;
+ while (i < seg.length - 1 && d > seg[i]) d -= seg[i++];
+ const f = seg[i] ? d / seg[i] : 0, a = pts[i], b = pts[i + 1];
+ return [a[0] + (b[0] - a[0]) * f, a[1] + (b[1] - a[1]) * f];
+}
+
+// a picture with its credit or name under it, and a quote typed beside it (an epigraph): portrait left, the quote large
+function epigraph(p, name, who, lines, tin, tq, tq1, tout) {
+ const g = G(p, {});
+ pic(g, name, { x: 330, y: 430, h: 440, r: -2, at: tin, from: [-500, 0] });
+ tag(g, who, 330, 690, tin + .5, { anchor: 'middle', size: 30, fill: CREAM });
+ say(g, lines, 620, 330, tq, tq1, { size: 62 });
+ if (tout !== undefined) tw(g, { x: -200, o: 0 }, tout, .7, io);
+ return g;
+}
+
+/* ---------- this film's own pieces ---------- */
+
+/* ---------- Proteus: one cut-paper body that changes shape ----------
+ Each shape is a polygon drawn around its feet (0, 0), resampled to the same number of points so any shape can melt
+ into any other; between shapes the body turns to water (its own blue) and ripples. drawPro() is a pure function of
+ the beat clock, so pause, seek and the export agree. */
+const SHEET = '#fbf7ee', WATER = '#6fb3c8', DEEP = '#2b6f8f',
+ RED = '#b5383c', BLUE = '#2b78a6', PURPLE = '#6a3f9c', BROWN = '#5b3c2d', OCHRE = '#d4952a', TEAL = '#2f8f7a', WOOD = '#8a6240';
+const NPTS = 180;
+const hex = c => [1, 3, 5].map(i => parseInt(c.slice(i, i + 2), 16));
+const tint = (a, b, q) => '#' + hex(a).map((v, i) => Math.round(v + (hex(b)[i] - v) * q).toString(16).padStart(2, '0')).join('');
+function resample(pts, n = NPTS) {
+ let area = 0;
+ pts.forEach(([x, y], i) => { const [u, v] = pts[(i + 1) % pts.length]; area += x * v - u * y; });
+ if (area < 0) pts = pts.slice().reverse();
+ const L = [0];
+ pts.forEach(([x, y], i) => { const [u, v] = pts[(i + 1) % pts.length]; L.push(L[i] + Math.hypot(u - x, v - y)); });
+ const out = [];
+ for (let k = 0, j = 0; k < n; k++) {
+ const d = L[pts.length] * k / n;
+ while (L[j + 1] < d) j++;
+ const [x, y] = pts[j], [u, v] = pts[(j + 1) % pts.length], q = (d - L[j]) / (L[j + 1] - L[j] || 1);
+ out.push([x + (u - x) * q, y + (v - y) * q]);
+ }
+ const cx = out.reduce((s, p) => s + p[0], 0) / n; // start every outline at its bottom middle, so shapes line up
+ let best = 0;
+ out.forEach(([x, y], i) => { if (Math.hypot(x - cx, y - 400) < Math.hypot(out[best][0] - cx, out[best][1] - 400)) best = i; });
+ return out.slice(best).concat(out.slice(0, best));
+}
+// a serpent from its centre line: half-widths, spikes on the back every other point
+function serpent(line, wid, head) {
+ const top = [], bot = [];
+ line.forEach(([x, y], i) => {
+ const [a, b] = line[Math.max(0, i - 1)], [c, d] = line[Math.min(line.length - 1, i + 1)];
+ const l = Math.hypot(c - a, d - b), nx = (d - b) / l, ny = -(c - a) / l, w = wid[i];
+ top.push([x + nx * w, y + ny * w]);
+ if (i % 2 && i < line.length - 1) top.push([x + nx * (w + 34), y + ny * (w + 34)]);
+ bot.push([x - nx * w, y - ny * w]);
+ });
+ return [...top, ...head, ...bot.reverse()];
+}
+// the mane: rays round the head, long and short in turn, from angle a0 to a1 (degrees, clockwise on screen)
+const mane = (cx, cy, a0, a1, n, r0, r1) => Array.from({ length: n + 1 }, (_, i) => {
+ const a = (a0 + (a1 - a0) * i / n) * Math.PI / 180, r = i % 2 ? r1 : r0;
+ return [cx + r * Math.cos(a), cy + r * Math.sin(a)];
+});
+const SHAPES = {
+ page: { col: SHEET, x: 800, y: 790, s: 1, lines: 1, eyes: [],
+ pts: [[-160, 0], [-160, -420], [160, -420], [160, 0]] },
+ water: { col: WATER, x: 470, y: 760, s: 1, eyes: [[-30, -205], [28, -210]],
+ pts: [[-175, 0], [-160, -70], [-120, -160], [-70, -240], [-15, -295], [40, -318], [95, -300], [128, -258], [122, -212],
+ [92, -192], [64, -204], [74, -162], [115, -112], [155, -58], [180, 0]] },
+ lion: { col: RED, x: 470, y: 760, s: 1, eyes: [[188, -228]],
+ pts: [[-300, -205], [-286, -228], [-266, -208], [-240, -172], [-205, -158], [-120, -175], [-20, -182], [30, -188],
+ ...mane(115, -212, 150, 330, 12, 92, 128), [215, -238], [244, -216], [238, -188], [205, -178],
+ ...mane(115, -212, 40, 100, 4, 92, 120), [150, -110], [142, -60], [152, 0], [120, 0], [110, -70], [90, -70],
+ [85, 0], [55, 0], [50, -95], [-40, -96], [-110, -100], [-115, 0], [-145, 0], [-150, -60], [-170, -60], [-180, 0],
+ [-210, 0], [-216, -110], [-212, -148], [-242, -158], [-272, -192], [-294, -192]] },
+ dragon: { col: BLUE, x: 1130, y: 760, s: 1, f: -1, eyes: [[186, -276]],
+ pts: serpent([[-320, -14], [-260, -40], [-190, -66], [-120, -56], [-50, -30], [20, -40], [80, -96], [112, -170], [140, -236]],
+ [3, 12, 22, 28, 30, 30, 28, 26, 24],
+ [[118, -300], [146, -284], [176, -294], [238, -278], [252, -258], [214, -250], [240, -236], [192, -226]]) },
+ leopard: { col: PURPLE, x: 470, y: 760, s: 1, eyes: [[244, -150]],
+ pts: [[-330, -232], [-318, -252], [-298, -246], [-304, -222], [-288, -190], [-250, -152], [-200, -142], [-100, -152],
+ [0, -152], [90, -146], [160, -152], [198, -168], [210, -194], [226, -172], [260, -162], [286, -140], [280, -120],
+ [250, -110], [215, -106], [190, -92], [205, 0], [175, 0], [160, -60], [140, -60], [135, 0], [105, 0], [100, -80],
+ [0, -76], [-100, -80], [-110, 0], [-140, 0], [-150, -55], [-170, -55], [-185, 0], [-215, 0], [-225, -90],
+ [-240, -130], [-280, -178], [-300, -214], [-316, -236]] },
+ boar: { col: OCHRE, x: 1130, y: 760, s: 1.05, f: -1, eyes: [[176, -152]],
+ pts: [[-256, -136], [-240, -152], [-200, -170], [-160, -196], [-145, -212], [-120, -206], [-100, -226], [-75, -219],
+ [-55, -242], [-30, -231], [-5, -247], [20, -229], [45, -236], [70, -211], [110, -192], [124, -218], [142, -186],
+ [190, -152], [250, -112], [266, -104], [268, -70], [246, -64], [262, -40], [234, -52], [190, -70], [160, -60],
+ [165, 0], [140, 0], [130, -45], [110, -45], [105, 0], [80, 0], [70, -60], [-60, -66], [-130, -70], [-140, 0],
+ [-165, 0], [-172, -40], [-190, -40], [-195, 0], [-220, 0], [-232, -82], [-244, -112]] },
+ // running water: a low stream; its crests run (live)
+ stream: { col: TEAL, x: 470, y: 760, s: 1, eyes: [[178, -112], [214, -118]], run: 1,
+ pts: [[-330, 0], ...Array.from({ length: 18 }, (_, i) => [-320 + i * 25, -34 - 8 * Math.sin(i * .9) - i * 1.6]),
+ [130, -84], [160, -134], [196, -166], [238, -176], [270, -160], [282, -130], [266, -110], [246, -120], [234, -102],
+ [262, -60], [300, -24], [330, 0]] },
+ tree: { col: WOOD, x: 560, y: 820, s: 1, eyes: [],
+ pts: [[-95, 0], [-55, -40], [-45, -180], [-120, -212], [-330, -250], [-334, -274], [-120, -246], [-44, -262],
+ [-38, -360], [-110, -394], [-292, -420], [-294, -444], [-110, -428], [-36, -404], [-30, -520], [-18, -600],
+ [-92, -610], [-92, -634], [92, -634], [92, -610], [18, -600], [26, -520], [35, -462], [300, -497], [302, -475],
+ [40, -432], [45, -300], [50, -288], [330, -332], [332, -310], [55, -256], [60, -40], [98, 0]] },
+};
+for (const k in SHAPES) SHAPES[k].pts = resample(SHAPES[k].pts);
+// what each animal does once it has its shape (u: seconds since it settled): a move of the whole body, and a bend of
+// its outline; each comes with its sound in the chapter
+const bump = (u, a, b) => Math.sin(Math.PI * span01(u, a, b));
+const tail = (x, x0, w) => Math.min(1, Math.max(0, (x0 - x) / w)); // 0 at the body, 1 at the tail's tip
+Object.assign(SHAPES.water, { bend: (x, y, u) => [x * (1 - .1 * bump(u, 0, .7)), y * (1 + .06 * bump(u, 0, .7))] }); // squeezed in the hands
+Object.assign(SHAPES.lion, { // rears back and roars; then swishes his tail
+ act: u => ({ r: -7 * bump(u, 0, 1) }),
+ bend: (x, y, u) => [x, y + 9 * Math.sin(u * 5) * tail(x, -215, 85)] });
+Object.assign(SHAPES.dragon, { bend: (x, y, u) => [x, y + 12 * Math.sin(x / 55 + u * 6) * (x > 100 ? .3 : 1)] }); // slithers, hissing
+Object.assign(SHAPES.leopard, { // crouches, springs, then flicks its tail
+ bend: (x, y, u) => [x + 8 * Math.sin(u * 6) * tail(x, -250, 80), y * (1 - .14 * bump(u, 0, .3)) + 10 * Math.cos(u * 6) * tail(x, -250, 80)],
+ act: u => ({ y: -80 * bump(u, .25, .75), r: -6 * bump(u, .25, .5) + 4 * bump(u, .5, .75) }) });
+Object.assign(SHAPES.boar, { // stamps and snorts, charges at its card, and stamps again
+ act: u => ({ y: -6 * Math.abs(Math.sin(u * 14)) * (u % 2.2 < .5 ? 1 : 0), x: -90 * bump(u, .5, 1.4), r: 4 * bump(u, .5, .9) }) });
+Object.assign(SHAPES.stream, { act: u => ({ x: 14 * Math.sin(u * 2.4) }) }); // the stream surges
+Object.assign(SHAPES.tree, { act: u => ({ r: 1.4 * Math.sin(u * 1.7) * span01(u, 0, .6) }) }); // sways
+// a second layer of paper on each shape, in its own colour: [d, fill, extra attributes]
+const ring = (cx, cy, r) => `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0Z`;
+const poly = pts => 'M' + pts.map(p => p.map(v => v.toFixed(1)).join(' ')).join('L') + 'Z';
+const DECOR = {
+ lion: [[poly(mane(115, -212, 0, 360, 22, 78, 104)) + ring(150, -208, 64), '#7d2326', { 'fill-rule': 'evenodd' }],
+ [poly([[-300, -205], [-286, -228], [-266, -208], [-282, -196]]), '#7d2326']],
+ dragon: [[[[-230, -54], [-160, -64], [-90, -46], [-20, -36], [50, -64], [96, -130], [124, -200]]
+ .map(([x, y]) => `M${x - 12} ${y - 6}l12 10l12 -10`).join(''), 'none', { stroke: '#8fc0de', 'stroke-width': 5, 'stroke-linejoin': 'round' }],
+ [poly([[118, -300], [146, -284], [132, -282]]), '#1d4f70']],
+ leopard: [[poly([[100, -80], [0, -76], [-100, -80], [-96, -96], [0, -92], [96, -96]]), '#8d67bd']],
+ boar: [[poly([[-200, -170], [-160, -196], [-145, -212], [-120, -206], [-100, -226], [-75, -219], [-55, -242], [-30, -231],
+ [-5, -247], [20, -229], [45, -236], [70, -211], [110, -192], [70, -186], [0, -206], [-80, -196], [-160, -176]]), '#9c6a16'],
+ [poly([[244, -64], [262, -40], [234, -52]]), SHEET]],
+ stream: [['M150 -126Q190 -170 238 -172Q266 -164 276 -138', 'none', { stroke: SHEET, 'stroke-width': 7, 'stroke-linecap': 'round', opacity: .8 }]],
+ tree: [['M-30 -90h22M10 -150h26M-34 -230h18M8 -330h24M-30 -430h20M6 -540h18M-200 -232h30M180 -320h28M-180 -416h24M160 -482h26',
+ 'none', { stroke: '#3b2a1c', 'stroke-width': 6, 'stroke-linecap': 'round' }]],
+};
+
+// the body, its paper shadow, eyes, and the page's text lines; kept on S so every beat moves the same Proteus
+function proteus() {
+ const back = G(scene, {});
+ const disc = mk('circle', { r: 300, fill: WATER }, back);
+ put(disc, { x: 1130, y: 410, o: .16 });
+ path(back, 'M-20 770L120 764L300 772L520 762L760 770L980 763L1220 771L1440 764L1620 770V920H-20Z', { fill: '#e8d9b8' });
+ const waves = [['#9cc6d8', 852, 0], ['#6fb3c8', 876, 60]].map(([fill, y, dx]) => {
+ const w = G(scene, {});
+ path(w, 'M-200 0' + Array.from({ length: 22 }, (_, i) => `q50 -26 100 0`).join('') + 'V60H-200Z', { fill, transform: `translate(${dx} ${y})` });
+ return w;
+ });
+ const g = G(scene, {});
+ mk('ellipse', { cx: 0, cy: 6, rx: 230, ry: 14, fill: 'rgba(60,40,20,.10)' }, g);
+ const shadow = mk('path', { fill: 'rgba(60,40,20,.20)', transform: 'translate(7 9)' }, g);
+ const body = mk('path', {}, g);
+ const decor = {};
+ for (const k in DECOR) {
+ decor[k] = G(g, { o: 0 });
+ decor[k]._in = mk('g', {}, decor[k]); // its own transform: the flip
+ DECOR[k].forEach(([d, fill, extra = {}]) => path(decor[k]._in, d, { fill, ...extra }));
+ }
+ const lines = G(g, {});
+ path(lines, 'M-120 -380H60', { stroke: INK, 'stroke-width': 10, 'stroke-linecap': 'round' });
+ mk('rect', { x: -120, y: -345, width: 110, height: 90, fill: WATER, opacity: .55 }, lines);
+ [-340, -318, -296, -274, -230, -208, -186, -164, -142, -120, -98, -76, -54].forEach((y, i) =>
+ path(lines, `M${y > -260 ? -120 : 4} ${y}H${i % 4 === 3 ? 60 : 120}`, { stroke: '#b9ad97', 'stroke-width': 7, 'stroke-linecap': 'round' }));
+ const eyes = [0, 1].map(() => {
+ const e = G(g, {});
+ mk('circle', { r: 11, fill: SHEET }, e);
+ const pupil = mk('ellipse', { cx: 2, rx: 5, ry: 5.5, fill: INK }, e);
+ return { e, pupil };
+ });
+ const drops = Array.from({ length: 9 }, () => mk('circle', { r: 9, fill: WATER, opacity: 0 }, scene));
+ return (S.pro = { g, shadow, body, lines, eyes, decor, drops, disc, waves, at: 'page' });
+}
+// write an attribute only when it changes: Firefox restyles on every write
+const setOnce = (e, k, v) => { if (e['_' + k] !== v) { e['_' + k] = v; e.setAttribute(k, v); } };
+// draw Proteus between shapes a and b at q (0..1) at beat time t
+function drawPro(a, b, q, t, u = -1) {
+ const A = SHAPES[a], B = SHAPES[b], pr = S.pro, k = Math.sin(Math.PI * q);
+ const f = (A.f || 1) + ((B.f || 1) - (A.f || 1)) * q; // a shape on the right faces left, toward its card
+ const amp = 1.6 + 18 * k, pts = [];
+ for (let i = 0; i < NPTS; i++) {
+ const [x0, y0] = A.pts[i], [x1, y1] = B.pts[i];
+ let x = (x0 * (A.f || 1) + (x1 * (B.f || 1) - x0 * (A.f || 1)) * q), y = y0 + (y1 - y0) * q;
+ const run = ((A.run || 0) * (1 - q) + (B.run || 0) * q) * (y < -20 ? 1 : 0) * (x < 110 ? 1.6 : .3); // the crest, round the eyes, barely moves
+ y += run * 10 * Math.sin(x / 38 - t * 7);
+ if (q === 1 && b !== 'page' && y < -20) y *= 1 + .012 * Math.sin(t * 2.6); // breathing
+ pts.push(q === 1 && B.bend ? B.bend(x, y, u) : [x, y]);
+ }
+ const d = pts.map(([x, y], i) => {
+ const [u, v] = pts[(i + NPTS - 1) % NPTS], [w, z] = pts[(i + 1) % NPTS], l = Math.hypot(w - u, z - v) || 1;
+ const o = amp * Math.sin(i * .42 + t * 4.2) * (y > -6 ? .2 : 1); // the feet stay on the ground
+ return (i ? 'L' : 'M') + (x + (z - v) / l * o).toFixed(1) + ' ' + (y - (w - u) / l * o).toFixed(1);
+ }).join('') + 'Z';
+ const col = q < .5 ? tint(A.col, WATER, q * 2) : tint(WATER, B.col, q * 2 - 1);
+ pr.body.setAttribute('d', d); pr.shadow.setAttribute('d', d); setOnce(pr.body, 'fill', col);
+ const gx = A.x + (B.x - A.x) * q, gy = A.y + (B.y - A.y) * q - (Math.abs(B.x - A.x) > 100 ? 160 * k : 0); // a leap across
+ const act = q === 1 && B.act ? B.act(u) : {};
+ put(pr.g, { x: gx + (act.x || 0), y: gy + (act.y || 0), s: A.s + (B.s - A.s) * q, r: act.r || 0 });
+ for (const n in pr.decor) {
+ put(pr.decor[n], { o: n === a && n === b ? 1 : n === a ? (1 - q) ** 4 : n === b ? q ** 4 : 0 });
+ setOnce(pr.decor[n]._in, 'transform', `scale(${n === a ? A.f || 1 : B.f || 1} 1)`);
+ }
+ pr.drops.forEach((e, i) => { // splashes while the body is water
+ const u = (q * 1.6 + i * .07) % 1, a0 = -Math.PI / 2 + (i - 4) * .3, v = 260 + (i % 3) * 60;
+ put(e, { x: gx + Math.cos(a0) * v * u, y: A.y + (B.y - A.y) * q - 120 + Math.sin(a0) * v * u + 420 * u * u, o: q > .02 && q < .95 ? .9 * (1 - u) : 0 });
+ });
+ put(pr.lines, { o: Math.max(A.lines ? 1 - q * 2.5 : 0, B.lines ? (q - .6) / .4 : 0, 0) });
+ const blink = t % 3.3 < .13 ? .15 : 1;
+ pr.eyes.forEach(({ e, pupil }, i) => {
+ const ea = A.eyes[i] || A.eyes[0] || B.eyes[i] || B.eyes[0] || [0, -200], eb = B.eyes[i] || B.eyes[0] || ea;
+ const oa = A.eyes[i] ? 1 : 0, ob = B.eyes[i] ? 1 : 0;
+ put(e, { x: ea[0] * (A.f || 1) + (eb[0] * (B.f || 1) - ea[0] * (A.f || 1)) * q, y: ea[1] + (eb[1] - ea[1]) * q, o: oa && ob ? 1 : oa ? (1 - q) ** 3 : ob * q * q });
+ setOnce(pupil, 'ry', (5.5 * blink).toFixed(2)); setOnce(pupil, 'cx', f < 0 ? -2 : 2);
+ });
+}
+// one beat of Proteus: hold `from`, melt into `to` from t0 over dur, then live in it until the beat's end; its act
+// (and its call, in the chapter) starts at actAt
+function morph(D, from, to, t0, dur = 1, actAt = t0 + dur) {
+ clockRun(t => drawPro(from, to, smooth01(span01(t, t0, t0 + dur)), t, t - actAt), D, { tail: true });
+ sea(D);
+ S.pro.at = to;
+}
+// the waves run on the film's own clock: S.at0 is the film time at this beat's start (set by the chapter, whose beats
+// have fixed lengths, FILM_LEN in all), and they drift a whole number of crests over the film, so the loop has no seam
+function sea(D) {
+ const T = S.at0 || 0, L = window.FILM_LEN, v = L ? Math.round(L * .3) * 100 / L : 30;
+ clockRun(t => S.pro.waves.forEach((w, i) => { const x = (v * (T + t)) % 100; put(w, { x: i ? -x : x }); }), D, { tail: true });
+}
+
+// a shape card: a sheet with the tier's colour along its top, popping in at t0
+function sheet(p, x, y, col, t0, { w = 520, h = 330, s = 1 } = {}) {
+ const g = G(p, { x, y, s: s * .92, o: 0 });
+ mk('rect', { x: -w / 2 + 8, y: -h / 2 + 10, width: w, height: h, fill: 'rgba(60,40,20,.14)' }, g);
+ mk('rect', { x: -w / 2, y: -h / 2, width: w, height: h, fill: SHEET }, g);
+ mk('rect', { x: -w / 2, y: -h / 2, width: w, height: 10, fill: col }, g);
+ tw(g, { s, o: 1 }, t0, .5, back);
+ return g;
+}
+const arrowTo = (p, x0, y0, x1, y1, col, t0, w = 6) => {
+ const a = Math.atan2(y1 - y0, x1 - x0), hx = x1 - 18 * Math.cos(a), hy = y1 - 18 * Math.sin(a);
+ draw(path(p, `M${x0} ${y0}L${hx} ${hy}`, { stroke: col, 'stroke-width': w, 'stroke-linecap': 'round' }, { d: 0 }), t0, .5);
+ const head = path(p, `M${x1} ${y1}L${hx - 9 * Math.sin(a)} ${hy + 9 * Math.cos(a)}L${hx + 9 * Math.sin(a)} ${hy - 9 * Math.cos(a)}Z`, { fill: col, o: 0 });
+ show(head, t0 + .45, .15);
+};
+// the five shapes' cards, each drawn around (0, 0) inside a card made by sheet(); t0 starts its motion
+const CARDS = {
+ lesson(g, t0) {
+ for (let x = -220; x <= 220; x += 40) path(g, `M${x} -130V140`, { stroke: '#ebe2d2', 'stroke-width': 2 });
+ for (let y = -130; y <= 140; y += 40) path(g, `M-220 ${y}H220`, { stroke: '#ebe2d2', 'stroke-width': 2 });
+ path(g, 'M-220 110H220M-140 -130V140', { stroke: '#b9ad97', 'stroke-width': 3 });
+ arrowTo(g, -140, 110, 20, 70, RED, t0 + .2);
+ arrowTo(g, -140, 110, -80, -40, RED, t0 + .7);
+ draw(path(g, 'M20 70L80 -80M-80 -40L80 -80', { stroke: RED, 'stroke-width': 3, 'stroke-dasharray': '8 8', opacity: .6 }, { d: 0 }), t0 + 1.2, .5);
+ arrowTo(g, -140, 110, 80, -80, '#7d2326', t0 + 1.6, 7);
+ [['a', 0, 104], ['b', -126, -40], ['a + b', 96, -84]].forEach(([s, x, y], i) =>
+ show(T(g, s, { x, y, size: 30, fill: i === 2 ? '#7d2326' : RED, font: SER, o: 0 }), t0 + [.6, 1.1, 2][i], .3));
+ g.querySelectorAll('text').forEach(e => e.setAttribute('font-style', 'italic'));
+ },
+ book(g, t0) {
+ mk('circle', { cx: 150, cy: -70, r: 34, fill: '#fffaf0' }, g);
+ path(g, 'M-260 70C-160 0 -60 10 40 60S200 30 260 50V165H-260Z', { fill: '#9cc2da' });
+ path(g, 'M-260 120C-140 70 20 90 120 110S220 90 260 100V165H-260Z', { fill: BLUE });
+ path(g, 'M-150 100L-150 30M-150 -40L-190 40H-110Z', { fill: '#1d4f70', stroke: '#1d4f70', 'stroke-width': 8 });
+ // a paper puppet: three pieces of a dragon pinned together, on two sticks; it swims and its jaw flaps
+ const pup = G(g, { x: 30, y: 0 }), sticks = path(g, 'M0 0', { stroke: '#7a6a55', 'stroke-width': 4 });
+ const seg = (parent, d, x) => { const e = G(parent, { x }); path(e, d, { fill: BLUE }); return e; };
+ const s1 = seg(pup, 'M0 -16L-70 -4L-110 12L-60 8L0 16Z', -60);
+ const s2 = seg(pup, 'M-60 -18L-40 -40L-20 -20L0 -36L20 -18L60 -16L60 16L-60 16Z', 0);
+ const s3 = seg(pup, 'M0 -14L30 -30L62 -24L74 -8L40 -4L0 14Z', 60);
+ const jaw = G(s3, { x: 30, y: 2 });
+ path(jaw, 'M-30 8L44 -2L40 10L-24 18Z', { fill: '#1d4f70' });
+ mk('circle', { cx: 50, cy: -18, r: 4, fill: SHEET }, s3);
+ [[-60, 0], [0, 0], [60, 0]].forEach(([x]) => mk('circle', { cx: x, cy: 0, r: 5, fill: SHEET, stroke: '#1d4f70', 'stroke-width': 2 }, pup));
+ clockRun(t => {
+ const u = Math.max(0, t - t0), x = 30 + 40 * Math.sin(u * 1.1), y = -50 + 12 * Math.sin(u * 2.4);
+ put(pup, { x, y, r: 4 * Math.sin(u * 2.4) });
+ put(s1, { x: -60, r: 14 * Math.sin(u * 3.2) }); put(s3, { x: 60, r: -10 * Math.sin(u * 3.2 + 1) });
+ put(jaw, { x: 30, y: 2, r: 12 * Math.max(0, Math.sin(u * 7)) });
+ sticks.setAttribute('d', `M${(x - 40).toFixed(1)} ${y.toFixed(1)}L${(x - 30).toFixed(1)} 165M${(x + 50).toFixed(1)} ${y.toFixed(1)}L${(x + 60).toFixed(1)} 165`);
+ }, 0, { tail: true });
+ },
+ film(g, t0) {
+ mk('rect', { x: -260, y: -165, width: 520, height: 330, fill: '#2d1a40' }, g);
+ path(g, 'M-260 -126H260M-260 126H260', { stroke: '#4a2f66', 'stroke-width': 3 });
+ const ship = G(g, { x: 0, y: 10 });
+ ['M-120 50Q0 90 120 50L100 30H-100Z', 'M-10 30V-90M-10 -86L60 0H-10M-10 -70L-80 10H-10', 'M-150 66Q-110 56 -70 66T10 66T90 66T170 66']
+ .forEach((d, i) => draw(path(ship, d, { stroke: '#f3ede0', 'stroke-width': 5, fill: 'none', 'stroke-linejoin': 'round' }, { d: 0 }), t0 - .1 + i * .25, .6));
+ tw(ship, { s: 1.08 }, t0, 1.4, lin);
+ const sub = G(g, { o: 0 }); // a subtitle strip: the film is narrated
+ mk('rect', { x: -170, y: 80, width: 340, height: 34, rx: 6, fill: 'rgba(0,0,0,.55)' }, sub);
+ T(sub, 'In 1494, a ship of fools set sail…', { x: 0, y: 104, size: 21, fill: '#f3ede0', font: SER, anchor: 'middle' });
+ show(sub, t0 + .5, .3);
+ },
+ short(g, t0, { w0 = 500, h0 = 310 } = {}) {
+ const fr = mk('rect', { fill: '#2d1a40' }, g), bar = mk('rect', { fill: '#f3ede0', height: 12, rx: 6 }, g);
+ const boar = G(g, { s: .34, o: 0 });
+ path(boar, 'M' + SHAPES.boar.pts.map(p => p.join(' ')).join('L') + 'Z', { fill: '#f0c069' });
+ const cap = [mk('rect', { fill: '#f3ede0', height: 12, rx: 6, opacity: 0 }, g), mk('rect', { fill: '#f3ede0', height: 12, rx: 6, opacity: 0 }, g)];
+ clockRun(t => {
+ const q = smooth01(span01(t, t0, t0 + .8)), w = w0 + (190 - w0) * q, h = h0 + (338 - h0) * q;
+ Object.entries({ x: -w / 2, y: -h / 2, width: w, height: h, rx: 22 * q }).forEach(([k, v]) => fr.setAttribute(k, v.toFixed(1)));
+ bar.setAttribute('x', (-w / 2 + 14).toFixed(1)); bar.setAttribute('y', (-h / 2 + 14).toFixed(1));
+ bar.setAttribute('width', ((w - 28) * span01(t, t0 + .6, t0 + 2.6)).toFixed(1));
+ put(boar, { x: 10 * Math.sin(t * 3), y: 40 + 3 * Math.abs(Math.sin(t * 9)), o: q });
+ cap.forEach((c, i) => { c.setAttribute('x', -60 + i * 20); c.setAttribute('y', 92 + i * 22); c.setAttribute('width', 120 - i * 40); c.setAttribute('opacity', q); });
+ }, 0, { tail: true });
+ },
+ map(g, t0) {
+ mk('rect', { x: -260, y: -155, width: 520, height: 320, fill: '#d6e6ea' }, g);
+ path(g, 'M-260 -155H120L90 -100L130 -40L60 10L100 80L20 165H-260Z', { fill: '#e8dcc0', stroke: BROWN, 'stroke-width': 3 });
+ path(g, 'M150 -60L230 -90L250 20L180 60Z', { fill: '#e8dcc0', stroke: BROWN, 'stroke-width': 3 });
+ const reg = path(g, 'M-90 -40L10 -60L40 20L-40 60L-110 20Z', { fill: TEAL, stroke: TEAL, 'stroke-width': 2 }, { o: 0 });
+ path(g, 'M-90 -40L-170 -90M10 -60L30 -155M40 20L80 80M-110 20L-200 70M-40 60L-60 165', { stroke: BROWN, 'stroke-width': 2, 'stroke-dasharray': '6 6', opacity: .6 });
+ path(g, 'M-90 -40L10 -60L40 20L-40 60L-110 20Z', { fill: 'none', stroke: BROWN, 'stroke-width': 2, opacity: .6 });
+ ['M-240 -130Q-150 -60 -100 -20T20 40T75 130', 'M-60 -150Q-40 -90 -30 -50T-20 40'].forEach((d, i) =>
+ draw(path(g, d, { stroke: DEEP, 'stroke-width': 5, fill: 'none', 'stroke-linecap': 'round' }, { d: 0 }), t0 + .1 + i * .3, 1));
+ const cur = G(g, { x: 180, y: 140, o: 0 });
+ path(cur, 'M0 0L0 34L9 25L16 40L23 37L16 22L28 22Z', { fill: INK, stroke: SHEET, 'stroke-width': 2 });
+ show(cur, t0 + .4, .3); tw(cur, { x: -40, y: 0 }, t0 + .5, .9, soft);
+ tw(cur, { s: .8 }, t0 + 1.45, .1); tw(cur, { s: 1 }, t0 + 1.55, .15);
+ show(reg, t0 + 1.5, .3);
+ },
+};
diff --git a/site/proteus/lib/fonts.css b/site/proteus/lib/fonts.css
new file mode 100644
index 0000000..6f0e95d
--- /dev/null
+++ b/site/proteus/lib/fonts.css
@@ -0,0 +1,81 @@
+/* Oswald and EB Garamond (SIL Open Font License 1.1), latin and latin-ext subsets, from Google Fonts */
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: italic;
+ font-weight: 400;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-italic-400-latin-ext.woff2) format('woff2');
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: italic;
+ font-weight: 400;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-italic-400-latin.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: normal;
+ font-weight: 400;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-normal-400-latin-ext.woff2) format('woff2');
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: normal;
+ font-weight: 400;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-normal-400-latin.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: normal;
+ font-weight: 500;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-normal-500-latin-ext.woff2) format('woff2');
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+@font-face {
+ font-family: 'EB Garamond';
+ font-style: normal;
+ font-weight: 500;
+ font-display: block;
+ src: url(../lib/fonts/EBGaramond-normal-500-latin.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+@font-face {
+ font-family: 'Oswald';
+ font-style: normal;
+ font-weight: 500;
+ font-display: block;
+ src: url(../lib/fonts/Oswald-normal-500-latin-ext.woff2) format('woff2');
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+@font-face {
+ font-family: 'Oswald';
+ font-style: normal;
+ font-weight: 500;
+ font-display: block;
+ src: url(../lib/fonts/Oswald-normal-500-latin.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
+@font-face {
+ font-family: 'Oswald';
+ font-style: normal;
+ font-weight: 600;
+ font-display: block;
+ src: url(../lib/fonts/Oswald-normal-600-latin-ext.woff2) format('woff2');
+ unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
+}
+@font-face {
+ font-family: 'Oswald';
+ font-style: normal;
+ font-weight: 600;
+ font-display: block;
+ src: url(../lib/fonts/Oswald-normal-600-latin.woff2) format('woff2');
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
+}
diff --git a/site/proteus/lib/fonts/EBGaramond-italic-400-latin-ext.woff2 b/site/proteus/lib/fonts/EBGaramond-italic-400-latin-ext.woff2
new file mode 100644
index 0000000..54a3a75
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-italic-400-latin-ext.woff2 differ
diff --git a/site/proteus/lib/fonts/EBGaramond-italic-400-latin.woff2 b/site/proteus/lib/fonts/EBGaramond-italic-400-latin.woff2
new file mode 100644
index 0000000..dbb5b42
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-italic-400-latin.woff2 differ
diff --git a/site/proteus/lib/fonts/EBGaramond-normal-400-latin-ext.woff2 b/site/proteus/lib/fonts/EBGaramond-normal-400-latin-ext.woff2
new file mode 100644
index 0000000..ac677d1
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-normal-400-latin-ext.woff2 differ
diff --git a/site/proteus/lib/fonts/EBGaramond-normal-400-latin.woff2 b/site/proteus/lib/fonts/EBGaramond-normal-400-latin.woff2
new file mode 100644
index 0000000..4971c6a
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-normal-400-latin.woff2 differ
diff --git a/site/proteus/lib/fonts/EBGaramond-normal-500-latin-ext.woff2 b/site/proteus/lib/fonts/EBGaramond-normal-500-latin-ext.woff2
new file mode 100644
index 0000000..0712a53
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-normal-500-latin-ext.woff2 differ
diff --git a/site/proteus/lib/fonts/EBGaramond-normal-500-latin.woff2 b/site/proteus/lib/fonts/EBGaramond-normal-500-latin.woff2
new file mode 100644
index 0000000..eebd0b1
Binary files /dev/null and b/site/proteus/lib/fonts/EBGaramond-normal-500-latin.woff2 differ
diff --git a/site/proteus/lib/fonts/OFL-EBGaramond.txt b/site/proteus/lib/fonts/OFL-EBGaramond.txt
new file mode 100644
index 0000000..c1ec5e1
--- /dev/null
+++ b/site/proteus/lib/fonts/OFL-EBGaramond.txt
@@ -0,0 +1,93 @@
+Copyright 2017 The EB Garamond Project Authors (https://github.com/octaviopardo/EBGaramond12)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/proteus/lib/fonts/OFL-Oswald.txt b/site/proteus/lib/fonts/OFL-Oswald.txt
new file mode 100644
index 0000000..4d4e319
--- /dev/null
+++ b/site/proteus/lib/fonts/OFL-Oswald.txt
@@ -0,0 +1,93 @@
+Copyright 2016 The Oswald Project Authors (https://github.com/googlefonts/OswaldFont)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/site/proteus/lib/fonts/Oswald-normal-500-latin-ext.woff2 b/site/proteus/lib/fonts/Oswald-normal-500-latin-ext.woff2
new file mode 100644
index 0000000..c05db68
Binary files /dev/null and b/site/proteus/lib/fonts/Oswald-normal-500-latin-ext.woff2 differ
diff --git a/site/proteus/lib/fonts/Oswald-normal-500-latin.woff2 b/site/proteus/lib/fonts/Oswald-normal-500-latin.woff2
new file mode 100644
index 0000000..371bb5e
Binary files /dev/null and b/site/proteus/lib/fonts/Oswald-normal-500-latin.woff2 differ
diff --git a/site/proteus/lib/fonts/Oswald-normal-600-latin-ext.woff2 b/site/proteus/lib/fonts/Oswald-normal-600-latin-ext.woff2
new file mode 100644
index 0000000..4e5bfd6
Binary files /dev/null and b/site/proteus/lib/fonts/Oswald-normal-600-latin-ext.woff2 differ
diff --git a/site/proteus/lib/fonts/Oswald-normal-600-latin.woff2 b/site/proteus/lib/fonts/Oswald-normal-600-latin.woff2
new file mode 100644
index 0000000..600dec1
Binary files /dev/null and b/site/proteus/lib/fonts/Oswald-normal-600-latin.woff2 differ
diff --git a/site/proteus/lib/math.js b/site/proteus/lib/math.js
new file mode 100644
index 0000000..19a26f5
--- /dev/null
+++ b/site/proteus/lib/math.js
@@ -0,0 +1,698 @@
+// Papermorph maths helpers: number lines, tiles, fractions, planes, dice, the number map, sorter.
+// A maths chapter loads this right after engine.js; it uses the engine's globals as it loads.
+'use strict';
+// Vertical number line at x; Yf maps a value to its y. Labels sit on the left.
+function vAxis(p, { x, Yf, lo, hi, step = 1, t0 = .1, unit = '' }) {
+ draw(path(p, `M${x} ${Yf(lo - .5)}V${Yf(hi + .5)}`, { stroke: COL.chalk, 'stroke-width': 3 }, { d: 0 }), t0, .8);
+ for (let v = lo; v <= hi; v += step) {
+ const g = G(p, { o: 0 });
+ path(g, `M${x - 9} ${Yf(v)}H${x + 9}`, { stroke: COL.dim, 'stroke-width': 2.5 });
+ T(g, num(v) + unit, { x: x - 46, y: Yf(v) + 9, size: 24, fill: v === 0 ? COL.chalk : COL.dim, font: MATH, anchor: 'end' });
+ show(g, t0 + .2 + Math.abs(v - lo) * .02);
+ }
+}
+// Thermometer from lo (bottom) to hi (top). set(v, t0, run) moves the column; run = tw (lesson) or fx (answer).
+function thermometer(p, { x = 800, bottom = 600, top = 200, lo = -10, hi = 15, step = 5, value = 0, color = COL.nat } = {}) {
+ const Yt = v => bottom - (v - lo) / (hi - lo) * (bottom - top), bulb = bottom + 32, g = G(p);
+ mk('rect', { x: x - 18, y: top - 24, width: 36, height: bulb - top + 24, rx: 18, fill: COL.board, stroke: COL.dim, 'stroke-width': 2.5 }, g);
+ mk('circle', { cx: x, cy: bulb, r: 26, fill: color }, g);
+ const merc = put(mk('rect', { x: x - 9, width: 18, rx: 9, fill: color }, g), { a_y: Yt(value), a_height: bulb - Yt(value) });
+ for (let v = lo; v <= hi; v += step) {
+ path(g, `M${x - 30} ${Yt(v)}H${x - 18}`, { stroke: COL.dim, 'stroke-width': 2 });
+ T(g, `${num(v)}°`, { x: x - 40, y: Yt(v) + 9, size: 24, fill: v === 0 ? COL.chalk : COL.dim, font: MATH, anchor: 'end' });
+ }
+ return { g, merc, Yt, set: (v, t0, run = tw, dur = 1.2) => run(merc, { a_y: Yt(v), a_height: bulb - Yt(v) }, t0, dur) };
+}
+/* ---------- fractions: rows with strikable parts, bars and brackets ---------- */
+// A row of fractions and symbols whose numerators and denominators can be struck out one by one.
+// items: { f: [n, d], fill } | 'symbol text'. The fraction bars sit on y.
+function fracRow(p, items, { x = 800, y = 300, size = 60, anchor = 'middle', o = 0 } = {}) {
+ const fs = size * .8, g = G(p, { o });
+ const els = items.map(it => {
+ if (typeof it === 'string') {
+ const w = textW(it, size);
+ return { w, draw(cx) { this.cx = cx; T(g, it, { x: cx, y: y + size * .33, size, font: MATH, fill: COL.chalk, anchor: 'middle' }); } };
+ }
+ const [n, d] = it.f.map(String), w = Math.max(textW(n, fs), textW(d, fs)) + size * .35, fill = it.fill || COL.chalk;
+ return { w, n, d, draw(cx) {
+ this.cx = cx;
+ path(g, `M${cx - w / 2 + 4} ${y}H${cx + w / 2 - 4}`, { stroke: fill, 'stroke-width': size * .055 });
+ this.num = T(g, n, { x: cx, y: y - size * .18, size: fs, font: MATH, fill, anchor: 'middle' });
+ this.den = T(g, d, { x: cx, y: y + size * .78, size: fs, font: MATH, fill, anchor: 'middle' });
+ } };
+ });
+ const total = els.reduce((a, e) => a + e.w, 0);
+ let cx = anchor === 'middle' ? x - total / 2 : x;
+ for (const e of els) { e.draw(cx + e.w / 2); cx += e.w; }
+ return Object.assign(els, { g, y, size, x0: anchor === 'middle' ? x - total / 2 : x, w: total });
+}
+// Strike the numerator ('num') or denominator ('den') of fraction k and write its reduced value beside it.
+function reduce(row, k, part, value, color, t0, run = tw) {
+ const e = row[k], { y, size } = row, top = part === 'num';
+ const cy = top ? y - size * .42 : y + size * .52, g = row.g;
+ const slash = path(g, `M${e.cx - size * .28} ${cy + size * .3}L${e.cx + size * .28} ${cy - size * .3}`, { stroke: color, 'stroke-width': 3.5 }, { d: 0 });
+ const nv = T(g, String(value), { x: e.cx + size * .02, y: top ? y - size * .92 : y + size * 1.36, size: size * .5, font: MATH, fill: color, anchor: 'middle', o: 0 });
+ run(slash, { d: 1 }, t0, .4); run(nv, { o: 1 }, t0 + .3, .4);
+ run(e[part], { o: .45 }, t0 + .3, .4);
+}
+function rect(p, x, y, w, h, fill, o = 0, stroke = 'none') {
+ return put(mk('rect', { x, y, width: w, height: h, fill, stroke, 'stroke-width': 2.5 }, p), { o });
+}
+function bracketH(p, x1, x2, y, label, color, t0) {
+ draw(path(p, `M${x1} ${y - 10}V${y}H${x2}V${y - 10}`, { stroke: color, 'stroke-width': 3 }, { d: 0 }), t0, .5);
+ show(T(p, label, { x: (x1 + x2) / 2, y: y + 32, size: 26, fill: color, font: MATH, anchor: 'middle', o: 0 }), t0 + .3);
+}
+
+/* ---------- decimal point that hops between digits (ch10, ch20) ---------- */
+// Digits in evenly spaced slots with a decimal point that can hop between them.
+// places = digits after the point (0 = point at the far right, hidden).
+function pointRow(p, digits, x, y, places, { size = 72, fill = COL.chalk, sign = '' } = {}) {
+ const g = G(p, { o: 0 }), w = size * .7, n = digits.length, x0 = x - n * w / 2;
+ if (sign) T(g, sign, { x: x0 - w * .6, y, size, fill, font: MATH, anchor: 'middle' });
+ const ds = [...digits].map((c, i) => T(g, c, { x: x0 + i * w + w / 2, y, size, fill, font: MATH, anchor: 'middle' }));
+ const px = k => x0 + (n - k) * w;
+ const dot = mk('circle', { r: size * .065, fill: COL.task }, g);
+ put(dot, { x: px(places), y: y - size * .02, o: places ? 1 : 0 });
+ const trail = path(g, '', { stroke: COL.task, 'stroke-width': 2.5, 'stroke-dasharray': '5 6' });
+ return { g, ds, dot, px, w,
+ hop(from, to, t0, run = tw, dur = .55) {
+ const steps = Math.abs(to - from);
+ run(dot, { o: 1 }, t0, .2);
+ let d = '';
+ for (let k = 0; k < steps; k++) {
+ const a = px(from + Math.sign(to - from) * k), b = px(from + Math.sign(to - from) * (k + 1));
+ d += `M${a} ${y - 10}Q${(a + b) / 2} ${y - size * .9} ${b} ${y - 10}`;
+ }
+ trail.setAttribute('d', d);
+ put(trail, { o: 0 }); run(trail, { o: .9 }, t0 + steps * dur, .3);
+ (run === tw ? prog : fxp)(q => {
+ const s = q * steps, k = Math.min(steps - 1, Math.floor(s)), f = s - k;
+ const a = px(from + Math.sign(to - from) * k), b = px(from + Math.sign(to - from) * (k + 1));
+ put(dot, { x: a + (b - a) * f, y: y - size * .02 - Math.sin(Math.PI * f) * size * .7 });
+ }, t0, steps * dur, lin);
+ } };
+}
+
+/* ---------- balance scale for equations (ch24, ch25) ---------- */
+// A balance scale. Its pans hang from the beam ends; tilt(deg, t0) rocks it (positive: left side down).
+function balance(p, { x = 800, y = 330, L = 300 } = {}) {
+ const g = G(p, { o: 0 });
+ path(g, `M${x} ${y}L${x - 50} ${y + 330}H${x + 50}Z`, { stroke: COL.dim, 'stroke-width': 3, fill: mix(COL.board, COL.dim, .15) });
+ const beam = G(g, { x, y });
+ path(beam, `M${-L} 0H${L}`, { stroke: COL.chalk, 'stroke-width': 6 });
+ mk('circle', { r: 10, fill: COL.chalk }, beam);
+ const pan = side => {
+ const pg = G(g, { x: x + side * L, y });
+ path(pg, 'M0 0L-90 110M0 0L90 110', { stroke: COL.dim, 'stroke-width': 2 });
+ path(pg, 'M-110 110Q0 150 110 110Z', { stroke: side < 0 ? COL.whole : COL.nat, 'stroke-width': 3, fill: mix(COL.board, side < 0 ? COL.whole : COL.nat, .2) });
+ return pg;
+ };
+ const Lp = pan(-1), Rp = pan(1);
+ let angle = 0;
+ const place = a => {
+ const r = a * Math.PI / 180, dx = L * Math.cos(r), dy = L * Math.sin(r);
+ put(beam, { r: -a }); put(Lp, { x: x - dx, y: y + dy }); put(Rp, { x: x + dx, y: y - dy });
+ };
+ return {
+ g, L: Lp, R: Rp,
+ // Content sits on a pan: text or math at (0, 90) in pan coordinates.
+ load(side, parts, color, t0, size = 44) { const e = M(side < 0 ? Lp : Rp, parts, { y: 96, size, fill: color, o: 0 }); show(e, t0); return e; },
+ tilt(a, t0, run = prog) { const from = angle; angle = a; run(q => place(from + (a - from) * back(q)), t0, .9); },
+ };
+}
+/* ---------- algebra tiles (ch23, ch25) ---------- */
+const XL = 120, UN = 30; // length of x, size of 1
+const TS = { x2: [XL, XL, COL.real], x: [UN, XL, COL.whole], y: [UN, 90, COL.nat], one: [UN, UN, COL.int] };
+function atile(p, kind, x, y, neg = false, o = 0) {
+ const [w, h, c] = TS[kind], g = G(p, { x, y, o, s: o ? 1 : .6 });
+ mk('rect', { x: -w / 2, y: -h / 2, width: w, height: h, rx: 5, fill: neg ? COL.board : mix(COL.board, c, .55), stroke: neg ? COL.bad : c, 'stroke-width': neg ? 3.5 : 2.5, 'stroke-dasharray': neg ? '7 5' : '' }, g);
+ g.kind = kind; g.neg = neg;
+ return g;
+}
+const popIn = (els, t0, step = .08) => els.forEach((e, i) => tw(e, { o: 1, s: 1 }, t0 + i * step, .35, back));
+// n tiles of a kind in a row starting at x.
+const tileRow = (p, kind, n, x, y, neg = false, gap = 12) => Array.from({ length: n }, (_, i) => atile(p, kind, x + i * (TS[kind][0] + gap), y, neg));
+// Pair each negative tile with a positive one: they move together and vanish.
+function cancel(pos, negs, t0) {
+ negs.forEach((n, i) => {
+ const a = pos[i];
+ tw(n, { x: st(a).x, y: st(a).y }, t0 + i * .3, .6);
+ tw(n, { o: 0, s: .5 }, t0 + i * .3 + .7, .3); tw(a, { o: 0, s: .5 }, t0 + i * .3 + .7, .3);
+ });
+}
+/* ---------- inequality graphs (ch26, ch27) ---------- */
+// Solution ray on the number line: endpoint v, closed or open circle, dir +1 (right) or −1 (left).
+function ray(p, v, closed, dir, t0, color = COL.task, run = tw) {
+ const end = X(dir > 0 ? 5.7 : -5.7), g = G(p, { o: 1 });
+ const line = path(g, `M${X(v)} ${Y0}H${end}`, { stroke: color, 'stroke-width': 7 }, { d: 0 });
+ const head = path(g, `M${end - 18 * dir} ${Y0 - 13}L${end} ${Y0}L${end - 18 * dir} ${Y0 + 13}`, { stroke: color, 'stroke-width': 6 }, { o: 0 });
+ const dot = G(g, { x: X(v), y: Y0, s: 0, o: 0 });
+ mk('circle', { r: 13, fill: closed ? color : COL.board, stroke: color, 'stroke-width': 4 }, dot);
+ run(dot, { s: 1, o: 1 }, t0, .4, back);
+ run(line, { d: 1 }, t0 + .3, .8); run(head, { o: 1 }, t0 + 1, .2);
+ return g;
+}
+// Segment between a and b on the number line, each end open or closed.
+function segment(p, a, b, ca, cb, t0, color = COL.task, run = tw) {
+ const g = G(p, { o: 1 });
+ const line = path(g, `M${X(a)} ${Y0}H${X(b)}`, { stroke: color, 'stroke-width': 7 }, { d: 0 });
+ const ends = [[a, ca], [b, cb]].map(([v, c]) => {
+ const d = G(g, { x: X(v), y: Y0, s: 0, o: 0 });
+ mk('circle', { r: 13, fill: c ? color : COL.board, stroke: color, 'stroke-width': 4 }, d);
+ run(d, { s: 1, o: 1 }, t0, .4, back);
+ return d;
+ });
+ run(line, { d: 1 }, t0 + .3, .8);
+ g.parentNode.appendChild(g); ends.forEach(e => g.appendChild(e));
+ return g;
+}
+/* ---------- equation steps (ch25 onward) ---------- */
+// One line of an equation or inequality with its sign at xEq, so a column of steps lines up. note: grey hint on the right.
+function eqLine(p, L, R, y, t0, { xEq = 760, fill = COL.chalk, size = 50, note, sym = '=', symFill, noteX = 1180 } = {}) {
+ const g = G(p, { o: 0 });
+ M(g, [].concat(L), { x: xEq - size * .6, y, size, fill, anchor: 'end' });
+ M(g, [sym], { x: xEq, y, size, fill: symFill || fill });
+ M(g, [].concat(R), { x: xEq + size * .6, y, size, fill, anchor: 'start' });
+ if (note) T(g, note, { x: noteX, y: y - 8, size: 26, fill: COL.task, weight: 600 });
+ show(g, t0);
+ return g;
+}
+/* ---------- data on a number line: dot plots (unit 7) ---------- */
+// Axis for data from lo to hi drawn between x0 and x1 at baseline y; every: label every n-th tick.
+// shape 'x' draws line-plot crosses instead of dots.
+// Returns D: D.V(value) -> x; D.dot(v, color, t0) stacks a dot above v; D.mark(v, color, t0, label) is a
+// balance triangle under the axis that can slide with D.slide(mark, v, t0).
+function dataLine(p, { lo, hi, x0 = 200, x1 = 1400, y = 600, step = 1, every = 1, t0 = .1, r = 13, size = 22, shape = 'dot' }) {
+ const V = v => x0 + (v - lo) / (hi - lo) * (x1 - x0), g = G(p, { o: 0 });
+ path(g, `M${x0 - 24} ${y}H${x1 + 24}`, { stroke: COL.dim, 'stroke-width': 3 });
+ for (let v = lo, i = 0; v <= hi + 1e-9; v += step, i++) {
+ path(g, `M${V(v)} ${y - 7}V${y + 7}`, { stroke: COL.dim, 'stroke-width': 2 });
+ if (i % every === 0) T(g, num(+v.toFixed(6)), { x: V(v), y: y + 26 + size, size, fill: COL.dim, font: MATH, anchor: 'middle' });
+ }
+ show(g, t0);
+ const D = {
+ g, V, y, r, count: {},
+ top: v => y - 6 - r - ((D.count[v] || 1) - 1) * (2 * r + 5),
+ dot(v, color, t0, { run = tw, into = p, from } = {}) {
+ D.count[v] = (D.count[v] || 0) + 1;
+ let d;
+ if (shape === 'x') { d = G(into); path(d, `M${-r * .75} ${-r * .75}L${r * .75} ${r * .75}M${r * .75} ${-r * .75}L${-r * .75} ${r * .75}`, { stroke: color, 'stroke-width': 5 }); }
+ else d = mk('circle', { r, fill: color, stroke: COL.board, 'stroke-width': 2 }, into);
+ put(d, { x: V(v), y: D.top(v), s: 0, o: 0 });
+ if (from !== undefined) { put(d, { y: from, s: 1 }); run(d, { o: 1 }, t0, .2); run(d, { y: D.top(v) }, t0, .7, back); }
+ else run(d, { s: 1, o: 1 }, t0, .45, back);
+ return d;
+ },
+ dots: (vals, color, t0, gap = .15, opts) => vals.map((v, i) => D.dot(v, color, t0 + i * gap, opts)),
+ mark(v, color, t0, label, { run = tw, into = p } = {}) {
+ const m = G(into, { x: V(v), y, o: 0 });
+ path(m, 'M0 4L-17 30H17Z', { fill: color, stroke: COL.board, 'stroke-width': 2 });
+ if (label) T(m, label, { y: 64 + size, size: 24, fill: color, weight: 600, anchor: 'middle' });
+ run(m, { o: 1 }, t0, .4);
+ return m;
+ },
+ slide: (m, v, t0, run = tw, dur = 1.2) => run(m, { x: V(v) }, t0, dur),
+ // Bracket above the data from a to b at height yb, with a label.
+ span(a, b, yb, label, color, t0, { run = tw, into = p } = {}) {
+ const g = G(into), l = path(g, `M${V(a)} ${yb + 12}V${yb}H${V(b)}V${yb + 12}`, { stroke: color, 'stroke-width': 3 }, { d: 0 });
+ run(l, { d: 1 }, t0, .6);
+ const t = M(g, [label], { x: (V(a) + V(b)) / 2, y: yb - 14, size: 28, fill: color, o: 0 });
+ run(t, { o: 1 }, t0 + .4, .4);
+ return g;
+ },
+ };
+ return D;
+}
+/* ---------- chance: number cubes, coins, spinners (unit 7) ---------- */
+// A number cube face showing n pips, centred on (x, y).
+const PIPS = { 1: [[0, 0]], 2: [[-1, -1], [1, 1]], 3: [[-1, -1], [0, 0], [1, 1]], 4: [[-1, -1], [1, -1], [-1, 1], [1, 1]],
+ 5: [[-1, -1], [1, -1], [0, 0], [-1, 1], [1, 1]], 6: [[-1, -1], [1, -1], [-1, 0], [1, 0], [-1, 1], [1, 1]] };
+function die(p, n, x, y, s = 96, o = 0) {
+ const g = G(p, { x, y, o, s: o ? 1 : .6 });
+ g._box = mk('rect', { x: -s / 2, y: -s / 2, width: s, height: s, rx: s * .18, fill: mix(COL.board, COL.chalk, .1), stroke: COL.chalk, 'stroke-width': 3 }, g);
+ PIPS[n].forEach(([a, b]) => mk('circle', { cx: a * s * .26, cy: b * s * .26, r: s * .085, fill: COL.chalk }, g));
+ return g;
+}
+// Spinner with equal sections; pointer starts straight up. land(k) is the rotation that points at section k.
+const SPIN = [COL.whole, COL.nat, COL.int, COL.whole, COL.irr, COL.nat, COL.whole, COL.int];
+function spinner(p, cx, cy, r, t0, cols = SPIN) {
+ const g = G(p, { x: cx, y: cy, o: 0 }), n = cols.length, secs = [];
+ cols.forEach((c, i) => {
+ const a1 = (-90 + i * 360 / n) * Math.PI / 180, a2 = (-90 + (i + 1) * 360 / n) * Math.PI / 180;
+ secs.push(path(g, `M0 0L${r * Math.cos(a1)} ${r * Math.sin(a1)}A${r} ${r} 0 0 1 ${r * Math.cos(a2)} ${r * Math.sin(a2)}Z`,
+ { fill: mix(COL.board, c, .7), stroke: COL.board, 'stroke-width': 3 }));
+ });
+ mk('circle', { r, fill: 'none', stroke: COL.chalk, 'stroke-width': 3 }, g);
+ const ptr = G(g);
+ path(ptr, `M0 ${r * .12}V${-r * .78}M-14 ${-r * .66}L0 ${-r * .8}L14 ${-r * .66}`, { stroke: COL.chalk, 'stroke-width': 7 });
+ mk('circle', { r: 12, fill: COL.chalk }, g);
+ show(g, t0);
+ return { g, secs, ptr, land: k => (k + .5) * 360 / n };
+}
+// Outline some spinner sections: a bright border that fades in.
+function outline(p, sp, ks, color, t0, run = tw) {
+ return ks.map(k => { const e = sp.secs[k].cloneNode(); e.setAttribute('fill', 'none'); e.setAttribute('stroke', color); e.setAttribute('stroke-width', 7); sp.g.insertBefore(e, sp.ptr); put(e, { o: 0 }); run(e, { o: 1 }, t0, .4); return e; });
+}
+// A coin face.
+function coin(p, side, x, y, t0, r = 34, run = tw) {
+ const g = G(p, { x, y, s: .5, o: 0 });
+ mk('circle', { r, fill: mix(COL.board, side === 'H' ? COL.int : COL.rat, .5), stroke: side === 'H' ? COL.int : COL.rat, 'stroke-width': 3 }, g);
+ T(g, side, { y: r * .36, size: r, fill: COL.chalk, weight: 700, anchor: 'middle' });
+ run(g, { s: 1, o: 1 }, t0, .45, back);
+ return g;
+}
+/* ---------- scaled axes for data and real-world graphs (ch41 onward) ---------- */
+// Axes with a scale on each; returns value -> pixel maps. ybreak draws a zigzag when y does not start at 0.
+function axes(p, { x0, y0, w, h, xs: [xlo, xhi, xst], ys: [ylo, yhi, yst], xl, yl, t0, ybreak }) {
+ const PX = v => x0 + (v - xlo) / (xhi - xlo) * w, PY = v => y0 - (v - ylo) / (yhi - ylo) * h, g = G(p, { o: 0 });
+ let d = '';
+ for (let v = xlo + xst; v <= xhi + 1e-9; v += xst) d += `M${PX(v)} ${y0}V${y0 - h}`;
+ for (let v = ylo + yst; v <= yhi + 1e-9; v += yst) d += `M${x0} ${PY(v)}H${x0 + w}`;
+ mk('path', { d, stroke: COL.chalk, 'stroke-opacity': .1, 'stroke-width': 1.5, fill: 'none' }, g);
+ path(g, `M${x0} ${y0 - h - 20}V${y0}H${x0 + w + 20}`, { stroke: COL.chalk, 'stroke-width': 3 });
+ if (ybreak) path(g, `M${x0 - 10} ${y0 - 22}L${x0 + 10} ${y0 - 30}M${x0 - 10} ${y0 - 34}L${x0 + 10} ${y0 - 42}`, { stroke: COL.chalk, 'stroke-width': 3 });
+ for (let v = xlo; v <= xhi + 1e-9; v += xst) T(g, String(v), { x: PX(v), y: y0 + 30, size: 20, fill: COL.dim, font: MATH, anchor: 'middle' });
+ for (let v = ylo; v <= yhi + 1e-9; v += yst) T(g, String(v), { x: x0 - 14, y: PY(v) + 7, size: 20, fill: COL.dim, font: MATH, anchor: 'end' });
+ T(g, xl, { x: x0 + w / 2, y: y0 + 66, size: 24, fill: COL.dim, anchor: 'middle' });
+ T(g, yl, { x: x0, y: y0 - h - 36, size: 24, fill: COL.dim, anchor: 'middle' });
+ show(g, t0);
+ return { PX, PY };
+}
+/* ---------- area grids for multiplying and factoring polynomials (ch51 onward) ---------- */
+// Area grid from (x0, y0): column widths ws, row heights hs, factor terms along the top and the left side.
+function areaGrid(p, x0, y0, ws, hs, colLab, rowLab, t0, { size = 40 } = {}) {
+ const xs = [x0], ys = [y0];
+ ws.forEach(w => xs.push(xs.at(-1) + w)); hs.forEach(h => ys.push(ys.at(-1) + h));
+ let d = '';
+ xs.forEach(x => { d += `M${x} ${y0}V${ys.at(-1)}`; }); ys.forEach(y => { d += `M${x0} ${y}H${xs.at(-1)}`; });
+ draw(path(p, d, { stroke: COL.chalk, 'stroke-width': 3 }, { d: 0 }), t0, .9);
+ colLab.forEach((l, j) => show(M(p, [].concat(l), { x: (xs[j] + xs[j + 1]) / 2, y: y0 - 22, size, fill: COL.whole, o: 0 }), t0 + .3 + j * .15));
+ rowLab.forEach((l, i) => show(M(p, [].concat(l), { x: x0 - 24, y: (ys[i] + ys[i + 1]) / 2 + size * .35, size, fill: COL.nat, anchor: 'end', o: 0 }), t0 + .3 + i * .15));
+ const box = (i, j, pad) => ({ x: xs[j] + pad, y: ys[i] + pad, width: xs[j + 1] - xs[j] - 2 * pad, height: ys[i + 1] - ys[i] - 2 * pad });
+ return {
+ xs, ys,
+ cell(i, j, parts, t0, { fill = COL.chalk, tint, run = tw, into = p } = {}) {
+ if (tint) { const r = put(mk('rect', { ...box(i, j, 3), fill: tint }, into), { o: 0 }); into.insertBefore(r, into.firstChild); run(r, { o: .3 }, t0, .4); }
+ const e = M(into, [].concat(parts), { x: (xs[j] + xs[j + 1]) / 2, y: (ys[i] + ys[i + 1]) / 2 + size * .35, size, fill, o: 0, s: .6 });
+ run(e, { o: 1, s: 1 }, t0, .4, back);
+ return e;
+ },
+ ring(i, j, color, t0, run = tw, into = p) { const r = put(mk('rect', { ...box(i, j, 8), rx: 12, fill: 'none', stroke: color, 'stroke-width': 4.5 }, into), { o: 0 }); run(r, { o: 1 }, t0, .3); return r; },
+ };
+}
+// A curved arrow from (x1, y1) to (x2, y2) bending up (h < 0) or down (h > 0).
+function arc(p, x1, y1, x2, y2, h, color, t0, run = tw) {
+ const mx = (x1 + x2) / 2, l = path(p, `M${x1} ${y1}Q${mx} ${y1 + h} ${x2} ${y2}`, { stroke: color, 'stroke-width': 3.5 }, { d: 0 });
+ run(l, { d: 1 }, t0, .5);
+ return l;
+}
+
+/* ---------- built-up fractions with math above and below the bar (ch60 onward) ---------- */
+// Width of math parts at a size, without leaving anything on the stage.
+function mathW(parts, size) { const e = M(scene, [].concat(parts), { size, o: 0 }), w = e._w; e.remove(); return w; }
+// A built-up fraction whose top and bottom are math parts (they may hold radicals); bar on y. Returns { g, w, t, b, x0 }.
+function frac(p, top, bot, x, y, t0, { size = 56, fill = COL.chalk, anchor = 'start', topFill, botFill } = {}) {
+ const g = G(p, { o: 0 });
+ const w = Math.max(mathW(top, size), mathW(bot, size)) + size * .3;
+ const x0 = anchor === 'middle' ? x - w / 2 : x;
+ const t = M(g, [].concat(top), { x: x0 + w / 2, y: y - size * .25, size, fill: topFill || fill });
+ const b = M(g, [].concat(bot), { x: x0 + w / 2, y: y + size * 1.05, size, fill: botFill || fill });
+ path(g, `M${x0} ${y}H${x0 + w}`, { stroke: fill, 'stroke-width': size * .05 });
+ if (t0 !== undefined) show(g, t0);
+ return { g, w, t, b, x0 };
+}
+
+/* ---------- coordinate plane (unit 6 onward) ---------- */
+// Grid centred on the origin at (cx, cy); u pixels per unit; x from x0 to x1, y from y0 to y1.
+// Returns { g, PX, PY, u, ... } with helpers to plot points, walk to a point, and draw lines.
+// The grid stays in p; marks go into P.layer (set it to the current panel so marks clear with the step) or opts.into.
+function plane(p, { cx = 800, cy = 450, u = 50, x0 = -6, x1 = 6, y0 = -6, y1 = 6, t0 = .1, labels = true, step = 1 } = {}) {
+ const PX = x => cx + x * u, PY = y => cy - y * u, g = G(p, { o: 0 });
+ let d = '';
+ for (let x = x0; x <= x1; x++) if (x) d += `M${PX(x)} ${PY(y0)}V${PY(y1)}`;
+ for (let y = y0; y <= y1; y++) if (y) d += `M${PX(x0)} ${PY(y)}H${PX(x1)}`;
+ mk('path', { d, stroke: COL.chalk, 'stroke-opacity': .1, 'stroke-width': 1.5, fill: 'none' }, g);
+ const ax = { stroke: COL.chalk, 'stroke-width': 3 };
+ path(g, `M${PX(x0 - .5)} ${cy}H${PX(x1 + .5)}M${PX(x1 + .5) - 14} ${cy - 9}L${PX(x1 + .5)} ${cy}L${PX(x1 + .5) - 14} ${cy + 9}`, ax);
+ path(g, `M${cx} ${PY(y0 - .5)}V${PY(y1 + .5)}M${cx - 9} ${PY(y1 + .5) + 14}L${cx} ${PY(y1 + .5)}L${cx + 9} ${PY(y1 + .5) + 14}`, ax);
+ T(g, 'x', { x: PX(x1 + .5) + 10, y: cy + 30, size: 28, fill: COL.dim, font: MATH, anchor: 'middle' }).setAttribute('font-style', 'italic');
+ T(g, 'y', { x: cx - 26, y: PY(y1 + .5) + 10, size: 28, fill: COL.dim, font: MATH, anchor: 'middle' }).setAttribute('font-style', 'italic');
+ if (labels) {
+ for (let x = x0; x <= x1; x += step) if (x) T(g, num(x), { x: PX(x), y: cy + 26, size: 18, fill: COL.dim, font: MATH, anchor: 'middle' });
+ for (let y = y0; y <= y1; y += step) if (y) T(g, num(y), { x: cx - 12, y: PY(y) + 6, size: 18, fill: COL.dim, font: MATH, anchor: 'end' });
+ }
+ show(g, t0, .5);
+ const P = {
+ g, PX, PY, u, cx, cy, x0, x1, y0, y1, layer: null,
+ dot(x, y, color, t0, { r = 10, label, run = tw, dx = 14, dy = -14, anchor = 'start', into = P.layer || p, open = false } = {}) {
+ const d = G(into, { x: PX(x), y: PY(y), s: 0, o: 0 });
+ mk('circle', open ? { r, fill: COL.board, stroke: color, 'stroke-width': 3.5 } : { r, fill: color, stroke: COL.board, 'stroke-width': 2 }, d);
+ run(d, { s: 1, o: 1 }, t0, .4, back);
+ if (label) { const l = M(into, [label], { x: PX(x) + dx, y: PY(y) + dy, size: 26, fill: color, anchor, o: 0 }); run(l, { o: 1 }, t0 + .2, .3); }
+ return d;
+ },
+ // Walk from the origin: along x, then along y, drawing arrows; then a dot.
+ walk(x, y, t0, { cx: colX = COL.whole, cy: colY = COL.nat, run = tw, color = COL.task, label, into = P.layer || p } = {}) {
+ const a = path(into, `M${PX(0)} ${PY(0)}H${PX(x)}`, { stroke: colX, 'stroke-width': 5 }, { d: 0 });
+ const b = path(into, `M${PX(x)} ${PY(0)}V${PY(y)}`, { stroke: colY, 'stroke-width': 5 }, { d: 0 });
+ run(a, { d: 1 }, t0, .3 + Math.abs(x) * .12, lin);
+ run(b, { d: 1 }, t0 + .4 + Math.abs(x) * .12, .3 + Math.abs(y) * .12, lin);
+ return P.dot(x, y, color, t0 + .8 + (Math.abs(x) + Math.abs(y)) * .12, { run, label, into });
+ },
+ // Arrow from (xa, ya) to (xb, yb) with an optional label beside its middle.
+ arrow(xa, ya, xb, yb, color, t0, { label, run = tw, into = P.layer || p } = {}) {
+ const a = [PX(xa), PY(ya)], b = [PX(xb), PY(yb)], L = Math.hypot(b[0] - a[0], b[1] - a[1]), ux = (b[0] - a[0]) / L, uy = (b[1] - a[1]) / L;
+ const l = path(into, `M${a[0]} ${a[1]}L${b[0]} ${b[1]}M${b[0] - 12 * ux - 8 * uy} ${b[1] - 12 * uy + 8 * ux}L${b[0]} ${b[1]}L${b[0] - 12 * ux + 8 * uy} ${b[1] - 12 * uy - 8 * ux}`, { stroke: color, 'stroke-width': 4 }, { d: 0 });
+ run(l, { d: 1 }, t0, .5);
+ if (label !== undefined) {
+ const vert = Math.abs(uy) > Math.abs(ux);
+ const t = M(into, [label], { x: (a[0] + b[0]) / 2 + (vert ? -24 : 0), y: (a[1] + b[1]) / 2 + (vert ? 9 : -12), size: 26, fill: color, anchor: vert ? 'end' : 'middle', o: 0 });
+ run(t, { o: 1 }, t0 + .3, .3);
+ }
+ return l;
+ },
+ // One slope step from (x, y): rise first (irr green), then run (real violet).
+ stair(x, y, rise, runX, t0, { run = tw, into = P.layer || p, labels = true } = {}) {
+ P.arrow(x, y, x, y + rise, COL.irr, t0, { label: labels ? num(rise) : undefined, run, into });
+ P.arrow(x, y + rise, x + runX, y + rise, COL.real, t0 + .6, { label: labels ? num(runX) : undefined, run, into });
+ },
+ // Shade the region where every a·x + b·y ≥ c in the list holds, clipped to the grid.
+ region(list, color, t0, { run = tw, into = P.layer || p, o = .22 } = {}) {
+ let pts = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
+ for (const [a, b, c] of list) {
+ const f = ([x, y]) => a * x + b * y - c, next = [];
+ pts.forEach((v, i) => {
+ const w = pts[(i + 1) % pts.length], fv = f(v), fw = f(w);
+ if (fv >= 0) next.push(v);
+ if (fv * fw < 0) { const t = fv / (fv - fw); next.push([v[0] + t * (w[0] - v[0]), v[1] + t * (w[1] - v[1])]); }
+ });
+ pts = next;
+ }
+ const e = path(into, pts.length ? 'M' + pts.map(([x, y]) => `${PX(x)} ${PY(y)}`).join('L') + 'Z' : '', { fill: color, stroke: 'none' }, { o: 0 });
+ into.insertBefore(e, into.firstChild);
+ run(e, { o }, t0, .6);
+ return e;
+ },
+ half: (a, b, c, color, t0, opts) => P.region([[a, b, c]], color, t0, opts),
+ // Graph of y = f(x) for x from xa to xb, drawn on; the part outside the grid's y range is cut off.
+ fn(f, xa, xb, color, t0, { run = tw, w = 4, into = P.layer || p, n = 160, dur = 1.2 } = {}) {
+ let d = '', pen = false;
+ for (let i = 0; i <= n; i++) {
+ const x = xa + (xb - xa) * i / n, y = f(x), inside = y >= y0 - .5 && y <= y1 + .5;
+ if (inside) { d += `${pen ? 'L' : 'M'}${PX(x).toFixed(1)} ${PY(y).toFixed(1)}`; pen = true; } else pen = false;
+ }
+ const l = path(into, d, { stroke: color, 'stroke-width': w }, { d: 0 });
+ run(l, { d: 1 }, t0, dur);
+ return l;
+ },
+ // Line through two points, extended to the edge of the grid.
+ line(xa, ya, xb, yb, color, t0, { run = tw, w = 4, dash, into = P.layer || p } = {}) {
+ const dx = xb - xa, dy = yb - ya, ts = [];
+ const clip = (t, v, lo, hi) => { if (v >= lo - 1e-9 && v <= hi + 1e-9) ts.push(t); };
+ if (dx) { for (const X of [x0, x1]) { const t = (X - xa) / dx; clip(t, ya + t * dy, y0, y1); } }
+ if (dy) { for (const Y of [y0, y1]) { const t = (Y - ya) / dy; clip(t, xa + t * dx, x0, x1); } }
+ const t1 = Math.min(...ts), t2 = Math.max(...ts);
+ // A dashed line fades in: drawing it on would need the dash array for the reveal.
+ const l = path(into, `M${PX(xa + t1 * dx)} ${PY(ya + t1 * dy)}L${PX(xa + t2 * dx)} ${PY(ya + t2 * dy)}`, { stroke: color, 'stroke-width': w, ...(dash ? { 'stroke-dasharray': dash } : {}) }, dash ? { o: 0 } : { d: 0 });
+ run(l, dash ? { o: 1 } : { d: 1 }, t0, dash ? .6 : 1);
+ return l;
+ },
+ };
+ return P;
+}
+// Question: pick a grid point. ans = [x, y]; no(x, y) explains a wrong pick. Arrows move a cursor, Enter picks.
+// test(x, y), when given, accepts any point it approves; ans is then the point Show answer uses.
+const pickPoint = (P, ans, yes, no, onRight, test) => (body, api) => {
+ const L = qlayer();
+ let cur = [0, 0], locked = false;
+ const cursor = G(L, { x: P.PX(0), y: P.PY(0) });
+ mk('circle', { r: 16, fill: 'none', stroke: COL.task, 'stroke-width': 3 }, cursor);
+ let tag = null;
+ const moveTo = (x, y) => {
+ cur = [Math.max(P.x0, Math.min(P.x1, x)), Math.max(P.y0, Math.min(P.y1, y))];
+ put(cursor, { x: P.PX(cur[0]), y: P.PY(cur[1]) });
+ tag?.remove();
+ tag = M(L, [`(${num(cur[0])}, ${num(cur[1])})`], { x: P.PX(cur[0]) + 22, y: P.PY(cur[1]) - 18, size: 24, fill: COL.task, anchor: 'start' });
+ };
+ moveTo(0, 0);
+ const pick = () => {
+ if (locked) return;
+ const [x, y] = cur;
+ if (test ? test(x, y) : x === ans[0] && y === ans[1]) { P.dot(x, y, COL.good, 0, { run: fx, into: L }); onRight?.(); api.grade(true, typeof yes === 'function' ? yes(x, y) : yes); }
+ else { const d = P.dot(x, y, COL.bad, 0, { run: fx, r: 8, into: L }); fx(d, { o: 0 }, 1.2, .4); shakeFx(cursor); api.grade(false, no(x, y)); }
+ };
+ const hit = mk('rect', { x: P.PX(P.x0 - .5), y: P.PY(P.y1 + .5), width: (P.x1 - P.x0 + 1) * P.u, height: (P.y1 - P.y0 + 1) * P.u, fill: 'transparent' }, L);
+ L.insertBefore(hit, L.firstChild);
+ hit.style.cursor = 'crosshair';
+ hit.addEventListener('click', e => {
+ if (locked) return;
+ const s = $('stage'), pt = s.createSVGPoint(); pt.x = e.clientX; pt.y = e.clientY;
+ const q = pt.matrixTransform(s.getScreenCTM().inverse());
+ moveTo(Math.round((q.x - P.cx) / P.u), Math.round((P.cy - q.y) / P.u));
+ pick();
+ });
+ return {
+ reveal() { moveTo(...ans); P.dot(ans[0], ans[1], COL.good, 0, { run: fx, into: L }); onRight?.(); return typeof yes === 'function' ? yes(...ans) : yes; },
+ lock() { locked = true; },
+ hint: [kbd('←'), kbd('↑'), kbd('↓'), kbd('→'), translate('hintMove'), kbd('Enter'), translate('hintChooseOrClickGrid')],
+ key(e) {
+ if (locked) return false;
+ const d = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] }[e.key];
+ if (d) { moveTo(cur[0] + d[0], cur[1] + d[1]); return true; }
+ if (e.key === 'Enter') { pick(); return true; }
+ return false;
+ },
+ };
+};
+/* ---------- signed numbers: number-line moves and plus/minus tiles ---------- */
+const POS = COL.whole, NEG = COL.nat; // positive: blue, negative: coral
+// Integer number line from lo to hi with arrows at both ends, drawn into S.line.
+function numberLine(t0 = .1, lo = -8, hi = 8) {
+ const L = S.line;
+ draw(path(L, `M${X(lo - .7)} ${Y0}H${X(hi + .7)}`, { stroke: COL.chalk, 'stroke-width': 3 }, { d: 0 }), t0, .8);
+ for (const [x, d] of [[X(hi + .7), 1], [X(lo - .7), -1]]) {
+ show(path(L, `M${x - 15 * d} ${Y0 - 10}L${x} ${Y0}L${x - 15 * d} ${Y0 + 10}`, { stroke: COL.chalk, 'stroke-width': 3 }, { o: 0 }), t0 + .7, .3);
+ }
+ for (let v = lo; v <= hi; v++) show(tick(v), t0 + .2 + Math.abs(v) * .04, .4);
+}
+// A move along the number line from a to b, drawn as an arrow at height y. run = tw (lesson) or fx (answer).
+function move(p, a, b, y, t0, run = tw) {
+ const x1 = X(a), x2 = X(b), d = Math.sign(b - a), color = d > 0 ? POS : NEG;
+ const dur = .35 + Math.abs(b - a) * .09;
+ const line = path(p, `M${x1} ${y}H${x2}`, { stroke: color, 'stroke-width': 5 }, { d: 0 });
+ const head = path(p, `M${x2 - 15 * d} ${y - 11}L${x2} ${y}L${x2 - 15 * d} ${y + 11}`, { stroke: color, 'stroke-width': 5 }, { o: 0 });
+ const lab = T(p, (d > 0 ? '+' : '−') + Math.abs(b - a), { x: (x1 + x2) / 2, y: y - 16, size: 28, fill: color, font: MATH, anchor: 'middle', o: 0 });
+ const drop = path(p, `M${x2} ${y + 12}V${Y0 - 14}`, { stroke: color, 'stroke-width': 2, 'stroke-dasharray': '5 6' }, { o: 0 });
+ run(line, { d: 1 }, t0, dur, lin); run(head, { o: 1 }, t0 + dur - .1, .15);
+ run(lab, { o: 1 }, t0 + .2, .3); run(drop, { o: .8 }, t0 + dur, .3);
+}
+function landDot(p, v, t0, color = COL.chalk, run = tw) {
+ const g = G(p, { x: X(v), y: Y0, s: 0, o: 0 });
+ mk('circle', { r: 12, fill: color, stroke: COL.board, 'stroke-width': 2 }, g);
+ run(g, { s: 1, o: 1 }, t0, .45, back);
+ return g;
+}
+function tile(p, sign, x, y, o = 0) {
+ const c = sign > 0 ? POS : NEG, g = G(p, { x, y, o, s: o ? 1 : .6 });
+ mk('rect', { x: -27, y: -27, width: 54, height: 54, rx: 10, fill: mix(COL.board, c, .45), stroke: c, 'stroke-width': 2.5 }, g);
+ M(g, [sign > 0 ? '+' : '−'], { y: 13, size: 40 });
+ return g;
+}
+const tiles = (p, n, sign, x0, y, gap = 70) => Array.from({ length: n }, (_, i) => tile(p, sign, x0 + i * gap, y));
+const popAll = (els, t0, step = .08) => els.forEach((e, i) => tw(e, { o: 1, s: 1 }, t0 + i * step, .35, back));
+// Circle each plus/minus pair, then let the pairs vanish: they make zero.
+function cancelPairs(p, tops, bottoms, t0) {
+ tops.forEach((a, i) => {
+ const b = bottoms[i], x = st(a).x, y1 = st(a).y, y2 = st(b).y;
+ const ring = put(mk('rect', { rx: 18, fill: 'none', stroke: COL.dim, 'stroke-width': 2.5, 'stroke-dasharray': '8 6' }, p),
+ { o: 0, a_x: x - 38, a_y: y1 - 38, a_width: 76, a_height: y2 - y1 + 76 });
+ tw(ring, { o: 1 }, t0 + i * .2, .3);
+ for (const e of [a, b, ring]) tw(e, { o: 0, ...(e === ring ? {} : { s: .5 }) }, t0 + 1.4 + i * .1, .4);
+ });
+}
+function brace(p, a, b, y, label, color, t0) {
+ const x1 = X(a), x2 = X(b);
+ draw(path(p, `M${x1} ${y - 10}V${y}H${x2}V${y - 10}`, { stroke: color, 'stroke-width': 3 }, { d: 0 }), t0, .6);
+ show(T(p, label, { x: (x1 + x2) / 2, y: y + 34, size: 26, fill: color, anchor: 'middle', o: 0 }), t0 + .4);
+}
+
+/* ---------- number map geometry ---------- */
+const RINGS = {
+ real: { cx: 640, cy: 470, rx: 610, ry: 390, lx: 640, ly: 128 },
+ rat: { cx: 500, cy: 480, rx: 400, ry: 320, lx: 500, ly: 202 },
+ int: { cx: 500, cy: 510, rx: 300, ry: 250, lx: 500, ly: 302 },
+ whole: { cx: 500, cy: 540, rx: 210, ry: 180, lx: 500, ly: 400 },
+ nat: { cx: 500, cy: 570, rx: 125, ry: 110, lx: 500, ly: 500 },
+ irr: { cx: 1060, cy: 480, rx: 140, ry: 170, lx: 1060, ly: 360 },
+};
+const CHAIN = { nat: ['nat', 'whole', 'int', 'rat', 'real'], whole: ['whole', 'int', 'rat', 'real'], int: ['int', 'rat', 'real'], rat: ['rat', 'real'], irr: ['irr', 'real'], real: ['real'] };
+const ell = r => `M${r.cx} ${r.cy - r.ry}A${r.rx} ${r.ry} 0 1 1 ${r.cx} ${r.cy + r.ry}A${r.rx} ${r.ry} 0 1 1 ${r.cx} ${r.cy - r.ry}`;
+const inRing = (k, x, y) => { const r = RINGS[k]; return ((x - r.cx) / r.rx) ** 2 + ((y - r.cy) / r.ry) ** 2 <= 1; };
+function regionAt(x, y) {
+ for (const k of ['nat', 'whole', 'int', 'rat', 'irr', 'real']) if (inRing(k, x, y)) return k;
+ return null;
+}
+function buildVenn(parent, hidden) {
+ const out = {};
+ for (const k of ['real', 'rat', 'int', 'whole', 'nat', 'irr']) {
+ const r = RINGS[k], g = G(parent);
+ const fill = path(g, ell(r), { fill: mix(COL.board, COL[k], k === 'real' ? .1 : .16), stroke: 'none' }, { o: hidden ? 0 : 1 });
+ const stroke = path(g, ell(r), { stroke: COL[k], 'stroke-width': 3 }, hidden ? { d: 0, 'a_stroke-width': 3 } : { 'a_stroke-width': 3 });
+ const lab = T(g, NAME[k], { x: r.lx, y: r.ly, size: 26, fill: COL[k], weight: 600, anchor: 'middle', o: hidden ? 0 : 1 });
+ out[k] = { g, fill, stroke, lab };
+ }
+ return out;
+}
+function glow(key, t0) {
+ const s = S.ring[key].stroke;
+ tw(s, { 'a_stroke-width': 9 }, t0, .22, out); tw(s, { 'a_stroke-width': 3 }, t0 + .25, .5);
+}
+function glowRun(key, t0) { CHAIN[key].forEach((k, i) => glow(k, t0 + i * .3)); }
+const glowFx = (key, delay = 0) => CHAIN[key].forEach((k, i) => {
+ const s = S.ring[k].stroke;
+ fx(s, { 'a_stroke-width': 9 }, delay + i * .28, .22, out); fx(s, { 'a_stroke-width': 3 }, delay + i * .28 + .25, .5);
+});
+function popDotFx(key, v, label) {
+ const L = S.q || qlayer();
+ const g = G(L, { x: X(v), y: Y0, s: 0, o: 0 });
+ mk('circle', { r: 7, fill: COL[key], stroke: COL.board, 'stroke-width': 2 }, g);
+ fx(g, { s: 1, o: 1 }, 0, .45, back);
+ if (label) fx(M(L, label, { x: X(v) + 10, y: Y0 + 56, size: 28, fill: COL[key], o: 0 }), { o: 1 }, .3, .4);
+}
+function hopsFx(n) {
+ for (let k = 1; k <= -n; k++) {
+ const a = X(1 - k), b = X(-k);
+ fx(path(S.q, `M${a} ${Y0 - 12}Q${(a + b) / 2} ${Y0 - 84} ${b} ${Y0 - 12}`, { stroke: COL.int, 'stroke-width': 3 }, { d: 0 }), { d: 1 }, (k - 1) * .35, .35, lin);
+ }
+ floatText(translate('stepsLeftOfZero', { n: -n }), X(n / 2), Y0 - 100, COL.int);
+}
+const FAMILIES = ['nat', 'whole', 'int', 'rat', 'irr', 'real'];
+const FAM_COLS = FAMILIES.map(k => [k, k === 'int' ? translate('integerColumn') : NAME[k], COL[k]]);
+const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
+// Drag number chips into the stage number map. items: [parts, smallest ring, explanation].
+const slot = (k, n) => {
+ if (k === 'real') return [[940, 210], [1000, 760], [820, 800]][n % 3]; // inside Real, outside every other ring
+ const r = RINGS[k];
+ return [r.lx + [-72, 72, 0][n % 3], r.ly + 50 + 56 * Math.floor(n / 2)];
+};
+const plain = parts => parts.map(p => typeof p === 'string' ? p : p.ov !== undefined ? p.ov + ' repeating' : p.tex !== undefined ? p.tex : p.f ? p.f.join('/') : p.sup !== undefined ? '^' + p.sup : (p.i ? p.i : '') + '√' + (p.r.f ? p.r.f.join('/') : p.r)).join('');
+const sorter = (items, trayXY) => (body, api) => {
+ const L = qlayer();
+ const bg = mk('rect', { width: 1600, height: 900, fill: 'transparent' }, L);
+ const svg = $('stage');
+ const pt = e => { const p = svg.createSVGPoint(); p.x = e.clientX; p.y = e.clientY; return p.matrixTransform(svg.getScreenCTM().inverse()); };
+ let sel = null, drag = null, locked = false;
+ const label = c => c.setAttribute('aria-label', c.region ? translate('chipPlaced', { x: c.say, ring: NAME[c.region] }) : translate('chipNotPlaced', { x: c.say }));
+ const outline = (c, colr, w = 2.5) => { c._rect.setAttribute('stroke', colr); c._rect.setAttribute('stroke-width', w); };
+ const choose = c => {
+ if (sel) outline(sel, COL.chalk);
+ sel = c;
+ if (sel) { outline(sel, COL.task, 4); L.append(sel); }
+ };
+ const select = c => choose(sel === c ? null : c);
+ // Number badges next to the ring names, for keys 1–6.
+ RING_KEYS.forEach((k, i) => {
+ const r = RINGS[k], g = G(L, { x: r.lx - uiW(NAME[k], 26) / 2 - 24, y: r.ly - 9 });
+ g.style.pointerEvents = 'none';
+ mk('circle', { r: 14, fill: COL.board, stroke: COL[k], 'stroke-width': 1.5 }, g);
+ T(g, String(i + 1), { y: 6.5, size: 18, fill: COL[k], anchor: 'middle', weight: 600 });
+ });
+ const place = (c, x, y) => {
+ c.region = regionAt(x, y);
+ if (!c.region) [x, y] = c.home;
+ put(c, { x, y });
+ outline(c, COL.chalk);
+ c.querySelector('.mark')?.remove();
+ if (sel === c) sel = null;
+ label(c);
+ };
+ const chips = items.map(([parts, answer, why], i) => {
+ const [x, y] = trayXY(i);
+ const c = chip(L, parts, COL.chalk, { x, y, size: 32 });
+ Object.assign(c, { answer, why, home: [x, y], region: null, say: plain(parts) });
+ c.classList.add('tok');
+ c.setAttribute('tabindex', 0);
+ c.setAttribute('role', 'button');
+ label(c);
+ c.addEventListener('pointerdown', e => {
+ if (locked) return;
+ e.preventDefault();
+ const p = pt(e);
+ drag = { dx: p.x - st(c).x, dy: p.y - st(c).y, sx: p.x, sy: p.y, moved: false };
+ L.append(c); // re-parent before capturing: moving a node drops its capture
+ c.setPointerCapture(e.pointerId);
+ });
+ c.addEventListener('pointermove', e => {
+ if (!drag) return;
+ const p = pt(e);
+ if (Math.hypot(p.x - drag.sx, p.y - drag.sy) > 6) drag.moved = true;
+ if (drag.moved) put(c, { x: p.x - drag.dx, y: p.y - drag.dy });
+ });
+ c.addEventListener('pointerup', () => {
+ if (!drag) return;
+ const moved = drag.moved;
+ drag = null;
+ if (moved) place(c, st(c).x, st(c).y); else select(c);
+ });
+ // A cancelled drag (a system gesture, a lost capture) drops the chip where it is instead of leaving it stuck to no pointer.
+ c.addEventListener('lostpointercapture', () => {
+ if (!drag) return;
+ const moved = drag.moved;
+ drag = null;
+ if (moved) place(c, st(c).x, st(c).y);
+ });
+ keyAct(c, () => { if (!locked) select(c); });
+ return c;
+ });
+ bg.addEventListener('pointerup', e => { if (sel && !locked) { const p = pt(e); place(sel, p.x, p.y); } });
+ return {
+ check() {
+ let right = 0;
+ const notes = h('ul');
+ for (const c of chips) {
+ c.querySelector('.mark')?.remove();
+ if (!c.region) { notes.append(h('li', '', translate('notPlacedYet', { x: c.say }))); continue; }
+ const ok = c.region === c.answer;
+ right += ok;
+ outline(c, ok ? COL.good : COL.bad, 4);
+ if (ok) { pulseFx(c, 1.25); glowFx(c.answer, right * .15); } else shakeFx(c);
+ const w = +c._rect.getAttribute('width');
+ T(c, ok ? '✓' : '✗', { x: w / 2 + 4, y: -16, size: 26, fill: ok ? COL.good : COL.bad, weight: 700 }).classList.add('mark');
+ if (!ok) notes.append(h('li', '', c.region === 'real'
+ ? translate('realRingIsEmpty', { x: c.say })
+ : c.why));
+ }
+ const all = right === chips.length;
+ api.grade(all, all ? [] : [translate('ringsRight', { r: right, n: chips.length }), notes], { right, total: chips.length });
+ },
+ reveal() {
+ const count = {};
+ chips.forEach((c, i) => {
+ const n = count[c.answer] = (count[c.answer] ?? -1) + 1;
+ const [x, y] = slot(c.answer, n);
+ c.region = c.answer;
+ c.querySelector('.mark')?.remove();
+ outline(c, COL.good, 4);
+ fx(c, { x, y }, i * .12, .8);
+ });
+ return translate('ringsShown');
+ },
+ lock() { locked = true; choose(null); },
+ hint: [kbd('←'), kbd('→'), translate('hintPickNumber'), kbd('1'), '–', kbd('6'), translate('hintPickRing')],
+ key(e) {
+ if (locked) return false;
+ const d = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;
+ if (d) {
+ const i = sel ? chips.indexOf(sel) : d > 0 ? -1 : 0;
+ choose(chips[(i + d + chips.length) % chips.length]);
+ return true;
+ }
+ const ring = RING_KEYS[+e.key - 1];
+ if (!ring || !sel) return false;
+ const c = sel;
+ place(c, ...slot(ring, chips.filter(x => x.region === ring && x !== c).length));
+ choose(chips.find(x => !x.region) || null);
+ return true;
+ },
+ };
+};
diff --git a/site/proteus/lib/units.css b/site/proteus/lib/units.css
new file mode 100644
index 0000000..e9c62cb
--- /dev/null
+++ b/site/proteus/lib/units.css
@@ -0,0 +1,79 @@
+/* The unit headers of a book's contents page, the same in every book: a strip of chalkboard per unit, with the unit's
+ label and title and a sketch of its ideas (UNIT_ART, from the book's own unit-art.js) drawn in the unit colour --c.
+ Markup and the scroll observer are in units.js. Uses the contents page's --book, --ui, --chalk and --ease. */
+.unit { position: relative; max-width: 1212px; margin: 0 auto; padding: 28px 16px 0; }
+.unit h2 { position: relative; display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 14px; min-height: 168px; margin: 0 0 16px; padding-top: 130px; font: 500 28px/1.2 var(--book); }
+.unit .grid { position: relative; }
+.unit::before { content: ""; position: absolute; inset: 0 16px auto; height: 208px; border-radius: 22px; pointer-events: none;
+ background: radial-gradient(ellipse 46% 90% at 74% 55%, color-mix(in srgb, var(--c) 11%, transparent), transparent 70%); }
+.unit-art { position: absolute; top: 20px; right: 28px; width: min(580px, 56%); height: auto; overflow: visible; pointer-events: none;
+ color: var(--c); fill: none; stroke: currentColor; stroke-width: 2.6; stroke-linecap: round; stroke-linejoin: round; opacity: .78; }
+.unit-art text { fill: currentColor; stroke: none; font-family: var(--book); font-style: italic; }
+.unit-art .a { color: var(--chalk); opacity: .55; }
+.unit-art .faint { opacity: .22; }
+.unit-art .d { stroke-dasharray: 1 1; stroke-dashoffset: 1; }
+.unit-art .t { opacity: 0; }
+.seen .unit-art .d { animation: art-draw 1.1s cubic-bezier(.5, 0, .3, 1) forwards; animation-delay: calc(var(--k) * 55ms + 120ms); }
+.seen .unit-art .t { animation: art-fade .6s ease-out forwards; animation-delay: calc(var(--k) * 55ms + 300ms); }
+.seen .unit-art .a.t { animation-name: art-fade-a; }
+@keyframes art-draw { to { stroke-dashoffset: 0; } }
+@keyframes art-fade { to { opacity: 1; } }
+@keyframes art-fade-a { to { opacity: .55; } }
+/* After the drawing, each sketch keeps one small motion that belongs to its topic. */
+.unit-art g { transform-box: fill-box; }
+.seen .unit-art .swap-a { animation: swap-a 6s var(--ease) 2.4s infinite; }
+.seen .unit-art .swap-b { animation: swap-b 6s var(--ease) 2.4s infinite; }
+@keyframes swap-a { 0%, 30%, 100% { transform: none; } 45%, 80% { transform: translate(80px, 0); } 37% { transform: translate(40px, -30px); } 88% { transform: translate(40px, 30px); } }
+@keyframes swap-b { 0%, 30%, 100% { transform: none; } 45%, 80% { transform: translate(-80px, 0); } 37% { transform: translate(-40px, 30px); } 88% { transform: translate(-40px, -30px); } }
+.seen .unit-art .step { animation: art-fade .6s ease-out forwards, step 4s ease-in-out infinite; animation-delay: calc(var(--k) * 55ms + 300ms), calc(var(--k) * 300ms + 2s); }
+@keyframes step { 0%, 20%, 100% { fill-opacity: 1; } 10% { fill-opacity: .3; } }
+.unit-art .hop, .unit-art .ride { offset-rotate: 0deg; }
+.seen .unit-art .hop { animation: art-fade .4s ease-out 2s forwards, along 3.4s linear 2s infinite; }
+.unit-art .orbit { offset-rotate: 0deg; }
+.seen .unit-art .orbit { animation: art-fade .4s ease-out 2s forwards, along 9s linear 2s infinite; }
+.seen .unit-art .ride { animation: art-fade .4s ease-out 2s forwards, along 4s ease-in-out 2s infinite alternate; }
+@keyframes along { from { offset-distance: 0%; } to { offset-distance: 100%; } }
+.unit-art .pie { stroke: currentColor; stroke-linecap: butt; stroke-dasharray: 0 100; }
+.seen .unit-art .pie { animation: art-fade .4s ease-out 1.6s forwards, pie 5s var(--ease) 1.6s infinite; }
+@keyframes pie { 0% { stroke-dasharray: 0 100; } 35%, 85% { stroke-dasharray: 25 100; } 100% { stroke-dasharray: 0 100; } }
+.seen .unit-art .tilt { transform-box: view-box; transform-origin: 300px 72px; animation: tilt 4.8s ease-in-out 2s infinite; }
+@keyframes tilt { 0%, 100% { transform: rotate(0); } 30% { transform: rotate(-4deg); } 60% { transform: rotate(2deg); } }
+.seen .unit-art .spin { transform-box: view-box; transform-origin: 320px 95px; animation: spin 5s cubic-bezier(.2, .7, .2, 1) 2s infinite; }
+@keyframes spin { from { transform: rotate(0); } 70%, to { transform: rotate(1530deg); } }
+.seen .unit-art .feed-in { animation: feed-in 4s ease-in-out 2s infinite; }
+.seen .unit-art .feed-out { opacity: 0; animation: feed-out 4s ease-in-out 2s infinite; }
+@keyframes feed-in { 0% { transform: none; opacity: 1; } 40% { transform: translate(100px, 0); opacity: 0; } 41%, 100% { transform: none; opacity: 0; } 95% { opacity: 1; } }
+@keyframes feed-out { 0%, 45% { transform: translate(-40px, 0); opacity: 0; } 70%, 90% { transform: none; opacity: 1; } 100% { opacity: 0; } }
+.unit-art .cell { opacity: .25; }
+.seen .unit-art .cell { animation: cell 5s ease-in-out infinite; animation-delay: calc(var(--j) * .5s + 2s); }
+@keyframes cell { 0%, 100% { opacity: .25; } 15%, 60% { opacity: 1; } }
+.unit-art .cut, .unit-art .shade { opacity: 0; }
+.seen .unit-art .cut { animation: cut 4s ease-in-out 2s infinite; }
+@keyframes cut { 0%, 100% { opacity: 0; } 30%, 70% { opacity: .5; } }
+.seen .unit-art .shade { animation: shade 1s ease-out 1.6s forwards; }
+@keyframes shade { to { opacity: .14; } }
+.seen .unit-art .diag { animation: art-draw 1.1s cubic-bezier(.5, 0, .3, 1) forwards, redraw 4s ease-in-out 2.5s infinite; }
+@keyframes redraw { 0%, 15% { stroke-dashoffset: 1; } 50%, 100% { stroke-dashoffset: 0; } }
+.seen .unit-art .root { animation: art-fade .4s ease-out 1.8s forwards, root 2.4s ease-in-out 2.2s infinite; }
+@keyframes root { 0%, 100% { r: 7px; } 50% { r: 11px; } }
+.seen .unit-art .breathe { transform-box: view-box; transform-origin: 380px 140px; animation: breathe 4s ease-in-out 2s infinite alternate; }
+@keyframes breathe { from { transform: scaleY(1); } to { transform: scaleY(.35); } }
+/* The label and the title share a line when they fit; a long title wraps below the label instead of running off. */
+.unit h2 .title { min-width: 0; text-wrap: balance; }
+.unit h2 .label { font: 600 14px var(--ui); letter-spacing: .14em; text-transform: uppercase; color: var(--c); white-space: nowrap; }
+/* Keep the sketches cheap: each is its own layer, so its loop repaints only itself, and loops pause while their unit is
+ off screen or under the sticky bar (units.js toggles .live), so the bar's blur is not redrawn every frame. */
+.unit-art { will-change: transform; contain: layout style; }
+.unit:not(.live) .unit-art, .unit:not(.live) .unit-art * { animation-play-state: paused; }
+@media (max-width: 560px) {
+ .unit-art { width: calc(100% - 32px); right: 16px; opacity: .32; }
+ .unit h2 { min-height: 0; padding-top: 104px; font-size: 24px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .unit-art * { animation: none !important; }
+ .unit-art .d { stroke-dashoffset: 0; }
+ .unit-art .t, .unit-art .cell { opacity: 1; }
+ .unit-art .a.t { opacity: .55; }
+ .unit-art .shade { opacity: .14; }
+ .unit-art .pie { stroke-dasharray: 25 100; }
+}
diff --git a/site/proteus/lib/units.js b/site/proteus/lib/units.js
new file mode 100644
index 0000000..e9e8c27
--- /dev/null
+++ b/site/proteus/lib/units.js
@@ -0,0 +1,26 @@
+// The unit headers of a book's contents page, the same in every book; styled by units.css. The sketches come from
+// the book's own unit-art.js (window.UNIT_ART, one SVG body per unit, viewBox 0 0 600 180).
+// Units.header(u, label, title) the sketch and heading for unit u, as HTML to put first in its <section class="unit">
+// Units.watch() draw each sketch the first time its unit scrolls into view, and run its loop only
+// while the unit is on screen
+'use strict';
+(() => {
+ const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;');
+ const header = (u, label, title) =>
+ `<svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${window.UNIT_ART?.[u] || ''}</svg>` +
+ `<h2><span class="label">${esc(label)}</span><span class="title">${esc(title)}</span></h2>`;
+
+ function watch(root = document) {
+ const units = root.querySelectorAll('.unit');
+ if (!('IntersectionObserver' in window)) return units.forEach(u => u.classList.add('seen', 'live'));
+ // The first sight draws the sketch; leaving the screen (or sliding under the sticky bar) pauses it.
+ const first = new IntersectionObserver(es => es.forEach(e => {
+ if (e.isIntersecting) { e.target.classList.add('seen'); first.unobserve(e.target); }
+ }), { threshold: .25 });
+ const live = new IntersectionObserver(es => es.forEach(e => e.target.classList.toggle('live', e.isIntersecting)),
+ { rootMargin: '-64px 0px 0px 0px' });
+ units.forEach(u => { first.observe(u); live.observe(u); });
+ }
+
+ window.Units = { header, watch };
+})();
diff --git a/site/proteus/lib/volume.css b/site/proteus/lib/volume.css
new file mode 100644
index 0000000..106dd36
--- /dev/null
+++ b/site/proteus/lib/volume.css
@@ -0,0 +1,24 @@
+/* Volume control for the player bar (volume.js); imported by engine.css. */
+.volume { display: flex; align-items: center; flex: none; width: 44px; height: 44px; overflow: hidden;
+ border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
+.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
+.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
+.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
+.volume .icon:focus-visible { outline: none; }
+.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
+.volume:hover input, .volume:focus-within input { width: 100px; opacity: 1; }
+.volume input:focus-visible { outline: none; }
+.volume input::-webkit-slider-runnable-track { height: 4px; border-radius: 999px;
+ background: linear-gradient(to right, var(--chalk) var(--volume, 100%), var(--faint) var(--volume, 100%)); }
+.volume input::-webkit-slider-thumb { appearance: none; width: 12px; height: 12px; margin-top: -4px; border: 0; border-radius: 50%; background: var(--chalk); }
+.volume input::-moz-range-track { height: 4px; border-radius: 999px; background: var(--faint); }
+.volume input::-moz-range-progress { height: 4px; border-radius: 999px; background: var(--chalk); }
+.volume input::-moz-range-thumb { width: 12px; height: 12px; border: 0; border-radius: 50%; background: var(--chalk); }
+@media (max-width: 700px) {
+ .volume { width: 36px; height: 40px; }
+ #bar .volume .icon { width: 34px; height: 38px; }
+ .volume:hover, .volume:focus-within { width: 158px; }
+ .volume input { height: 38px; }
+}
+@media (prefers-reduced-motion: reduce) { .volume { transition: none; } }
diff --git a/site/proteus/lib/volume.js b/site/proteus/lib/volume.js
new file mode 100644
index 0000000..4ea3a55
--- /dev/null
+++ b/site/proteus/lib/volume.js
@@ -0,0 +1,23 @@
+/* Volume control for the player bar: a speaker button that opens a slider. engine.js loads this file and reads
+ #volume when it starts each beat's audio, so the control is the same in every book. */
+'use strict';
+{
+ document.getElementById('bHelp').insertAdjacentHTML('beforebegin', `<div class="volume">
+ <button class="icon" id="bVolume" aria-label="${translate('volumeLabel')}" aria-controls="volume" title="${translate('volumeTitle')}">
+ <svg viewBox="0 0 24 24" aria-hidden="true">
+ <path d="M3 9v6h4l5 4V5L7 9z" fill="currentColor"/>
+ <path d="M16 8a6 6 0 0 1 0 8m3-11a10 10 0 0 1 0 14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>
+ </svg>
+ </button>
+ <input id="volume" type="range" min="0" max="1" step="0.05" value="1" aria-label="${translate('volumeSlider')}">
+ </div>`);
+ const input = document.getElementById('volume');
+ document.getElementById('bVolume').onclick = () => input.focus();
+ const apply = () => {
+ input.style.setProperty('--volume', +input.value * 100 + '%');
+ if (P.audio) P.audio.volume = +input.value;
+ };
+ // the volume carries over to the next chapter; a muted slider does not, so a new visit always has sound
+ try { const v = +localStorage.getItem('papermorph:volume'); if (v) { input.value = v; apply(); } } catch {}
+ input.oninput = () => { apply(); try { localStorage.setItem('papermorph:volume', input.value); } catch {} };
+}