Skip to content

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

refactor(engine): one shared engine for every book, synced from the Skill

yzr1e5021d2f1c9
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index 2e4f163..0027b22 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -23,7 +23,8 @@ tools/<book>/ targeted tests when needed
site/ static output; private sources stay outside
<book>/index.html cover + contents (assets/templates/book.html)
<book>/unit-art.js unit sketches (assets/templates/unit-art.js)
- <book>/lib/engine.js, .css this book's engine copy (assets/engine/)
+ <book>/lib/engine.*, volume.* the shared engine, copied from assets/engine/ by scripts/sync_engine.py
+ <book>/lib/book.css this book's engine settings and style overrides
<book>/chNN/index.html a lesson (assets/templates/chapter.html)
<book>/chNN/audio/<lang>/ beat MP3s + timings.js
```
diff --git a/.claude/skills/papermorph/assets/engine/book.css b/.claude/skills/papermorph/assets/engine/book.css
new file mode 100644
index 0000000..5d49bfb
--- /dev/null
+++ b/.claude/skills/papermorph/assets/engine/book.css
@@ -0,0 +1,9 @@
+/* This book's own settings, imported by engine.css. The engine files next to this one are the same in every book
+ and are replaced when the engine is updated; this file is not.
+ Settings (uncomment to use):
+:root {
+ --math-font: "Avenir Next", Arial, sans-serif; face for numbers and formulas (default: a serif, see engine.js)
+ --progress-key: "progress"; localStorage key shared with the cover (default: one per book folder)
+}
+ Style overrides go here too. They come before the engine's rules, so make each selector more specific than the
+ engine's, e.g. ':root .card.band' for '.card.band'. */
diff --git a/.claude/skills/papermorph/assets/engine/engine.css b/.claude/skills/papermorph/assets/engine/engine.css
index 17c8684..fd097e4 100644
--- a/.claude/skills/papermorph/assets/engine/engine.css
+++ b/.claude/skills/papermorph/assets/engine/engine.css
@@ -1,3 +1,5 @@
+@import url(volume.css);
+@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
:root {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
@@ -107,6 +109,16 @@ button[hidden] { display: none; }
.seg.ask { background: #2d4a57; }
.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(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; }
+ .segs { order: 1; }
+ .segs { min-width: 80px; margin: 0; }
+}
.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
@@ -146,6 +158,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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; }
@@ -159,7 +172,9 @@ svg.m { display: inline-block; overflow: visible; }
.screen .kicker { font-size: 22px; }
.screen .prompt { font-size: 40px; font-weight: 600; }
.screen .body { margin-top: 30px; }
-.screen .fb { position: absolute; left: 70px; bottom: 56px; max-width: 1080px; margin: 0; font-size: 24px; }
+.card.screen { display: flex; flex-direction: column; }
+.screen .head { order: 1; } .screen .body { order: 2; }
+.screen .fb { order: 3; max-width: 1080px; margin: 26px 0 0; font-size: 24px; } /* feedback right under the answers */
.screen .acts { position: absolute; right: 70px; bottom: 48px; }
.screen .grid .row { grid-template-columns: 200px minmax(0, 1fr) 40px; padding: 9px 0 9px 12px; }
.screen .grid.text .row { grid-template-columns: minmax(0, 1fr) auto 40px; }
@@ -170,11 +185,12 @@ svg.m { display: inline-block; overflow: visible; }
.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 { left: auto; right: 34px; bottom: 116px; width: 330px; max-height: 240px; overflow: auto; font-size: 20px; }
+.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; } }
diff --git a/.claude/skills/papermorph/assets/engine/engine.js b/.claude/skills/papermorph/assets/engine/engine.js
index 9f39f14..84ba624 100644
--- a/.claude/skills/papermorph/assets/engine/engine.js
+++ b/.claude/skills/papermorph/assets/engine/engine.js
@@ -82,10 +82,14 @@ const NS = 'http://www.w3.org/2000/svg';
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' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
-const MATH = '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,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');
+const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };
// Card positions inside the 1600×900 picture.
-const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // below the number line
+const BAND = { x: 96, y: 686, w: 1408, 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: 1600, cls: 'screen' };
@@ -134,6 +138,7 @@ const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|s
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 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). Baseline at y; anchor start/middle/end.
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 });
@@ -180,6 +185,10 @@ function M(parent, parts, { x = 0, y = 0, size = 36, fill = COL.chalk, anchor =
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;
@@ -926,13 +935,21 @@ function dot(key, v, r = 9, name = v) {
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
- if (S.panel) { // fade the old panel, then take it out of rendering
- const old = S.panel;
+ 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.
+function retire(e) {
+ e.style.transition = 'opacity .15s linear';
+ e.style.opacity = '0';
+ setTimeout(() => { e.style.display = 'none'; }, 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);
@@ -994,6 +1011,8 @@ function finishCard() {
/* ---------- 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);
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
@@ -1011,11 +1030,19 @@ function rich(parts, size = 28) {
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, 900 - 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.
@@ -1384,7 +1411,7 @@ const slot = (k, n) => {
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.f ? p.f.join('/') : p.sup !== undefined ? '^' + p.sup : (p.i ? p.i : '') + '√' + (p.r.f ? p.r.f.join('/') : p.r)).join('');
+const plain = parts => parts.map(p => typeof p === 'string' ? p : p.ov !== undefined ? p.ov + ' repeating' : 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);
@@ -1557,7 +1584,11 @@ function start(i, play) {
evalTo(0);
const a = P.audio = new Audio(`audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3`);
a.preload = 'auto';
- a.onerror = () => { if (P.audio === a) soundFailed(); };
+ a.volume = +($('volume')?.value ?? 1);
+ // 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) $('soundNote').hidden = true; };
const b = BEATS[i];
if (b.ask) b.ask(() => { if (P.i === i) { evalTo(Infinity); start(i + 1, true); } });
setPlaying(play);
@@ -1588,7 +1619,7 @@ function frame(now) {
// While the clip plays, its clock drives the picture; before it starts or after it ends, wall time does.
if (a && !P.afail && !a.ended) {
if (a.currentTime > 0) { P.t = Math.max(P.t, a.currentTime); P.stall = 0; }
- else if ((P.stall += dt) > 4) soundFailed();
+ else if ((P.stall += dt) > 8 && a.readyState < 2) soundFailed(); // still nothing to play after 8 s
} else P.t += dt;
evalTo(P.t);
if (P.t >= P.end) beatDone();
@@ -1659,8 +1690,8 @@ 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')) { // typing an answer: only Enter (check) and Escape (leave the box) are ours
- if (k === 'Enter' && P.keys) { e.preventDefault(); P.keys(e); }
+ 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;
}
@@ -1682,14 +1713,14 @@ document.addEventListener('keydown', e => {
// 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;
-const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, innerHeight / 1000));
+const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, (innerHeight - (innerWidth <= 700 ? 120 : 0)) / 1000));
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.
// Per-book progress shared with the cover/contents at the parent URL folder.
-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('../', location.href).pathname;
+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) || '{}');
diff --git a/.claude/skills/papermorph/assets/engine/volume.css b/.claude/skills/papermorph/assets/engine/volume.css
new file mode 100644
index 0000000..195fe1f
--- /dev/null
+++ b/.claude/skills/papermorph/assets/engine/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: #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/.claude/skills/papermorph/assets/engine/volume.js b/.claude/skills/papermorph/assets/engine/volume.js
new file mode 100644
index 0000000..91695ee
--- /dev/null
+++ b/.claude/skills/papermorph/assets/engine/volume.js
@@ -0,0 +1,20 @@
+/* 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="Adjust volume" aria-controls="volume" title="Volume (0 = muted)">
+ <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="Volume">
+ </div>`);
+ const input = document.getElementById('volume');
+ document.getElementById('bVolume').onclick = () => input.focus();
+ input.oninput = () => {
+ input.style.setProperty('--volume', +input.value * 100 + '%');
+ if (P.audio) P.audio.volume = +input.value;
+ };
+}
diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.md
index 357dbb7..1eaac74 100644
--- a/.claude/skills/papermorph/references/engine.md
+++ b/.claude/skills/papermorph/references/engine.md
@@ -2,6 +2,8 @@
A chapter page loads the engine and its `audio/<lang>/timings.js`, defines `CHAPTER` (including `language` when different from `en`), drawing helpers, `BEATS` and questions, then calls `boot()`. The engine provides the stage, drawing, timeline, question types, guide and player. Use the code's signatures if they differ from this reference.
+Every book keeps a copy of the shared engine in `lib/` (`engine.*`, `volume.*`), so the book runs on its own. Change the engine in `assets/engine/`, then copy it to the books with `python3 SKILL/scripts/sync_engine.py site` (`--check` lists copies that differ); a book's copy is not edited by hand. The book's own settings and style overrides live in `lib/book.css`, imported by `engine.css` and never overwritten: `--math-font` for numbers and formulas, `--progress-key` when the cover uses a key other than the default.
+
Many helpers are mathematical because the first book was algebra. Use those that fit, implement new ones in the chapter as needed, and share them in the book's engine when another chapter uses them.
## Stage and state
diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.md
index 3dbd529..6246c51 100644
--- a/.claude/skills/papermorph/references/site.md
+++ b/.claude/skills/papermorph/references/site.md
@@ -11,7 +11,7 @@ BOOK_ID=history
BOOK_SITE="site/$BOOK_ID"
BOOK_WORK="books/$BOOK_ID"
mkdir -p "$BOOK_SITE/lib" "$BOOK_SITE/ch01" "$BOOK_WORK/chapters" "content/$BOOK_ID/ch01" "tools/$BOOK_ID"
-cp "$SKILL/assets/engine/engine.js" "$SKILL/assets/engine/engine.css" "$BOOK_SITE/lib/"
+python3 "$SKILL/scripts/sync_engine.py" "$BOOK_SITE" # the shared engine into lib/, plus lib/book.css for this book's settings
cp "$SKILL/assets/templates/book.html" "$BOOK_SITE/index.html"
cp "$SKILL/assets/templates/unit-art.js" "$BOOK_SITE/unit-art.js"
cp "$SKILL/assets/templates/chapter.html" "$BOOK_SITE/ch01/index.html"
@@ -20,7 +20,7 @@ cp "$SKILL/assets/templates/narration.en.json" "content/$BOOK_ID/ch01/narration.
Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`). Choose the voice and translate the template's visible UI text as needed before the pilot.
-Each book has its own engine, source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.
+Each book has its own engine copy (kept in step with `sync_engine.py`, see [engine.md](engine.md)), source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.
A chapter returns to its book's index. Preserve cover → contents → chapter navigation and the return from contents to cover. The book opens directly at `/<book>/`; it needs no parent index page. Keep existing books' navigation when editing them.
diff --git a/.claude/skills/papermorph/scripts/sync_engine.py b/.claude/skills/papermorph/scripts/sync_engine.py
new file mode 100644
index 0000000..ae8ee66
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/sync_engine.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Copy the skill's engine into books, or check that their copies match.
+
+ python3 sync_engine.py site/history # one book
+ python3 sync_engine.py site # every book in site/ (each folder with lib/engine.js)
+ python3 sync_engine.py site --check # report copies that differ; exit status 1 if any
+
+Each book keeps a full copy of the engine in lib/, so it runs on its own. The copies are not edited by hand:
+change assets/engine/ and sync. lib/book.css holds the book's own settings and overrides; it is created from
+the default when missing and never overwritten.
+"""
+import argparse, filecmp, shutil, sys
+from pathlib import Path
+
+ENGINE = Path(__file__).resolve().parent.parent / 'assets' / 'engine'
+OWN = 'book.css'
+
+
+def books(target: Path):
+ if (target / 'lib' / 'engine.js').exists():
+ return [target]
+ return sorted(p.parent.parent for p in target.glob('*/lib/engine.js')) or [target] # or a new book
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('target', type=Path, help='a book folder, or a folder of books')
+ ap.add_argument('--check', action='store_true', help='only report differing copies')
+ a = ap.parse_args()
+ shared = sorted(p for p in ENGINE.iterdir() if p.is_file() and p.name != OWN)
+ stale = []
+ for book in books(a.target):
+ lib = book / 'lib'
+ for src in shared:
+ dst = lib / src.name
+ if dst.exists() and filecmp.cmp(src, dst, shallow=False):
+ continue
+ stale.append(dst)
+ if not a.check:
+ lib.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src, dst)
+ if not (lib / OWN).exists():
+ stale.append(lib / OWN)
+ if not a.check:
+ shutil.copyfile(ENGINE / OWN, lib / OWN)
+ verb = 'differs' if a.check else 'updated'
+ for p in stale:
+ print(f'{verb}: {p}')
+ if not stale:
+ print('all engine copies match' if a.check else 'nothing to update')
+ sys.exit(1 if a.check and stale else 0)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/site/elementary-algebra/ch38/index.html b/site/elementary-algebra/ch38/index.html
index 792bdf2..1ef557c 100644
--- a/site/elementary-algebra/ch38/index.html
+++ b/site/elementary-algebra/ch38/index.html
@@ -13,7 +13,7 @@
<script>
'use strict';
const CHAPTER = { number: 38, title: 'Solving Systems of Linear Inequalities by Graphing', minutes: 6, next: '../ch39/' };
-const L1 = COL.whole, L2 = COL.rat, OV = COL.real, DASH = '14 10';
+const L1 = COL.whole, L2 = COL.rat, OVERLAP = COL.real, DASH = '14 10';
/* ---------- chapter drawing helpers ---------- */
const mline = (p, parts, x, y, t0, fill = COL.chalk, size = 48, anchor = 'middle') => { const e = M(p, [].concat(parts), { x, y, size, fill, anchor, o: 0 }); show(e, t0); return e; };
@@ -36,7 +36,7 @@ function mixed(P, t, run = tw) {
P.line(0, -1, 1, 0, L2, t[1], { run });
P.half(3, 1, -5, L1, t[2], { run });
P.half(1, -1, 1, L2, t[3], { run });
- P.region([[3, 1, -5], [1, -1, 1]], OV, t[4], { run, o: .5 });
+ P.region([[3, 1, -5], [1, -1, 1]], OVERLAP, t[4], { run, o: .5 });
}
/* ---------- beats ---------- */
@@ -66,9 +66,9 @@ const BEATS = [
const p = S.qp, P = S.P;
side(p, ['2(0) − 0 > 10 ✗'], 540, m('t2'), L2, 34);
P.half(2, -1, 10, L2, m('s2'));
- P.region([[-1, -1, -2], [2, -1, 10]], OV, m('both'), { o: .5 });
- note(p, 'solution: the overlap', 610, m('both', 1), OV);
- P.dot(4, -2, OV, m('corner'), { open: true, label: '(4, −2)', dx: 16, dy: -8 });
+ P.region([[-1, -1, -2], [2, -1, 10]], OVERLAP, m('both'), { o: .5 });
+ note(p, 'solution: the overlap', 610, m('both', 1), OVERLAP);
+ P.dot(4, -2, OVERLAP, m('corner'), { open: true, label: '(4, −2)', dx: 16, dy: -8 });
note(p, 'corner on dashed lines: not included', 660, m('corner', 2), COL.dim);
}],
['q1', 'Quick check', () => {
@@ -80,7 +80,7 @@ const BEATS = [
id: 'c-both', prompt: ['Pick any point that is a solution of both inequalities.'],
build: pickPoint(S.P, [0, 0], (x, y) => `(${num(x)}, ${num(y)}) is in both shaded regions.`,
(x, y) => y <= -x + 3 ? 'That point satisfies y ≤ −x + 3 only. It must be in both shaded regions.' : y >= x - 3 ? 'That point satisfies y ≥ x − 3 only. It must be in both shaded regions.' : 'That point satisfies neither inequality.',
- () => S.P.region([[-1, -1, -3], [-1, 1, -3]], OV, 0, { run: fx, into: S.qp, o: .5 }), (x, y) => y <= -x + 3 && y >= x - 3),
+ () => S.P.region([[-1, -1, -3], [-1, 1, -3]], OVERLAP, 0, { run: fx, into: S.qp, o: .5 }), (x, y) => y <= -x + 3 && y >= x - 3),
}], done) }],
['mixed', 'Solid and dashed', (m) => {
const [p, P] = stage();
@@ -92,7 +92,7 @@ const BEATS = [
side(p, ['0 > −5 ✓'], 430, m('t', .5), L1, 34);
side(p, ['0 ≤ −1 ✗'], 490, m('t2', .5), L2, 34);
note(p, 'solid edge: included. dashed edge: not.', 570, m('edge'));
- P.dot(-1, -2, OV, m('corner'), { open: true, label: '(−1, −2)', dx: -16, dy: -10, anchor: 'end' });
+ P.dot(-1, -2, OVERLAP, m('corner'), { open: true, label: '(−1, −2)', dx: -16, dy: -10, anchor: 'end' });
note(p, 'corner on the dashed line: not included', 620, m('corner', 1.5));
}],
['q2', 'Quick check', () => {
diff --git a/site/elementary-algebra/lib/book.css b/site/elementary-algebra/lib/book.css
new file mode 100644
index 0000000..a604da6
--- /dev/null
+++ b/site/elementary-algebra/lib/book.css
@@ -0,0 +1,5 @@
+/* This book's own settings, imported by engine.css; the engine files next to it are shared and replaced on update.
+ Overrides come before the engine's rules, so their selectors must be more specific (e.g. ':root .card.band'). */
+:root {
+ --progress-key: "progress"; /* the first book on the site kept the original key, so readers keep their progress */
+}
diff --git a/site/elementary-algebra/lib/engine.css b/site/elementary-algebra/lib/engine.css
index 32acb76..fd097e4 100644
--- a/site/elementary-algebra/lib/engine.css
+++ b/site/elementary-algebra/lib/engine.css
@@ -1,3 +1,5 @@
+@import url(volume.css);
+@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
:root {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
@@ -15,7 +17,8 @@ button[hidden] { display: none; }
/* One fixed 1600×960 frame (900 stage + 60 controls), scaled to fit the window. */
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; 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: 1600px; height: 900px; display: block; }
+#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
#ui { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; pointer-events: none; }
#ui > * { pointer-events: auto; }
@@ -106,6 +109,16 @@ button[hidden] { display: none; }
.seg.ask { background: #2d4a57; }
.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(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; }
+ .segs { order: 1; }
+ .segs { min-width: 80px; margin: 0; }
+}
.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
@@ -145,6 +158,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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; }
@@ -158,7 +172,9 @@ svg.m { display: inline-block; overflow: visible; }
.screen .kicker { font-size: 22px; }
.screen .prompt { font-size: 40px; font-weight: 600; }
.screen .body { margin-top: 30px; }
-.screen .fb { position: absolute; left: 70px; bottom: 56px; max-width: 1080px; margin: 0; font-size: 24px; }
+.card.screen { display: flex; flex-direction: column; }
+.screen .head { order: 1; } .screen .body { order: 2; }
+.screen .fb { order: 3; max-width: 1080px; margin: 26px 0 0; font-size: 24px; } /* feedback right under the answers */
.screen .acts { position: absolute; right: 70px; bottom: 48px; }
.screen .grid .row { grid-template-columns: 200px minmax(0, 1fr) 40px; padding: 9px 0 9px 12px; }
.screen .grid.text .row { grid-template-columns: minmax(0, 1fr) auto 40px; }
@@ -169,11 +185,12 @@ svg.m { display: inline-block; overflow: visible; }
.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 { left: auto; right: 34px; bottom: 116px; width: 330px; max-height: 240px; overflow: auto; font-size: 20px; }
+.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; } }
diff --git a/site/elementary-algebra/lib/engine.js b/site/elementary-algebra/lib/engine.js
index 2e2f2c2..84ba624 100644
--- a/site/elementary-algebra/lib/engine.js
+++ b/site/elementary-algebra/lib/engine.js
@@ -5,19 +5,6 @@
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
<svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="Lesson animation">
- <defs>
- <filter id="grain" x="0" y="0" width="100%" height="100%">
- <feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="2" seed="7" />
- <feColorMatrix values="0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0" />
- </filter>
- <radialGradient id="vignette" cx=".5" cy=".45" r=".75">
- <stop offset=".6" stop-color="#000" stop-opacity="0" />
- <stop offset="1" stop-color="#000" stop-opacity=".35" />
- </radialGradient>
- </defs>
- <rect width="1600" height="900" fill="#1d2b27" />
- <rect width="1600" height="900" filter="url(#grain)" />
- <rect width="1600" height="900" fill="url(#vignette)" />
<g id="scene"></g>
</svg>
<div id="ui"></div>
@@ -80,15 +67,29 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
</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 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' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
-const MATH = '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,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');
+const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };
// Card positions inside the 1600×900 picture.
-const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // below the number line
+const BAND = { x: 96, y: 686, w: 1408, 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: 1600, cls: 'screen' };
@@ -105,11 +106,11 @@ function mk(tag, attrs = {}, parent) {
// 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;
- if (s.x || s.y || s.s !== 1 || s.r) e.setAttribute('transform', `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})`);
- else e.removeAttribute('transform');
- e.setAttribute('opacity', s.o);
+ 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;
+ if (tf !== e._tf) { 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' : '';
@@ -137,6 +138,7 @@ const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|s
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 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). Baseline at y; anchor start/middle/end.
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 });
@@ -183,6 +185,10 @@ function M(parent, parts, { x = 0, y = 0, size = 36, fill = COL.chalk, anchor =
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;
@@ -827,6 +833,83 @@ function evalTo(t, list = TW) {
}
}
+/* ---------- 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.
+const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// 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 = 800, y = 450, z, r = 0, bg = COL.board } = {}) {
+ const [bx, by, bw, bh] = box || [0, 0, 1600, 900];
+ 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 / 1600, bh / 900) : 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);
+ return cam;
+}
+
/* ---------- scene ---------- */
const scene = document.getElementById('scene');
const S = {};
@@ -852,9 +935,21 @@ function dot(key, v, r = 9, name = v) {
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
- if (S.panel) hide(S.panel, t0, .4);
+ 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.
+function retire(e) {
+ e.style.transition = 'opacity .15s linear';
+ e.style.opacity = '0';
+ setTimeout(() => { e.style.display = 'none'; }, 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);
@@ -916,6 +1011,8 @@ function finishCard() {
/* ---------- 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);
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
@@ -933,11 +1030,19 @@ function rich(parts, size = 28) {
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, 900 - 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.
@@ -1306,7 +1411,7 @@ const slot = (k, n) => {
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.f ? p.f.join('/') : p.sup !== undefined ? '^' + p.sup : (p.i ? p.i : '') + '√' + (p.r.f ? p.r.f.join('/') : p.r)).join('');
+const plain = parts => parts.map(p => typeof p === 'string' ? p : p.ov !== undefined ? p.ov + ' repeating' : 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);
@@ -1477,9 +1582,13 @@ function start(i, play) {
Object.assign(P, { i, t: 0, waiting: false, done: false, afail: false, stall: 0 });
P.end = runBeat(i);
evalTo(0);
- const a = P.audio = new Audio(`audio/en/${BEATS[i].id}.mp3`);
+ const a = P.audio = new Audio(`audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3`);
a.preload = 'auto';
- a.onerror = () => { if (P.audio === a) soundFailed(); };
+ a.volume = +($('volume')?.value ?? 1);
+ // 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) $('soundNote').hidden = true; };
const b = BEATS[i];
if (b.ask) b.ask(() => { if (P.i === i) { evalTo(Infinity); start(i + 1, true); } });
setPlaying(play);
@@ -1510,7 +1619,7 @@ function frame(now) {
// While the clip plays, its clock drives the picture; before it starts or after it ends, wall time does.
if (a && !P.afail && !a.ended) {
if (a.currentTime > 0) { P.t = Math.max(P.t, a.currentTime); P.stall = 0; }
- else if ((P.stall += dt) > 4) soundFailed();
+ else if ((P.stall += dt) > 8 && a.readyState < 2) soundFailed(); // still nothing to play after 8 s
} else P.t += dt;
evalTo(P.t);
if (P.t >= P.end) beatDone();
@@ -1581,8 +1690,8 @@ 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')) { // typing an answer: only Enter (check) and Escape (leave the box) are ours
- if (k === 'Enter' && P.keys) { e.preventDefault(); P.keys(e); }
+ 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;
}
@@ -1604,19 +1713,20 @@ document.addEventListener('keydown', e => {
// 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;
-const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, innerHeight / 1000));
+const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, (innerHeight - (innerWidth <= 700 ? 120 : 0)) / 1000));
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.
-// Per-browser progress shared with the contents page: last chapter opened, chapters finished.
+// 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('progress') || '{}');
+ 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('progress', JSON.stringify(p));
+ f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));
} catch {}
}
function boot() {
diff --git a/site/elementary-algebra/lib/volume.css b/site/elementary-algebra/lib/volume.css
new file mode 100644
index 0000000..195fe1f
--- /dev/null
+++ b/site/elementary-algebra/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: #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/elementary-algebra/lib/volume.js b/site/elementary-algebra/lib/volume.js
new file mode 100644
index 0000000..91695ee
--- /dev/null
+++ b/site/elementary-algebra/lib/volume.js
@@ -0,0 +1,20 @@
+/* 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="Adjust volume" aria-controls="volume" title="Volume (0 = muted)">
+ <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="Volume">
+ </div>`);
+ const input = document.getElementById('volume');
+ document.getElementById('bVolume').onclick = () => input.focus();
+ input.oninput = () => {
+ input.style.setProperty('--volume', +input.value * 100 + '%');
+ if (P.audio) P.audio.volume = +input.value;
+ };
+}
diff --git a/site/math-notebook/lib/book.css b/site/math-notebook/lib/book.css
new file mode 100644
index 0000000..5d49bfb
--- /dev/null
+++ b/site/math-notebook/lib/book.css
@@ -0,0 +1,9 @@
+/* This book's own settings, imported by engine.css. The engine files next to this one are the same in every book
+ and are replaced when the engine is updated; this file is not.
+ Settings (uncomment to use):
+:root {
+ --math-font: "Avenir Next", Arial, sans-serif; face for numbers and formulas (default: a serif, see engine.js)
+ --progress-key: "progress"; localStorage key shared with the cover (default: one per book folder)
+}
+ Style overrides go here too. They come before the engine's rules, so make each selector more specific than the
+ engine's, e.g. ':root .card.band' for '.card.band'. */
diff --git a/site/math-notebook/lib/engine.css b/site/math-notebook/lib/engine.css
index 32acb76..fd097e4 100644
--- a/site/math-notebook/lib/engine.css
+++ b/site/math-notebook/lib/engine.css
@@ -1,3 +1,5 @@
+@import url(volume.css);
+@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
:root {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
@@ -15,7 +17,8 @@ button[hidden] { display: none; }
/* One fixed 1600×960 frame (900 stage + 60 controls), scaled to fit the window. */
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; 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: 1600px; height: 900px; display: block; }
+#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
#ui { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; pointer-events: none; }
#ui > * { pointer-events: auto; }
@@ -106,6 +109,16 @@ button[hidden] { display: none; }
.seg.ask { background: #2d4a57; }
.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(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; }
+ .segs { order: 1; }
+ .segs { min-width: 80px; margin: 0; }
+}
.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
@@ -145,6 +158,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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; }
@@ -158,7 +172,9 @@ svg.m { display: inline-block; overflow: visible; }
.screen .kicker { font-size: 22px; }
.screen .prompt { font-size: 40px; font-weight: 600; }
.screen .body { margin-top: 30px; }
-.screen .fb { position: absolute; left: 70px; bottom: 56px; max-width: 1080px; margin: 0; font-size: 24px; }
+.card.screen { display: flex; flex-direction: column; }
+.screen .head { order: 1; } .screen .body { order: 2; }
+.screen .fb { order: 3; max-width: 1080px; margin: 26px 0 0; font-size: 24px; } /* feedback right under the answers */
.screen .acts { position: absolute; right: 70px; bottom: 48px; }
.screen .grid .row { grid-template-columns: 200px minmax(0, 1fr) 40px; padding: 9px 0 9px 12px; }
.screen .grid.text .row { grid-template-columns: minmax(0, 1fr) auto 40px; }
@@ -169,11 +185,12 @@ svg.m { display: inline-block; overflow: visible; }
.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 { left: auto; right: 34px; bottom: 116px; width: 330px; max-height: 240px; overflow: auto; font-size: 20px; }
+.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; } }
diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.js
index 84cb026..84ba624 100644
--- a/site/math-notebook/lib/engine.js
+++ b/site/math-notebook/lib/engine.js
@@ -5,19 +5,6 @@
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
<svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="Lesson animation">
- <defs>
- <filter id="grain" x="0" y="0" width="100%" height="100%">
- <feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="2" seed="7" />
- <feColorMatrix values="0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0" />
- </filter>
- <radialGradient id="vignette" cx=".5" cy=".45" r=".75">
- <stop offset=".6" stop-color="#000" stop-opacity="0" />
- <stop offset="1" stop-color="#000" stop-opacity=".35" />
- </radialGradient>
- </defs>
- <rect width="1600" height="900" fill="#1d2b27" />
- <rect width="1600" height="900" filter="url(#grain)" />
- <rect width="1600" height="900" fill="url(#vignette)" />
<g id="scene"></g>
</svg>
<div id="ui"></div>
@@ -80,15 +67,29 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
</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 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' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
-const MATH = '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,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');
+const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };
// Card positions inside the 1600×900 picture.
-const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // below the number line
+const BAND = { x: 96, y: 686, w: 1408, 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: 1600, cls: 'screen' };
@@ -105,11 +106,11 @@ function mk(tag, attrs = {}, parent) {
// 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;
- if (s.x || s.y || s.s !== 1 || s.r) e.setAttribute('transform', `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})`);
- else e.removeAttribute('transform');
- e.setAttribute('opacity', s.o);
+ 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;
+ if (tf !== e._tf) { 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' : '';
@@ -832,6 +833,83 @@ function evalTo(t, list = TW) {
}
}
+/* ---------- 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.
+const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// 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 = 800, y = 450, z, r = 0, bg = COL.board } = {}) {
+ const [bx, by, bw, bh] = box || [0, 0, 1600, 900];
+ 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 / 1600, bh / 900) : 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);
+ return cam;
+}
+
/* ---------- scene ---------- */
const scene = document.getElementById('scene');
const S = {};
@@ -857,9 +935,21 @@ function dot(key, v, r = 9, name = v) {
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
- if (S.panel) hide(S.panel, t0, .4);
+ 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.
+function retire(e) {
+ e.style.transition = 'opacity .15s linear';
+ e.style.opacity = '0';
+ setTimeout(() => { e.style.display = 'none'; }, 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);
@@ -921,6 +1011,8 @@ function finishCard() {
/* ---------- 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);
const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
@@ -938,11 +1030,19 @@ function rich(parts, size = 28) {
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, 900 - 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.
@@ -1484,7 +1584,11 @@ function start(i, play) {
evalTo(0);
const a = P.audio = new Audio(`audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3`);
a.preload = 'auto';
- a.onerror = () => { if (P.audio === a) soundFailed(); };
+ a.volume = +($('volume')?.value ?? 1);
+ // 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) $('soundNote').hidden = true; };
const b = BEATS[i];
if (b.ask) b.ask(() => { if (P.i === i) { evalTo(Infinity); start(i + 1, true); } });
setPlaying(play);
@@ -1515,7 +1619,7 @@ function frame(now) {
// While the clip plays, its clock drives the picture; before it starts or after it ends, wall time does.
if (a && !P.afail && !a.ended) {
if (a.currentTime > 0) { P.t = Math.max(P.t, a.currentTime); P.stall = 0; }
- else if ((P.stall += dt) > 4) soundFailed();
+ else if ((P.stall += dt) > 8 && a.readyState < 2) soundFailed(); // still nothing to play after 8 s
} else P.t += dt;
evalTo(P.t);
if (P.t >= P.end) beatDone();
@@ -1586,8 +1690,8 @@ 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')) { // typing an answer: only Enter (check) and Escape (leave the box) are ours
- if (k === 'Enter' && P.keys) { e.preventDefault(); P.keys(e); }
+ 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;
}
@@ -1609,14 +1713,14 @@ document.addEventListener('keydown', e => {
// 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;
-const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, innerHeight / 1000));
+const fit = () => document.documentElement.style.setProperty('--k', Math.min(innerWidth / 1640, (innerHeight - (innerWidth <= 700 ? 120 : 0)) / 1000));
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.
// Per-book progress shared with the cover/contents at the parent URL folder.
-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('../', location.href).pathname;
+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) || '{}');
diff --git a/site/math-notebook/lib/volume.css b/site/math-notebook/lib/volume.css
new file mode 100644
index 0000000..195fe1f
--- /dev/null
+++ b/site/math-notebook/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: #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/math-notebook/lib/volume.js b/site/math-notebook/lib/volume.js
new file mode 100644
index 0000000..91695ee
--- /dev/null
+++ b/site/math-notebook/lib/volume.js
@@ -0,0 +1,20 @@
+/* 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="Adjust volume" aria-controls="volume" title="Volume (0 = muted)">
+ <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="Volume">
+ </div>`);
+ const input = document.getElementById('volume');
+ document.getElementById('bVolume').onclick = () => input.focus();
+ input.oninput = () => {
+ input.style.setProperty('--volume', +input.value * 100 + '%');
+ if (P.audio) P.audio.volume = +input.value;
+ };
+}
diff --git a/site/science/lib/book.css b/site/science/lib/book.css
new file mode 100644
index 0000000..bc7e284
--- /dev/null
+++ b/site/science/lib/book.css
@@ -0,0 +1,11 @@
+/* This book's own settings, imported by engine.css; the engine files next to it are shared and replaced on update.
+ Overrides come before the engine's rules, so their selectors must be more specific (e.g. ':root .card.band'). */
+:root {
+ --math-font: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif; /* one face for words, numbers and formulas */
+}
+/* Band card: prompt and buttons on top, answers below at full width, feedback last. A prompt beside the answers
+ lost the width race to long choices or answer rows (it was squeezed to a word per line, worst in Firefox). */
+:root .card.band { grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "pic head acts" "pic body body" "pic fb fb"; row-gap: 12px; }
+:root .band .head { align-self: auto; }
+:root .band .fb { align-self: auto; margin-top: 0; }
+:root .band .body { min-width: 0; }
diff --git a/site/science/lib/engine.css b/site/science/lib/engine.css
index e4e2e97..fd097e4 100644
--- a/site/science/lib/engine.css
+++ b/site/science/lib/engine.css
@@ -1,4 +1,5 @@
@import url(volume.css);
+@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
:root {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
@@ -39,13 +40,11 @@ button[hidden] { display: none; }
/* Question cards inside the picture. */
.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: rgba(34, 50, 45, .97); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
-/* Band card: prompt and buttons on top, answers below at full width, feedback last. A prompt beside the answers
- lost the width race to long choices or answer rows (it was squeezed to a word per line, worst in Firefox). */
-.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; grid-template-areas: "pic head acts" "pic body body" "pic fb fb"; column-gap: 28px; row-gap: 12px; align-items: center; align-content: center; min-height: 150px; }
+.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; }
-.band .fb { grid-area: fb; margin-top: 0; }
-.band .body { grid-area: body; min-width: 0; }
+.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); }
@@ -191,6 +190,7 @@ svg.m { display: inline-block; overflow: visible; }
.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; } }
diff --git a/site/science/lib/engine.js b/site/science/lib/engine.js
index 0a67ea7..84ba624 100644
--- a/site/science/lib/engine.js
+++ b/site/science/lib/engine.js
@@ -82,7 +82,11 @@ const NS = 'http://www.w3.org/2000/svg';
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' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
-const MATH = UI; // science book: one face for numbers and formulas in demos and questions
+// 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');
+const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };
// Card positions inside the 1600×900 picture.
const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // bottom band (moves up when taller than the space left)
@@ -134,6 +138,7 @@ const VAR = /(?<![A-Za-z°])(?:(?!(?:of|in|is|to|or|at|on|by|as|an|if|it|be|no|s
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 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). Baseline at y; anchor start/middle/end.
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 });
@@ -180,6 +185,10 @@ function M(parent, parts, { x = 0, y = 0, size = 36, fill = COL.chalk, anchor =
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;
@@ -1402,7 +1411,7 @@ const slot = (k, n) => {
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.f ? p.f.join('/') : p.sup !== undefined ? '^' + p.sup : (p.i ? p.i : '') + '√' + (p.r.f ? p.r.f.join('/') : p.r)).join('');
+const plain = parts => parts.map(p => typeof p === 'string' ? p : p.ov !== undefined ? p.ov + ' repeating' : 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);
@@ -1711,7 +1720,7 @@ 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.
// Per-book progress shared with the cover/contents at the parent URL folder.
-const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('../', location.href).pathname;
+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) || '{}');