Skip to content

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

feat(site): Energy & Change, a light notebook edition of the energy chapter

yzrfe731d7954a6
diff --git a/site/index.html b/site/index.html
index aad816f..c483fa4 100644
--- a/site/index.html
+++ b/site/index.html
@@ -29,6 +29,7 @@
<a class="book-hotspot physics-book" data-book="science" href="science/" aria-label="Open Elementary Physics, 4 narrated chapters and a sample chapter">
<span class="book-caption"><strong>Elementary Physics <span aria-hidden="true">↗</span></strong><small>4 narrated chapters · 1 sample</small></span>
</a>
+ <a class="also-label" href="physics-notebook/" aria-label="Also: Energy and Change, the physics book's energy chapter in a light notebook edition">Also: <b>Energy &amp; Change</b> · light notebook edition ↗</a>
</section>
<section class="shelf-tier" aria-labelledby="picture-title">
<h2 class="visually-hidden" id="picture-title">Picture books for children · Coming soon</h2>
diff --git a/site/lib/bookshelf.css b/site/lib/bookshelf.css
index 1f31a18..dee9c07 100644
--- a/site/lib/bookshelf.css
+++ b/site/lib/bookshelf.css
@@ -33,6 +33,10 @@ a { color: inherit; }
.book-caption strong > span { position: absolute; right: 1.2cqw; top: 1.1cqw; color: #e8c68b; }
.book-caption small { color: #e2dbca; font-size: 1.03cqw; letter-spacing: .03em; }
.resume-label { position: absolute; padding: .46cqw .74cqw; background: #fcf4df; color: #3c4336; box-shadow: 1px 2px 5px #0003; font: 1.03cqw var(--ui); transform: rotate(-3deg); }
+.also-label { position: absolute; left: 70.5%; top: 28.75%; padding: .4cqw .8cqw; background: #fcf9ef; color: #2e2a24; box-shadow: 1px 2px 5px #0003;
+ font: 1.03cqw var(--ui); text-decoration: none; white-space: nowrap; transform: rotate(-1.5deg); border-left: .3cqw solid #f2a7b5; }
+.also-label b { font-weight: 600; color: #e0457b; }
+.also-label:hover { box-shadow: 1px 3px 9px #0005; }
.github-drawer { position: absolute; left: 9%; top: 87.5%; width: 68%; height: 8.5%; text-decoration: none; }
.shelf-noscript { position: absolute; bottom: 0; left: 24px; margin: 0; font: 11px var(--ui); color: #352c21; }
.shelf-footer { position: absolute; inset: auto 0 0; display: flex; justify-content: center; align-items: center; gap: 3%; height: 3%; padding: 0 3%; color: #594129; font: 500 clamp(10px, .85vw, 14px)/1.4 var(--ui); text-shadow: 0 1px #ffe6bd66; }
diff --git a/site/physics-notebook/ch13/audio/en/bumper.mp3 b/site/physics-notebook/ch13/audio/en/bumper.mp3
new file mode 100644
index 0000000..068ece7
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/bumper.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/count.mp3 b/site/physics-notebook/ch13/audio/en/count.mp3
new file mode 100644
index 0000000..02c7c3d
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/count.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/depends.mp3 b/site/physics-notebook/ch13/audio/en/depends.mp3
new file mode 100644
index 0000000..7469f7c
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/depends.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/final1.mp3 b/site/physics-notebook/ch13/audio/en/final1.mp3
new file mode 100644
index 0000000..bdd28f2
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/final1.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/finish.mp3 b/site/physics-notebook/ch13/audio/en/finish.mp3
new file mode 100644
index 0000000..fe2c916
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/finish.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/forms.mp3 b/site/physics-notebook/ch13/audio/en/forms.mp3
new file mode 100644
index 0000000..eefa684
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/forms.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/golf.mp3 b/site/physics-notebook/ch13/audio/en/golf.mp3
new file mode 100644
index 0000000..1362c93
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/golf.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/hill.mp3 b/site/physics-notebook/ch13/audio/en/hill.mp3
new file mode 100644
index 0000000..b1f4dd1
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/hill.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/intro.mp3 b/site/physics-notebook/ch13/audio/en/intro.mp3
new file mode 100644
index 0000000..7c41d44
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/intro.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/kinetic.mp3 b/site/physics-notebook/ch13/audio/en/kinetic.mp3
new file mode 100644
index 0000000..4d40159
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/kinetic.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/law.mp3 b/site/physics-notebook/ch13/audio/en/law.mp3
new file mode 100644
index 0000000..2d7dd7a
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/law.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/pen.mp3 b/site/physics-notebook/ch13/audio/en/pen.mp3
new file mode 100644
index 0000000..92ead2b
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/pen.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/potential.mp3 b/site/physics-notebook/ch13/audio/en/potential.mp3
new file mode 100644
index 0000000..23b7ccb
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/potential.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/q1.mp3 b/site/physics-notebook/ch13/audio/en/q1.mp3
new file mode 100644
index 0000000..76852e6
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/q1.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/q2.mp3 b/site/physics-notebook/ch13/audio/en/q2.mp3
new file mode 100644
index 0000000..cd3b705
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/q2.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/q3.mp3 b/site/physics-notebook/ch13/audio/en/q3.mp3
new file mode 100644
index 0000000..739cf7e
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/q3.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/q4.mp3 b/site/physics-notebook/ch13/audio/en/q4.mp3
new file mode 100644
index 0000000..eccdd4d
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/q4.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/shelf.mp3 b/site/physics-notebook/ch13/audio/en/shelf.mp3
new file mode 100644
index 0000000..f27a0b7
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/shelf.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/sun.mp3 b/site/physics-notebook/ch13/audio/en/sun.mp3
new file mode 100644
index 0000000..a2e5fa7
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/sun.mp3 differ
diff --git a/site/physics-notebook/ch13/audio/en/timings.js b/site/physics-notebook/ch13/audio/en/timings.js
new file mode 100644
index 0000000..99108de
--- /dev/null
+++ b/site/physics-notebook/ch13/audio/en/timings.js
@@ -0,0 +1,606 @@
+window.TIMINGS = {
+ "intro": {
+ "dur": 11.925,
+ "marks": {
+ "title": 3.3,
+ "blob": 4.612,
+ "forms": 8.075,
+ "never": 10.162
+ },
+ "cues": [
+ [
+ 0.425,
+ "Unit four, energy."
+ ],
+ [
+ 2.038,
+ "Chapter thirteen: forms of energy."
+ ],
+ [
+ 4.612,
+ "Meet Blip."
+ ],
+ [
+ 5.675,
+ "Blip is a little bundle of energy."
+ ],
+ [
+ 8.075,
+ "Watch it change form again and again, but never disappear."
+ ]
+ ]
+ },
+ "forms": {
+ "dur": 12.975,
+ "marks": {
+ "heat": 4.225,
+ "sound": 5.088,
+ "light": 5.975,
+ "motion": 6.575,
+ "same": 7.713
+ },
+ "cues": [
+ [
+ 0.4,
+ "Energy is a property of matter, and it comes in many forms."
+ ],
+ [
+ 4.225,
+ "Heat."
+ ],
+ [
+ 5.088,
+ "Sound."
+ ],
+ [
+ 5.975,
+ "Light."
+ ],
+ [
+ 6.575,
+ "And motion."
+ ],
+ [
+ 7.713,
+ "Different forms, but it's the same energy underneath, just wearing a different costume."
+ ]
+ ]
+ },
+ "golf": {
+ "dur": 15.6,
+ "marks": {
+ "swing": 3.888,
+ "hit": 8.387,
+ "pass": 10.363,
+ "fly": 13.2
+ },
+ "cues": [
+ [
+ 0.4,
+ "Energy can also move from one object to another."
+ ],
+ [
+ 3.888,
+ "When a golfer swings, the moving club carries energy of motion."
+ ],
+ [
+ 8.387,
+ "The moment it strikes the ball, most of that energy is transferred to the ball, which flies off toward the hole."
+ ]
+ ]
+ },
+ "law": {
+ "dur": 23.925,
+ "marks": {
+ "club": 2.675,
+ "after": 4.975,
+ "tock": 7.2,
+ "total": 10.35,
+ "law": 13.925,
+ "neither": 16.962,
+ "change": 20.025
+ },
+ "cues": [
+ [
+ 0.4,
+ "Let's count the energy in that swing."
+ ],
+ [
+ 2.675,
+ "Before the hit, it's all in the club."
+ ],
+ [
+ 4.975,
+ "After the hit, most is in the ball, and a little became the sound of the hit and a bit of heat."
+ ],
+ [
+ 10.35,
+ "Add it all up, and the total is exactly the same."
+ ],
+ [
+ 13.925,
+ "This is the law of conservation of energy: energy can neither be created nor destroyed."
+ ],
+ [
+ 20.025,
+ "It simply changes form, or moves between objects."
+ ]
+ ]
+ },
+ "sun": {
+ "dur": 21.575,
+ "marks": {
+ "sun": 2.737,
+ "leaf": 5.138,
+ "eat": 10.575,
+ "run": 14.925,
+ "solar": 18.65
+ },
+ "cues": [
+ [
+ 0.375,
+ "Here's an energy chain you're part of."
+ ],
+ [
+ 2.737,
+ "Light from the sun reaches a plant."
+ ],
+ [
+ 5.138,
+ "The leaves absorb that light, and the plant stores it as chemical energy as it grows."
+ ],
+ [
+ 10.575,
+ "When you eat your veggies, that chemical energy is transferred to your body."
+ ],
+ [
+ 14.925,
+ "And when you run, you release it as energy of motion."
+ ],
+ [
+ 18.65,
+ "So, technically, you're solar-powered!"
+ ]
+ ]
+ },
+ "q1": {
+ "dur": 4.8,
+ "marks": {},
+ "cues": [
+ [
+ 0.35,
+ "Quick check."
+ ],
+ [
+ 1.225,
+ "Which statement is the law of conservation of energy?"
+ ]
+ ]
+ },
+ "pen": {
+ "dur": 30.95,
+ "marks": {
+ "hold": 2.9,
+ "pe": 7.675,
+ "drop": 9.037,
+ "ke": 10.925,
+ "bars": 15.113,
+ "sum": 17.4,
+ "land": 19.975,
+ "mech": 23.938
+ },
+ "cues": [
+ [
+ 0.425,
+ "Now meet two big families of energy."
+ ],
+ [
+ 2.9,
+ "Hold a pen up high."
+ ],
+ [
+ 4.4,
+ "It isn't moving, but it has stored energy because of its height, called potential energy."
+ ],
+ [
+ 9.037,
+ "Let it go."
+ ],
+ [
+ 10.1,
+ "As it falls, potential energy turns into kinetic energy, the energy of motion."
+ ],
+ [
+ 15.113,
+ "One bar shrinks while the other grows, and together they add up to the same amount."
+ ],
+ [
+ 19.975,
+ "When the pen lands, its energy becomes a little sound and heat."
+ ],
+ [
+ 23.938,
+ "Potential and kinetic energy are both mechanical energy: energy from an object's position or motion."
+ ]
+ ]
+ },
+ "hill": {
+ "dur": 29.925,
+ "marks": {
+ "kick": 2.263,
+ "slow": 6.562,
+ "stop": 12.45,
+ "back": 17.438,
+ "fast": 18.962,
+ "grav": 22.488
+ },
+ "cues": [
+ [
+ 0.4,
+ "Now kick a ball up a hill."
+ ],
+ [
+ 2.263,
+ "Right after the kick, it's moving fast, with lots of kinetic energy."
+ ],
+ [
+ 6.562,
+ "As it climbs, it slows down, and its energy of motion becomes potential energy in its position."
+ ],
+ [
+ 12.45,
+ "At the top, it stops for a moment."
+ ],
+ [
+ 15.05,
+ "Now its energy is all stored."
+ ],
+ [
+ 17.438,
+ "Then it rolls back down, and the potential energy turns back into kinetic energy."
+ ],
+ [
+ 22.488,
+ "Energy stored because of height is called gravitational potential energy: gravity can release it at any moment."
+ ]
+ ]
+ },
+ "bumper": {
+ "dur": 14.25,
+ "marks": {
+ "ride": 4.013,
+ "bump": 5.875,
+ "pass": 7.925,
+ "move": 9.675
+ },
+ "cues": [
+ [
+ 0.35,
+ "Kinetic energy can also be passed along in a collision."
+ ],
+ [
+ 4.013,
+ "Think of bumper cars."
+ ],
+ [
+ 5.875,
+ "When one car bumps into another, it transfers its energy, and the other car starts to move, while the first one slows down."
+ ]
+ ]
+ },
+ "q2": {
+ "dur": 4.575,
+ "marks": {},
+ "cues": [
+ [
+ 0.35,
+ "Quick check."
+ ],
+ [
+ 1.262,
+ "Click the ball where it has the most potential energy."
+ ]
+ ]
+ },
+ "depends": {
+ "dur": 26.5,
+ "marks": {
+ "mass": 2.9,
+ "drop": 4.838,
+ "hit": 7.75,
+ "speed": 12.188,
+ "low": 14.363,
+ "high": 17.6,
+ "more": 22.387
+ },
+ "cues": [
+ [
+ 0.375,
+ "How much kinetic energy does something have?"
+ ],
+ [
+ 2.9,
+ "First, it depends on mass."
+ ],
+ [
+ 4.838,
+ "Drop a tennis ball and a bowling ball together."
+ ],
+ [
+ 7.75,
+ "At the same speed, the bowling ball, with much more mass, hits far harder."
+ ],
+ [
+ 12.188,
+ "Second, it depends on velocity."
+ ],
+ [
+ 14.363,
+ "A tennis ball dropped from two feet lands gently."
+ ],
+ [
+ 17.6,
+ "Dropped from the top of a skyscraper, it's moving much faster, and hits much harder."
+ ],
+ [
+ 22.387,
+ "More mass, or more velocity, means more kinetic energy."
+ ]
+ ]
+ },
+ "shelf": {
+ "dur": 20.675,
+ "marks": {
+ "shelf": 3.462,
+ "top": 6.513,
+ "fall": 10.55,
+ "heavy": 12.8,
+ "pe2": 16.5
+ },
+ "cues": [
+ [
+ 0.35,
+ "Potential energy depends on mass and height."
+ ],
+ [
+ 3.462,
+ "Here are two identical books on a bookcase."
+ ],
+ [
+ 6.513,
+ "The one on the top shelf has more potential energy than the one on the bottom, because it has farther to fall."
+ ],
+ [
+ 12.8,
+ "And a heavier book on the same shelf stores even more."
+ ],
+ [
+ 16.5,
+ "More mass, or more height, means more potential energy."
+ ]
+ ]
+ },
+ "q3": {
+ "dur": 5.725,
+ "marks": {},
+ "cues": [
+ [
+ 0.35,
+ "Quick check."
+ ],
+ [
+ 1.275,
+ "What two things decide an object's gravitational potential energy?"
+ ]
+ ]
+ },
+ "kinetic": {
+ "dur": 28.8,
+ "marks": {
+ "kin": 3.85,
+ "mechk": 6.45,
+ "thermal": 9.188,
+ "em": 14.412,
+ "snd": 19.762,
+ "elec": 24.6
+ },
+ "cues": [
+ [
+ 0.425,
+ "Scientists sort the many forms into two groups."
+ ],
+ [
+ 3.375,
+ "First, kinetic energies: energy on the move."
+ ],
+ [
+ 6.45,
+ "Mechanical kinetic energy: moving objects."
+ ],
+ [
+ 9.188,
+ "Thermal energy: molecules vibrating."
+ ],
+ [
+ 11.65,
+ "The faster they jiggle, the hotter something is."
+ ],
+ [
+ 14.412,
+ "Electromagnetic energy: light waves, both the ones we can see and the ones we can't."
+ ],
+ [
+ 19.762,
+ "Sound energy: molecules bumping into each other, passing the sound along."
+ ],
+ [
+ 24.6,
+ "And electric energy: the flow of electrons through a wire."
+ ]
+ ]
+ },
+ "potential": {
+ "dur": 35.75,
+ "marks": {
+ "pot": 1.275,
+ "grav2": 4.513,
+ "elastic": 8.113,
+ "nuc": 13.05,
+ "split": 17.587,
+ "chem": 23.975,
+ "fuel": 28.875
+ },
+ "cues": [
+ [
+ 0.35,
+ "The second group is potential energies: energy that is stored."
+ ],
+ [
+ 4.513,
+ "Gravitational potential energy, stored in an object's height."
+ ],
+ [
+ 8.113,
+ "Elastic energy, stored when something is stretched or squeezed, like a rubber band."
+ ],
+ [
+ 13.05,
+ "Nuclear energy, stored in the nucleus of an atom."
+ ],
+ [
+ 16.312,
+ "In nuclear fission, heavy atoms split apart and release that energy."
+ ],
+ [
+ 20.762,
+ "That's how nuclear power plants make electricity."
+ ],
+ [
+ 23.975,
+ "And chemical energy, stored in the bonds that hold atoms together."
+ ],
+ [
+ 28.875,
+ "Food, oil, gas, firewood and coal all store chemical energy."
+ ],
+ [
+ 33.462,
+ "That's why we call them fuels."
+ ]
+ ]
+ },
+ "count": {
+ "dur": 15.1,
+ "marks": {
+ "two": 2.3,
+ "seven": 3.975,
+ "nine": 4.9,
+ "matter": 6.438,
+ "chg": 11.475
+ },
+ "cues": [
+ [
+ 0.4,
+ "So how many forms are there?"
+ ],
+ [
+ 2.3,
+ "Some scientists say two, some say seven, others say nine!"
+ ],
+ [
+ 6.438,
+ "What matters is this: energy comes in many forms, moving and stored, and it is constantly changing from one form to another."
+ ]
+ ]
+ },
+ "q4": {
+ "dur": 4.325,
+ "marks": {},
+ "cues": [
+ [
+ 0.35,
+ "Quick check."
+ ],
+ [
+ 1.038,
+ "Is each form moving energy, or stored energy?"
+ ]
+ ]
+ },
+ "wrap": {
+ "dur": 27.175,
+ "marks": {
+ "w1": 1.363,
+ "w2": 6.662,
+ "w3": 11.637,
+ "w4": 18.125,
+ "end": 24.675
+ },
+ "cues": [
+ [
+ 0.35,
+ "To sum up."
+ ],
+ [
+ 1.363,
+ "Energy is never created or destroyed."
+ ],
+ [
+ 4.05,
+ "It only changes form or moves."
+ ],
+ [
+ 6.662,
+ "Kinetic energy is the energy of motion."
+ ],
+ [
+ 9.25,
+ "It grows with mass and velocity."
+ ],
+ [
+ 11.637,
+ "Potential energy is stored energy."
+ ],
+ [
+ 14.338,
+ "Gravitational potential energy grows with mass and height."
+ ],
+ [
+ 18.125,
+ "Heat, light, sound, electricity, chemical and nuclear energy are all forms of energy."
+ ],
+ [
+ 24.675,
+ "Now try the chapter practice."
+ ]
+ ]
+ },
+ "final1": {
+ "dur": 4.425,
+ "marks": {},
+ "cues": [
+ [
+ 0.375,
+ "Chapter practice."
+ ],
+ [
+ 1.75,
+ "Seven questions about the whole chapter."
+ ]
+ ]
+ },
+ "finish": {
+ "dur": 3.65,
+ "marks": {},
+ "cues": [
+ [
+ 0.4,
+ "Well done."
+ ],
+ [
+ 1.175,
+ "That's the end of chapter thirteen."
+ ]
+ ]
+ }
+};
diff --git a/site/physics-notebook/ch13/audio/en/wrap.mp3 b/site/physics-notebook/ch13/audio/en/wrap.mp3
new file mode 100644
index 0000000..e6418f6
Binary files /dev/null and b/site/physics-notebook/ch13/audio/en/wrap.mp3 differ
diff --git a/site/physics-notebook/ch13/index.html b/site/physics-notebook/ch13/index.html
new file mode 100644
index 0000000..36ab77d
--- /dev/null
+++ b/site/physics-notebook/ch13/index.html
@@ -0,0 +1,753 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Forms of Energy</title>
+<link rel="stylesheet" href="../lib/engine.css">
+<link rel="expect" href="#bar" blocking="render"><!-- hold the first frame until the player exists, so the page transition can run -->
+</head>
+<body>
+<script src="../lib/engine.js"></script>
+<script src="../lib/notebook.js"></script>
+<script src="../lib/energy.js"></script>
+<script src="audio/en/timings.js"></script>
+<script>
+'use strict';
+const CHAPTER = { number: 13, title: 'Forms of Energy', minutes: 9, language: 'en' };
+
+/* ---------- chapter drawing helpers ---------- */
+const DEG = Math.PI / 180;
+const ink = (p, d, w = 5, attrs = {}) => path(p, d, { stroke: INK, 'stroke-width': w, ...attrs });
+const ground = (p, y, x1 = 150, x2 = 1570) => ink(p, `M${x1} ${y}C${x1 + 300} ${y - 5} ${x2 - 500} ${y + 5} ${x2} ${y - 2}`, 4);
+const circ = (p, cx, cy, r, fill = '#fff', w = 4) => mk('circle', { cx, cy, r, fill, stroke: INK, 'stroke-width': w }, p);
+const pale = c => mix(c, '#ffffff', .55);
+// Largest size up to `size` at which str fits in w px.
+const fitSize = (str, w, size, font = HAND) => Math.min(size, size * w / handW(str, size, font));
+
+// A doodled kid: ink limbs, a shirt, a round head. Origin at the feet; faces right (flip for left).
+// Pose angles in degrees, 0 = hanging straight down, positive = toward the way the kid faces. Forearms and shins
+// are relative to their upper limb. b = back limb, f = front limb.
+const KL = { torso: 80, head: 28, ua: 44, fa: 40, th: 50, sh: 48 };
+const STAND = { lean: 0, ub: -10, fb: 12, uf: 10, ff: 8, tb: -5, sb: 0, tf: 5, sf: 0 };
+function kid(p, { x = 0, y = 0, s = 1, shirt = HL.blue, flip = false, o = 1, pose = STAND } = {}) {
+ const g = G(p, { x, y, s, o });
+ const f = mk('g', {}, g);
+ const L = KL, hipY = -(L.th + L.sh), P = { ...pose };
+ const back = ink(f, '', 5.5);
+ const shirtP = mk('path', { fill: shirt, stroke: INK, 'stroke-width': 4, 'stroke-linejoin': 'round' }, f);
+ const headG = G(f);
+ circ(headG, 0, 0, L.head, '#fff', 4.5);
+ ink(headG, 'M-24 -14Q-14 -36 8 -27Q14 -33 22 -24', 4.5);
+ mk('circle', { cx: 9, cy: -2, r: 3.6, fill: INK }, headG);
+ mk('circle', { cx: 21, cy: -2, r: 3.6, fill: INK }, headG);
+ const mouth = ink(headG, 'M9 11Q16 17 23 10', 3.5);
+ const front = ink(f, '', 5.5);
+ const sn = a => Math.sin(a * DEG), cs = a => Math.cos(a * DEG);
+ const seg = ([x0, y0], a, l) => [x0 + sn(a) * l, y0 + cs(a) * l];
+ const pl = pts => 'M' + pts.map(q => q[0].toFixed(1) + ' ' + q[1].toFixed(1)).join('L');
+ const K = { g, P, mouth, head: headG };
+ function joints() {
+ const H = [0, hipY], N = [sn(P.lean) * L.torso, hipY - cs(P.lean) * L.torso];
+ const Sh = [N[0] - sn(P.lean) * 8, N[1] + cs(P.lean) * 8];
+ const arm = (u, fo) => { const E = seg(Sh, u, L.ua); return [Sh, E, seg(E, u + fo, L.fa)]; };
+ const leg = (t, k) => { const Kn = seg(H, t, L.th); return [H, Kn, seg(Kn, t + k, L.sh)]; };
+ return { H, N, ab: arm(P.ub, P.fb), af: arm(P.uf, P.ff), lb: leg(P.tb, P.sb), lf: leg(P.tf, P.sf) };
+ }
+ const foot = l => { const F = l[2]; return `M${(F[0] - 3).toFixed(1)} ${F[1].toFixed(1)}L${(F[0] + 15).toFixed(1)} ${F[1].toFixed(1)}`; };
+ K.update = () => {
+ const J = K.J = joints(), px = cs(P.lean), py = sn(P.lean);
+ back.setAttribute('d', pl(J.ab) + pl(J.lb) + foot(J.lb));
+ front.setAttribute('d', pl(J.af) + pl(J.lf) + foot(J.lf));
+ const [N, H] = [J.N, J.H];
+ shirtP.setAttribute('d', pl([[N[0] + px * 15, N[1] + py * 15], [H[0] + px * 20, H[1] + py * 20 + 6],
+ [H[0] - px * 20, H[1] - py * 20 + 6], [N[0] - px * 15, N[1] - py * 15]]) + 'Z');
+ put(headG, { x: N[0] + sn(P.lean) * (L.head + 3), y: N[1] - cs(P.lean) * (L.head + 3) });
+ };
+ K.face = left => { flip = left; f.setAttribute('transform', left ? 'scale(-1 1)' : ''); return K; };
+ K.pose = Q => { Object.assign(P, Q); K.update(); return K; };
+ K.to = (Q, t0, dur = .4, ease = io) => {
+ let from;
+ prog(q => { if (!from) from = { ...P }; for (const k in Q) P[k] = from[k] + (Q[k] - from[k]) * q; K.update(); }, t0, dur, ease);
+ return K;
+ };
+ // A hand ('f' or 'b') in the parent's coordinates, from the current pose and the group's place.
+ K.hand = (w = 'f') => {
+ const s = st(g), J = joints(), q = (w === 'f' ? J.af : J.ab)[2];
+ return [s.x + s.s * (flip ? -q[0] : q[0]), s.y + s.s * q[1]];
+ };
+ K.update();
+ return flip ? K.face(true) : K;
+}
+const POSE = {
+ swingBack: { lean: 18, ub: -150, fb: 10, uf: -140, ff: 10, tb: -12, sb: 4, tf: 12, sf: -4 },
+ swingHit: { lean: 22, ub: 6, fb: 0, uf: 14, ff: 0, tb: -12, sb: 4, tf: 12, sf: -4 },
+ holdUp: { lean: 0, ub: -8, fb: 12, uf: 112, ff: -8, tb: -5, sb: 0, tf: 5, sf: 0 },
+ kickBack: { lean: -6, ub: 30, fb: 30, uf: -30, ff: 40, tb: -40, sb: -60, tf: 4, sf: 0 },
+ kick: { lean: -14, ub: -40, fb: 40, uf: 40, ff: 30, tb: 5, sb: 0, tf: 70, sf: -8 },
+ run: { lean: 14, ub: -50, fb: 70, uf: 50, ff: 80, tb: -38, sb: -62, tf: 46, sf: -12 },
+ eat: { lean: 6, ub: -8, fb: 14, uf: 40, ff: 128, tb: -5, sb: 0, tf: 5, sf: 0 },
+ wheel: { lean: 4, ub: 40, fb: 40, uf: 50, ff: 40, tb: 0, sb: 0, tf: 0, sf: 0 },
+ cheer: { lean: 0, ub: -150, fb: -10, uf: 150, ff: 10, tb: -8, sb: 0, tf: 8, sf: 0 },
+ follow: { lean: 6, ub: 150, fb: 20, uf: 160, ff: 20, tb: -12, sb: 4, tf: 12, sf: -4 },
+ trap: { lean: 0, ub: -10, fb: 12, uf: 10, ff: 8, tb: -5, sb: 0, tf: 28, sf: -14 },
+ shout: { lean: 4, ub: -20, fb: 30, uf: 60, ff: 70, tb: -6, sb: 0, tf: 6, sf: 0 },
+};
+
+/* ---------- props ---------- */
+function ball(p, x, y, r = 24, fill = '#ff6f8f') {
+ const g = G(p, { x, y });
+ circ(g, 0, 0, r, fill, 4);
+ ink(g, `M${-r * .55} ${-r * .3}Q${-r * .35} ${-r * .62} ${-r * .05} ${-r * .66}`, 3.5, { stroke: '#fff', opacity: .7 });
+ return g;
+}
+function tennisBall(p, x, y, r = 22) {
+ const g = G(p, { x, y });
+ circ(g, 0, 0, r, '#d7ef3f', 4);
+ ink(g, `M${-r * .9} ${-r * .3}Q0 ${r * .25} ${r * .9} ${-r * .3}`, 3, { stroke: '#fff' });
+ return g;
+}
+function bowlingBall(p, x, y, r = 46) {
+ const g = G(p, { x, y });
+ circ(g, 0, 0, r, '#3c4a8c', 4.5);
+ for (const [a, b] of [[-12, -18], [4, -22], [-4, -6]]) mk('circle', { cx: a * r / 46, cy: b * r / 46, r: 5 * r / 46, fill: INK }, g);
+ return g;
+}
+function flame(p, x, y, s = 1) {
+ const g = G(p, { x, y, s });
+ path(g, 'M0 40C-34 40 -40 8 -22 -14C-14 -24 -10 -36 -12 -48C6 -38 30 -18 30 10C30 30 18 40 0 40Z', { fill: EN.thermal, stroke: INK, 'stroke-width': 4 });
+ path(g, 'M0 38C-14 38 -18 22 -10 10C-4 2 0 -6 0 -14C10 -4 16 8 14 20C12 32 8 38 0 38Z', { fill: EN.light });
+ return g;
+}
+function speaker(p, x, y, s = 1) {
+ const g = G(p, { x, y, s });
+ path(g, 'M-40 -14H-22L0 -34V34L-22 14H-40Z', { fill: pale(EN.sound), stroke: INK, 'stroke-width': 4 });
+ for (const r of [16, 30, 44]) ink(g, `M${8 + r * .4} ${-r}Q${14 + r} 0 ${8 + r * .4} ${r}`, 4, { stroke: EN.sound });
+ return g;
+}
+function sunDoodle(p, x, y, r = 46) {
+ const g = G(p, { x, y });
+ for (let i = 0; i < 12; i++) {
+ const a = i * 30 * DEG;
+ ink(g, `M${Math.cos(a) * (r + 10)} ${Math.sin(a) * (r + 10)}L${Math.cos(a) * (r + 30)} ${Math.sin(a) * (r + 30)}`, 4.5, { stroke: '#e0a400' });
+ }
+ circ(g, 0, 0, r, EN.light, 4);
+ mk('circle', { cx: -r * .3, cy: -r * .12, r: r * .07, fill: INK }, g);
+ mk('circle', { cx: r * .3, cy: -r * .12, r: r * .07, fill: INK }, g);
+ ink(g, `M${-r * .3} ${r * .22}Q0 ${r * .48} ${r * .3} ${r * .22}`, 3.5);
+ return g;
+}
+function speedLines(p, x, y, n = 3, len = 60, color = INK) {
+ const g = G(p, { x, y });
+ for (let i = 0; i < n; i++) ink(g, `M${-len - i * 10} ${(i - (n - 1) / 2) * 16}H${-12 - i * 6}`, 4, { stroke: color });
+ return g;
+}
+function plant(p, x, y, s = 1) {
+ const g = G(p, { x, y, s });
+ ink(g, 'M0 0C4 -60 -6 -130 0 -200', 6, { stroke: '#3f7d1c' });
+ const leaf = (d, r) => path(g, d, { fill: '#9fd356', stroke: INK, 'stroke-width': 3.5, transform: r ? `rotate(${r})` : '' });
+ leaf('M0 -80C-40 -110 -90 -96 -110 -70C-70 -60 -30 -62 0 -80Z');
+ leaf('M2 -130C40 -160 90 -150 108 -122C70 -110 30 -112 2 -130Z');
+ leaf('M0 -196C-20 -230 -60 -238 -78 -226C-60 -200 -30 -192 0 -196Z');
+ path(g, 'M-34 0H34L26 46H-26Z', { fill: '#e9925a', stroke: INK, 'stroke-width': 4 });
+ return g;
+}
+function plate(p, x, y) {
+ const g = G(p, { x, y });
+ mk('ellipse', { cx: 0, cy: 0, rx: 70, ry: 16, fill: '#fff', stroke: INK, 'stroke-width': 4 }, g);
+ for (const [bx, r] of [[-24, 14], [-8, 16], [8, 13]]) circ(g, bx, -18, r, '#6cb33a', 3);
+ ink(g, 'M-16 -2V-12', 5, { stroke: '#3f7d1c' });
+ path(g, 'M22 -6L58 -26L52 -4Z', { fill: '#ff9a3c', stroke: INK, 'stroke-width': 3 });
+ return g;
+}
+function golfClub(p) { // shaft along +y from the grip at (0, 0)
+ const g = G(p);
+ ink(g, 'M0 0V150', 5);
+ path(g, 'M-4 146H26Q32 158 22 162H-6Z', { fill: '#9aa3ad', stroke: INK, 'stroke-width': 3.5 });
+ return g;
+}
+function bumperCar(p, x, y, color, flip = false) { // origin at the floor under the middle
+ const g = G(p, { x, y });
+ const f = mk('g', flip ? { transform: 'scale(-1 1)' } : {}, g);
+ path(f, 'M-120 -30C-124 -60 -110 -96 -70 -100L40 -100C60 -100 76 -84 84 -66L120 -52C130 -48 132 -36 126 -30Z',
+ { fill: color, stroke: INK, 'stroke-width': 4.5 });
+ path(f, 'M-132 -34H138Q150 -34 150 -20Q150 -6 138 -6H-132Q-144 -6 -144 -20Q-144 -34 -132 -34Z', { fill: '#3a3a3a', stroke: INK, 'stroke-width': 4 });
+ ink(f, 'M40 -100L60 -140', 5); ink(f, 'M46 -144L76 -134', 6);
+ return g;
+}
+function bookcase(p, x, y, w, h, shelves) { // top left at (x, y); shelves: y values of shelf tops
+ const g = G(p);
+ mk('rect', { x, y, width: w, height: h, fill: '#f0d3a6', stroke: INK, 'stroke-width': 5, rx: 4 }, g);
+ for (const sy of shelves) mk('rect', { x: x + 2, y: sy, width: w - 4, height: 14, fill: '#d8a868', stroke: INK, 'stroke-width': 3.5 }, g);
+ ink(g, `M${x + 16} ${y + h}V${y + h + 22}M${x + w - 16} ${y + h}V${y + h + 22}`, 6);
+ return g;
+}
+function bookDoodle(p, x, y, w, h, color) { // bottom middle at (x, y)
+ const g = G(p, { x, y });
+ mk('rect', { x: -w / 2, y: -h, width: w, height: h, fill: color, stroke: INK, 'stroke-width': 4, rx: 3 }, g);
+ ink(g, `M${-w / 2 + 6} ${-h + 16}H${w / 2 - 6}M${-w / 2 + 6} ${-24}H${w / 2 - 6}`, 3);
+ return g;
+}
+function skyscraper(p, x, top, w, base) {
+ const g = G(p);
+ mk('rect', { x, y: top, width: w, height: base - top, fill: '#cfd8e3', stroke: INK, 'stroke-width': 4.5 }, g);
+ for (let yy = top + 26; yy < base - 40; yy += 46) for (let k = 0; k < 3; k++)
+ mk('rect', { x: x + 18 + k * (w - 36) / 3, y: yy, width: (w - 36) / 3 - 14, height: 24, fill: '#8fc3ea', stroke: INK, 'stroke-width': 2.5 }, g);
+ return g;
+}
+// The book's wavy highlighter frame around a heading.
+function wavyHeading(p, str, x, y, color, { size = 64, t0 = 0 } = {}) {
+ const g = G(p, { o: 0 });
+ const w = handW(str.toUpperCase(), size, HEAD) + str.length * 1.5 + 70, h = size + 50;
+ let d = `M${x - w / 2} ${y - h / 2 - size * .33}`;
+ const k = 14, n = Math.round(w / 40);
+ const top = y - h / 2 - size * .33, bot = y + h / 2 - size * .33;
+ for (let i = 1; i <= n; i++) d += `Q${x - w / 2 + (i - .5) * w / n} ${top - (i % 2 ? k : -k) * .5} ${x - w / 2 + i * w / n} ${top}`;
+ d += `Q${x + w / 2 + 24} ${(top + bot) / 2} ${x + w / 2} ${bot}`;
+ for (let i = n - 1; i >= 0; i--) d += `Q${x - w / 2 + (i + .5) * w / n} ${bot + (i % 2 ? k : -k) * .5} ${x - w / 2 + i * w / n} ${bot}`;
+ d += `Q${x - w / 2 - 24} ${(top + bot) / 2} ${x - w / 2} ${top}`;
+ path(g, d, { stroke: color, 'stroke-width': 12, fill: '#fff' });
+ const t = head(g, str, x, y, { size, fill: '#fff' });
+ t.setAttribute('stroke', INK); t.setAttribute('stroke-width', 2.5); t.setAttribute('paint-order', 'stroke');
+ show(g, t0);
+ return g;
+}
+// A ribbon card from the book's lists: name in capitals, a short description under it.
+function ribbon(p, x, y, w, name, desc, color, t0) {
+ const g = G(p, { x, y, o: 0, s: .9 });
+ path(g, `M${-w / 2 + 8} -48L${w / 2} -52L${w / 2 + 10} 48L${-w / 2} 52Z`, { fill: color });
+ const ns = fitSize(name.toUpperCase(), w - 24, 26, HEAD);
+ head(g, name, 0, -10, { size: ns });
+ hand(g, desc, 0, 30, { size: fitSize(desc, w - 20, 27) });
+ pop(g, t0);
+ return g;
+}
+// A picture frame for one form of energy (circle) with a drawing inside.
+function vignette(p, x, y, r, t0) {
+ const g = G(p, { x, y, o: 0, s: .8 });
+ circ(g, 0, 0, r, '#fff', 4.5);
+ pop(g, t0);
+ return g;
+}
+
+/* ---------- scene builders shared by beats ---------- */
+const HILL = { x0: 360, x1: 1250, yb: 790, yt: 330, r: 26 };
+const hillY = x => { const u = Math.min(1, Math.max(0, (x - HILL.x0) / (HILL.x1 - HILL.x0))); return HILL.yb - (HILL.yb - HILL.yt) * (3 * u * u - 2 * u * u * u); };
+function drawHill(p) {
+ let d = `M150 ${HILL.yb}L${HILL.x0} ${HILL.yb}`;
+ for (let x = HILL.x0; x <= 1570; x += 20) d += `L${x} ${hillY(x).toFixed(1)}`;
+ path(p, d + 'L1570 900L150 900Z', { fill: '#e4f2c9', stroke: 'none' });
+ ink(p, d, 5);
+ for (const x of [520, 760, 980, 1180, 1400]) ink(p, `M${x} ${hillY(x) + 40}l6 -14l6 14l6 -12`, 3, { stroke: '#7fb24a' });
+}
+const ballOnHill = x => { const dx = 1, s = (hillY(x + dx) - hillY(x - dx)) / (2 * dx), n = Math.hypot(1, s); return [x + s * HILL.r / n, hillY(x) - HILL.r / n]; };
+
+/* ---------- motion helpers: everything below is a pure function of the beat time ---------- */
+const clamp01 = v => Math.max(0, Math.min(1, v));
+const lerp = (a, b, q) => a + (b - a) * q;
+const lerpPose = (A, B, q) => { const o = {}; for (const k in A) o[k] = lerp(A[k], B[k] ?? A[k], q); return o; };
+// Poses keyed by time [[t, pose, ease?], …]: held before the first key and after the last, eased between.
+function poseAt(keys, t) {
+ if (t <= keys[0][0]) return keys[0][1];
+ for (let i = 0; i < keys.length - 1; i++) {
+ const [t0, A] = keys[i], [t1, B, e = io] = keys[i + 1];
+ if (t < t1) return lerpPose(A, B, e(clamp01((t - t0) / (t1 - t0))));
+ }
+ return keys[keys.length - 1][1];
+}
+// A running (or walking) pose at gait phase ph; one cycle is two steps. Drive ph from the distance covered.
+function gait(ph, run = true) {
+ const a = run ? 40 : 24, b0 = run ? 15 : 4, b1 = run ? 70 : 35, arm = run ? 45 : 22, fa = run ? 85 : 20;
+ const leg = q => [(run ? 8 : 2) + a * Math.sin(q), -(b0 + b1 * Math.max(0, Math.cos(q)))];
+ const [tf, sf] = leg(ph), [tb, sb] = leg(ph + Math.PI);
+ return { lean: run ? 14 : 3, uf: 10 - arm * Math.sin(ph), ff: fa, ub: 10 + arm * Math.sin(ph), fb: fa, tf, sf, tb, sb };
+}
+const STRIDE = 186; // world px per gait cycle at s = 1 (two steps)
+// Hops as a function of t: from `start`, each move [t0, dur, x, y, h] jumps along an arc h high.
+function hopsAt(start, moves, t) {
+ let [x, y] = start;
+ for (const [t0, dur, x2, y2, h = 80] of moves) {
+ if (t < t0) break;
+ const q = clamp01((t - t0) / dur);
+ if (q < 1) return [lerp(x, x2, q), lerp(y, y2, q) - h * 4 * q * (1 - q)];
+ [x, y] = [x2, y2];
+ }
+ return [x, y];
+}
+const star = (p, x, y, s = 1) => {
+ const g = G(p, { x, y, s: 0, o: 0 });
+ path(g, 'M0 -34L8 -10L32 -10L12 4L20 28L0 14L-20 28L-12 4L-32 -10L-8 -10Z', { fill: EN.light, stroke: INK, 'stroke-width': 3 });
+ g._s = s;
+ return g;
+};
+const flash = (g, t0, hold = .35) => { tw(g, { s: g._s, o: 1 }, t0, .15, out); tw(g, { o: 0, s: g._s * 1.3 }, t0 + hold, .3); };
+const stripedBall = (p, x, y, r, fill) => { const g = ball(p, x, y, r, fill); ink(g, `M${-r} 0H${r}`, 3, { stroke: '#fff', opacity: .8 }); return g; };
+
+/* ---------- beats: [id, title, run(m, D), { ask }?] ---------- */
+const BEATS = [
+ ['intro', 'Forms of energy', (m, D) => {
+ const p = G(scene);
+ S.panel = p;
+ show(hand(p, 'Unit 4 · Energy', 200, 230, { size: 36, fill: COL.dim, anchor: 'start', o: 0 }), .2);
+ show(hand(p, 'Chapter 13', 200, 300, { size: 44, anchor: 'start', o: 0 }), .3);
+ term(p, 'Forms of', 200, 440, { size: 100, anchor: 'start', color: HL.yellow, t0: m('title') });
+ term(p, 'Energy', 200, 580, { size: 130, anchor: 'start', color: HL.pink, t0: m('title', .35) });
+ ground(p, 760, 960, 1480);
+ const b = blip(p, { x: 1220, y: 470, s: 1.7, o: 0, form: 'light' }).live(D);
+ show(b.g, m('blob', -.1), .15); tw(b.g, { y: 760 }, m('blob', -.1), .42, q => q * q); b.squash(m('blob', .32), .3, .45);
+ ['chemical', 'thermal', 'sound', 'kinetic'].forEach((f, i) => { const t = m('forms', i * .7); b.hop(1220, 760, t, .5, 60); b.form(f, t + .15, .3); });
+ show(hand(p, 'changes form · never disappears', 1220, 840, { size: 34, fill: COL.dim, o: 0 }), m('never'));
+ }],
+ ['forms', 'Many forms', (m, D) => {
+ const p = panel(0);
+ ground(p, 760, 520, 1080);
+ const b = blip(p, { x: 800, y: 760, s: 1.5, form: 'kinetic' }).live(D, 1);
+ const spots = [['heat', 330, 360, 'thermal', g => flame(g, 0, 4, 1.3)], ['sound', 620, 250, 'sound', g => speaker(g, -6, 0, 1.2)],
+ ['light', 980, 250, 'light', g => sunDoodle(g, 0, 0, 34)], ['motion', 1270, 360, 'kinetic', g => { ball(g, 18, 0, 30); speedLines(g, -14, 0, 3, 50); }]];
+ for (const [mark, x, y, form, drawIt] of spots) {
+ const v = vignette(p, x, y, 92, m(mark));
+ drawIt(v);
+ hand(v, mark, 0, 140, { size: 40, fill: mix(EN[form], INK, .3) });
+ b.hop(800, 760, m(mark, -.08), .4, 36).form(form, m(mark), .25).look((x - 800) / 480, -1, m(mark));
+ }
+ b.look(0, 0, m('same')).mouth('open', m('same')).mouth('smile', m('same', .9));
+ term(p, 'same energy, different costume', 800, 850, { size: 38, font: HAND, color: HL.yellow, t0: m('same') });
+ }],
+ ['golf', 'Energy moves', (m, D) => {
+ const p = panel(0);
+ const cam = camera(p, D), w = cam.world;
+ ground(w, 740, -200, 1800);
+ for (const x of [260, 640, 900, 1150]) ink(w, `M${x} 740l6 -14l6 14l6 -12`, 3, { stroke: '#7fb24a' });
+ mk('ellipse', { cx: 1430, cy: 742, rx: 30, ry: 7, fill: INK }, w);
+ ink(w, 'M1430 742V520', 5);
+ path(w, 'M1432 522L1520 548L1432 576Z', { fill: '#ff5b5b', stroke: INK, 'stroke-width': 4 });
+ const k = kid(w, { x: 330, y: 740, s: 1.4, pose: POSE.swingHit, shirt: HL.green });
+ const B0 = [520, 718], HOLE = [1430, 726], H = 380, T = 4;
+ const trail = path(w, `M${B0[0]} ${B0[1]}Q${(B0[0] + HOLE[0]) / 2} ${B0[1] - 2 * H} ${HOLE[0]} ${HOLE[1]}`, { stroke: COL.faint, 'stroke-width': 3 }, { d: 0 });
+ const club = golfClub(w), bl = ball(w, B0[0], B0[1], 20, '#fff');
+ const b = blip(w, { s: .36, o: 0 }).live(D, 2);
+ const hit = star(w, B0[0] - 16, B0[1] - 4, .9);
+ const tS = m('swing'), tH = m('hit'), tL = tH + T;
+ const aBall = (() => { const [hx, hy] = k.hand('f'); return Math.atan2(-(B0[0] - 8 - hx), B0[1] + 12 - hy) / DEG; })();
+ // address, backswing, a fast downswing that meets the ball on 'hit', follow-through
+ const keys = [[tS, POSE.swingHit], [tS + 1, POSE.swingBack], [tH - .3, POSE.swingBack], [tH, POSE.swingHit, q => q * q], [tH + .55, POSE.follow, out]];
+ const ang = t => t < tS ? aBall : t < tS + 1 ? lerp(aBall, 160, out(clamp01(t - tS))) : t < tH - .3 ? 160
+ : t < tH ? lerp(160, aBall, ((t - tH + .3) / .3) ** 2) : lerp(aBall, -215, out(clamp01((t - tH) / .55)));
+ const fl = t => clamp01((t - tH) / T);
+ const ballAt = t => { const u = fl(t); return [lerp(B0[0], HOLE[0], u), lerp(B0[1], HOLE[1], u) - 4 * H * u * (1 - u)]; };
+ clockRun(t => {
+ k.pose(poseAt(keys, t));
+ const [hx, hy] = k.hand('f'), a = ang(t);
+ put(club, { x: hx, y: hy, r: a });
+ const [bx, by] = ballAt(t);
+ put(bl, { x: bx, y: by, o: fl(t) < 1 ? 1 : 0 });
+ put(trail, { d: fl(t) });
+ // Blip rides the club head, jumps into the ball at contact, and hops out beside the hole when it drops in
+ if (t < tH) put(b.g, { x: hx - Math.sin(a * DEG) * 152, y: hy + Math.cos(a * DEG) * 152 - 4 });
+ else if (t < tL) put(b.g, { x: bx, y: by - 16 });
+ else { const [x, y] = hopsAt([HOLE[0], HOLE[1] - 16], [[tL, .6, 1370, 740, 70]], t); put(b.g, { x, y }); }
+ }, D);
+ show(b.g, tS - .3, .3); b.squash(tL + .6, .25);
+ flash(hit, tH);
+ cam.to({ x: 470, y: 560, z: 1.8 }, tH - 2.4, 1.8).to({ x: 800, y: 450, z: 1 }, tH + .25, 1.8);
+ term(p, 'most of the energy went into the ball', 1100, 600, { size: 34, font: HAND, color: HL.pink, t0: m('pass') });
+ }],
+ ['law', 'Conservation of energy', (m, D) => {
+ const p = panel(0), under = G(p); // highlights go under the bar labels
+ const E = energyBars(p, { x: 260, y: 700, h: 340, w: 74, gap: 40, title: 'energy in the swing', o: 0, keys: [
+ { key: 'club', label: 'club', color: EN.kinetic }, { key: 'ball', label: 'ball', color: EN.kinetic },
+ { key: 'sound', label: 'sound', color: EN.sound }, { key: 'heat', label: 'heat', color: EN.thermal }] });
+ E.set([1, 0, 0, 0]);
+ show(E.g, .2);
+ const mark = (i, c, t) => swipe(under, 254 + i * 114, 728, 86, { h: 34, color: c, t0: t, o: .6 });
+ mark(0, HL.pink, m('club'));
+ E.to([.12, .76, .04, .08], m('after'), 1.2);
+ mark(1, HL.pink, m('after', .3));
+ mark(2, HL.lilac, m('tock')); mark(3, HL.orange, m('tock', .25));
+ show(hand(p, 'tock!', 525, 600, { size: 36, o: 0 }), m('tock'));
+ const tot = G(p, { o: 0 });
+ hand(tot, 'same', 856, 330, { size: 38, anchor: 'start' }); hand(tot, 'total', 856, 372, { size: 38, anchor: 'start' });
+ ink(tot, 'M866 340Q846 352 832 368', 4);
+ show(tot, m('total'));
+ defCard(p, 1270, 360, 520, 260, [['Law of conservation', 34, 'head'], ['of energy', 34, 'head']], { color: HL.blue, t0: m('law') });
+ const l1 = G(p, { o: 0, y: 10 });
+ hand(l1, 'Energy can neither be created', 1270, 590, { size: 36 }); hand(l1, 'nor destroyed.', 1270, 636, { size: 36 });
+ tw(l1, { o: 1, y: 0 }, m('neither'), .5);
+ term(p, 'It only changes form or moves.', 1270, 720, { size: 36, font: HAND, color: HL.yellow, t0: m('change') });
+ }],
+ ['sun', 'Solar-powered', (m, D) => {
+ const p = panel(0);
+ ground(p, 770, 420);
+ sunDoodle(p, 250, 220, 70);
+ const pl = plant(p, 620, 724, 1.05);
+ const tb = G(p);
+ ink(tb, 'M790 650H940M810 650V770M920 650V770', 6);
+ const pt = plate(p, 865, 638);
+ const k = kid(p, { x: 1020, y: 770, s: 1.25, pose: STAND, shirt: HL.orange, flip: true });
+ const b = blip(p, { x: 300, y: 300, s: 0, o: 0, form: 'light' }).live(D, 3);
+ const lab = (str, x, y, c, t) => term(p, str, x, y, { size: 34, font: HAND, color: c, t0: t });
+ const tSun = m('sun'), tLeaf = m('leaf'), tE = m('eat'), tR = m('run'), tBite = tE + 2.2, tEnd = tR + 2.6;
+ inkArrow(p, 330, 260, 500, 500, { bend: -30, color: '#e0a400', t0: tSun }); lab('light', 470, 330, HL.yellow, tSun);
+ tw(b.g, { s: .55, o: 1 }, tSun, .4, back);
+ tw(pl, { s: 1.2 }, tLeaf + .6, 2.4, out); // the plant grows on the stored energy
+ b.form('chemical', tLeaf - .2);
+ lab('chemical energy', 620, 830, HL.green, tLeaf);
+ inkArrow(p, 700, 520, 840, 590, { bend: -40, color: '#5c9a26', t0: tE });
+ tw(b.g, { s: 0 }, tBite + .55, .25); // eaten
+ tw(pt, { o: .35 }, tBite + .6, .4);
+ tw(b.g, { s: .55 }, tR + .2, .35, back); b.form('kinetic', tR + .2, .2);
+ lab('motion', 1400, 830, HL.pink, tR + .4);
+ const X0 = 1020, X1 = 1420, kx = t => lerp(X0, X1, clamp01((t - tR) / (tEnd - tR)));
+ const eat0 = { ...STAND, uf: 34, ff: 30 };
+ clockRun(t => {
+ const x = kx(t), ph = 2 * Math.PI * (x - X0) / (STRIDE * 1.25);
+ let P;
+ if (t < tE) P = STAND;
+ else if (t < tR) P = lerpPose(eat0, POSE.eat, t < tE + .5 ? io((t - tE) / .5) * .3 : .5 - .5 * Math.cos((t - tE - .5) * 2 * Math.PI / 1.7));
+ else if (t < tEnd) P = lerpPose(STAND, gait(ph), clamp01((t - tR) / .25));
+ else P = poseAt([[tEnd, gait(2 * Math.PI * (X1 - X0) / (STRIDE * 1.25))], [tEnd + .4, STAND], [m('solar'), STAND], [m('solar', .4), POSE.cheer, back]], t);
+ k.face(t < tR); k.pose(P); put(k.g, { x });
+ if (t < tR) {
+ const [bx, by] = hopsAt([300, 300], [[tSun + .5, 1.6, 500, 640, 40], [tE + .1, .9, 865, 618, 150], [tBite, .5, 990, 520, 50]], t);
+ put(b.g, { x: bx, y: by });
+ } else put(b.g, { x: x + 6, y: 770 - 1.25 * 262 - 14 - 16 * Math.abs(Math.sin(ph * 2)) });
+ }, D);
+ wavyHeading(p, 'technically, we\'re solar-powered!', 1050, 170, HL.yellow, { size: 40, t0: m('solar') });
+ }],
+ ['q1', 'Quick check', (m, D) => {
+ const p = panel(0);
+ ground(p, 760, 170, 560);
+ blip(p, { x: 360, y: 760, s: 1.6, form: 'light' }).live(D, 8);
+ hand(p, 'light, chemical, motion…', 360, 830, { size: 32, fill: COL.dim });
+ }, { ask: done => quiz({ x: 640, y: 190, w: 880, cls: 'side' }, [{
+ id: 'c-law', prompt: ['Which statement is the law of conservation of energy?'],
+ build: choice([['Energy can change form, but the total never changes.'], ['Energy is used up when things move.'], ['Plants create new energy as they grow.']], 0,
+ 'Energy is never created or destroyed; it only changes form or moves between objects.',
+ [null, 'Moving things pass their energy on, often as heat and sound. It is not used up; the total stays the same.',
+ 'Plants store energy that came from sunlight. They change its form; they do not create it.']),
+ }], done) }],
+ ['pen', 'Potential and kinetic', (m, D) => {
+ const p = panel(0);
+ const FLOOR = 780, under = G(p);
+ ground(p, FLOOR, 150, 820);
+ const k = kid(p, { x: 260, y: FLOOR, s: 1.45, pose: POSE.holdUp, shirt: HL.lilac });
+ const [hx, hy] = k.hand('f');
+ const pen = G(p, { x: hx, y: hy + 86 }); // origin at the tip, so it can tip over on landing
+ path(pen, 'M-7 -92H7V-16L0 0L-7 -16Z', { fill: '#4a7fd6', stroke: INK, 'stroke-width': 3.5 });
+ const E = energyBars(p, { x: 900, y: 700, h: 300, w: 80, gap: 70, title: 'the pen\'s energy', keys: [
+ { label: 'potential', color: EN.potential }, { label: 'kinetic', color: EN.kinetic }, { label: 'heat & sound', color: EN.thermal }] });
+ term(p, 'potential energy', 640, 300, { size: 34, font: HEAD, color: HL.blue, t0: m('pe') });
+ show(hand(p, 'stored', 640, 350, { size: 32, o: 0 }), m('pe'));
+ term(p, 'kinetic energy', 640, 560, { size: 34, font: HEAD, color: HL.pink, t0: m('ke') });
+ show(hand(p, 'motion', 640, 610, { size: 32, o: 0 }), m('ke'));
+ // Two drops: one at about real speed, then a slow-motion replay that lands on 'land'.
+ const drops = [[m('drop'), .9], [m('bars'), m('land') - m('bars')]], reset = m('bars', -.5);
+ const fall = t => { const [t0, T] = t >= reset ? drops[1] : drops[0]; return t < t0 ? [0, Infinity] : [clamp01((t - t0) / T) ** 2, t0 + T]; };
+ const drop = FLOOR - (hy + 86);
+ clockRun(t => {
+ const [f, tl] = fall(t), after = t - tl;
+ put(pen, { y: hy + 86 + drop * f, r: after > 0 ? -84 * out(clamp01(after / .45)) : 0, o: t > reset - .25 && t < reset ? 0 : 1 });
+ const heat = after > 0 ? clamp01(after / .35) : 0;
+ E.set([1 - f, f * (1 - heat), heat]);
+ }, D);
+ const slow = G(p, { o: 0 });
+ term(slow, 'slow motion replay', 470, 470, { size: 30, font: HAND, color: HL.lilac, t0: reset });
+ show(slow, reset, .2); hide(slow, m('land', .8));
+ swipe(under, 1374, 726, 102, { h: 34, color: HL.yellow, t0: m('sum'), o: .7 });
+ defCard(p, 1200, 160, 600, 130, [['Mechanical energy', 32, 'head'], ['position or motion', 30]], { color: HL.green, t0: m('mech') });
+ }],
+ ['hill', 'Up the hill and back', (m, D) => {
+ const p = panel(0);
+ drawHill(p);
+ const k = kid(p, { x: 250, y: HILL.yb, s: 1.3, pose: STAND, shirt: HL.blue });
+ const E = energyBars(p, { x: 560, y: 440, h: 220, w: 60, gap: 50, title: 'the ball\'s energy', keys: [
+ { label: 'potential', color: EN.potential }, { label: 'kinetic', color: EN.kinetic }] });
+ const X0 = 352, XS = 1060, tk = m('kick'), tc = (m('stop') + m('back')) / 2, Td = m('fast') + 1.5 - tc, tRet = tc + Td;
+ const peak = HILL.yb - hillY(XS);
+ // Up: steady slowing to a turn near the top; down: speeding up; then the kid traps it.
+ const bx = t => t < tk ? X0 : t < tc ? XS - (XS - X0) * ((tc - t) / (tc - tk)) ** 2 : t < tRet ? XS - (XS - X0) * ((t - tc) / Td) ** 2 : X0;
+ const bl = stripedBall(p, 0, 0, HILL.r, '#ff6f8f');
+ const keys = [[0, STAND], [tk - .7, POSE.kickBack], [tk - .18, POSE.kickBack], [tk, POSE.kick, q => q * q], [tk + .8, STAND],
+ [m('back'), STAND], [m('back', .3), POSE.shout], [tRet - .5, POSE.shout], [tRet - .05, POSE.trap], [tRet + .6, STAND]];
+ clockRun(t => {
+ const x = bx(t), [px, py] = ballOnHill(x);
+ put(bl, { x: px, y: py, r: (x - X0) / HILL.r / DEG });
+ const pe = (HILL.yb - hillY(x)) / peak;
+ E.set([pe, 1 - pe]);
+ k.pose(poseAt(keys, t));
+ }, D);
+ const kin = term(p, 'kinetic!', 500, 690, { size: 36, font: HEAD, color: HL.pink, t0: tk });
+ tw(kin.g, { o: 0 }, m('slow', 1), .5); tw(kin.g, { o: 1 }, m('fast', .6), .4);
+ const pot = term(p, 'potential', 1060, 290, { size: 36, font: HEAD, color: HL.blue, t0: m('stop') });
+ hide(pot.g, m('fast', .4));
+ hide(bubble(p, 'Come back!', 420, 470, 300, 560, { t0: m('back', .2) }), tRet + .3);
+ hide(E.g, tRet + .3); hide(kin.g, tRet + .3); // trapped: the ball's energy went into the kid's foot
+ defCard(p, 1300, 150, 500, 150, [['Gravitational', 30, 'head'], ['potential energy', 30, 'head'], ['stored because of height', 28]], { color: HL.blue, t0: m('grav') });
+ }],
+ ['bumper', 'Bumper cars', (m, D) => {
+ const p = panel(0);
+ mk('rect', { x: 150, y: 760, width: 1420, height: 140, fill: '#ece6f5' }, p);
+ ground(p, 760);
+ const kA = kid(p, { s: 1.1, pose: POSE.wheel, shirt: HL.blue }), kB = kid(p, { s: 1.1, pose: POSE.wheel, shirt: HL.pink });
+ const A = bumperCar(p, 0, 760, '#ff7aa8'), Bc = bumperCar(p, 0, 760, '#7cc6f2');
+ const linesA = speedLines(p, 0, 700, 3, 70), linesB = speedLines(p, 0, 700, 3, 70);
+ const E = energyBars(p, { x: 1060, y: 400, h: 200, w: 60, gap: 60, title: 'energy', keys: [
+ { label: 'pink car', color: EN.kinetic }, { label: 'blue car', color: EN.kinetic }, { label: 'heat & sound', color: EN.thermal }] });
+ const b = blip(p, { s: .4, form: 'kinetic' }).live(D, 4);
+ const tB = m('bump'), v = 51, XB = 1010, XA = XB - 294;
+ // Pink: steady until contact, then a quarter of its speed, braking within a second. Blue: 0.92 v after.
+ const xA = t => t < tB ? XA - v * (tB - t) : XA + .25 * v * (Math.min(1, t - tB) - Math.min(1, t - tB) ** 2 / 2);
+ const xB = t => t < tB ? XB : XB + .92 * v * (t - tB);
+ const jolt = t => t < tB ? 0 : Math.exp(-(t - tB) * 4) * Math.sin((t - tB) * 18);
+ clockRun(t => {
+ const a = xA(t), c = xB(t);
+ put(A, { x: a, r: -2 * jolt(t) }); put(Bc, { x: c, r: 2 * jolt(t) });
+ put(kA.g, { x: a - 40, y: 730 }); kA.pose({ ...POSE.wheel, lean: 4 + 18 * jolt(t) });
+ put(kB.g, { x: c - 40, y: 730 }); kB.pose({ ...POSE.wheel, lean: 4 - 16 * jolt(t) });
+ put(linesA, { x: a - 140, o: t < tB ? 1 : 0 }); put(linesB, { x: c - 140, o: t < tB ? 0 : 1 });
+ const q = clamp01((t - tB) / .25), brake = clamp01(t - tB);
+ E.set([lerp(1, .06, q) * (1 - brake), lerp(0, .84, q), lerp(0, .1, q) + .06 * q * brake]);
+ const [hx, hy] = hopsAt([0, 0], [[tB, .45, 1, 0, 70]], t); // hx: 0 on pink, 1 on blue
+ put(b.g, { x: lerp(a + 30, c + 30, hx), y: 662 + hy });
+ }, D);
+ flash(star(p, XA + 147, 740, 1), tB);
+ }],
+ ['q2', 'Quick check', (m, D) => {
+ const p = panel(0);
+ drawHill(p);
+ S.q2 = [460, 820, 1140].map(x => { const [bx, by] = ballOnHill(x); return { el: ball(p, bx, by, HILL.r), x: bx, y: by }; });
+ }, { ask: done => quiz({ x: 170, y: 70, w: 600, cls: 'side' }, [{
+ id: 'c-hill', prompt: ['Click the ball with the most potential energy.'],
+ build: pickEls(S.q2.map((b, i) => ({ el: b.el, box: [b.x - 44, b.y - 44, 88, 88], label: ['low ball', 'middle ball', 'high ball'][i] })), 2,
+ 'The highest ball has the most potential energy: it has the farthest to fall.',
+ i => i === 0 ? 'This ball is near the bottom, so it has little height to fall from.' : 'Higher than the first, but another ball sits higher still.'),
+ }], done) }],
+ ['depends', 'Mass and velocity', (m, D) => {
+ const p = panel(0);
+ ink(p, 'M800 200V840', 3, { 'stroke-dasharray': '8 10', stroke: COL.faint });
+ term(p, 'mass', 460, 150, { size: 44, font: HEAD, color: HL.pink, t0: m('mass') });
+ for (const x0 of [200, 860]) mk('rect', { x: x0, y: 720, width: 560, height: 40, fill: '#f3dfab', stroke: INK, 'stroke-width': 3.5, rx: 6 }, p);
+ // A ball falls from y0 so it lands on t1 (falling for T s), then sinks `sink` px into the sand.
+ const drop = (el, x, y0, yl, t1, T, sink = 0) => {
+ prog(q => put(el, { y: lerp(y0, yl, q * q) }), t1 - T, T, lin);
+ if (sink) tw(el, { y: yl + sink }, t1, .2, out);
+ };
+ const splash = (x, w, t) => { const g = G(p, { x, y: 712, s: .3, o: 0 }); for (const s of [-1, 1]) ink(g, `M${s * w * .3} 0Q${s * w * .6} ${-w * .7} ${s * w} ${-w * .2}`, 4); tw(g, { s: 1, o: 1 }, t, .3, out); };
+ const meter = (x, y, w, str, t) => {
+ const g = G(p, { o: 0 }), r = mk('rect', { x, y, width: 0, height: 24, fill: EN.kinetic, stroke: INK, 'stroke-width': 3, rx: 4 }, g);
+ hand(g, str, x - 12, y + 20, { size: 26, anchor: 'end' }); show(g, t, .2); tw(r, { a_width: w }, t, .6, out);
+ };
+ const tb = tennisBall(p, 330, 260), bb = bowlingBall(p, 590, 240);
+ put(tb, { o: 0 }); put(bb, { o: 0 }); show(tb, m('drop')); show(bb, m('drop'));
+ drop(tb, 330, 260, 698, m('hit'), .9); drop(bb, 590, 240, 674, m('hit'), .9, 10);
+ splash(330, 40, m('hit')); splash(590, 120, m('hit'));
+ meter(330, 790, 40, 'tennis', m('hit', .2)); meter(330, 830, 300, 'bowling', m('hit', .2));
+ term(p, 'velocity', 1150, 150, { size: 44, font: HEAD, color: HL.pink, t0: m('speed') });
+ skyscraper(p, 1350, 230, 160, 720);
+ const t1 = tennisBall(p, 950, 610), t2 = tennisBall(p, 1290, 250);
+ put(t1, { o: 0 }); put(t2, { o: 0 }); show(t1, m('low', -.6)); show(t2, m('high', -.6));
+ ink(p, 'M910 610V720', 3); hand(p, '2 ft', 900, 670, { size: 26, anchor: 'end' });
+ drop(t1, 950, 610, 698, m('low', .6), .35); splash(950, 30, m('low', .6)); meter(990, 790, 40, '2 ft', m('low', .8));
+ const sl = G(p, { x: 1290, o: 0 });
+ for (const dx of [-14, 0, 14]) ink(sl, `M${dx} -60V-20`, 3.5);
+ prog(q => { const y = lerp(250, 698, q * q); put(sl, { y, o: q > .3 && q < 1 ? 1 : 0 }); }, m('high', .1), 1.2, lin);
+ drop(t2, 1290, 250, 698, m('high', 1.3), 1.2); splash(1290, 110, m('high', 1.3)); meter(990, 830, 330, 'skyscraper', m('high', 1.5));
+ term(p, 'more mass or more velocity = more kinetic energy', 800, 70, { size: 34, font: HAND, color: HL.yellow, t0: m('more') });
+ }],
+ ['shelf', 'Mass and height', (m, D) => {
+ const p = panel(0);
+ ground(p, 800, 150, 860);
+ bookcase(p, 300, 150, 420, 630, [300, 460, 620, 760]);
+ const bA = bookDoodle(p, 420, 300, 42, 120, '#5b8fe0'), bB = bookDoodle(p, 420, 760, 42, 120, '#5b8fe0');
+ put(bA, { o: 0 }); put(bB, { o: 0 }); show(bA, m('shelf')); show(bB, m('shelf', .3));
+ const bH = bookDoodle(p, 660, 300, 96, 130, '#2e5aa8'); put(bH, { o: 0 });
+ const E = energyBars(p, { x: 1000, y: 700, h: 380, w: 80, gap: 50, total: false, title: 'potential energy', keys: [
+ { label: 'top book', color: EN.potential }, { label: 'bottom book', color: EN.potential }, { label: 'heavy book', color: '#1f6fae' }] });
+ E.to([.45, .05, 0], m('top'), .9);
+ const drop = G(p);
+ draw(ink(drop, 'M250 300V800', 3, { 'stroke-dasharray': '8 9' }), m('fall'), .8);
+ show(ink(G(drop, { o: 0 }), 'M236 300H264M236 800H264', 3), m('fall'));
+ show(hand(drop, 'farther', 240, 520, { size: 28, anchor: 'end', o: 0 }), m('fall', .5)); show(hand(drop, 'to fall', 240, 556, { size: 28, anchor: 'end', o: 0 }), m('fall', .6));
+ tw(bH, { o: 1, x: 560 }, m('heavy'), .6, out); E.to([.45, .05, .9], m('heavy', .4), .9);
+ term(p, 'more mass or more height = more potential energy', 800, 70, { size: 34, font: HAND, color: HL.blue, t0: m('pe2') });
+ }],
+ ['q3', 'Quick check', () => {}, { ask: done => quiz({ x: 940, y: 150, w: 620, cls: 'side' }, [{
+ id: 'c-factors', prompt: ['Which two things decide an object\'s gravitational potential energy?'],
+ build: choice([['mass and height'], ['mass and velocity'], ['height and colour']], 0,
+ 'More mass or more height means more stored energy.',
+ [null, 'Mass and velocity decide kinetic energy, the energy of motion. Stored energy from gravity depends on height.',
+ 'Colour makes no difference. Think of the two books: what was different about them?']),
+ }], done) }],
+ ['kinetic', 'Kinetic energies', (m, D) => {
+ const p = panel(0);
+ wavyHeading(p, 'Kinetic energies', 800, 130, HL.yellow, { t0: m('kin') });
+ const xs = [250, 525, 800, 1075, 1350], y = 380;
+ const b = blip(p, { x: 250, y: 860, s: .45, form: 'kinetic', o: 0 }).live(D, 5);
+ // Each picture moves from its word on: the forms of kinetic energy are all something moving.
+ const items = [['mechk', 'mechanical', 'moving objects', 'kinetic', g => {
+ const bl = stripedBall(g, 24, 0, 34, '#ff6f8f'), sl = speedLines(g, -16, 0, 3, 50);
+ return t => { put(bl, { r: t * 300 }); put(sl, { x: -16 - 6 * Math.abs(Math.sin(t * 9)) }); }; }],
+ ['thermal', 'thermal', 'vibrating molecules', 'thermal', g => {
+ const ms = [[-40, -30], [10, -44], [44, -6], [-30, 20], [20, 34], [-2, -2]].map(([a, c]) => { const e = G(g, { x: a, y: c }); circ(e, 0, 0, 13, pale(EN.thermal), 3); return [e, a, c]; });
+ return t => ms.forEach(([e, a, c], i) => put(e, { x: a + 5 * Math.sin(t * 23 + i * 1.7), y: c + 5 * Math.cos(t * 19 + i * 2.3) })); }],
+ ['em', 'electromagnetic', 'light waves', 'light', g => {
+ const wv = ink(g, '', 5, { stroke: '#e0a400' });
+ return t => { let d = ''; for (let x = -84; x <= 84; x += 6) d += (d ? 'L' : 'M') + x + ' ' + (-34 * Math.sin((x - t * 90) / 22) * Math.min(1, (96 - Math.abs(x)) / 30)).toFixed(1); wv.setAttribute('d', d); }; }],
+ ['snd', 'sound', 'molecules bumping', 'sound', g => {
+ speaker(g, -40, 0, .9);
+ const ds = [14, 30, 46, 62, 78].map(a => { const e = G(g, { x: a }); circ(e, 0, 0, 6, pale(EN.sound), 2.5); return [e, a]; });
+ return t => ds.forEach(([e, a]) => put(e, { x: a + 6 * Math.sin(t * 8 - a / 9) })); }],
+ ['elec', 'electric', 'flow of electrons', 'electric', g => {
+ ink(g, 'M-70 30H70', 6, { stroke: '#a26b2e' });
+ circ(g, 0, -30, 30, '#fff59d', 4); ink(g, 'M-12 0V-14H12V0', 4);
+ const es = [0, 35, 70, 105].map(a => { const e = G(g, { y: 30 }); circ(e, 0, 0, 7, EN.electric, 2.5); return [e, a]; });
+ return t => { es.forEach(([e, a]) => put(e, { x: (a + t * 60) % 140 - 70 })); }; }]];
+ const live = [];
+ items.forEach(([mark, name, desc, form, build], i) => {
+ const v = vignette(p, xs[i], y, 108, m(mark));
+ live.push([m(mark), build(v)]);
+ ribbon(p, xs[i], 610, 250, name, desc, i % 2 ? pale(HL.yellow) : HL.pink, m(mark));
+ if (i) b.hop(xs[i], 860, m(mark, -.1), .5, 70); else show(b.g, m(mark));
+ b.form(form, m(mark), .25);
+ });
+ clockRun(t => live.forEach(([t0, f]) => f(Math.max(0, t - t0))), D);
+ }],
+ ['potential', 'Potential energies', (m, D) => {
+ const p = panel(0);
+ wavyHeading(p, 'Potential energies', 800, 130, HL.blue, { t0: m('pot') });
+ const xs = [290, 620, 950, 1280], y = 370;
+ const b = blip(p, { x: 1460, y: 200, s: .45, form: 'potential' }).live(D, 6);
+ let halves;
+ const items = [['grav2', 'gravitational', 'stored in height', 'potential', g => { ink(g, 'M-80 60H0V-20H80', 5); path(g, 'M-30 -20L-10 -60H40L50 -20Z', { fill: '#b9a68f', stroke: INK, 'stroke-width': 4 }); ink(g, 'M60 -10V60', 3, { 'stroke-dasharray': '6 8' }); }],
+ ['elastic', 'elastic', 'stretched or squeezed', 'elastic', g => { ink(g, 'M-60 -50V60M60 -50V60', 7, { stroke: '#a26b2e' }); ink(g, 'M-60 -40Q0 60 60 -40', 5, { stroke: EN.elastic }); circ(g, 0, 18, 16, '#c9c9c9', 3.5); }],
+ ['nuc', 'nuclear', 'in the nucleus', 'nuclear', g => {
+ halves = [G(g), G(g)];
+ for (const [a, c, col, h] of [[-14, -12, '#ff7a7a', 0], [12, -14, '#7ab8ff', 1], [0, 6, '#ff7a7a', 1], [-18, 12, '#7ab8ff', 0], [18, 10, '#ff7a7a', 1], [2, -30, '#7ab8ff', 1], [-30, -6, '#7ab8ff', 0], [28, -4, '#ff7a7a', 1]])
+ circ(halves[h], a, c, 14, col, 3); }],
+ ['chem', 'chemical', 'in the bonds of atoms', 'chemical', g => { ink(g, 'M-50 10L0 -20L50 10', 7); circ(g, -50, 10, 22, '#ff8a8a', 3.5); circ(g, 0, -20, 28, '#9a9a9a', 3.5); circ(g, 50, 10, 22, '#ff8a8a', 3.5); }]];
+ items.forEach(([mark, name, desc, form, drawIt], i) => {
+ drawIt(vignette(p, xs[i], y, 112, m(mark)));
+ ribbon(p, xs[i], 600, 280, name, desc, i % 2 ? pale(HL.blue) : HL.green, m(mark));
+ b.hop(1460, 200, m(mark, -.1), .45, 50).form(form, m(mark), .25);
+ });
+ // fission: the nucleus splits and the two halves fly apart with a flash
+ const ts = m('split');
+ tw(halves[0], { x: -48, r: -20 }, ts, .5, out); tw(halves[1], { x: 48, r: 20 }, ts, .5, out);
+ flash(star(p, xs[2], y, 1.1), ts, .5);
+ const fuels = [['food', g => { circ(g, 0, 0, 24, '#ff6b6b', 3.5); ink(g, 'M0 -24V-36', 4); }], ['oil', g => path(g, 'M0 -30C14 -10 22 2 22 12A22 22 0 0 1 -22 12C-22 2 -14 -10 0 -30Z', { fill: '#3a3a3a', stroke: INK, 'stroke-width': 3 })],
+ ['gas', g => flame(g, 0, -4, .6)], ['firewood', g => { mk('rect', { x: -34, y: -12, width: 68, height: 26, rx: 12, fill: '#b07a43', stroke: INK, 'stroke-width': 3.5 }, g); }],
+ ['coal', g => path(g, 'M-24 10L-16 -16L8 -24L26 -4L18 18L-8 22Z', { fill: '#2b2b2b', stroke: INK, 'stroke-width': 3 })]];
+ fuels.forEach(([name, drawIt], i) => { const g = G(p, { x: 470 + i * 165, y: 780, o: 0, s: .7 }); drawIt(g); hand(g, name, 0, 66, { size: 28 }); pop(g, m('fuel', i * .45)); });
+ }],
+ ['count', 'Always changing', (m, D) => {
+ const p = panel(0);
+ const ask = term(p, 'how many forms of energy?', 800, 600, { size: 44, font: HAND, color: HL.yellow, t0: .2 });
+ hide(ask.g, m('matter', -.2), .4);
+ [['two', '2', 380], ['seven', '7', 800], ['nine', '9', 1220]].forEach(([mark, n, x]) => {
+ const g = G(p, { x, y: 300, o: 0, s: .6 });
+ head(g, n, 0, 30, { size: 150 }); hand(g, 'some say', 0, -130, { size: 34, fill: COL.dim });
+ pop(g, m(mark)); tw(g, { o: 0, s: .8 }, m('matter', -.2), .4);
+ });
+ const forms = ['kinetic', 'thermal', 'light', 'sound', 'electric', 'potential', 'elastic', 'nuclear', 'chemical'];
+ const names = ['motion', 'thermal', 'light', 'sound', 'electric', 'gravitational', 'elastic', 'nuclear', 'chemical'];
+ const ang = i => -Math.PI / 2 + i * 2 * Math.PI / 9;
+ forms.forEach((f, i) => {
+ const x = 800 + 470 * Math.cos(ang(i)), y = 470 + 270 * Math.sin(ang(i));
+ const g = G(p, { o: 0 });
+ blip(g, { x, y: y + 40, s: .42, form: f });
+ hand(g, names[i], x, y + 80, { size: 28, fill: mix(EN[f], INK, .35) });
+ show(g, m('matter', .2 + i * .18), .3);
+ });
+ const arrows = G(p, { o: 0 });
+ for (let i = 0; i < 9; i++) {
+ const a1 = ang(i + .3), a2 = ang(i + .7);
+ inkArrow(arrows, 800 + 330 * Math.cos(a1), 470 + 180 * Math.sin(a1), 800 + 330 * Math.cos(a2), 470 + 180 * Math.sin(a2), { bend: -14, width: 3.5, t0: 0, dur: .001 });
+ }
+ show(arrows, m('chg'));
+ term(p, 'always changing', 800, 482, { size: 44, font: HEAD, color: HL.yellow, t0: m('chg') });
+ // one Blip travels the loop, taking on each form it passes
+ const tr = blip(p, { s: .5, o: 0 }).live(D, 9);
+ show(tr.g, m('chg'), .3);
+ clockRun(t => {
+ const u = Math.max(0, t - m('chg')) * .55, a = ang(u);
+ put(tr.g, { x: 800 + 300 * Math.cos(a), y: 470 + 150 * Math.sin(a) + 40 });
+ tr.body.setAttribute('fill', EN[forms[Math.round(u) % 9]]);
+ }, D);
+ }],
+ ['q4', 'Quick check', (m, D) => {
+ const p = panel(0);
+ const boxes = [['kinetic', 'moving', 260, 'kinetic'], ['potential', 'stored', 600, 'potential']];
+ for (const [name, sub, y, form] of boxes) {
+ mk('rect', { x: 170, y: y - 140, width: 420, height: 280, rx: 18, fill: pale(EN[form]), stroke: INK, 'stroke-width': 4 }, p);
+ head(p, name, 380, y - 80, { size: 40 });
+ hand(p, sub, 380, y - 40, { size: 32 });
+ const b = blip(p, { x: 380, y: y + 115, s: .7, form }).live(D, y);
+ if (form === 'kinetic') speedLines(p, 320, y + 60, 3, 60);
+ else hand(p, 'z z z', 470, y + 10, { size: 34, fill: COL.dim });
+ }
+ }, { ask: done => quiz({ x: 650, y: 80, w: 900, cls: 'side', maxH: 760 }, [{
+ id: 'c-sort', prompt: ['Is each form moving energy (kinetic) or stored energy (potential)?'],
+ build: grid([['Thermal energy', 'k', 'Thermal energy is molecules vibrating: motion.'], ['Elastic energy', 'p', 'Elastic energy is stored in a stretch or squeeze.'],
+ ['Sound energy', 'k', 'Sound is molecules bumping into each other: motion.'], ['Chemical energy', 'p', 'Chemical energy is stored in the bonds of atoms.'],
+ ['Electric energy', 'k', 'Electric energy is electrons flowing: motion.'], ['Nuclear energy', 'p', 'Nuclear energy is stored in the nucleus.']]
+ .map(([t, a, why]) => ({ parts: [t], ans: [a], why })),
+ [['k', 'kinetic', EN.kinetic], ['p', 'potential', EN.potential]], { multi: false, text: true }),
+ }], done) }],
+ ['wrap', 'Summary', (m, D) => {
+ const p = panel(0);
+ head(p, 'To sum up', 220, 140, { size: 56, anchor: 'start' });
+ [['Energy is never created or destroyed: it changes form or moves.', 'w1', HL.yellow],
+ ['Kinetic energy is motion; it grows with mass and velocity.', 'w2', HL.pink],
+ ['Potential energy is stored; gravitational grows with mass and height.', 'w3', HL.blue],
+ ['Heat, light, sound, electric, chemical, nuclear: all energy.', 'w4', HL.green]].forEach(([str, mark, c], i) => {
+ const g = G(p, { o: 0, x: -20 }), y = 270 + i * 140;
+ circ(g, 250, y - 12, 34, c, 4);
+ head(g, String(i + 1), 250, y + 4, { size: 40 });
+ hand(g, str, 310, y, { size: 40, anchor: 'start' });
+ tw(g, { o: 1, x: 0 }, m(mark), .6, out);
+ });
+ const b = blip(p, { x: 1440, y: 860, s: .9, form: 'light' }).live(D, 7);
+ b.hop(1440, 860, m('end'), .5, 60).mouth('open', m('end'));
+ }],
+ ['final1', 'Chapter practice', () => { panel(0); }, { ask: done => quiz(SCREEN, PRACTICE, done, 'Chapter practice') }],
+ ['finish', 'Finished', () => { panel(0); }, { ask: finishCard }],
+].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));
+
+/* ---------- practice ---------- */
+const PRACTICE = [
+ { id: 'p-match', prompt: ['Match each description with its term.'],
+ build: grid([
+ ['Stored energy', 'p', 'Potential energy is stored energy, waiting to be released.'],
+ ['Energy can never be created or destroyed; the total in a system stays the same.', 'c', 'That is the law of conservation of energy.'],
+ ['The energy of an object because of its motion', 'k', 'Kinetic energy is the energy of motion.']].map(([t, a, why]) => ({ parts: [t], ans: [a], why })),
+ [['c', 'conservation'], ['p', 'potential'], ['k', 'kinetic']], { multi: false, text: true }) },
+ { id: 'p-cow', prompt: ['A cow digests grass. The chemical energy stored in the grass becomes…'],
+ build: choice([['thermal and kinetic energy'], ['nuclear energy'], ['nothing: the energy is used up']], 0,
+ 'The cow\'s body releases the stored chemical energy as heat (thermal) and motion (kinetic).',
+ [null, 'Nuclear energy is stored in the nuclei of atoms; digestion rearranges chemical bonds.', 'Energy is never destroyed; it changes form.']) },
+ { id: 'p-chem', prompt: ['What is chemical energy?'],
+ build: choice([['energy stored in the bonds between atoms'], ['energy of flowing electrons'], ['energy stored in an object\'s height']], 0,
+ 'Chemical energy is stored in chemical bonds, as in food and fuel.',
+ [null, 'That is electric energy.', 'That is gravitational potential energy.']) },
+ { id: 'p-shelf', prompt: ['Books on the same bookcase. Which has the most potential energy?'],
+ build: choice([['a 2 kg book on the top shelf'], ['a 1 kg book on the top shelf'], ['a 2 kg book on the bottom shelf']], 0,
+ 'It has both more mass and more height.',
+ [null, 'Same height as the 2 kg book on the top shelf, but less mass.', 'Same mass as the 2 kg book on the top shelf, but much less height.']) },
+ { id: 'p-ke', prompt: ['A tennis ball and a bowling ball roll at the same speed. Which has more kinetic energy?'],
+ build: choice([['the bowling ball'], ['the tennis ball'], ['they have the same, because the speed is the same']], 0,
+ 'At the same speed, more mass means more kinetic energy.',
+ [null, 'The tennis ball has less mass, so less kinetic energy at the same speed.', 'Speed is only half of it: kinetic energy also grows with mass.']) },
+ { id: 'p-change', prompt: ['Energy is constantly ______ from one form to another.'],
+ build: choice([['changing'], ['being destroyed'], ['being created']], 0,
+ 'Energy keeps changing form: light to chemical to motion, and on.',
+ [null, 'Energy is never destroyed.', 'Energy is never created.']) },
+ { id: 'p-bump', prompt: ['Your bumper car hits your friend\'s car, and hers moves forward. What kind of energy did yours pass to hers?'],
+ build: choice([['kinetic energy'], ['potential energy'], ['nuclear energy']], 0,
+ 'Energy of motion passed from one car to the other in the collision.',
+ [null, 'Nothing was lifted or stretched; the energy passed on was motion.', 'Nuclear energy is stored inside atoms; a bump does not release it.']) },
+];
+
+nbBoot();
+</script>
+</body>
+</html>
diff --git a/site/physics-notebook/index.html b/site/physics-notebook/index.html
new file mode 100644
index 0000000..d7ff260
--- /dev/null
+++ b/site/physics-notebook/index.html
@@ -0,0 +1,334 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<script>
+// Observe aborted incoming transitions before the first rendering opportunity.
+addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
+</script>
+<title>Energy &amp; Change</title>
+<meta name="description" content="An animated notebook about energy: Blip, a little bundle of energy, changes form but never disappears.">
+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='14' fill='%231d2b27'/%3E%3Ctext x='32' y='45' text-anchor='middle' font-size='48' fill='%23f0b45a'%3E∞%3C/text%3E%3C/svg%3E">
+<script src="unit-art.js"></script>
+<link rel="expect" href="#ch13" blocking="render">
+<style>
+:root {
+ /* the notebook look of the lessons (lib/book.css): ink on lined paper, hand fonts */
+ --page: #d9d3c4; --board: #fcfaf3; --panel: #fffdf8; --edge: #d4ccb8;
+ --chalk: #26241f; --dim: #6c665a; --faint: #a39b8a; --task: #e5398a; --quiz: #2d8fd0; --good: #2f9a5c;
+ --ui: "Patrick Hand", "Avenir Next", "Segoe UI", sans-serif;
+ --book: "Luckiest Guy", "Patrick Hand", sans-serif;
+ --ease: cubic-bezier(.2, .8, .2, 1);
+ color-scheme: light;
+}
+@font-face { font-family: "Patrick Hand"; src: url(lib/fonts/PatrickHand-Regular.ttf) format("truetype"); font-display: swap; }
+@font-face { font-family: "Luckiest Guy"; src: url(lib/fonts/LuckiestGuy-Regular.ttf) format("truetype"); font-display: swap; }
+* { 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); }
+/* Notebook paper: blue rules and a red margin, like the lesson stage. */
+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
+ background: linear-gradient(90deg, transparent 56px, #f2a7b5 56px 58px, transparent 58px),
+ repeating-linear-gradient(180deg, transparent 0 34px, #bfe0ef 34px 35px); }
+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; }
+#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: normal; }
+.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: rgba(252, 250, 243, .9); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #ddd5c3; }
+.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; }
+.unit { position: relative; max-width: 1212px; margin: 0 auto; padding: 28px 16px 0; }
+.unit h2 { position: relative; display: flex; align-items: baseline; gap: 14px; min-height: 168px; margin: 0 0 16px; padding-top: 130px; font: 500 28px/1.2 var(--book); }
+.unit .grid { position: relative; }
+/* Each unit header is a strip of chalkboard with a sketch of its mathematics, drawn in the unit colour. */
+.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; }
+.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); } }
+.unit h2 span { font: 600 14px var(--ui); letter-spacing: .14em; text-transform: uppercase; color: var(--c); white-space: nowrap; }
+.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 rgba(60, 50, 30, .18); }
+.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: "✓ Finished · "; color: var(--good); font-weight: 600; }
+.ch.last small::after { content: " · 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; } }
+.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); }
+
+/* Links back to the project bookshelf (not part of the Skill's template). */
+.back-shelf { color: var(--dim); font: 13px var(--ui); text-decoration: none; white-space: nowrap; }
+.back-shelf:hover { color: var(--chalk); }
+.cover-back { position: absolute; top: 24px; left: 24px; }
+.contents-back { margin-left: 16px; }
+
+/* ---------- 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; }
+ .unit-art { width: calc(100% - 32px); right: 16px; opacity: .32; }
+ .unit h2 { min-height: 0; padding-top: 104px; }
+ .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; }
+ .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; }
+ .chalk span { opacity: .075; }
+}
+</style>
+</head>
+<body>
+<section id="cover">
+ <div class="chalk" aria-hidden="true"><!-- a few faint formulas or phrases from the book, drawn in chalk -->
+ <span style="left:7%;top:13%;--d:1.6">energy is never used up</span>
+ <span style="right:8%;top:17%;--d:1.9">kinetic = motion</span>
+ <span style="left:5%;bottom:20%;--d:2.2">potential = stored</span>
+ <span style="right:6%;bottom:15%;--d:2.5">we're solar-powered!</span>
+ </div>
+ <svg class="mascot draw" id="guide" width="210" height="147"></svg>
+ <p class="kicker">An animated notebook</p>
+ <h1>Energy <i>&amp;</i> Change</h1>
+ <p class="lede">Follow Blip, a little bundle of energy, from sunlight to salad to a sprint. Watch balls roll, pens drop and bumper cars collide, and see why energy never disappears.</p>
+ <div class="acts">
+ <a class="btn go" href="#contents">Open the book<svg viewBox="0 0 16 16"><path d="M6 2.5 11.5 8 6 13.5 4.6 12.1 8.7 8 4.6 3.9z"/></svg></a>
+ <a class="btn quiet" id="resume" hidden></a>
+ </div>
+ <p class="meta" id="meta"></p>
+ <a class="back-shelf cover-back" href="../">← Back to the bookshelf</a>
+</section>
+
+<main id="contents">
+ <header class="top">
+ <a class="home" href="#book" aria-label="Back to the cover"><svg class="mascot" id="guideSmall" width="52" height="36"></svg><strong>Energy <i>&amp;</i> Change</strong></a>
+ <span class="prog" id="prog"></span>
+ <a class="back-shelf contents-back" href="../">← Bookshelf</a>
+ </header>
+ <div id="units"></div>
+</main>
+
+<script>
+'use strict';
+// Units and chapters are numbered in order from START (a book whose scope starts mid-way keeps the original numbers).
+// Add a chapter here when its lesson is ready.
+const START = { unit: 4, chapter: 13 };
+const UNITS = [ // [unit title, [[chapter title, minutes], ...]]
+ ['Energy', [['Forms of Energy', 9]]],
+];
+const HUES = ['#e5398a', '#2d8fd0', '#e89a00', '#2f9a5c', '#7b55c9']; // marker colours that read on paper
+const id = n => 'ch' + String(n).padStart(2, '0');
+let P = {};
+const BOOK_PROGRESS_KEY = 'animebook:progress:' + new URL('.', location.href).pathname;
+try {
+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');
+ if (saved && typeof saved === 'object' && !Array.isArray(saved)) P = saved;
+} catch {}
+const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);
+
+// Contents.
+let n = START.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order
+const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
+document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {
+ return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}"><svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${UNIT_ART[u] || ''}</svg><h2><span>Unit ${u + START.unit}</span>${esc(name)}</h2><div class="grid">` +
+ chs.map(([t, min]) => { n++; total++;
+ const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');
+ return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;
+ }).join('') + '</div></section>';
+}).join('');
+// A unit's sketch draws itself the first time the unit scrolls into view.
+const seen = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('seen'); seen.unobserve(e.target); } }), { threshold: .25 });
+document.querySelectorAll('.unit').forEach(u => seen.observe(u));
+const finished = [...done].filter(k => k >= START.chapter && k <= n).length;
+document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;
+const pl = (k, w) => `${k} ${w}${k === 1 ? '' : 's'}`;
+document.getElementById('meta').textContent = `${pl(total, 'chapter')} · ${pl(UNITS.length, 'unit')} · with sound`;
+const last = Number.isInteger(P.last) && document.getElementById(id(P.last));
+if (last) {
+ const r = document.getElementById('resume');
+ r.hidden = false;
+ r.href = last.getAttribute('href');
+ r.textContent = `Continue · Chapter ${P.last}`;
+}
+
+// The guide, drawn the same way as in the lessons.
+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';
+}
+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="#26241f" 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="#26241f"/><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 and the contents share this page: no hash or #book shows the cover, #contents or #chNN the contents.
+// Lessons link back with #chNN, so the reader lands on the chapter they just left.
+const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
+function show(animate) {
+ const open = location.hash.length > 1 && location.hash !== '#book';
+ const apply = () => {
+ document.body.classList.toggle('open', open);
+ document.body.classList.toggle('stagger', animate && open);
+ const here = open ? document.getElementById(location.hash.slice(1)) : null;
+ document.querySelectorAll('.here').forEach(e => e.classList.remove('here'));
+ if (here?.classList.contains('ch')) { here.scrollIntoView({ block: 'center' }); here.classList.add('here'); }
+ else scrollTo(0, 0);
+ if (animate) {
+ const heading = document.querySelector(open ? '#contents .home' : '#cover h1');
+ 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 && document.getElementById(location.hash.slice(1))?.closest('.ch')) || (named?.offsetParent && named);
+ name(e.viewTransition && target ? target : null);
+ e.viewTransition?.finished.then(() => name(null), () => name(null));
+});
+</script>
+</body>
+</html>
diff --git a/site/physics-notebook/lib/book.css b/site/physics-notebook/lib/book.css
new file mode 100644
index 0000000..3a498c5
--- /dev/null
+++ b/site/physics-notebook/lib/book.css
@@ -0,0 +1,31 @@
+/* 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.
+ The look: a lined school notebook, black ink, highlighter colours (style.json "look"). The engine is drawn for a
+ dark board, so its colours are redefined here (':root:root' outranks the engine's ':root') and its few fixed dark
+ colours are overridden below. lib/notebook.js does the same for the drawing palette COL. */
+@font-face { font-family: "Patrick Hand"; src: url(fonts/PatrickHand-Regular.ttf) format("truetype"); font-display: block; }
+@font-face { font-family: "Luckiest Guy"; src: url(fonts/LuckiestGuy-Regular.ttf) format("truetype"); font-display: block; }
+:root:root {
+ --page: #d9d3c4; --board: #fcfaf3; --panel: #fffdf8; --edge: #d4ccb8;
+ --chalk: #26241f; --dim: #6c665a; --faint: #b9b1a0;
+ --task: #e89a00; --quiz: #2d8fd0; --good: #2f9a5c; --bad: #d9473a;
+ --ui: "Patrick Hand", "Avenir Next", "Segoe UI", sans-serif;
+ --math-font: "Patrick Hand", "Avenir Next", sans-serif;
+ color-scheme: light;
+}
+/* Lined paper with a red margin: one static image (CSS gradients here cost Firefox ~20 ms a frame under camera moves). */
+:root #stage { background: url(paper.png) 0 0 / 1600px 900px no-repeat, #fcfaf3; }
+:root #frame { box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(60, 50, 30, .25); }
+:root .card { background: rgba(255, 253, 247, .98); box-shadow: 0 10px 30px rgba(60, 50, 30, .18); }
+:root .opt[aria-pressed="true"] { color: #fff; }
+:root .btn.go { color: #fff; }
+:root .grid .row, :root .blanks .brow { border-bottom-color: #e6dfcf; }
+:root .box { background: rgba(45, 143, 208, .07); }
+:root .grid .row.cur { background: rgba(45, 143, 208, .07); }
+:root #bar { background: #f1ece0; border-top-color: #ddd5c3; }
+:root .seg { background: #ddd5c3; }
+:root .seg.ask { background: #c6dcea; }
+:root .cover { background: rgba(252, 250, 243, .55); }
+:root .cover-t { font-family: "Luckiest Guy", var(--ui); letter-spacing: .02em; }
+:root .help { background: rgba(60, 52, 40, .45); }
+:root .paused-mark div, :root .sound-note, :root .caption { background: rgba(255, 253, 247, .94); color: var(--chalk); box-shadow: 0 6px 20px rgba(60, 50, 30, .2); }
diff --git a/site/physics-notebook/lib/energy.js b/site/physics-notebook/lib/energy.js
new file mode 100644
index 0000000..b46e7b6
--- /dev/null
+++ b/site/physics-notebook/lib/energy.js
@@ -0,0 +1,115 @@
+'use strict';
+// Energy unit components (style.json "components"). Load after engine.js and notebook.js.
+// blip(p, {x, y, s, form}) Blip, the energy mascot: hops, squashes, changes colour with its form, looks, blinks.
+// energyBars(p, {...}) bars for each store of energy plus a stacked total that stays the same height.
+
+// ---------- Blip ----------
+// Drawn around its feet at (0, 0), about 150 px tall at s = 1. Every move is on the beat clock.
+const BLIP_BODY = 'M-60 -8C-66 -58 -34 -100 2 -102C8 -116 16 -122 26 -130C24 -116 28 -106 32 -98C58 -86 68 -52 62 -10' +
+ 'C60 -2 56 0 48 0L-48 0C-56 0 -60 -2 -60 -8Z';
+function blip(p, { x = 0, y = 0, s = 1, form = 'kinetic', o = 1, face = 1 } = {}) {
+ const g = G(p, { x, y, s, o });
+ const shape = mk('g', {}, g); // squash and stretch (non-uniform, so set directly)
+ const body = path(shape, BLIP_BODY, { fill: EN[form], stroke: INK, 'stroke-width': 5 });
+ path(shape, 'M-40 -40C-42 -62 -28 -80 -10 -84', { stroke: '#ffffff', 'stroke-width': 7, opacity: .55 });
+ const faceG = G(shape, { o: face });
+ const eyes = mk('g', {}, faceG), pupils = G(eyes);
+ for (const ex of [-20, 18]) {
+ mk('ellipse', { cx: ex, cy: -52, rx: 13, ry: 16, fill: '#fff', stroke: INK, 'stroke-width': 3.5 }, eyes);
+ }
+ for (const ex of [-20, 18]) mk('circle', { cx: ex + 2, cy: -50, r: 6.5, fill: INK }, pupils);
+ const mouths = {
+ smile: path(faceG, 'M-12 -24Q0 -13 12 -24', { stroke: INK, 'stroke-width': 4 }),
+ open: path(faceG, 'M-10 -26Q0 -6 10 -26Z', { stroke: INK, 'stroke-width': 3.5, fill: '#7a1f2f' }, { o: 0 }),
+ oh: path(faceG, 'M0 -28a6 8 0 1 0 .1 0Z', { stroke: INK, 'stroke-width': 3.5, fill: '#7a1f2f' }, { o: 0 }),
+ };
+ let sq = [1, 1], breath = [1, 1], blink = 1; // squash from actions times a slow breath
+ const shapeTf = () => shape.setAttribute('transform', `scale(${sq[0] * breath[0]} ${sq[1] * breath[1]})`);
+ const eyeTf = () => eyes.setAttribute('transform', blink === 1 ? '' : `translate(0 ${-52 * (1 - blink)}) scale(1 ${blink})`);
+ const B = { g, body, face: faceG, pupils,
+ // Change form: body colour to EN[name].
+ form(name, t0, dur = .5) { tw(body, { c_fill: EN[name] }, t0, dur); return B; },
+ // Jump to (x, y) along an arc `h` high, squashing on take-off and landing.
+ hop(x2, y2, t0, dur = .7, h = 110) {
+ let from;
+ B.squash(t0 - .12, .18, .2);
+ prog(q => {
+ const s = st(g);
+ if (!from) from = [s.x, s.y];
+ put(g, { x: from[0] + (x2 - from[0]) * q, y: from[1] + (y2 - from[1]) * q - h * 4 * q * (1 - q) });
+ }, t0, dur, lin);
+ B.squash(t0 + dur, .22, .35);
+ return B;
+ },
+ // A squash and rebound: k = how flat (0.2 = 20 %).
+ squash(t0, k = .2, dur = .4) {
+ prog(q => {
+ const e = Math.sin(q * Math.PI) * (1 - q * .4) - .25 * Math.sin(q * 2 * Math.PI) * q;
+ sq = [1 + k * e, 1 - k * e]; shapeTf();
+ }, Math.max(0, t0), dur, lin);
+ return B;
+ },
+ // Keep alive for the whole beat: a slow breath and a blink every few seconds.
+ live(D, seed = 0) {
+ clockRun(t => {
+ const b = .018 * Math.sin((t + seed) * 2.4);
+ breath = [1 - b, 1 + b]; shapeTf();
+ const k = ((t + seed * 1.7) % 3.7) / .16;
+ blink = k < 1 ? 1 - .9 * Math.sin(k * Math.PI) : 1; eyeTf();
+ }, D);
+ return B;
+ },
+ // Look toward a direction (dx, dy each -1..1).
+ look(dx, dy, t0, dur = .3) { tw(pupils, { x: dx * 6, y: dy * 5 }, t0, dur); return B; },
+ mouth(name, t0) { for (const k in mouths) tw(mouths[k], { o: k === name ? 1 : 0 }, t0, .12, lin); return B; },
+ };
+ return B;
+}
+
+// ---------- energy bars ----------
+// One bar per store and, on the right, the total as a stack of the same colours. The total's height never changes
+// when only transfers happen: that is conservation, visible. keys: [{key, label, color}]; values 0..1 of the full
+// height h; set(values) redraws at once, so drive it from prog/clockRun with the same function as the motion.
+function energyBars(p, { x, y, h = 280, w = 54, gap = 26, keys, total = true, title = 'energy', o = 1 }) {
+ const g = G(p, { x, y, o }); // (x, y) = bottom left of the first bar
+ const n = keys.length, tx = n * (w + gap) + 30;
+ hand(g, title, (tx + (total ? w + 10 : -gap)) / 2, -h - 28, { size: 28, fill: COL.dim });
+ path(g, `M-14 0H${tx + (total ? w + 14 : -gap + 14)}`, { stroke: INK, 'stroke-width': 3 });
+ const bars = keys.map((k, i) => {
+ const bx = i * (w + gap);
+ mk('rect', { x: bx, y: -h, width: w, height: h, fill: 'none', stroke: COL.faint, 'stroke-width': 2, 'stroke-dasharray': '6 6', rx: 4 }, g);
+ const r = mk('rect', { x: bx, y: 0, width: w, height: 0, fill: k.color, stroke: INK, 'stroke-width': 3, rx: 4 }, g);
+ hand(g, k.label, bx + w / 2, 36, { size: 26, fill: mix(k.color, INK, .35) });
+ return r;
+ });
+ let stack = [];
+ if (total) {
+ mk('rect', { x: tx, y: -h, width: w + 10, height: h, fill: 'none', stroke: COL.faint, 'stroke-width': 2, 'stroke-dasharray': '6 6', rx: 4 }, g);
+ stack = keys.map(k => mk('rect', { x: tx, y: 0, width: w + 10, height: 0, fill: k.color }, g));
+ const outline = mk('rect', { x: tx, y: 0, width: w + 10, height: 0, fill: 'none', stroke: INK, 'stroke-width': 3, rx: 4 }, g);
+ stack.push(outline);
+ hand(g, 'total', tx + (w + 10) / 2, 36, { size: 26, fill: INK });
+ }
+ const E = { g, bars, h,
+ set(v) {
+ E.v = v.slice();
+ let acc = 0;
+ v.forEach((val, i) => {
+ const hh = Math.max(0, val) * h;
+ bars[i].setAttribute('y', -hh); bars[i].setAttribute('height', hh);
+ if (total) { stack[i].setAttribute('y', -acc - hh); stack[i].setAttribute('height', hh); }
+ acc += hh;
+ });
+ if (total) { stack[n].setAttribute('y', -acc); stack[n].setAttribute('height', acc); }
+ return E;
+ },
+ // Move from the values at t0 to v over dur (lazy start, like tw).
+ to(v, t0, dur = .8, ease = io) {
+ let from;
+ prog(q => { if (!from) from = E.v.slice(); E.set(from.map((a, i) => a + (v[i] - a) * q)); }, t0, dur, ease);
+ return E;
+ },
+ };
+ E.v = keys.map(() => 0);
+ return E;
+}
diff --git a/site/physics-notebook/lib/engine.css b/site/physics-notebook/lib/engine.css
new file mode 100644
index 0000000..0c532ab
--- /dev/null
+++ b/site/physics-notebook/lib/engine.css
@@ -0,0 +1,235 @@
+@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;
+ --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ color-scheme: dark;
+}
+* { 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. */
+#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;
+ 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; }
+
+.cover { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: rgba(15, 22, 19, .5); 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: 1200px; 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: 1600px; height: 900px; display: none; place-items: center; pointer-events: none; }
+.paused .paused-mark { display: grid; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 22px; }
+
+/* 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); }
+.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: #1b2320; font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px rgba(143, 214, 176, .35); }
+.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: #10242e; }
+.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 #2e433b; }
+.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; }
+.tok { cursor: grab; }
+
+/* Controls strip, part of the frame. */
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+.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: #2f4640; 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: #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; }
+ #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; }
+}
+.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; }
+.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: rgba(236, 232, 220, .07); 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: rgba(134, 201, 232, .16); }
+.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: rgba(236, 232, 220, .05); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: rgba(10, 16, 14, .72); }
+.help[hidden] { display: none; }
+.help-box { width: 1120px; 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 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: 1180px; padding: 10px 24px; border-radius: 14px; background: rgba(10, 16, 14, .82); 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: 1080px; 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; }
+.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; }
+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; }
diff --git a/site/physics-notebook/lib/engine.js b/site/physics-notebook/lib/engine.js
new file mode 100644
index 0000000..207de8f
--- /dev/null
+++ b/site/physics-notebook/lib/engine.js
@@ -0,0 +1,1872 @@
+// 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(() => {}));
+document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
+ <svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="Lesson animation">
+ <g id="scene"></g>
+ </svg>
+ <div id="ui"></div>
+ <div class="paused-mark"><div>Paused. Press space or click to continue.</div></div>
+ <div class="caption" id="caption" hidden></div>
+ <div class="help" id="help" hidden role="dialog" aria-label="Keyboard shortcuts">
+ <div class="help-box">
+ <h2>Keyboard shortcuts</h2>
+ <div class="help-cols">
+ <div><h3>Lesson</h3><dl>
+ <dt><kbd>Space</kbd></dt><dd>Play or pause</dd>
+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>Previous or next step</dd>
+ <dt><kbd>Shift</kbd><kbd>←</kbd><kbd>→</kbd></dt><dd>Change step during a question</dd>
+ <dt><kbd>Home</kbd></dt><dd>Start over</dd>
+ <dt><kbd>C</kbd></dt><dd>Captions on or off</dd>
+ <dt><kbd>&lt;</kbd><kbd>&gt;</kbd></dt><dd>Slower or faster</dd>
+ <dt><kbd>F</kbd></dt><dd>Full screen</dd>
+ <dt><kbd>?</kbd></dt><dd>Show this list</dd>
+ </dl></div>
+ <div><h3>Questions</h3><dl>
+ <dt><kbd>1</kbd>–<kbd>6</kbd></dt><dd>Choose an answer or a ring</dd>
+ <dt><kbd>T</kbd><kbd>F</kbd></dt><dd>True or false</dd>
+ <dt><kbd>↑</kbd><kbd>↓</kbd></dt><dd>Move between rows</dd>
+ <dt><kbd>←</kbd><kbd>→</kbd></dt><dd>Move along the number line, or pick a number to sort</dd>
+ <dt><kbd>Enter</kbd></dt><dd>Check, then continue</dd>
+ <dt><kbd>S</kbd></dt><dd>Show the answer</dd>
+ <dt><kbd>Esc</kbd></dt><dd>Leave an answer box</dd>
+ </dl></div>
+ </div>
+ <p class="help-close">Press <kbd>Esc</kbd> to close.</p>
+ </div>
+ </div>
+ <p class="sound-note" id="soundNote" hidden>Sound could not play. The lesson continues with the on-screen text.</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>Start lesson</span>
+ <small><span id="coverMeta"></span> Press <kbd>Space</kbd> to start, <kbd>?</kbd> for shortcuts.</small>
+ </div></button>
+ <div id="bar">
+ <a class="icon" id="bHome" href="../" aria-label="All chapters" title="All chapters">
+ <svg viewBox="0 0 18 18"><path d="M2 2h6v6H2zM10 2h6v6h-6zM2 10h6v6H2zM10 10h6v6h-6z"/></svg>
+ </a>
+ <button class="icon" id="bPlay" aria-label="Play or pause (space)">
+ <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="Previous step (left arrow)">
+ <svg viewBox="0 0 18 18"><path d="M3 2h2.5v14H3zM16 2v14L6.5 9z"/></svg>
+ </button>
+ <button class="icon" id="bRestart" aria-label="Restart lesson">
+ <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="Keyboard shortcuts (?)" title="Keyboard shortcuts (?)">?</button>
+ <button class="icon txt speed" id="bSpeed" aria-label="Playback speed (&lt; and &gt;)" title="Playback speed (&lt; and &gt;)">1×</button>
+ <button class="icon cc" id="bCC" aria-pressed="false" aria-label="Captions (C)" title="Captions (C)">CC</button>
+ <button class="icon" id="bFull" aria-label="Full screen">
+ <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 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';
+// 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
+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)
+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' };
+const SORT_SCREEN = { x: 0, y: 0, w: 1600, 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;
+ 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' : '';
+ }
+ 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 });
+}
+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));
+}
+// 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('→'), ' move, ', kbd('Enter'), ' choose, or click the grid'],
+ 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);
+}
+
+// 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;
+}
+
+/* ---------- 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;
+}
+
+/* ---------- 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) => tw(e, { o: 1 }, t0, dur);
+const hide = (e, t0, dur = .5) => tw(e, { o: 0 }, t0, dur);
+const draw = (e, t0, dur = .9) => tw(e, { d: 1 }, t0, dur);
+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 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)); }
+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.
+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 = {};
+const AXIS = { o: 800, 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 ? '−' : '') + Math.abs(v);
+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.
+let seeking = false;
+function retire(e) {
+ if (seeking) { e.style.display = 'none'; return; }
+ 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);
+ 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); };
+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 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);
+}
+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(`${-n} steps left of 0`, X(n / 2), Y0 - 100, COL.int);
+}
+
+/* ---------- shared answer columns ---------- */
+const FAMILIES = ['nat', 'whole', 'int', 'rat', 'irr', 'real'];
+const FAM_COLS = FAMILIES.map(k => [k, k === 'int' ? 'Integer' : NAME[k], COL[k]]);
+const TF = [['t', 'True', null, 'T'], ['f', 'False', 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 ? `${name}: ${r} of ${t} right on the first try.` : `${name}: not attempted.`);
+ progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ const home = h('a', 'btn quiet', 'All chapters');
+ home.href = $('bHome').href;
+ const again = h('button', 'btn' + (CHAPTER.next ? ' quiet' : ' go'), ['Watch again', kbd(CHAPTER.next ? 'R' : 'Enter')]);
+ again.onclick = restart;
+ const next = CHAPTER.next && h('button', 'btn go', ['Next chapter', kbd('Enter')]);
+ if (next) next.onclick = () => { location.href = CHAPTER.next; };
+ P.keys = e => e.key === 'Enter' ? ((next ? next.onclick() : restart()), true)
+ : (e.key === 'r' || e.key === 'R') ? (restart(), true) : false;
+ const guide = mascotEl(240);
+ c.append(h('div', 'finwrap', [guide, h('p', 'kicker', `Chapter ${CHAPTER.number} complete`), h('p', 'prompt', CHAPTER.title),
+ line('Quick checks', sum('c-')), line('Chapter practice', sum('p-')), h('div', 'acts', next ? [home, again, next] : [home, again])]));
+ 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);
+const uiW = (str, size) => { ctx2d.font = `600 ${size}px ${UI}`; return ctx2d.measureText(str).width; };
+const RING_KEYS = ['nat', 'whole', 'int', 'rat', 'irr', 'real']; // number keys 1–6 in sorting questions
+const SCORE = {}; // question id -> first-attempt {right, total}
+
+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, 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.
+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 = 'Quick check') {
+ 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');
+ const bCheck = h('button', 'btn', ['Check', kbd('Enter')]), bShow = h('button', 'btn quiet', ['Show answer', kbd('S')]);
+ const bNext = h('button', 'btn go', [k < qs.length - 1 ? 'Next question' : '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 ? 'Correct. ' : 'Not quite. ', ...[].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('', ['Answer: ', ...[].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 ((e.key === 's' || e.key === 'S') && !bShow.hidden) { bShow.click(); return true; }
+ return false;
+ };
+ const kick = label + (qs.length > 1 ? ` ${k + 1} of ${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', ['Keys: ', ...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; },
+ };
+};
+// Tap a point on the stage number line.
+const tap = (values, right, yes, no, onRight) => (body, api) => {
+ const L = qlayer(), hits = {};
+ let locked = false;
+ for (const v of values) {
+ const g = G(L, { x: X(v), y: Y0 });
+ g.classList.add('hit');
+ g.setAttribute('tabindex', 0);
+ g.setAttribute('role', 'button');
+ g.setAttribute('aria-label', `The point ${num(v)}`);
+ mk('circle', { r: 30, class: 'ring' }, g);
+ const act = () => {
+ if (locked) return;
+ if (v === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }
+ else { g.classList.add('bad'); shakeFx(S.dots[v]); api.grade(false, no(v)); }
+ };
+ g.addEventListener('click', act);
+ keyAct(g, act);
+ hits[v] = g;
+ }
+ const gs = values.map(v => hits[v]);
+ let cur = -1;
+ return {
+ reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },
+ lock() { locked = true; },
+ hint: [kbd('←'), kbd('→'), ' move along the line, ', kbd('Enter'), ' choose'],
+ key(e) {
+ const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (!d || locked) return false;
+ cur = cur < 0 ? (d > 0 ? 0 : gs.length - 1) : (cur + d + gs.length) % gs.length;
+ gs[cur].focus();
+ return true;
+ },
+ };
+};
+// 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();
+ let locked = false, cur = -1;
+ const hits = idx.map(i => {
+ const e = row[i], w = e._w + 18, g = G(L, { x: e._px, y: row.y });
+ g.classList.add('hit');
+ g.setAttribute('tabindex', 0);
+ g.setAttribute('role', 'button');
+ g.setAttribute('aria-label', e.textContent.trim());
+ mk('rect', { class: 'ring', x: -w / 2, y: -row.size * .95, width: w, height: row.size * 1.3, rx: 12 }, g);
+ const act = () => {
+ if (locked) return;
+ if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }
+ else { g.classList.add('bad'); shakeFx(e); api.grade(false, no(i)); }
+ };
+ g.addEventListener('click', act);
+ keyAct(g, act);
+ return g;
+ });
+ return {
+ reveal() { hits[idx.indexOf(right)].classList.add('good'); onRight?.(); return yes; },
+ lock() { locked = true; },
+ hint: [kbd('←'), kbd('→'), ' move, ', kbd('Enter'), ' choose'],
+ key(e) {
+ const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (!d || locked) return false;
+ cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;
+ hits[cur].focus();
+ return true;
+ },
+ };
+};
+// 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();
+ let locked = false, cur = -1;
+ const hits = items.map((it, i) => {
+ const [x, y, w, hh] = it.box, g = G(L);
+ g.classList.add('hit');
+ g.setAttribute('tabindex', 0);
+ g.setAttribute('role', 'button');
+ g.setAttribute('aria-label', it.label);
+ mk('rect', { class: 'ring', x, y, width: w, height: hh, rx: 12 }, g);
+ const act = () => {
+ if (locked) return;
+ if (i === right) { g.classList.add('good'); onRight?.(); api.grade(true, yes); }
+ else { g.classList.add('bad'); shakeFx(it.el); api.grade(false, no(i)); }
+ };
+ g.addEventListener('click', act);
+ keyAct(g, act);
+ return g;
+ });
+ return {
+ reveal() { hits[right].classList.add('good'); onRight?.(); return yes; },
+ lock() { locked = true; },
+ hint: [kbd('←'), kbd('→'), ' move, ', kbd('Enter'), ' choose, or click'],
+ key(e) {
+ const d = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (!d || locked) return false;
+ cur = cur < 0 ? (d > 0 ? 0 : hits.length - 1) : (cur + d + hits.length) % hits.length;
+ hits[cur].focus();
+ return true;
+ },
+ };
+};
+// 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 ? [] : [`${right} of ${rows.length} right. Fix the rows marked ✗ and check again.`], { 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 : 'the correct choices are now selected.';
+ },
+ lock() { locked = true; showCur(); rows.forEach(r => r.bs.forEach(b => { b.disabled = true; })); },
+ hint: [...(single ? [] : [kbd('↑'), kbd('↓'), ' row, ']), ...(/\d/.test(hot[0]) ? [kbd(hot[0]), '–', kbd(hot[hot.length - 1])] : hot.map(kbd)), ' choose'],
+ 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 => x.toLowerCase() === e.key.toLowerCase());
+ 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. Never evaluates the text as code.
+function rat(str) {
+ const t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ 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', 'Answer');
+ 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;
+ };
+ requestAnimationFrame(() => 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 ? [] : [`${right} of ${rows.length} right. Fix the rows marked ✗ and check again.`];
+ 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 : 'the correct numbers are filled in.';
+ },
+ lock() { all.forEach(b => { b.disabled = true; }); },
+ hint: [all.some(b => b.dataset.ans.includes('/')) ? 'type numbers like 3/4 or −2 1/4, ' : 'type the number, ', kbd('Tab'), ' next box, ', kbd('Enter'), ' check, ', kbd('Esc'), ' leave the box'],
+ };
+};
+// 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.say}, ${c.region ? 'placed in ' + NAME[c.region] : 'not placed'}`);
+ 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);
+ });
+ 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', '', `${c.say} is not placed yet.`)); 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'
+ ? `${c.say}: every real number is rational or irrational, so that space has no numbers of its own.`
+ : c.why));
+ }
+ const all = right === chips.length;
+ api.grade(all, all ? [] : [`${right} of ${chips.length} in the right ring.`, 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 'every number is now in its smallest ring.';
+ },
+ lock() { locked = true; choose(null); },
+ hint: [kbd('←'), kbd('→'), ' pick a number, ', kbd('1'), '–', kbd('6'), ' choose its ring'],
+ 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;
+ },
+ };
+};
+
+/* ---------- player ---------- */
+const P = { i: 0, t: 0, end: 1, 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];
+ const m = (k, off = 0) => {
+ if (!(k in tm.marks)) throw new Error(`${b.id}: missing mark ${k}`);
+ return tm.marks[k] + off;
+ };
+ S.cleared = false;
+ b.run(m, tm.dur);
+ if (S.cleared && b.lead !== false) leadIn();
+ TW.sort((a, c) => a.t0 - c.t0);
+ return Math.max(tm.dur, ...TW.map(w => w.t0 + w.dur)) + .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 t = BEATS[i].ask ? 0 : frac * TIMINGS[BEATS[i].id].dur;
+ if (t < .3) return;
+ P.t = t;
+ evalTo(t);
+ if (P.audio) P.audio.currentTime = t;
+}
+function start(i, play) {
+ stopAudio(); clearCards();
+ Object.assign(P, { i, t: 0, waiting: false, done: false, afail: false, stall: 0 });
+ P.end = runBeat(i);
+ evalTo(0);
+ const a = P.audio = beatClip(i, true);
+ 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 = P.t; } // sound came back late: rejoin the picture where it is
+ };
+ const b = BEATS[i];
+ if (b.ask) b.ask(() => { if (P.i === i) { evalTo(Infinity); start(i + 1, true); } });
+ 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) {
+ const src = `audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3`;
+ 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;
+ if (v && !P.waiting && !a.ended && !P.afail) a.play().catch(e => { if (P.audio === a && e.name === 'NotAllowedError') soundFailed(); });
+ else a.pause();
+}
+function beatDone() {
+ evalTo(Infinity);
+ 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); }
+}
+let last = performance.now();
+function frame(now) {
+ const dt = Math.min(.1, (now - last) / 1000);
+ 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;
+ // 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) > (a.readyState < 2 ? 8 : 15)) soundFailed(); // nothing to play after 8 s, or stuck for 15
+ } else P.t += dt * P.rate;
+ evalTo(P.t);
+ if (P.t >= P.end) beatDone();
+ }
+ ui();
+ requestAnimationFrame(frame);
+}
+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', `Go to step ${i + 1}: ${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;
+ });
+}
+function ui() {
+ segs.forEach((f, k) => { f.style.width = (k < P.i || P.done ? 100 : k > P.i ? 0 : Math.min(100, P.t / P.end * 100)) + '%'; });
+ $('frame').classList.toggle('is-playing', P.playing && !P.done && !P.waiting);
+ $('frame').classList.toggle('paused', P.started && !P.playing && !P.waiting && !P.done && !BEATS[P.i].ask);
+ $('stepName').textContent = `${P.i + 1} / ${BEATS.length} ${BEATS[P.i].title}`;
+ const b = BEATS[P.i];
+ let text = '';
+ if (captions && P.started && !b.ask && !P.done) {
+ for (const [t, line] of TIMINGS[b.id].cues) { if (t > P.t + .05) break; text = line; }
+ }
+ if (text !== capText) { capText = text; $('caption').textContent = text; $('caption').hidden = !text; }
+}
+let captions = false, capText = '';
+try { captions = localStorage.getItem('captions') === '1'; } catch {}
+function setCaptions(on) {
+ captions = on;
+ $('bCC').setAttribute('aria-pressed', String(on));
+ try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
+}
+setCaptions(captions);
+function hideCover() { P.started = true; $('cover').hidden = true; }
+function togglePlay() {
+ if (!P.started) { hideCover(); return setPlaying(true); }
+ if (P.waiting || P.done) 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 => {
+ const b = BEATS[P.i];
+ if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+});
+$('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();
+const toggleFull = () => document.fullscreenElement ? document.exitFullscreen() : document.documentElement.requestFullscreen?.();
+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);
+}
+// 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 ((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;
+ 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 (k === 'c' || k === 'C') setCaptions(!captions);
+ else if (k === '<' || k === ',') stepSpeed(-1);
+ else if (k === '>' || k === '.') stepSpeed(1);
+ else if (k === 'f' || k === '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;
+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 = 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 {}
+}
+function boot() {
+ $('coverK').textContent = `Chapter ${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', `Lesson animation: ${CHAPTER.title}`);
+ $('coverMeta').textContent = `About ${CHAPTER.minutes} minutes, with sound and quick checks.`;
+ buildSegs();
+ const qs = new URLSearchParams(location.search);
+ if (qs.has('beat')) {
+ $('cover').hidden = true;
+ seek(+qs.get('beat'), false);
+ P.t = +(qs.get('t') || 0);
+ evalTo(P.t);
+ } else seek(0, false);
+ requestAnimationFrame(frame);
+}
diff --git a/site/physics-notebook/lib/fonts/LuckiestGuy-LICENSE.txt b/site/physics-notebook/lib/fonts/LuckiestGuy-LICENSE.txt
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/site/physics-notebook/lib/fonts/LuckiestGuy-LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/site/physics-notebook/lib/fonts/LuckiestGuy-Regular.ttf b/site/physics-notebook/lib/fonts/LuckiestGuy-Regular.ttf
new file mode 100644
index 0000000..5ca663c
Binary files /dev/null and b/site/physics-notebook/lib/fonts/LuckiestGuy-Regular.ttf differ
diff --git a/site/physics-notebook/lib/fonts/PatrickHand-OFL.txt b/site/physics-notebook/lib/fonts/PatrickHand-OFL.txt
new file mode 100644
index 0000000..4d5f944
--- /dev/null
+++ b/site/physics-notebook/lib/fonts/PatrickHand-OFL.txt
@@ -0,0 +1,93 @@
+Copyright (c) 2010-2012 Patrick Wagesreiter ([email protected])
+
+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:
+http://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/physics-notebook/lib/fonts/PatrickHand-Regular.ttf b/site/physics-notebook/lib/fonts/PatrickHand-Regular.ttf
new file mode 100644
index 0000000..fb45ccd
Binary files /dev/null and b/site/physics-notebook/lib/fonts/PatrickHand-Regular.ttf differ
diff --git a/site/physics-notebook/lib/fonts/README.md b/site/physics-notebook/lib/fonts/README.md
new file mode 100644
index 0000000..2c50897
--- /dev/null
+++ b/site/physics-notebook/lib/fonts/README.md
@@ -0,0 +1,3 @@
+Fonts used by this book (from github.com/google/fonts):
+- Patrick Hand, by Patrick Wagesreiter, SIL Open Font License 1.1 (PatrickHand-OFL.txt)
+- Luckiest Guy, by Astigmatic, Apache License 2.0 (LuckiestGuy-LICENSE.txt)
diff --git a/site/physics-notebook/lib/notebook.js b/site/physics-notebook/lib/notebook.js
new file mode 100644
index 0000000..c5603a2
--- /dev/null
+++ b/site/physics-notebook/lib/notebook.js
@@ -0,0 +1,97 @@
+'use strict';
+// The notebook look shared by the Energy unit (style.json "look", "components"). Load after engine.js.
+// The engine draws for a dark board; its palette is redefined here to ink on lined paper (book.css does the same
+// for the CSS colours). Text helpers write in a hand font; highlighter swipes and definition cards are the book's
+// own way of marking a term.
+
+Object.assign(COL, { chalk: '#26241f', dim: '#6c665a', faint: '#b9b1a0', board: '#fcfaf3',
+ task: '#e89a00', good: '#2f9a5c', bad: '#d9473a' });
+const INK = COL.chalk;
+const HAND = '"Patrick Hand","Avenir Next",sans-serif';
+const HEAD = '"Luckiest Guy","Patrick Hand",sans-serif';
+// One colour per form of energy, the same in every chapter of the unit.
+const EN = { light: '#ffc928', chemical: '#7dbb35', kinetic: '#f0568f', potential: '#2fa3e0', thermal: '#f2653a',
+ sound: '#9a68d8', electric: '#14ada0', elastic: '#5468d4', nuclear: '#ff9419' };
+// Pale highlighter versions (the book's marker colours) for swipes and cards.
+const HL = { yellow: '#fff06a', pink: '#f7a8c8', green: '#c5e15a', blue: '#8fd3f5', orange: '#ffc477', lilac: '#d6c2f2' };
+
+// Fonts must be ready before anything is measured or drawn: call nbBoot() instead of boot().
+function nbBoot() {
+ Promise.all(['40px "Patrick Hand"', '40px "Luckiest Guy"'].map(f => document.fonts.load(f))).finally(boot);
+}
+
+// Text in the hand font (o: 0 unless shown later).
+function hand(p, str, x, y, { size = 34, fill = INK, anchor = 'middle', o = 1, weight = 400 } = {}) {
+ return T(p, str, { x, y, size, fill, anchor, o, font: HAND, weight });
+}
+// A heading in the book's chunky capitals.
+function head(p, str, x, y, { size = 52, fill = INK, anchor = 'middle', o = 1 } = {}) {
+ const t = T(p, str.toUpperCase(), { x, y, size, fill, anchor, o, font: HEAD, weight: 400 });
+ t.setAttribute('letter-spacing', '1.5');
+ return t;
+}
+const handW = (str, size, font = HAND) => { ctx2d.font = `${size}px ${font}`; return ctx2d.measureText(str).width; };
+
+// A highlighter swipe from x to x + w with its middle at y, drawn on left to right at t0.
+// Slightly tilted and ragged like a real marker. Create it before the text it sits behind.
+function swipe(p, x, y, w, { h = 44, color = HL.yellow, t0 = 0, dur = .45, o = .9 } = {}) {
+ const d = `M${x} ${y + 3}C${x + w * .3} ${y - 1} ${x + w * .7} ${y + 2} ${x + w} ${y - 2}`;
+ const s = path(p, d, { stroke: color, 'stroke-width': h, 'stroke-linecap': 'butt', opacity: o }, { d: 0 });
+ tw(s, { d: 1 }, t0, dur, out);
+ return s;
+}
+// A term with a swipe behind it: { g, w } with the text centred on x (or starting at x for anchor 'start').
+function term(p, str, x, y, { size = 40, color = HL.yellow, t0 = 0, font = HEAD, anchor = 'middle', fill = INK } = {}) {
+ const g = G(p);
+ const w = handW(font === HEAD ? str.toUpperCase() : str, size, font) + (font === HEAD ? str.length * 1.5 : 0);
+ const x0 = anchor === 'middle' ? x - w / 2 : x;
+ swipe(g, x0 - 12, y - size * .33, w + 24, { h: size * 1.05, color, t0 });
+ const t = font === HEAD ? head(g, str, x0, y, { size, anchor: 'start', o: 0, fill })
+ : hand(g, str, x0, y, { size, anchor: 'start', o: 0, fill });
+ show(t, t0 + .1, .3);
+ return { g, w, t };
+}
+
+// A definition card like the book's: a tilted block with an ink edge and a darker side for depth.
+// Centred on (x, y); lines: [[text, size, font?]]. Pops in at t0 (pass t0 = null to build it hidden).
+function defCard(p, x, y, w, h, lines, { color = HL.blue, tilt = -2, t0 = 0 } = {}) {
+ const g = G(p, { x, y, r: tilt, s: .85, o: 0 });
+ const side = mix(color, '#000000', .25);
+ mk('path', { d: `M${-w / 2 + 10} ${h / 2}L${w / 2} ${h / 2}L${w / 2 + 12} ${h / 2 - 12}L${w / 2 + 12} ${-h / 2 + 4}L${w / 2} ${-h / 2}Z`,
+ fill: side, stroke: INK, 'stroke-width': 3, 'stroke-linejoin': 'round' }, g);
+ mk('rect', { x: -w / 2, y: -h / 2, width: w, height: h, fill: color, stroke: INK, 'stroke-width': 3, rx: 3 }, g);
+ const total = lines.reduce((a, [, s]) => a + s * 1.15, 0);
+ let yy = -total / 2;
+ for (const [str, size, font] of lines) {
+ yy += size * 1.15;
+ font === 'head' ? head(g, str, 0, yy - size * .22, { size }) : hand(g, str, 0, yy - size * .22, { size });
+ }
+ if (t0 !== null) pop(g, t0);
+ return g;
+}
+
+// A speech bubble pointing down-left to (tx, ty), text centred on (x, y).
+function bubble(p, str, x, y, tx, ty, { size = 32, t0 = 0 } = {}) {
+ const w = handW(str, size) + 40, h = size + 30;
+ const g = G(p, { o: 0, s: .7, x, y });
+ const bx = tx - x, by = ty - y;
+ mk('path', { d: `M${-w / 2 + 18} ${h / 2 - 2}L${bx} ${by}L${-w / 2 + 44} ${h / 2 - 2}`, fill: '#fff', stroke: INK, 'stroke-width': 3, 'stroke-linejoin': 'round' }, g);
+ mk('rect', { x: -w / 2, y: -h / 2, width: w, height: h, rx: h / 2, fill: '#fff', stroke: INK, 'stroke-width': 3 }, g);
+ mk('rect', { x: -w / 2 + 16, y: h / 2 - 6, width: 32, height: 8, fill: '#fff' }, g);
+ hand(g, str, 0, size * .34, { size });
+ if (t0 !== null) pop(g, t0);
+ return g;
+}
+
+// A hand-drawn arrow from (x1, y1) to (x2, y2), bending by `bend` px; drawn on at t0.
+function inkArrow(p, x1, y1, x2, y2, { bend = 40, color = INK, width = 4, t0 = 0, dur = .6 } = {}) {
+ const mx = (x1 + x2) / 2, my = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, L = Math.hypot(dx, dy) || 1;
+ const cx = mx - dy / L * bend, cy = my + dx / L * bend;
+ const a = Math.atan2(y2 - cy, x2 - cx), k = 18;
+ const g = G(p);
+ const line = path(g, `M${x1} ${y1}Q${cx} ${cy} ${x2} ${y2}`, { stroke: color, 'stroke-width': width }, { d: 0 });
+ const tip = path(g, `M${x2 - k * Math.cos(a - .45)} ${y2 - k * Math.sin(a - .45)}L${x2} ${y2}L${x2 - k * Math.cos(a + .45)} ${y2 - k * Math.sin(a + .45)}`,
+ { stroke: color, 'stroke-width': width }, { o: 0 });
+ draw(line, t0, dur); show(tip, t0 + dur * .85, .15);
+ return g;
+}
diff --git a/site/physics-notebook/lib/paper.png b/site/physics-notebook/lib/paper.png
new file mode 100644
index 0000000..7befc86
Binary files /dev/null and b/site/physics-notebook/lib/paper.png differ
diff --git a/site/physics-notebook/lib/volume.css b/site/physics-notebook/lib/volume.css
new file mode 100644
index 0000000..195fe1f
--- /dev/null
+++ b/site/physics-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/physics-notebook/lib/volume.js b/site/physics-notebook/lib/volume.js
new file mode 100644
index 0000000..91695ee
--- /dev/null
+++ b/site/physics-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/physics-notebook/unit-art.js b/site/physics-notebook/unit-art.js
new file mode 100644
index 0000000..9fbf224
--- /dev/null
+++ b/site/physics-notebook/unit-art.js
@@ -0,0 +1,25 @@
+// Chalk sketches for the unit headers on the contents page, one per unit, drawn in the unit's colour.
+// Each entry is the inside of an SVG with viewBox 0 0 600 180; keep the left ~200 px light (the unit title sits there
+// on narrow screens). Classes, styled in book.html:
+// d a stroke that draws itself in when the unit scrolls into view (--k orders the strokes)
+// t text or a filled shape that fades in
+// a faint chalk white instead of the unit colour; faint even fainter
+// A sketch may add one looping motion after it is drawn: give an element a class and add a .seen .unit-art .NAME
+// rule with its keyframes in book.html (see the examples there: swap-a, hop, spin, tilt, breathe, ...).
+'use strict';
+(() => {
+ let k = 0;
+ const P = (d, cls = '', extra = '') => `<path class="d ${cls}" pathLength="1" style="--k:${k++}" d="${d}" ${extra}/>`;
+ const Tx = (x, y, s, size = 24, cls = '', anchor = 'start') => `<text class="t ${cls}" style="--k:${k++}" x="${x}" y="${y}" font-size="${size}" text-anchor="${anchor}">${s}</text>`;
+ const C = (cx, cy, r, cls = '') => `<circle class="d ${cls}" pathLength="1" style="--k:${k++}" cx="${cx}" cy="${cy}" r="${r}"/>`;
+ const reset = s => { k = 0; return s; };
+
+ window.UNIT_ART = [
+ // Unit 4, Energy: a ball rolls up a hill and back, the sun shines, two bars trade height.
+ reset(P('M220 150H300C380 150 420 60 520 56H580') +
+ `<circle class="t hop" r="11" fill="currentColor" stroke="none" style="--k:${k++};offset-path:path('M290 139C370 139 410 58 470 52C410 58 370 139 290 139')"/>` +
+ C(540, 30, 14, 'a') + P('M520 30h-10M560 30h10M540 10v-8M540 50v8', 'a') +
+ P('M240 120V70', '', 'stroke-width="14"') + P('M262 120V100', '', 'stroke-width="14"') +
+ Tx(240, 172, 'energy changes form', 20, 'a')),
+ ];
+})();