Skip to content

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

feat: animebook skill covers the whole book pipeline

yzrb6155304aa5b
diff --git a/.claude/skills/animebook-chapter/SKILL.md b/.claude/skills/animebook-chapter/SKILL.md
deleted file mode 100644
index 29a8e32..0000000
--- a/.claude/skills/animebook-chapter/SKILL.md
+++ /dev/null
@@ -1,73 +0,0 @@
----
-name: animebook-chapter
-description: 为 AnimeBook 制作或修改一章数学动画课:读参考书页、写分镜与英文讲稿、用 Edge TTS 生成逐词对齐的语音、用 SVG 编写动画步骤、设计画面内小测和全屏整章练习、截图审阅并跑浏览器端到端检查。只要在这个仓库里做新章节(ch02…ch68)、改第一章的动画/讲稿/小测/练习、调语音同步、加题型或调播放器,都先用这个技能,即使用户只说“做下一章”“改一下这段动画”“这里加个题”。
----
-
-# AnimeBook 章节制作
-
-第一章 `site/ch01/index.html` 是用户认可的样板,第二章沿用同一套约定(“非常接近我们想要的”)。新章节要达到同样的质量,并沿用同样的交互约定。先读 `plan.md` 和 `CLAUDE.md`;本技能讲的是**怎么做**,以及第一章踩过的坑。
-
-## 用户已拍板的约定(不要回退)
-
-- **一块画面**:整页只有一块 16:9 画面(1600×900 舞台 + 60 高控制条),不在画面外另放练习区。
-- **全部在屏幕上完成**:不设纸笔任务。需要示范计算时写成讲解例题。
-- **小测插在讲解中途**,只考已经讲过的内容;尽量让学生直接操作画面里的数学对象(点数轴、拖进集合图),而不是只点文字选项。
-- **两个练习不能接连出现**(小测后面至少隔一段讲解);例外是结尾的整章练习组。
-- **结尾的整章练习**每组全屏,标“Chapter practice N of M”,最后是成绩页。
-- **答题有画面动画**:答对让相关数学对象动起来(点跳动、圈层依次亮、画出跳步弧线),答错抖动并给出针对这个错误的解释,可“Show answer”。
-- **角色**是 SVG 画的无穷符号 ∞(`mascotEl`),只出现在小测卡片和结束页。不用狗狗素材,不用 π(有知名 YouTuber 在用)。
-- **字幕**:CC 按钮或 C 键,默认关,逐句显示旁白;讲解主要靠画面内文字。
-- **键盘**:拖拽之外的所有操作都要有快捷键,按钮上标出按键,`?` 列出全部。新题型必须同时给出键盘操作。
-- **语言与语气**:先做英文,中文最后补;面向初一左右,语气不幼稚。
-- **数学约定**:natural numbers 从 1 开始,whole numbers 含 0;同一个数可属于多个集合。
-- **原书只作参考**:不截图、不照搬题干和讲解;读书页时留意原书错误(第一章就有三处),改写时修正并告诉用户。
-
-## 制作流程
-
-1. **读书页**:`book_pages/chNN/`(用 `sections.json` 找页码范围)。列出知识点、原书例题、原书错误和容易超纲的地方。
-2. **分镜**:把内容拆成若干“步”(beat),每步一段旁白(通常 5–30 秒)加一组画面动作。确定小测插在哪里、考什么、怎么操作画面对象、答对答错时画面怎么动。大改前把分镜要点给用户过目。
-3. **讲稿**:写进 `content/chNN/narration.en.json`。在需要画面同步的词前面放 `[[mark]]`,例如 `"you say [[c1]]one, [[c2]]two"`。旁白要把数学读成口语(“negative seven halves”),画面上再写成符号。
-4. **生成语音**(需联网,只重做改动过的步):
- ```sh
- uv run --with edge-tts tools/tts.py content/chNN/narration.en.json site/chNN/audio/en
- ```
- 输出每步 MP3 与 `timings.js`(时长、mark 时间、逐句字幕)。
-5. **写步骤代码**:见 `references/engine.md`。动作时间一律用 `m('mark', 偏移)` 或基于时长 `D`,不要手写秒数去猜语音。
-6. **截图审阅**:启动 `python3 -m http.server 8765 -d site`,用 `?beat=N&t=秒` 定格任意时刻;逐步看首尾画面,检查遮挡、标签重叠、数学位置是否准确。截图时一次一个浏览器进程(并行会拖慢加载,画面停在半截),`t` 设在淡入完成之后。
-7. **端到端检查**:参照 `tools/e2e_ch02.py` 写 `tools/e2e_chNN.py`,用纯键盘把每道题走一遍,覆盖答对、答错、看答案三种情况,最后逐步快进全部步骤;控制台不能有报错。有拖拽题时,参照 `tools/e2e_ch01.py` 补一遍鼠标操作。
-8. **更新文档**:`plan.md` 记录新决定,`CLAUDE.md` 更新目录地图。提交前先问用户。
-
-## 开场不留白(用户 2026-10-03 指出)
-
-旁白开始时画面不能是空的。新的一步清空画面(`panel(0)`)后,引擎会把开场一组动作前移到 0.4 秒(见 `engine.md` 的 `leadIn`),但编排时仍应主动让本步的主题算式、题目或图形先出现,再随旁白逐步标注。做完一章后运行 `uv run --with playwright tools/check_blank.py chNN`,没有输出才算通过。正常转场和思考停顿保留,不要求画面一直在动。
-
-## 第一章踩过的坑
-
-- **重播靠快进**:跳到第 N 步时,页面重建场景,再把前面每一步的 `run` 以 `evalTo(Infinity)` 瞬间执行一遍。因此 `run` 里只能用补间函数(`tw/prog/show/draw…`)排动作,不能用 `setTimeout`、随机数或读取当前时间,否则跳步后画面和正常播放不一致。交互元素只能在 `ask` 里创建。
-- **画面时钟跟随音频**:播放时 `P.t = audio.currentTime`。用 Python `http.server` 测试时,它不支持 Range 请求,给 audio 设 `currentTime` 会跳回开头;测试请让音频自然播完。
-- **小测提前继续**:学生答完直接继续时,本步还没播完的补间要先收尾(`evalTo(Infinity)`),否则淡出做一半的东西会残留到下一步。
-- **拖拽**:先 `append` 把元素移到最上层,再 `setPointerCapture`;移动 DOM 节点会丢失指针捕获。
-- **BEATS 里的对象字面量在定义时求值**:被引用的常量(卡片位置、`$m` 等)必须定义在 `BEATS` 之前。
-- **布局分区**(避免挡住数学):数轴 `Y0 = 610`,下方 `BAND` 卡片 y 686–886;数轴场景右上 `TOPR` 卡片不超过 470 高;集合图场景右栏 x ≥ 1258;字幕在 y ≈ 884 之上,小测时自动隐藏。
-- **行内数学**用 `mathEl`,基线已和正文对齐;分数、根号、循环节都由 `M()` 绘制,不引入公式库。
-- **斜体变量**:`M()` 会把 1–2 个字母的小写片段排成斜体变量,所以数学串里的单位(m、cm、kg)也会变斜体。单位请写成完整单词(meters),或放进 `T()` 的普通文字里。
-- **斜体误判**:单字母 a、x 等在 `M()` 里总是斜体,所以普通英文句子(“3% a year”)不要放进 `M()`/`mline`,要用 `T()` 或改写成 “per year”。
-- **小写的英文短词**:`M()` 把 by、my、an、if、in、is、of、or 等当成英文单词排成正体,算式里的 by、my、an 要写成 `b\u200By`、`m\u200By`、`a\u200Bn`(ch53)。
-- **大写变量与英文短词**:`M()` 不把 By、If、In 等看成变量,所以 `Ax + By = C` 里的 By 会是正体。写成 `B\u200By`(中间零宽空格)即可让 B、y 都变斜体。
-- **grid / choice 的 parts 是 HTML 文字**:里面的算式要用 `$m(...)` 包起来才是数学排版(斜体变量、分数),普通字符串只是正文字体。
-- **`BAND` 卡片放不下长填空**:一行里有多个空或文字较长时,把题拆成几行 `blanks`,并用自定义的 `{ x, y, w, cls: 'side' }` 宽卡片放在图形旁边(见 ch18 的第一次小测)。
-- **引擎里已有的名字不能在章节里再用 `const` 声明**(如 `popIn`、`rect`、`eqLine`),否则整页脚本报错、画面空白。新增章节后先用 `?beat=0` 检查控制台,再跑测试。
-- **结束页按 Enter 会进入下一章**;测试里要用 R 键回到开头。
-- **示意图不能误导**:比例放大的图形(如利息块)必须在画面上注明“drawn larger”。
-- **光标在填空框里时**,只有 Enter(检查)和 Esc(离开输入框)会被拦截,其余按键都当作打字;测试里按 S 看答案之前,要先按 Esc。
-- **Playwright 选择器**:`text=Check` 不区分大小写且按子串匹配,会命中“Quick check”;按钮名里带有按键提示(“1Rational”)。请用 CSS 类或序号定位。
-- **判题只看数学意义**:分类题按集合判断,顺序无关;不能凭有限位小数断言无理数;分母不能为 0;先化简再归类(√9、12/4)。
-
-## 引擎与章节文件
-
-通用部分在 `site/lib/engine.js` 和 `site/lib/engine.css`:播放器、绘图、题型、角色、画面框架。每章一个 `site/chNN/index.html`,只写 `CHAPTER`、本章的绘图小函数、`BEATS` 和题目数据,最后调用 `boot()`。新章节从 `site/ch02/index.html` 开始改最方便,它展示了算式、面积模型、点阵、数轴跳步等常用写法。
-
-章节页 `<head>` 保留 `<link rel="expect" href="#bar" blocking="render">`:没有它,Chromium 常在播放器生成前就渲染首帧,目录卡片放大成画面的页面过渡会被取消。新章节做好后,在 `site/index.html` 的 `UNITS` 里加一行(标题、分钟数),章号按顺序自动编号;上一章的 `CHAPTER.next` 指向新章。
-
-- 改引擎后,必须重跑所有已完成章节的 `tools/e2e_chNN.py`。
-- 某个画法第二次用到时,再把它从章节文件挪进引擎,不要提前抽象。
diff --git a/.claude/skills/animebook-chapter/references/engine.md b/.claude/skills/animebook-chapter/references/engine.md
deleted file mode 100644
index 9d5a427..0000000
--- a/.claude/skills/animebook-chapter/references/engine.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# 课程引擎速查(以 site/lib/engine.js 为准)
-
-写步骤代码或新题型前先读本文件。函数名如与代码不一致,以代码为准,并顺手更新本文件。
-
-## 舞台与状态
-
-- 舞台为 SVG,`viewBox 0 0 1600 900`,所有动画元素画在 `#scene` 中。HTML 卡片放在 `#ui`,坐标系与舞台相同。
-- 每个动画元素带一个状态对象,由 `render()` 写回 DOM:`x y`(平移)、`s`(缩放)、`r`(旋转,度)、`o`(不透明度)、`d`(描边绘制进度 0–1)、`a_<属性>`(数值属性,如 `'a_stroke-width'`)、`c_<属性>`(十六进制颜色)。补间用到的键要先在创建时赋初值;`a_`/`c_` 键若没有初值,补间开始时从元素的同名属性读取(属性须是数值或十六进制颜色)。
-- 缩放、旋转都绕元素自身原点。所以把内容画在 (0,0) 周围,再用 `x/y` 摆放位置。
-- `S` 保存本章跨步骤共用的对象(`S.line`、`S.dots`、`S.ring`、`S.panel`……)。`reset()` 会清空它,需要跨步使用的对象都要登记在 `S` 上。
-
-## 绘图
-
-| 函数 | 用途 |
-| --- | --- |
-| `G(parent, {x,y,s,r,o})` | 分组 |
-| `path(parent, d, attrs, {d:0})` | 路径;传 `d:0` 表示之后用 `draw()` 逐步画出 |
-| `T(parent, str, {x,y,size,fill,font,weight,anchor,o})` | 文字(默认 UI 字体) |
-| `M(parent, parts, {x,y,size,fill,anchor,o,s})` | 数学式,基线在 y;`parts` 由字符串、`F(n,d)` 分数、`R(x)` 根号组成;返回的元素带 `_w` 宽度 |
-| `chip(parent, parts, color, {x,y,size})` | 胶囊形数字卡片,中心在 (x,y) |
-| `tokens(parent, items, {x,y,size,anchor})` | 一行算式拆成可单独移动的记号;项可以是字符串、parts 数组或 `{t, fill}`;返回数组,带 `.w`、`.y`、`.size` |
-| `mathEl(parts, size)` | HTML 行内数学(小 SVG),基线与正文对齐 |
-| `rich([...])` | HTML 富文本:字符串、DOM 节点、`$m(...parts)` 行内数学 |
-
-数学字符串里 1–2 个字母的小写片段(a、x、ab)自动排成斜体变量;更长的单词保持正体。
-
-数轴:`X(v)`、`Y0`、`tick`、`dot`;章节可改 `AXIS.o`(0 的横坐标)和 `AXIS.u`(每单位像素)。`panel(t0)` 淡出上一个场景组并新建一个,`header()` 写小标题。第一章专用:家族列表 `row`(在 ch01 页面里)、集合图(`RINGS`、`CHAIN`、`buildVenn`、`regionAt`)。新章节需要的新场景(坐标系、方程两边等)按同样方式写一组小函数。
-
-## 按主题的现成画法(第 2–10 章加入引擎)
-
-| 函数 | 用途 |
-| --- | --- |
-| `collapse(row, i, j, parts, t0, {color, live})` | 框住 tokens 行里第 i..j 个记号,缩成一个结果并合拢空隙;返回新行。`live: true` 用于答题动画 |
-| `numberLine(t0, lo, hi)`、`move(p, a, b, y, t0)`、`landDot(p, v, t0, color)`、`brace(p, a, b, y, label, color, t0)` | 整数数轴、带箭头的移动、落点、区间括号;`POS`/`NEG` 为正负颜色 |
-| `tile / tiles / popAll / cancelPairs` | 正负方块与成对抵消 |
-| `vAxis(p, {x, Yf, lo, hi, step})`、`thermometer(p, {...}).set(v, t0, run)` | 竖直数轴、温度计 |
-| `fracRow(p, items, {x, y, size})`、`reduce(row, k, 'num'/'den', value, color, t0)` | 分数行,可逐个划掉分子分母写约分结果 |
-| `rect(p, x, y, w, h, fill, o, stroke)`、`bracketH(p, x1, x2, y, label, color, t0)` | 面积模型用的矩形和水平括号 |
-
-| `pointRow(p, digits, x, y, places)` + `.hop(from, to, t0)` | 小数点在数字间跳动(ch10、ch20) |
-| `balance(p, {x, y, L})` + `.load(side, parts, color, t0)`、`.tilt(deg, t0)` | 天平(ch24、ch25) |
-| `atile(p, kind, x, y, neg)`、`tileRow`、`cancel`、`popIn` | 代数方块 x²、x、y、1 及正负抵消(ch23、ch25) |
-| `eqLine(p, L, R, y, t0, {xEq, sym, note})` | 等号(或不等号)对齐的一行推导,右侧可带注释 |
-| `ray(p, v, closed, dir, t0)`、`segment(p, a, b, ca, cb, t0)` | 数轴上的射线与线段解集(ch26、ch27) |
-| `E(exp)` | `M()` 中的上标指数 |
-| `R(x, i)` | 根号:`x` 可以是数字串或 `F(n, d)`(分数在根号下),`i` 为根指数,如 `R(125, 3)` 是立方根(ch57 起) |
-| `plane(p, {cx, cy, u, x0, x1, y0, y1, t0})` | 坐标系(ch30 起)。返回 `P`:`PX/PY` 换算、`dot(x, y, color, t0, {label, dx, dy, anchor, into, run})`、`walk`(从原点沿 x 再沿 y 走到点)、`line(xa, ya, xb, yb, color, t0)`(延长到网格边)、`arrow(xa, ya, xb, yb, color, t0, {label})`、`stair(x, y, rise, run, t0, {labels})`(先竖后横的斜率台阶)、`fn(f, xa, xb, color, t0, {w, dur})`(描出 y = f(x) 的曲线,超出网格的部分不画,ch47 起)、`half(a, b, c, color, t0)`(给 a·x + b·y ≥ c 的半平面着色,裁在网格内);`line` 传 `dash` 时淡入而不是描出。每步设 `P.layer = panel(0)`,点和线画进本步面板,换步自动淡出;答题动画传 `{run: fx, into: 层}` |
-| `die(p, n, x, y, s, o)`、`coin(p, 'H'/'T', x, y, t0, r, run)`、`spinner(p, cx, cy, r, t0, colors)` + `.land(k)`、`outline(p, sp, ks, color, t0, run)` | 骰子点数面、硬币、等分转盘(指针转角 `land(k)` 指向第 k 格)及高亮格子(ch42 起) |
-| `axes(p, {x0, y0, w, h, xs: [lo, hi, step], ys: [lo, hi, step], xl, yl, t0, ybreak})` | 带刻度和轴名的第一象限坐标轴(散点图、实际情境图,ch41 起),返回 `{PX, PY}` |
-| `areaGrid(p, x0, y0, ws, hs, 列标签, 行标签, t0, {size})` + `.cell(i, j, parts, t0, {fill, tint, run, into})`、`.ring(i, j, color, t0)`;`arc(p, x1, y1, x2, y2, h, color, t0)` | 多项式乘法与因式分解的面积网格(列标签在上、行标签在左),弧形箭头(ch51 起) |
-| `frac(p, top, bot, x, y, t0, {size, fill, anchor, topFill, botFill})` | 分子分母都是 parts 的大分数(可含根号,如求根公式),横线在 y;返回 `{g, w, t, b, x0}`(ch60 起) |
-| `dataLine(p, {lo, hi, x0, x1, y, step, every, r})` | 数据数轴(ch40 起)。返回 `D`:`V(v)` 换算横坐标,`dot(v, color, t0, {from})` 在 v 上方叠点(`from` 给出时从该高度落下),`dots(vals, …)`,`mark(v, color, t0, label)` 轴下的平衡三角(`slide(mark, v, t0)` 滑动),`span(a, b, y, label, color, t0)` 上方区间括号;答题动画传 `{run: fx, into}` |
-
-题型补充:`pickEls(items, right, 答对说明, i => 错因, 答对动画?)` 点选画面里任意对象(表格单元格、柱子、小图),`items` 为 `[{el, box: [x, y, w, h], label}]`,←/→ 切换、Enter 选定(ch41 起);`pickPoint(P, [x, y], 答对说明, (x, y) => 错因, 答对动画?, test?)`(`test(x, y)` 给出时接受任何满足的点,`[x, y]` 只用于 Show answer;答对说明也可以是 `(x, y) => 文本`) 在坐标系上选格点,方向键移动光标、Enter 选定或直接点击;同一 quiz 连续两题时,前一题的答对动画要画进本步面板(qlayer 会在下一题清空)。`tapEls(row, idx, right, yes, no, onRight)` 点选画面里算式的某个记号(如“先算哪一步”);`blanks` 的格子接受分数与带分数,`{box: '3/4', lowest: true}` 要求最简形式。行上给 `test(values)` 时整行一起判(如两个因式顺序任意,ch54 起),Show answer 仍填各格的 `box`。
-
-## 步骤(BEATS)
-
-```js
-['sqrt2', '标题', (m, D) => {
- const p = panel(0); // 面板:先淡出上一个,再新建
- draw(path(S.line, '…', {…}, { d: 0 }), m('sq'), 1.1);
- show(T(p, '…', { o: 0 }), m('dec', 3.6)); // 该 mark 的词开始后 3.6 秒出现
-}, { ask: done => quiz(BAND, [问题…], done) }], // 可选:本步是小测
-```
-
-- `m(name, 偏移)` 返回讲稿里 `[[name]]` 后第一个词开始的秒数;拼错名字会直接报错。`D` 是本段语音时长。
-- 补间函数:`tw(e, to, t0, dur, ease)`、`prog(q => …, t0, dur)`(自定义进度,例如滚动圆、弧线运动)、`show/hide/draw/pop/pulse`、`glow/glowRun`(集合圈描边闪亮)、`stream`(数字逐位出现)。缓动有 `io`、`out`、`back`、`lin`。
-- 普通步骤播完自动进入下一步;带 `ask` 的步骤播完旁白后等待学生答完再继续。
-- 开场前移(`leadIn`):本步在 0.5 秒前调用了 `panel()`(清空画面,或标题后的第一个面板),且 0.8 秒内没有新对象出现时,`runBeat` 把首个出现对象之后 1.2 秒内的全部补间整体前移到 0.4 秒开始。某步需要刻意留白时,在步骤的第四项写 `{ lead: false }`。
-
-## 小测与练习
-
-```js
-quiz(位置, [{ id: 'c-xxx', prompt: [...rich], build: 题型(...) }, …], done, 'Quick check')
-```
-
-- 位置:`BAND`(数轴下方横条)、`TOPR`(数轴场景右上)、`RIGHT`(集合图右栏)、`SCREEN`(全屏)、`SORT_SCREEN`(全屏集合图分类)。
-- `id` 前缀:`c-` 表示讲解中途的小测,`p-` 表示整章练习;结束页按前缀汇总首次作答成绩。
-- 题型:
- - `choice(选项, 正确序号, 答对说明, 各选项错因[], 答对动画?)`:单选,数字键作答。
- - `tap(数值[], 正确值, 答对说明, v => 错因, 答对动画?)`:点数轴上的点,←/→ 移动,Enter 选定。
- - `grid(行[{parts, ans:[键], why, fx?}], 列[[键, 名称, 颜色?, 快捷键?]], {multi, text})`:表格勾选,↑/↓ 换行,数字键或字母键选择。
- - `sorter(卡片[[parts, 最小圈, 错因]], i => [x, y])`:拖进集合图,←/→ 挑卡片,1–6 放入圈。
- - `blanks(行[{parts: [..., {box: '21'}, ...], why, hint?, fx?}])`:在算式里填数字,Tab 切换格子,Enter 检查;接受 “−5”“-5”;答错显示 hint,答对显示 why。
-- 新题型的 `build(body, api)` 需返回 `{ reveal, check?, lock?, key?(e), hint? }`,判完调用 `api.grade(是否正确, 说明, {right, total})`。`key` 处理本题快捷键,返回 true 表示已处理;`hint` 显示在题干下方。
-- 答题动画使用独立时钟,函数有 `fx`、`fxp`、`pulseFx`、`shakeFx`、`glowFx`、`popDotFx`、`floatText`、`hopsFx`。离开本步时会自动收尾,不必自己清理。
-
-## 播放器
-
-`seek(i, play)` 重建并快进到第 i 步;`start(i, play)` 从当前画面开始第 i 步。`P.keys` 是当前题目的按键处理器,由 `quiz` 设置,由 `clearCards` 清除。字幕数据来自 `TIMINGS[id].cues`。
diff --git a/.claude/skills/animebook/SKILL.md b/.claude/skills/animebook/SKILL.md
new file mode 100644
index 0000000..5f7aeb1
--- /dev/null
+++ b/.claude/skills/animebook/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: animebook
+description: Turn a book (PDF) into an animated, narrated, interactive web book — a static site whose chapters are drawn step by step in SVG, narrated with Edge TTS synced word by word, with quick checks inside the picture, graded end-of-chapter practice, a cover, a contents page and a bookshelf. Use it for any part of that pipeline: splitting a PDF into chapters, planning a book, making or fixing a chapter (animation, narration, questions), reviewing and testing lessons, the contents page, publishing. Also when the user only says "do the next chapter", "fix this animation" or "add a question here".
+---
+
+# AnimeBook
+
+You turn a reference book into an animated book. Each chapter is one web page holding one 16:9 picture (a 1600×900 SVG stage plus a control bar). A lesson is a list of **beats**; each beat is one narration clip plus the animation timed to its words. Quick checks pause inside the picture; full-screen practice and a score card end the chapter. Everything is drawn in code: no images from the book, no stock art.
+
+The pipeline below is fixed; it was worked out over a full 68-chapter book. The design inside it is yours (see *Creative freedom*). The user may add their own requests at any point; they override defaults here.
+
+## Project layout
+
+```
+book.pdf, sections.json reference book and its page map (private)
+book_pages/chNN/ page images + text.md per chapter (private)
+BOOK.md the book plan: decisions, conventions, chapter status, errata — keep it current
+content/chNN/narration.en.json narration script with [[marks]]; TTS cache beside it
+tools/e2e_chNN.py per-chapter keyboard test
+site/ the only published folder
+ index.html, lib/bookshelf.* bookshelf (once there are books)
+ <book>/index.html cover + contents (assets/templates/book.html)
+ <book>/unit-art.js unit sketches (assets/templates/unit-art.js)
+ <book>/lib/engine.js, .css this book's engine copy (assets/engine/)
+ <book>/chNN/index.html a lesson (assets/templates/chapter.html)
+ <book>/chNN/audio/en/ beat MP3s + timings.js
+```
+
+`SKILL` below means this skill's folder. Needs: `uv` (scripts run as `uv run --with <deps>`), `ffmpeg` (ffprobe, for clip lengths), network access for Edge TTS, and Playwright's Chromium for review (`uv run --with playwright playwright install chromium`). Audio needs a local server: `python3 -m http.server 8765 -d site`.
+
+## Pipeline
+
+Gates marked **(user)** need the user's go-ahead; everything else you just do.
+
+1. **Intake (user).** Start BOOK.md from `SKILL/assets/templates/BOOK.md`. Ask once, briefly: readers (age, level), tone, narration language (others come later), anything to skip or add, a guide character if any, where it will be published. Offer defaults; record answers in BOOK.md.
+2. **Split.** `SKILL/scripts/outline.py book.pdf` prints the bookmark tree; rerun with `--level N -o sections.json` at the chapter depth (no bookmarks: write sections.json by hand from the contents pages). Check it against the book's contents, then `SKILL/scripts/split_pages.py book.pdf` (needs `--with pymupdf`) for page images and each chapter's `text.md`.
+3. **Book map (user).** Skim every chapter's `text.md` (text only). Write in BOOK.md: units and chapters with minute estimates, a colour per unit, and the recurring visual models across the book (number line, timeline, map, graph, …) — these become engine helpers. Show the user the chapter list and the visual approach.
+4. **Pilot chapter (user).** Make chapter 1 completely (chapter loop below). This is where look, pacing, voice and question style get approved; expect several rounds. Record every decision in BOOK.md under *Conventions*; later chapters follow them. Build helpers for the recurring models now, not halfway through the book.
+5. **Chapter loop.** One chapter at a time, each in a fresh context (see *Budget*). Commit per unit if the user agrees.
+6. **Finish the book.** Contents page with a sketch per unit, cover text, bookshelf entry, whole-book `check_blank.py` and all tests. Deploy only when asked. See `references/site.md`.
+
+## Chapter loop
+
+1. **Read** `book_pages/chNN/text.md`; open a page image only where a diagram matters. Note concepts, worked examples, exercises and answers. **Recompute every answer**: reference books have errors. Fix them in your version and log them in BOOK.md.
+2. **Storyboard**: a short beat list — what each beat shows, why it is true, where the quick checks go. → `references/authoring.md`
+3. **Narration**: write `content/chNN/narration.en.json` (template in `SKILL/assets/templates/`), then `uv run --with edge-tts SKILL/scripts/tts.py content/chNN/narration.en.json site/<book>/chNN/audio/en`. Only changed beats are re-synthesized.
+4. **Beats**: write `site/<book>/chNN/index.html` from the template or the closest finished chapter. API → `references/engine.md`.
+5. **Review**: `SKILL/scripts/shot.py chNN --url …` and read the contact sheets; then `SKILL/scripts/check_blank.py site/<book> chNN --url …` must print nothing. → `references/review.md`
+6. **Test**: `tools/e2e_chNN.py` from the template: every question wrong then right, one Show answer, the finish card, every beat rebuilt; no console errors.
+7. **Register**: add the chapter to `UNITS` in the book's index.html, set the previous chapter's `CHAPTER.next`, update BOOK.md (status, errata, new conventions).
+
+## Non-negotiables
+
+- **Original work.** Never copy the book's wording, examples or page images; rewrite and redraw. Book pages and the PDF are never published.
+- **Correct over faithful.** Facts and answers are verified, not trusted; tell the user what you corrected.
+- **Picture and voice agree.** Every action is timed by a narration mark (`m('mark')`), never by guessed seconds. The picture is never empty while the narration speaks.
+- **The picture teaches.** On-screen text is the key formula or phrase, placed beside what it describes, not a transcript. Captions (CC) exist but are optional.
+- **Questions.** Only on what was just taught; never two question beats in a row (except the final practice); every question can be played by keyboard; a wrong answer gets feedback about that specific mistake and a Show answer; a right answer animates the object it is about. Grade the meaning (equivalent forms, any order where order does not matter).
+- **One picture.** Everything happens inside the 16:9 stage; no paper-and-pencil tasks.
+- **Deterministic beats.** A beat's `run` only schedules tweens: seeking rebuilds the scene by replaying earlier beats, so no timers, randomness or clock reads in `run`.
+- **Engine change → rerun every chapter's test.** Each book has its own engine copy; improve `SKILL/assets/engine/` too when a change is general.
+- **Publishing, pushing and deploying only when the user asks.**
+
+## Creative freedom
+
+The process is fixed; the design is yours. For each idea pick the visual argument that makes it obvious — rearrange, split, morph, balance, slide, count, compare — and invent scenes, helpers, question types and motion as the content needs. The templates are skeletons, not styles to copy; don't reuse an old chapter's choreography unless it truly fits. Judge every animation by one question: does watching it show *why*? Once the pilot is approved, keep the book consistent: palette, type, character, controls, question feel.
+
+## Budget
+
+A book is long; spend tokens on design, not on re-reading.
+
+- **Fresh context per chapter** (a new session, or a subagent briefed with the chapter number, BOOK.md and the files to touch). Anything later chapters need lives in files — BOOK.md, `references/` — not in conversation memory.
+- **Text before images**: read `text.md`; open a page image only for a diagram.
+- **Don't read engine.js**; use `references/engine.md` and grep for one function when needed.
+- **Screenshots as sheets**: read the 4-up contact sheets from `shot.py` (open and end frames first), single shots only where a sheet shows a problem. Don't re-screenshot what a test already proves.
+- **Write a page in one pass**, fix with small edits, and don't re-read a file you just wrote.
+- **Short output**: the scripts print summaries; pipe long output through `tail`.
+- **Regression only after engine changes**, run in the background.
+
+## References
+
+- `references/authoring.md` — chapter shape, storyboard, narration and marks, questions and practice, content rules.
+- `references/engine.md` — the engine: stage, drawing, timing, question types, player; the known traps.
+- `references/review.md` — screenshots, what to look for, blank check, end-to-end tests, regression.
+- `references/site.md` — starting a book folder, cover and contents, unit sketches, guide character, bookshelf, deploying.
diff --git a/.claude/skills/animebook/assets/engine/engine.css b/.claude/skills/animebook/assets/engine/engine.css
new file mode 100644
index 0000000..32acb76
--- /dev/null
+++ b/.claude/skills/animebook/assets/engine/engine.css
@@ -0,0 +1,210 @@
+: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; }
+#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; }
+.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 "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 { 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; }
+.screen .fb { position: absolute; left: 70px; bottom: 56px; max-width: 1080px; margin: 0; font-size: 24px; }
+.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 { 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 .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; }
diff --git a/.claude/skills/animebook/assets/engine/engine.js b/.claude/skills/animebook/assets/engine/engine.js
new file mode 100644
index 0000000..681ed5e
--- /dev/null
+++ b/.claude/skills/animebook/assets/engine/engine.js
@@ -0,0 +1,1631 @@
+// AnimeBook lesson engine: stage, drawing, timeline, questions, player.
+// A chapter page loads this file, defines CHAPTER and BEATS, then calls boot().
+'use strict';
+document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
+ <svg id="stage" viewBox="0 0 1600 900" role="img" aria-label="Lesson animation">
+ <defs>
+ <filter id="grain" x="0" y="0" width="100%" height="100%">
+ <feTurbulence type="fractalNoise" baseFrequency=".85" numOctaves="2" seed="7" />
+ <feColorMatrix values="0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0" />
+ </filter>
+ <radialGradient id="vignette" cx=".5" cy=".45" r=".75">
+ <stop offset=".6" stop-color="#000" stop-opacity="0" />
+ <stop offset="1" stop-color="#000" stop-opacity=".35" />
+ </radialGradient>
+ </defs>
+ <rect width="1600" height="900" fill="#1d2b27" />
+ <rect width="1600" height="900" filter="url(#grain)" />
+ <rect width="1600" height="900" fill="url(#vignette)" />
+ <g id="scene"></g>
+ </svg>
+ <div id="ui"></div>
+ <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>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 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>`);
+
+/* ---------- drawing helpers ---------- */
+const NS = 'http://www.w3.org/2000/svg';
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
+const MATH = '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
+const NAME = { nat: 'Natural', whole: 'Whole', int: 'Integers', rat: 'Rational', irr: 'Irrational', real: 'Real' };
+// Card positions inside the 1600×900 picture.
+const BAND = { x: 96, y: 686, w: 1408, cls: 'band' }; // below the number line
+const 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; }
+function render(e) {
+ const s = e._st;
+ if (s.x || s.y || s.s !== 1 || s.r) e.setAttribute('transform', `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})`);
+ else e.removeAttribute('transform');
+ e.setAttribute('opacity', s.o);
+ 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
+// Math expression from parts: 'text' | F(n,d) | R(x) | E(exp). Baseline at y; anchor start/middle/end.
+function M(parent, parts, { x = 0, y = 0, size = 36, fill = COL.chalk, anchor = 'middle', o = 1, s = 1 } = {}) {
+ const g = G(parent, { x, y, o, s });
+ 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;
+ for (const p of parts) {
+ if (typeof p === 'string') cx += text(p, cx, 0, size);
+ 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;
+ }
+ }
+ const dx = anchor === 'middle' ? -cx / 2 : anchor === 'end' ? -cx : 0;
+ inner.setAttribute('transform', `translate(${dx},0)`);
+ g._w = cx;
+ 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), h = size * (parts.some(p => p.f) ? 1.75 : 1.45);
+ 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;
+ const box = put(mk('rect', { rx: 10, fill: 'none', stroke: color, 'stroke-width': 3 }, p),
+ { o: 0, a_x: left - 8, a_y: y - size * .95, a_width: right - left + 16, a_height: size * 1.3 });
+ 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' });
+ const top = size * 1.05, h = size * 1.5;
+ svg.setAttribute('viewBox', `0 ${-top} ${m._w + 2} ${h}`);
+ svg.setAttribute('width', m._w + 2);
+ svg.setAttribute('height', h);
+ svg.style.verticalAlign = `${-size * .45}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;
+ }
+}
+
+/* ---------- 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
+ if (S.panel) hide(S.panel, t0, .4);
+ return (S.panel = G(scene));
+}
+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);
+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;
+}
+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);
+ 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) { 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) => r.el.classList.toggle('cur', !single && !locked && i === cur));
+ 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; return [(m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)), d]; }
+ m = t.match(/^(-?)(?:(\d+) )?(\d+) ?\/ ?(\d+)$/);
+ if (m && Number(m[4]) > 0) { const d = Number(m[4]); return [(m[1] ? -1 : 1) * (Number(m[2] || 0) * d + Number(m[3])), d]; }
+ 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 && got[0] * want[1] === want[0] * 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.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: [] };
+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();
+ for (let k = 0; k < i; k++) { runBeat(k); evalTo(Infinity); }
+ start(i, play);
+}
+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 = new Audio(`audio/en/${BEATS[i].id}.mp3`);
+ a.preload = 'auto';
+ a.onerror = () => { if (P.audio === a) soundFailed(); };
+ const b = BEATS[i];
+ if (b.ask) b.ask(() => { if (P.i === i) { evalTo(Infinity); start(i + 1, true); } });
+ setPlaying(play);
+}
+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) > 4) soundFailed();
+ } else P.t += dt;
+ 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}`);
+ s.onclick = () => { hideCover(); seek(i, true); };
+ $('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);
+$('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')) { // typing an answer: only Enter (check) and Escape (leave the box) are ours
+ if (k === 'Enter' && 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 === '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 / 1000));
+addEventListener('resize', fit);
+fit();
+
+// Start the lesson once the chapter page has defined CHAPTER and BEATS.
+// ?beat=N&t=S opens a paused frame, for reviewing a single moment.
+// Per-browser progress shared with the contents page: last chapter opened, chapters finished.
+function progress(f) {
+ try { const p = JSON.parse(localStorage.getItem('progress') || '{}'); f(p); localStorage.setItem('progress', 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/.claude/skills/animebook/assets/templates/BOOK.md b/.claude/skills/animebook/assets/templates/BOOK.md
new file mode 100644
index 0000000..d18c62f
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/BOOK.md
@@ -0,0 +1,27 @@
+# <Book title> — book plan
+
+The working memory of this book. Every session starts by reading it; update it whenever something is decided.
+
+## Intake
+- Readers: … · Tone: … · Narration language: … · Guide character: … · Publish to: …
+- Source: `book.pdf`, N pages, N chapters in N units (`sections.json`).
+
+## Conventions (approved in the pilot; later chapters follow them)
+- Look: palette, fonts, how a new idea enters, how steps are laid out …
+- Narration: voice, rate, how numbers and symbols are read …
+- Questions: placement, typical types, feedback style …
+- Subject conventions (definitions, notation, rounding) …
+
+## Recurring visual models → engine helpers
+- … (which chapters use it, helper name once built)
+
+## Chapters
+| # | Title | Unit | Status | Book errors fixed |
+| --- | --- | --- | --- | --- |
+| 1 | … | 1 | planned / draft / reviewed / approved | … |
+
+## User feedback and decisions (dated)
+- YYYY-MM-DD: …
+
+## Releases
+- YYYY-MM-DD commit … deployment …
diff --git a/.claude/skills/animebook/assets/templates/book.html b/.claude/skills/animebook/assets/templates/book.html
new file mode 100644
index 0000000..fd2efa2
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/book.html
@@ -0,0 +1,318 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>BOOK TITLE</title>
+<meta name="description" content="ONE SENTENCE ABOUT THE BOOK.">
+<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="#ch01" blocking="render">
+<style>
+:root {
+ --page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
+ --chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068; --task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0;
+ --ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --book: "Iowan Old Style", Palatino, Georgia, serif;
+ --ease: cubic-bezier(.2, .8, .2, 1);
+ color-scheme: dark;
+}
+* { box-sizing: border-box; }
+html { scroll-padding-top: 90px; }
+body { margin: 0; min-height: 100svh; background: var(--board); color: var(--chalk); font: 18px/1.5 var(--ui); }
+/* Chalkboard: the same grain and vignette as the lesson stage. */
+body::before { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
+ background: radial-gradient(ellipse at 50% 42%, transparent 55%, rgba(0, 0, 0, .38)),
+ url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='g'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' seed='7'/%3E%3CfeColorMatrix values='0 0 0 0 .92 0 0 0 0 .95 0 0 0 0 .9 0 0 0 .07 0'/%3E%3C/filter%3E%3Crect width='240' height='240' filter='url(%23g)'/%3E%3C/svg%3E"); }
+a { color: inherit; }
+a:focus-visible { outline: 3px solid var(--task); outline-offset: 3px; }
+.kicker { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .16em; text-transform: uppercase; color: var(--quiz); }
+
+/* ---------- cover ---------- */
+#cover { position: relative; min-height: 100svh; display: flex; flex-direction: column; align-items: center; justify-content: center;
+ padding: 48px 16px 64px; text-align: center; overflow: hidden; }
+.open #cover, body:not(.open) #contents { display: none; }
+#cover > * { animation: rise .8s var(--ease) backwards; }
+#cover .mascot { animation: none; margin-bottom: 26px; view-transition-name: guide; }
+#cover .kicker { animation-delay: .9s; }
+#cover h1 { animation-delay: 1s; }
+#cover .lede { animation-delay: 1.12s; }
+#cover .acts { animation-delay: 1.24s; }
+#cover .meta { animation-delay: 1.36s; }
+h1 { margin: 14px 0 18px; font: 500 clamp(44px, 8.4vw, 92px)/1.02 var(--book); letter-spacing: -.01em; view-transition-name: book; }
+h1 i { color: var(--task); font-style: italic; }
+.lede { max-width: 34em; margin: 0 0 34px; color: var(--dim); font-size: clamp(17px, 2.2vw, 20px); text-wrap: balance; }
+.acts { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; }
+.btn { display: inline-flex; align-items: center; gap: 12px; padding: 14px 30px; border-radius: 999px; font-weight: 600; font-size: 19px; text-decoration: none;
+ transition: transform .25s var(--ease), background-color .25s, border-color .25s; }
+.btn[hidden] { display: none; }
+.btn:hover { transform: translateY(-2px); }
+.btn.go { background: var(--chalk); color: var(--board); }
+.btn.quiet { border: 1.5px solid var(--edge); color: var(--chalk); }
+.btn.quiet:hover { border-color: var(--dim); }
+.btn svg { width: 15px; height: 15px; fill: currentColor; }
+.meta { margin: 30px 0 0; color: var(--faint); font-size: 15px; letter-spacing: .04em; }
+/* Faint chalk notes around the edges of the board. */
+.chalk { position: absolute; inset: 0; z-index: -1; pointer-events: none; animation: none !important; }
+.chalk span { position: absolute; font: italic 400 clamp(22px, 3vw, 38px) var(--book); color: var(--chalk); opacity: 0; white-space: nowrap;
+ animation: chalk 1.6s ease-out forwards, drift 14s ease-in-out infinite alternate; animation-delay: calc(var(--d) * 1s), calc(var(--d) * 1s); }
+@keyframes chalk { to { opacity: .075; } }
+@keyframes drift { to { translate: 0 -10px; } }
+@keyframes rise { from { opacity: 0; transform: translateY(16px); } }
+
+/* ---------- the guide: an infinity sign whose loops are its eyes ---------- */
+.mascot { display: block; overflow: visible; }
+.mascot .mbody { transform-box: view-box; transform-origin: 60px 46px; animation: bob 3.4s ease-in-out infinite; }
+.mascot .pupil { transform-box: fill-box; transform-origin: center; animation: blink 5s infinite; }
+.mascot .joy { display: none; }
+#cover:has(.go:hover, .go:focus-visible) .pupil { display: none; }
+#cover:has(.go:hover, .go:focus-visible) .joy { display: inline; }
+.draw .loop { stroke-dasharray: 1 1; animation: draw 1.3s cubic-bezier(.6, 0, .3, 1) .15s backwards; }
+.draw .face { animation: pop .45s var(--ease) 1.25s backwards; }
+@keyframes draw { from { stroke-dashoffset: 1; } }
+@keyframes pop { from { opacity: 0; transform: scale(.6); } }
+.draw .face { transform-box: view-box; transform-origin: 60px 44px; }
+@keyframes bob { 50% { transform: translateY(-3px) rotate(-2deg); } }
+@keyframes blink { 0%, 93%, 100% { transform: scaleY(1); } 96% { transform: scaleY(.1); } }
+
+/* ---------- contents ---------- */
+.top { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 14px; padding: 12px max(16px, calc(50% - 590px));
+ background: rgba(22, 33, 29, .86); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-bottom: 1px solid #2a3b35; }
+.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(0, 0, 0, .3); }
+.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); }
+
+.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; }
+::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-back { margin-left: 0; font-size: 11px; }
+ #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">PHRASE ONE</span>
+ <span style="right:8%;top:17%;--d:1.9">PHRASE TWO</span>
+ <span style="left:5%;bottom:20%;--d:2.2">PHRASE THREE</span>
+ <span style="right:6%;bottom:15%;--d:2.5">PHRASE FOUR</span>
+ </div>
+ <svg class="mascot draw" id="guide" width="210" height="147"></svg>
+ <p class="kicker">An animated book</p>
+ <h1>BOOK <i>&amp;</i> TITLE</h1>
+ <p class="lede">ONE OR TWO SENTENCES ABOUT WHAT THE READER WILL SEE AND DO.</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>BOOK <i>&amp;</i> TITLE</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';
+// Chapters are numbered in order through the units. Add a chapter here when its lesson is ready.
+const UNITS = [ // [unit title, [[chapter title, minutes], ...]]; chapters are numbered in order. Add a chapter when its lesson is ready.
+ ['First unit', [['First chapter', 8]]],
+];
+const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];
+const id = n => 'ch' + String(n).padStart(2, '0');
+let P = {};
+try { P = JSON.parse(localStorage.getItem('progress') || '{}'); } catch {}
+const done = new Set(P.done || []);
+
+// Contents.
+let n = 0, 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 + 1}</span>${esc(name)}</h2><div class="grid">` +
+ chs.map(([t, min]) => { n++;
+ 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('');
+total = n;
+// 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 <= total).length;
+document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;
+document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;
+const last = 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="#ece8dc" 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="#ece8dc"/><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) {
+ 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/.claude/skills/animebook/assets/templates/chapter.html b/.claude/skills/animebook/assets/templates/chapter.html
new file mode 100644
index 0000000..c5f9d4a
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/chapter.html
@@ -0,0 +1,63 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>CHAPTER TITLE</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="audio/en/timings.js"></script>
+<script>
+'use strict';
+// A starting skeleton, not a design. Replace every beat; keep the shape: intro, lesson beats with
+// quick checks between them, a summary, full-screen practice, finish. Beat ids match narration.en.json.
+const CHAPTER = { number: 1, title: 'CHAPTER TITLE', minutes: 8 }; // set next: '../chNN/' once the next chapter exists
+
+/* ---------- chapter drawing helpers ---------- */
+const mline = (p, parts, x, y, t0, fill = COL.chalk, size = 48, anchor = 'middle') => { const e = M(p, [].concat(parts), { x, y, size, fill, anchor, o: 0 }); show(e, t0); return e; };
+const text = (p, str, x, y, t0, { size = 30, fill = COL.chalk, anchor = 'start', weight = 500 } = {}) => { const e = T(p, str, { x, y, size, fill, anchor, weight, o: 0 }); show(e, t0); return e; };
+
+/* ---------- beats: [id, title, run(m, D), { ask }?] ---------- */
+const BEATS = [
+ ['intro', 'TOPIC', (m, D) => {
+ const g = G(scene, { o: 0, y: 24 });
+ T(g, 'Unit 1, Chapter 1', { x: 800, y: 330, size: 28, fill: COL.dim, anchor: 'middle' });
+ T(g, 'CHAPTER TITLE', { x: 800, y: 430, size: 88, weight: 600, anchor: 'middle' });
+ tw(g, { o: 1, y: 0 }, .2, 1.1, out);
+ const r = text(scene, 'one line that says what this chapter is for', 800, 600, m('sub'), { size: 34, fill: COL.dim, anchor: 'middle' });
+ tw(g, { o: 0, y: -24 }, D - .9, .8); hide(r, D - .9, .8);
+ }],
+ ['idea', 'FIRST IDEA', (m) => {
+ const p = panel(0); // fades the last picture; put the topic on screen at once
+ mline(p, '3 + 4 = 7', 800, 260, .2, COL.chalk, 64);
+ text(p, 'a note that appears with its word', 800, 380, m('note'), { size: 30, fill: COL.task, anchor: 'middle', weight: 600 });
+ }],
+ ['q1', 'Quick check', () => { panel(0); }, { ask: done => quiz(BAND, [{
+ id: 'c-first', prompt: ['A question about what was just shown.'],
+ build: blanks([{ parts: ['3 + 4 = ', { box: '7' }], why: 'Why the answer is right.', hint: 'A hint aimed at the likely mistake.' }]),
+ }], done) }],
+ ['wrap', 'Summary', (m) => {
+ const p = panel(0);
+ [['First takeaway.', 'w1'], ['Second takeaway.', 'w2']].forEach(([str, mark], i) => {
+ const g = G(p, { x: -16, y: 300 + i * 140, o: 0 });
+ mk('circle', { cx: 200, cy: -12, r: 26, fill: COL.task }, g);
+ T(g, String(i + 1), { x: 200, y: -1, size: 30, fill: COL.board, weight: 700, anchor: 'middle' });
+ T(g, str, { x: 260, size: 34, weight: 600 });
+ tw(g, { o: 1, x: 0 }, m(mark), .6);
+ });
+ }],
+ ['final1', 'Chapter practice', () => { panel(0); }, { ask: done => quiz(SCREEN, [{
+ id: 'p-one', prompt: ['Practice that covers the whole chapter.'],
+ build: choice([['right answer'], ['tempting wrong answer']], 0, 'Why it is right.', [null, 'What this mistake misunderstands.']),
+ }], done, 'Chapter practice 1 of 1') }],
+ ['finish', 'Finished', () => { panel(0); }, { ask: finishCard }],
+].map(([id, title, run, extra]) => ({ id, title, run, ...extra }));
+
+/* ---------- practice data (constants used inside BEATS must be defined above it) ---------- */
+boot();
+</script>
+</body>
+</html>
diff --git a/.claude/skills/animebook/assets/templates/e2e.py b/.claude/skills/animebook/assets/templates/e2e.py
new file mode 100644
index 0000000..2b294b4
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/e2e.py
@@ -0,0 +1,61 @@
+"""Keyboard-only walk through chapter NN: each question answered wrong, right, and once via Show answer.
+
+ python3 -m http.server 8765 -d site &
+ uv run --with playwright tools/e2e_chNN.py
+
+Beat numbers follow BEATS in the chapter page. Rerun every chapter's test after an engine change.
+"""
+import asyncio, os
+from playwright.async_api import async_playwright
+CH = "ch01"
+URL = os.environ.get("URL", f"http://localhost:8765/{CH}/index.html")
+
+
+async def main():
+ async with async_playwright() as p:
+ b = await p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])
+ pg = await b.new_page(viewport={"width": 1440, "height": 900})
+ errs = []
+ pg.on("pageerror", lambda e: errs.append(str(e)))
+ pg.on("console", lambda m: m.type == "error" and errs.append(m.text))
+ await pg.goto(URL); await pg.wait_for_timeout(400)
+ ev = pg.evaluate
+
+ async def keys(*ks):
+ for k in ks:
+ await pg.keyboard.press(k); await pg.wait_for_timeout(60)
+
+ async def typed(*vals): # fills answer boxes in order (Tab between them)
+ for i, v in enumerate(vals):
+ if i: await keys("Tab")
+ await pg.keyboard.type(v); await pg.wait_for_timeout(40)
+
+ async def at(i): # jump to beat i, playing
+ await ev(f"seek({i}, true)"); await pg.wait_for_timeout(250)
+
+ async def ok():
+ assert "Correct" in await pg.inner_text(".card .fb"), await pg.inner_text(".card .fb")
+
+ score = lambda k: ev(f"SCORE['{k}'] && SCORE['{k}'].right") # first-try score of question id k
+ await keys("Space"); await pg.wait_for_timeout(1500)
+ assert await ev("P.playing && P.t > .5"), "lesson plays"
+
+ await at(2) # q1: wrong first, then right
+ await typed("6"); await keys("Enter"); assert await score("c-first") == 0
+ await pg.locator(".box").nth(0).fill("7"); await keys("Enter"); await ok()
+ await keys("Enter"); assert await ev("P.i") == 3
+
+ await at(4) # practice: one wrong, then Show answer (Esc first if a box has focus)
+ await keys("2"); assert await score("p-one") == 0
+ await keys("s"); assert "Answer" in await pg.inner_text(".card .fb")
+ await keys("Enter"); await pg.wait_for_timeout(200)
+ assert f"chapter {int(CH[2:])} complete" in (await pg.inner_text(".card")).lower()
+ await keys("r"); await pg.wait_for_timeout(200); assert await ev("P.i") == 0 # Enter on the finish card opens the next chapter
+
+ for i in range(await ev("BEATS.length")): # every beat must rebuild without errors
+ await ev(f"seek({i}, false)")
+ assert not errs, errs
+ print(f"{CH} keyboard walk-through passed")
+ await b.close()
+
+asyncio.run(main())
diff --git a/.claude/skills/animebook/assets/templates/narration.en.json b/.claude/skills/animebook/assets/templates/narration.en.json
new file mode 100644
index 0000000..8771e4c
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/narration.en.json
@@ -0,0 +1,12 @@
+{
+ "voice": "en-US-AndrewMultilingualNeural",
+ "rate": "-4%",
+ "beats": {
+ "intro": "Chapter one. [[sub]]One sentence that says what this chapter is for.",
+ "idea": "Say the idea while the picture shows it. [[note]]The mark goes right before the word the animation waits for.",
+ "q1": "Quick check. A few words that name the task.",
+ "wrap": "To sum up. [[w1]]First takeaway. [[w2]]Second takeaway. [[end]]Now try the chapter practice.",
+ "final1": "Chapter practice. Name the task.",
+ "finish": "Well done. That's the end of chapter one."
+ }
+}
diff --git a/.claude/skills/animebook/assets/templates/unit-art.js b/.claude/skills/animebook/assets/templates/unit-art.js
new file mode 100644
index 0000000..67f3507
--- /dev/null
+++ b/.claude/skills/animebook/assets/templates/unit-art.js
@@ -0,0 +1,23 @@
+// 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 = [
+ // 1 An example: a number line with a dot hopping along it.
+ reset(P('M228 130H572') + Array.from({ length: 7 }, (_, i) => P(`M${250 + i * 50} 122v16`, 'a')).join('') +
+ `<circle class="t hop" r="8" fill="currentColor" stroke="none" style="--k:${k++};offset-path:path('M250 116Q275 84 300 116Q325 84 350 116Q375 84 400 116')"/>` +
+ Tx(250, 60, 'a sketch of this unit', 26) + C(530, 70, 24, 'a')),
+ ];
+})();
diff --git a/.claude/skills/animebook/references/authoring.md b/.claude/skills/animebook/references/authoring.md
new file mode 100644
index 0000000..c57588e
--- /dev/null
+++ b/.claude/skills/animebook/references/authoring.md
@@ -0,0 +1,77 @@
+# Authoring a chapter
+
+## Shape
+
+A chapter runs about 5–11 minutes: 10–20 beats, each 5–40 seconds of narration.
+
+| Beat | Purpose |
+| --- | --- |
+| `intro` | Title card (unit and chapter number, title, one line of purpose). |
+| lesson beats | One idea each, built up in the picture while the narration explains it. |
+| `q1`, `q2`, … | A quick check after every one to three lesson beats, inside the picture. |
+| `wrap` | Three or four numbered takeaways. |
+| `final1` … | Two to four full-screen practice sets labelled "Chapter practice N of M", covering the whole chapter. |
+| `finish` | Score card (`finishCard`): first-try results for quick checks and practice. |
+
+Beat ids are shared by the page (`BEATS`) and the narration file; a beat with `ask` waits for the answers before moving on.
+
+## Storyboard
+
+Before writing code, list the beats. For each lesson beat decide:
+
+- what the eye should watch, and what changes;
+- why that change is true (the animation is the argument, not decoration);
+- which words trigger which actions (these become `[[marks]]`);
+- what text appears on screen: the key formula, rule or label, placed beside the thing it names;
+- what is still on screen from the previous beat, and what fades.
+
+Principles that held up over a whole book:
+
+- **Open on the subject.** When a beat clears the picture, the new topic (expression, diagram, question) appears right away; labels and steps then follow the words. The engine moves an opening group forward if nothing appears in the first 0.8 s, but design for it. Normal transitions and short pauses for thought are fine; the picture need not move all the time.
+- **One new thing at a time.** Don't introduce several objects, colours and texts at once.
+- **Same colour, same meaning** within a chapter (and, where it fits, across the book).
+- **Be exact.** Number lines, grids and areas are to scale; a deliberately enlarged drawing says "drawn larger" on screen. Approximations are written as approximations (≈ 4.47…, never = 4.47).
+- **Teach the chapter's scope.** If the book jumps ahead or uses something not yet taught, leave it out or say so.
+- **Show the common mistake** where one exists (e.g. squaring the coefficient too), visually crossed out, then the right way.
+
+## Narration
+
+`content/chNN/narration.en.json`:
+
+```json
+{ "voice": "en-US-AndrewMultilingualNeural", "rate": "-4%",
+ "beats": { "intro": "Chapter five. [[sub]]Subtraction undoes addition.", "...": "..." } }
+```
+
+- `[[name]]` goes right before the word an action waits for; `m('name', offset)` in the page returns when that word starts. Names are unique within a beat; a misspelt mark makes the page throw, and a mark that matches no spoken word makes `tts.py` stop.
+- Write for the ear: short sentences, one idea each. Say math in words ("negative seven halves", "x squared"); the picture shows the symbols.
+- Match the audience: plain, warm, never childish. Explain why, not only how.
+- Question beats get one short line ("Quick check. Find the mean."); the card holds the question.
+- `tts.py` caches word timings and only re-synthesizes beats whose text or voice changed. It writes `audio/en/<beat>.mp3` and `timings.js` (duration, mark times, one caption cue per sentence). Edge TTS needs network access.
+
+## Questions
+
+Pick the type that lets the student act on the picture itself whenever possible (click the point, the cell, the step) rather than choosing text.
+
+| Type | Use for |
+| --- | --- |
+| `choice` | One answer from a few options, each wrong option with its own explanation |
+| `blanks` | Typed numbers inside an expression; fractions and mixed numbers accepted; `test` judges a whole row (answers in any order) |
+| `grid` | Several items, each classified (yes/no, which category, true/false) |
+| `tap` / `tapEls` / `pickEls` | Click a point on the number line / a token in an expression / any drawn object |
+| `pickPoint` | Choose a grid point on a coordinate plane |
+| `sorter` | Drag items into regions (the number-set diagram) |
+
+New types are welcome when the content calls for one; each needs keyboard play (see engine.md).
+
+- Ids: `c-…` for quick checks, `p-…` for practice; the score card adds them up.
+- The prompt is HTML text; put math in it with `$m(...)`.
+- Feedback: right → `why` (and an animation via `fx`/`onRight`); wrong → a hint aimed at that mistake; after a wrong try, Show answer.
+- Grade meaning: equal values match (6/8 = 3/4) unless the lowest form is asked for; sets and pairs in any order; no denominators of zero; never judge irrationality from finitely many digits.
+- Place cards so they don't cover the object being asked about (`BAND` under a number line, `TOPR` top right, a custom `{x, y, w, cls: 'side'}` beside a figure, `SCREEN` for practice).
+
+## Content rules
+
+- Rewrite everything in your own words with your own examples and numbers; keep the book's topics and order unless the user decides otherwise.
+- Recompute every worked example and every answer key entry. Wrong statements, wrong answers and ambiguous exercises are common; fix or drop them, and log each in BOOK.md (chapter, what was wrong, what you did).
+- Keep one consistent set of conventions (definitions, notation, rounding) for the whole book and record them in BOOK.md.
diff --git a/.claude/skills/animebook/references/engine.md b/.claude/skills/animebook/references/engine.md
new file mode 100644
index 0000000..d835f94
--- /dev/null
+++ b/.claude/skills/animebook/references/engine.md
@@ -0,0 +1,79 @@
+# The engine (lib/engine.js, lib/engine.css)
+
+A chapter page loads the engine and its `audio/en/timings.js`, defines `CHAPTER`, its own small drawing helpers, `BEATS` and question data, then calls `boot()`. The engine provides the stage, drawing, a timeline, question types, the guide character and the player. If a name below disagrees with the code, the code wins; fix this file.
+
+Many helpers are mathematical (number lines, planes, tiles) because the first book was algebra. Use what fits; for other subjects write new helpers in the chapter page, and move one into the engine the second time it is needed — not earlier.
+
+## Stage and state
+
+- The stage is SVG, `viewBox 0 0 1600 900`; animated things live in `#scene`. HTML cards go in `#ui`, in the same coordinates.
+- Every animated element carries a state object written to the DOM by `render()`: `x y` (translate), `s` (scale), `r` (rotate, degrees), `o` (opacity), `d` (stroke drawn, 0–1), `a_<attr>` (numeric attribute, e.g. `'a_stroke-width'`), `c_<attr>` (hex colour). Give a key a starting value before tweening it; an `a_`/`c_` key without one starts from the element's attribute.
+- Scale and rotation are about the element's own origin: draw around (0,0) and place with `x/y`.
+- `S` holds objects shared across beats (`S.panel`, `S.line`, …). `reset()` clears it, so anything a later beat needs must be stored on `S`.
+- Palette `COL`: `chalk dim faint task good bad board` plus six hues `nat whole int rat irr real`. Fonts: `UI` (text), `MATH` (serif).
+
+## Drawing
+
+| Function | Use |
+| --- | --- |
+| `G(parent, {x,y,s,r,o})` | group |
+| `path(parent, d, attrs, {d:0})` | path; `{d: 0}` makes it ready to be drawn on with `draw()` |
+| `T(parent, str, {x,y,size,fill,font,weight,anchor,o})` | text |
+| `M(parent, parts, {x,y,size,fill,anchor,o,s})` | math with its baseline at y; parts are strings, `F(n,d)` fractions, `R(x, i)` roots (x may be `F(...)`, i the index), `E(exp)` exponents; returns a group with `_w` (width) |
+| `mathW(parts, size)` | width of math without drawing it |
+| `frac(p, top, bot, x, y, t0, opts)` | built-up fraction whose top and bottom are math parts |
+| `chip(parent, parts, color, {x,y,size})` | pill-shaped token centred on (x,y) |
+| `tokens(parent, items, {x,y,size,anchor})` | a row of separately movable math tokens (items: string, parts, or `{t, fill}`); returns the array with `.w .y .size`, each token with `_px` (centre) |
+| `collapse(row, i, j, parts, t0)` | box tokens i..j, shrink them into one result, close the gap; returns the new row |
+| `eqLine(p, L, R, y, t0, {xEq, sym, note})` | one line of a derivation aligned on its `=` (or `<`, …) with an optional note |
+| `mathEl(parts, size)`, `rich([...])`, `$m(...parts)` | inline math in HTML (cards, prompts) |
+| `panel(t0)` | fade the current scene group and start a new one; call it at the start of a beat that changes the picture |
+
+Topic helpers already in the engine: number lines (`numberLine`, `X(v)`, `Y0`, `tick`, `dot`, `move`, `landDot`, `brace`, `AXIS`), signed tiles (`tile`, `tiles`, `cancelPairs`), algebra tiles (`atile`, `tileRow`, `cancel`, `popIn`, sizes in `TS`), fraction rows (`fracRow`, `reduce`), a decimal point that hops (`pointRow`), a balance (`balance`), inequality graphs (`ray`, `segment`), a coordinate plane (`plane`: `PX/PY`, `dot`, `walk`, `line`, `arrow`, `stair`, `region`, `half`, `fn` for y = f(x); set `P.layer = panel(0)` so marks clear with the beat), scaled axes (`axes`), dot plots (`dataLine`), chance objects (`die`, `coin`, `spinner`, `outline`), area grids (`areaGrid` with `.cell`, `.ring`; `arc`), rectangles (`rect`, `bracketH`), vertical scales (`vAxis`, `thermometer`), the number-set diagram (`RINGS`, `buildVenn`, `regionAt`). Read the function in engine.js before first use.
+
+## Timing
+
+```js
+['idea', 'Short title', (m, D) => {
+ const p = panel(0);
+ draw(path(p, 'M100 600H1500', { stroke: COL.chalk, 'stroke-width': 3 }, { d: 0 }), .2, .8);
+ show(T(p, 'a label', { x: 800, y: 560, o: 0 }), m('label', .3)); // .3 s after the word after [[label]] starts
+}, { ask: done => quiz(BAND, [/* questions */], done) }], // optional: a question beat
+```
+
+- `m('name', offset)` is the start time of the word after `[[name]]`; `D` is the clip's length. Never hard-code seconds that should follow the voice.
+- Tweens: `tw(e, to, t0, dur, ease)`, `prog(q => …, t0, dur, ease)` for custom motion (arcs, counters, live redraws), `show`, `hide`, `draw`, `pop`, `pulse`, `stream`. Eases: `io`, `out`, `back`, `lin`.
+- A lesson beat ends after its narration and its last tween, then the next starts; an `ask` beat waits for `done()`.
+- **Opening lead-in**: if a beat calls `panel()` (before 0.5 s) and nothing appears within 0.8 s, `runBeat` moves the opening group (every tween starting within 1.2 s of the first reveal) to start at 0.4 s. Opt out with `{ lead: false }` in the beat's fourth slot.
+- **Seeking replays**: jumping to beat N rebuilds the scene and runs every earlier beat's `run` instantly. So `run` may only schedule tweens — no `setTimeout`, `Math.random`, `Date`, or reading the current state to decide what to draw. Interactive elements are created only inside `ask`.
+- Constants used in a `BEATS` literal are evaluated when it is defined, so define them above `BEATS`. Data used only inside an `ask` closure may sit below.
+
+## Questions
+
+```js
+quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'], build: blanks([...]) }, …], done, 'Quick check')
+```
+
+- Positions: `BAND` (below a number line, y 686–886), `TOPR` (top right, ≤ 470 high), `RIGHT`, `SCREEN` (full-screen practice; label `'Chapter practice N of M'`), `SORT_SCREEN`, or any `{x, y, w, cls: 'side'}`.
+- `choice(options, right, why, wrongWhys[], onRight?)` — number keys.
+- `blanks(rows)` — rows `{parts: [..., {box: '21'}, ...], why, hint?, fx?, test?}`; accepts −5, 3/4, 2 1/4, 0.75 as exact values; `{box, lowest: true}` demands lowest terms; `test(values)` judges the whole row (e.g. two factors in either order). Tab moves between boxes, Enter checks, Esc leaves a box.
+- `grid(rows, cols, {multi, text})` — rows `{parts, ans: [keys], why, fx?}`, cols `[[key, label, colour?, hotkey?]]`; with `text: true` parts are rich text (math via `$m`). ↑/↓ change rows.
+- `tap(values, right, why, v => wrongWhy, onRight?)` points on the number line; `tapEls(row, idx, right, …)` tokens of a `tokens` row; `pickEls([{el, box: [x,y,w,h], label}], right, …)` any drawn objects; `pickPoint(P, [x,y], why, (x,y) => wrongWhy, onRight?, test?)` grid points (arrows + Enter or click); `sorter(items, trayXY)` drag into the set diagram (keys 1–6).
+- Answer animations run on their own clock: `fx`, `fxp`, `pulseFx`, `shakeFx`, `floatText`, `qlayer()` (a layer cleared with the question). They are finished automatically when the beat is left.
+- A new type: `build(body, api)` returns `{ reveal, check?, lock?, key?(e), hint? }` and calls `api.grade(ok, message, {right, total})`. `key` handles its shortcuts (return true when used); `hint` lists the keys under the prompt. Every action needs a key; the help overlay (`?`) lists the global ones.
+- Scores: `SCORE[id]` keeps the first try; a multi-row question scores one per row.
+
+## Player
+
+Space play/pause, ←/→ previous/next beat (Shift+←/→ during a question), Home restart, C captions, F full screen, ? help. `seek(i, play)` rebuilds and jumps; `start(i, play)` begins a beat from the current picture. While audio plays, the beat clock follows `audio.currentTime`. `?beat=N&t=S` in the URL opens a frozen frame for review. The finish card's Enter opens `CHAPTER.next`, R replays.
+
+Keep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head; without it Chromium may paint before the player exists and cancel the page transition from the contents page.
+
+## Traps
+
+- `M()` italicises 1–2 letter lowercase runs (variables) and runs of capitals, but keeps common short English words upright (by, my, an, if, in, is, of, or, …; capitalised: By, If, In, …). In maths write `b​y`, `m​y`, `a​n`, `B​y` to keep them italic. Units inside `M()` turn italic too: write them as words in `T()` text ("meters"). Never put an English sentence in `M()`.
+- Prompts, `grid` text rows and `choice` options are HTML: plain strings render as text, so wrap math in `$m(...)`.
+- Don't redeclare an engine name with `const` in a chapter (`rect`, `popIn`, `eqLine`, `fit`, `slot`, `Y0`, …): the page script dies and the stage stays empty. After writing a page, load `?beat=0` and check the console first.
+- Drag handling: re-parent (append) the element before `setPointerCapture`; moving a node drops its capture.
+- A card whose content is too long for `BAND` should become several `blanks` rows in a wider side card.
+- When a question beat is continued early, the engine finishes the beat's pending tweens first; don't rely on half-finished fades.
diff --git a/.claude/skills/animebook/references/review.md b/.claude/skills/animebook/references/review.md
new file mode 100644
index 0000000..2f6c11b
--- /dev/null
+++ b/.claude/skills/animebook/references/review.md
@@ -0,0 +1,53 @@
+# Review and tests
+
+Serve the site first (audio needs HTTP): `python3 -m http.server 8765 -d site`. For a book in `site/<book>/`, pass `--url http://localhost:8765/<book>/` to the scripts. Python's server has no Range requests, so setting `audio.currentTime` jumps back to the start; tests let audio play or use `seek()`.
+
+## 1. Load check
+
+Open `…/chNN/index.html?beat=0&t=0` (or run `shot.py` with one spec). Any console error usually means a redeclared engine name, a missing mark, or a constant used in `BEATS` before it is defined.
+
+## 2. Screenshots
+
+```sh
+uv run --with playwright --with pillow SKILL/scripts/shot.py chNN --url … --out /tmp/shots
+```
+
+Every beat at 1.2 s (`open`), middle and end, saved as 4-up contact sheets `chNN_sheet_{open,mid,end}_K.png`. Read the `open` and `end` sheets; look at `mid` or a single shot only to chase a problem; use `shot.py chNN 5:7.5` for a specific moment. One browser at a time, and pick times after fades finish.
+
+Look for:
+
+- the picture empty or unrelated at `open`;
+- text over drawings, labels colliding, anything clipped or off the stage;
+- a question card covering the object it asks about;
+- leftovers from the previous beat, half faded;
+- wrong mathematics in the drawing: points off their values, unequal spacing, an area not matching its label;
+- text too small to read at half size, or too much text at once;
+- inconsistent colours for the same idea.
+
+## 3. Opening blanks
+
+```sh
+uv run --with playwright SKILL/scripts/check_blank.py site/<book> chNN --url …
+```
+
+No output means no beat leaves the picture empty for more than 1 s after the narration starts (`LIMIT=0.6` for stricter). Fix the beat's opening, don't raise the limit.
+
+## 4. End-to-end test
+
+Copy `SKILL/assets/templates/e2e.py` to `tools/e2e_chNN.py` and fill in the chapter's questions: each answered wrong then right (first-try score 0), at least one Show answer, the finish card, R back to the start, then `seek` through every beat; no console errors. Run `uv run --with playwright tools/e2e_chNN.py` (set `URL` for a book folder).
+
+- Keyboard only (plus one mouse pass for drag questions).
+- With focus in an answer box only Enter and Esc are handled; press Esc before S (Show answer).
+- Playwright's `text=Check` matches case-insensitively and by substring ("Quick check"); buttons include their key label ("1Rational"). Use CSS classes or indexes.
+- A multi-row `blanks`/`grid` question scores one per row.
+- Enter on the finish card opens the next chapter; use R in tests.
+
+## 5. Regression
+
+After any engine change, run every chapter's test (in the background, two at a time):
+
+```sh
+ls tools/e2e_ch*.py | xargs -P 2 -I{} sh -c 'uv run -q --with playwright {} >/dev/null 2>&1 || echo "FAIL {}"'
+```
+
+Also rerun `check_blank.py` for the whole book when timing logic changes.
diff --git a/.claude/skills/animebook/references/site.md b/.claude/skills/animebook/references/site.md
new file mode 100644
index 0000000..ac3f5b1
--- /dev/null
+++ b/.claude/skills/animebook/references/site.md
@@ -0,0 +1,60 @@
+# The site: book folder, contents, bookshelf, publishing
+
+The site is static: HTML, JS, CSS, MP3. No build step, backend, database or accounts; reading progress lives in the browser (`localStorage`). Only `site/` is published.
+
+## Start a book folder
+
+```sh
+B=site/<book-slug>
+mkdir -p $B/lib $B/ch01 content/ch01 tools
+cp SKILL/assets/engine/engine.js SKILL/assets/engine/engine.css $B/lib/
+cp SKILL/assets/templates/book.html $B/index.html
+cp SKILL/assets/templates/unit-art.js $B/unit-art.js
+cp SKILL/assets/templates/chapter.html $B/ch01/index.html
+cp SKILL/assets/templates/narration.en.json content/ch01/
+cp SKILL/assets/templates/e2e.py tools/e2e_ch01.py
+```
+
+Each book keeps its own engine copy, so improving one book never breaks another. A chapter links back to `../` (the book's index) and the index links back to `../` (the bookshelf).
+
+## Cover and contents (`index.html`)
+
+One page: no hash or `#book` shows the cover, `#contents` or `#chNN` the contents; a lesson's home button returns to `#chNN`, and the card grows into the lesson frame through a view transition.
+
+- Edit the title, kicker, lede, the faint chalk phrases on the cover (a few formulas or lines from the book), and the `<title>`.
+- `UNITS`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order. Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`.
+- `HUES`: one colour per unit, cycling.
+
+## Unit sketches (`unit-art.js`)
+
+Each unit header is a strip of chalkboard with a small drawing of that unit's ideas in the unit colour. It draws itself the first time the unit scrolls into view, then keeps one gentle loop that fits the topic (two terms swapping places, a dot hopping along a line, a balance tilting, a spinner turning). Draw from the book's own content — a timeline for a history unit, a map, a family tree, a key quotation — with paths and text only. Keep the left third light (the title sits there on phones); test at 1440 px and 390 px wide; motion stops under `prefers-reduced-motion`. The classes and loop examples are documented at the top of `unit-art.js` and in the `.unit-art` CSS of `index.html`.
+
+## Guide character
+
+The engine's `mascotEl` draws the guide shown on question cards and the score card (and the cover uses the same drawing). The first book used an infinity sign whose loops are eyes. For a new book, draw a simple SVG character that suits it, in `mascotEl` and in the cover script, with the same moods (blink, hop when right, tilt when wrong). Never use a famous or branded character.
+
+## Bookshelf
+
+`site/index.html` with `lib/bookshelf.js` and `.css` lists the books. Add an entry to `books` in `bookshelf.js`:
+
+```js
+{ id: 'history', title: '…', subject: 'History', href: 'history/', coverTitle: ['Line one', 'line two'],
+ series: 'An animated book', description: '…', chapters: 24, units: 6,
+ artwork: '<svg viewBox="0 0 260 175" class="book-art">…</svg>', features: ['…', '…', '…'] }
+```
+
+Only list books that are published; never placeholders.
+
+## Publishing
+
+Only when the user asks. Any static host works; for Cloudflare Pages:
+
+```sh
+npx wrangler pages deploy site --project-name <project> --branch main --commit-hash $(git rev-parse --short HEAD)
+```
+
+Commit first, deploy the committed state, then confirm the live URL serves the new files (`curl` a changed file with a cache-busting query) and record the deployment id in BOOK.md. Never publish the PDF, `book_pages/` or tools; they live outside `site/`.
+
+## Languages
+
+Narration and on-screen text are written in one language first. A second language comes after the book is done and approved: keep beat ids and question ids stable, add `narration.<lang>.json` and audio per language, and decide with the user how switching behaves mid-lesson before building it.
diff --git a/.claude/skills/animebook/scripts/check_blank.py b/.claude/skills/animebook/scripts/check_blank.py
new file mode 100644
index 0000000..720c56b
--- /dev/null
+++ b/.claude/skills/animebook/scripts/check_blank.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Find opening blanks: the narration has started but the picture is still empty.
+
+ python3 -m http.server 8765 -d site &
+ uv run --with playwright check_blank.py site # every chapter of the book in site/
+ uv run --with playwright check_blank.py site/history ch05 ch06 --url http://localhost:8765/history/
+ LIMIT=0.6 uv run --with playwright check_blank.py site # stricter
+
+book_dir holds the chNN folders; --url is where that folder is served. For each lesson beat
+(question beats are skipped) whose picture stays empty longer than LIMIT seconds (default 1)
+near its start, prints: chapter, beat index, beat id, empty from, empty until, seconds.
+No output means no opening blank. Exit status 1 when something is found.
+"""
+import argparse, asyncio, os, sys
+from pathlib import Path
+from playwright.async_api import async_playwright
+
+LIMIT = float(os.environ.get("LIMIT", "1.0"))
+PROBE = r"""
+(i) => {
+ seek(i, false);
+ const b = BEATS[i], tm = TIMINGS[b.id], first = (tm.cues[0] || [0])[0];
+ const visible = () => { // drawn leaves whose opacity, multiplied up to the scene, is above .05
+ let n = 0;
+ for (const e of scene.querySelectorAll('text,path,circle,rect,ellipse,line,polygon')) {
+ if (e.closest('.qlayer')) continue;
+ let o = 1, x = e;
+ while (x && x !== scene) { o *= +(x.getAttribute('opacity') ?? 1); if (x.style && x.style.visibility === 'hidden') o = 0; x = x.parentNode; }
+ const r = e.getBoundingClientRect();
+ if (o >= .05 && (r.width >= 2 || r.height >= 2)) n++;
+ }
+ return n;
+ };
+ const out = [];
+ for (let t = 0; t <= Math.min(tm.dur, 12); t += .2) { P.t = t; evalTo(t); out.push([+t.toFixed(1), visible()]); }
+ return { id: b.id, ask: !!b.ask, first, dur: tm.dur, out };
+}
+"""
+
+
+async def main(book: Path, chapters, url):
+ found = []
+ async with async_playwright() as p:
+ browser = await p.chromium.launch()
+ pg = await browser.new_page(viewport={"width": 1600, "height": 960})
+ for ch in chapters:
+ await pg.goto(f"{url}{ch}/index.html?beat=0&t=0"); await pg.wait_for_timeout(300)
+ for i in range(await pg.evaluate("BEATS.length")):
+ r = await pg.evaluate(PROBE, i)
+ if r["ask"] or r["id"] == "finish":
+ continue
+ empty = [t for t, c in r["out"] if c == 0]
+ if not empty or empty[0] >= 3:
+ continue
+ start = max(empty[0], r["first"])
+ end = next((t for t, c in r["out"] if t > empty[0] and c > 0), r["dur"])
+ if end - start > LIMIT:
+ found.append((ch, i, r["id"], round(start, 1), round(end, 1), round(end - start, 1)))
+ await browser.close()
+ for row in found:
+ print(*row)
+ return 1 if found else 0
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("book_dir", type=Path)
+ ap.add_argument("chapters", nargs="*")
+ ap.add_argument("--url", default="http://localhost:8765/")
+ a = ap.parse_args()
+ chs = a.chapters or sorted(d.name for d in a.book_dir.glob("ch[0-9][0-9]") if d.is_dir())
+ sys.exit(asyncio.run(main(a.book_dir, chs, a.url if a.url.endswith("/") else a.url + "/")))
diff --git a/.claude/skills/animebook/scripts/outline.py b/.claude/skills/animebook/scripts/outline.py
new file mode 100644
index 0000000..5dbe049
--- /dev/null
+++ b/.claude/skills/animebook/scripts/outline.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Draft sections.json (the page map of a book) from the PDF's bookmarks.
+
+ uv run --with pymupdf outline.py book.pdf # show the bookmark tree
+ uv run --with pymupdf outline.py book.pdf --level 2 -o sections.json
+
+--level is the bookmark depth that marks chapters (look at the tree first). The parent
+bookmarks one level up (units, parts) are recorded as each chapter's "unit"; a unit's
+title pages are put at the start of its first chapter, and "chapter_start" keeps the
+page where the chapter itself begins. Pages before the first chapter become
+"00_front"; pages after the last chapter's own bookmark range become "99_back".
+Every PDF page lands in exactly one section, numbered by PDF page order (from 1),
+not by printed page numbers.
+
+Without bookmarks, nothing is guessed: read the contents pages (render them with
+split_pages.py --only 00_front) and write sections.json by hand in the same format.
+Always check the result against the book before rendering pages.
+"""
+import argparse
+import json
+import sys
+from pathlib import Path
+
+import pymupdf
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("pdf", type=Path)
+ ap.add_argument("--level", type=int, help="bookmark depth of chapters; omit to print the tree")
+ ap.add_argument("-o", "--output", type=Path, help="write sections.json here (default: print)")
+ a = ap.parse_args()
+ doc = pymupdf.open(a.pdf)
+ toc = doc.get_toc() # [level, title, page]
+ n = len(doc)
+ if not toc:
+ sys.exit("No bookmarks in this PDF. Write sections.json by hand from the contents pages.")
+ if a.level is None:
+ for lv, title, page in toc:
+ print(f"{' ' * (lv - 1)}[{lv}] p{page} {title}")
+ print(f"\n{n} pages. Rerun with --level N (the depth whose entries are chapters).")
+ return
+
+ chapters = [(i, t, p) for i, (lv, t, p) in enumerate(toc) if lv == a.level and p >= 1]
+ if not chapters:
+ sys.exit(f"No bookmarks at level {a.level}.")
+ # The first bookmark after the last chapter that is not inside it (an index, appendix, ...) ends the chapters.
+ last_i = chapters[-1][0]
+ after = next((p for lv, t, p in toc[last_i + 1:] if lv <= a.level and p > chapters[-1][2]), n + 1)
+
+ def parent(i):
+ for lv, t, p in reversed(toc[:i]):
+ if lv < a.level:
+ return t, p
+ return None, None
+
+ sections, starts = [], []
+ for k, (i, title, page) in enumerate(chapters):
+ unit, upage = parent(i)
+ first_in_unit = unit is not None and (k == 0 or parent(chapters[k - 1][0])[0] != unit)
+ start = upage if first_in_unit and upage < page else page
+ starts.append(start)
+ s = {"folder": f"ch{k + 1:02d}", "title": title, "start": start, "end": None, "chapter_start": page}
+ if unit:
+ s["unit"] = unit
+ sections.append(s)
+ for k, s in enumerate(sections):
+ s["end"] = (starts[k + 1] if k + 1 < len(starts) else after) - 1
+ if starts[0] > 1:
+ sections.insert(0, {"folder": "00_front", "title": "Front matter", "start": 1, "end": starts[0] - 1})
+ if after <= n:
+ sections.append({"folder": "99_back", "title": "Back matter", "start": after, "end": n})
+ for s in sections:
+ if s["end"] < s["start"]:
+ sys.exit(f"Bad range for {s['folder']} ({s['start']}-{s['end']}); bookmarks out of order? Fix by hand.")
+ text = json.dumps(sections, ensure_ascii=False, indent=2) + "\n"
+ if a.output:
+ a.output.write_text(text, encoding="utf-8")
+ print(f"{len(sections)} sections, {sum(1 for s in sections if s['folder'].startswith('ch'))} chapters -> {a.output}")
+ else:
+ print(text)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/animebook/scripts/shot.py b/.claude/skills/animebook/scripts/shot.py
new file mode 100644
index 0000000..38a0d1c
--- /dev/null
+++ b/.claude/skills/animebook/scripts/shot.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Screenshot beats of a chapter for review, plus contact sheets of four shots each.
+
+ uv run --with playwright --with pillow shot.py ch07 # every beat at 1.2 s, middle and end
+ uv run --with playwright --with pillow shot.py ch07 3:end 5:4.5 6:mid # chosen moments (seconds, mid, end)
+ ... --url http://localhost:8765/history/ --out /tmp/shots
+
+Writes OUT/chNN_bII_T.png and OUT/chNN_sheet_T_K.png (2x2, half size; open the sheets first).
+Uses ?beat=N&t=S, which seeks to the beat and freezes at that time. Run one browser at a
+time: parallel runs slow page loads and catch pictures half faded in.
+"""
+import argparse, asyncio
+from pathlib import Path
+from playwright.async_api import async_playwright
+from PIL import Image
+
+
+async def main(a):
+ a.out.mkdir(parents=True, exist_ok=True)
+ async with async_playwright() as p:
+ b = await p.chromium.launch()
+ pg = await b.new_page(viewport={"width": 1600, "height": 960})
+ errs = []
+ pg.on("pageerror", lambda e: errs.append(str(e)))
+ pg.on("console", lambda m: m.type == "error" and errs.append(m.text))
+ base = f"{a.url}{a.chapter}/index.html"
+ await pg.goto(base + "?beat=0&t=0"); await pg.wait_for_timeout(500)
+ if errs:
+ print("page errors:", errs); return
+ n = await pg.evaluate("BEATS.length")
+ durs = await pg.evaluate("BEATS.map(b => TIMINGS[b.id].dur)")
+ specs = a.specs or [f"{i}:{t}" for t in ("open", "mid", "end") for i in range(n)]
+ groups = {}
+ for s in specs:
+ i, t = s.split(":"); i = int(i)
+ sec = {"open": 1.2, "end": durs[i] + 3, "mid": durs[i] / 2}.get(t)
+ sec = float(t) if sec is None else sec
+ await pg.goto(f"{base}?beat={i}&t={sec}"); await pg.wait_for_timeout(450)
+ f = a.out / f"{a.chapter}_b{i:02d}_{t}.png"
+ await pg.screenshot(path=str(f))
+ groups.setdefault(t, []).append(f)
+ await b.close()
+ for t, fs in groups.items():
+ for k in range(0, len(fs), 4):
+ sheet = Image.new("RGB", (1600, 960), "black")
+ for j, f in enumerate(fs[k:k + 4]):
+ sheet.paste(Image.open(f).resize((800, 480)), ((j % 2) * 800, (j // 2) * 480))
+ sheet.save(a.out / f"{a.chapter}_sheet_{t}_{k // 4}.png")
+ print("errors:", sorted(set(errs))[:8] or "none", "| shots in", a.out)
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("chapter")
+ ap.add_argument("specs", nargs="*")
+ ap.add_argument("--url", default="http://localhost:8765/")
+ ap.add_argument("--out", type=Path, default=Path("/tmp/animebook-shots"))
+ a = ap.parse_args()
+ a.url = a.url if a.url.endswith("/") else a.url + "/"
+ asyncio.run(main(a))
diff --git a/.claude/skills/animebook/scripts/split_pages.py b/.claude/skills/animebook/scripts/split_pages.py
new file mode 100644
index 0000000..d661ad7
--- /dev/null
+++ b/.claude/skills/animebook/scripts/split_pages.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Render every PDF page to PNG, one folder per section of sections.json.
+
+ uv run --with pymupdf split_pages.py book.pdf --sections sections.json --out book_pages
+ uv run --with pymupdf split_pages.py book.pdf --list # check the map only
+ uv run --with pymupdf split_pages.py book.pdf --only ch05 # one section
+ uv run --with pymupdf split_pages.py book.pdf --text-only # text layer only, no images
+
+Each section folder also gets text.md: the PDF's own text layer, page by page. Read that
+first; open a page image only for diagrams, layout or text the layer gets wrong (it is far
+cheaper than an image). Scanned books have no text layer, so text.md comes out empty.
+
+Files are named page_NNNN.png by PDF page order (from 1), never by printed page numbers.
+The script refuses a map with gaps or overlaps, and refuses to overwrite existing images
+unless --overwrite is given. The pages are a private reference for the author; they are
+never published with the site.
+"""
+import argparse
+import json
+from pathlib import Path
+
+import pymupdf
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("pdf", type=Path)
+ ap.add_argument("--sections", type=Path, default=Path("sections.json"))
+ ap.add_argument("--out", type=Path, default=Path("book_pages"))
+ ap.add_argument("--dpi", type=int, default=150)
+ ap.add_argument("--list", action="store_true", help="print the map and stop")
+ ap.add_argument("--only", nargs="*", help="render only these section folders")
+ ap.add_argument("--overwrite", action="store_true")
+ ap.add_argument("--text-only", action="store_true", help="write text.md files, skip the images")
+ a = ap.parse_args()
+ sections = json.loads(a.sections.read_text(encoding="utf-8"))
+ with pymupdf.open(a.pdf) as doc:
+ nxt, seen = 1, set()
+ for s in sections:
+ f, st, en = s["folder"], s["start"], s["end"]
+ if not f or "/" in f or "\\" in f or f in (".", "..") or f in seen:
+ ap.error(f"bad or repeated folder name: {f!r}")
+ if st != nxt or en < st or en > len(doc):
+ ap.error(f"pages must run on without gaps or overlaps: {f} ({st}-{en}), expected start {nxt}")
+ seen.add(f)
+ nxt = en + 1
+ if nxt != len(doc) + 1:
+ ap.error(f"the map ends at page {nxt - 1}; the PDF has {len(doc)} pages")
+ print(f"{len(doc)} pages, {len(sections)} sections, {a.dpi} dpi")
+ if a.list:
+ for s in sections:
+ print(f'{s["folder"]}: {s["start"]}-{s["end"]} {s["title"]}')
+ return
+ todo = [s for s in sections if not a.only or s["folder"] in a.only]
+ for s in todo:
+ d = a.out / s["folder"]
+ d.mkdir(parents=True, exist_ok=True)
+ text = [f"## page {p}\n\n{doc[p - 1].get_text().strip()}\n" for p in range(s["start"], s["end"] + 1)]
+ (d / "text.md").write_text(f"# {s['title']}\n\n" + "\n".join(text), encoding="utf-8")
+ if a.text_only:
+ continue
+ for p in range(s["start"], s["end"] + 1):
+ target = d / f"page_{p:04d}.png"
+ if target.exists() and not a.overwrite:
+ continue
+ tmp = target.with_suffix(".tmp") # never leave half an image behind
+ tmp.write_bytes(doc[p - 1].get_pixmap(dpi=a.dpi, colorspace=pymupdf.csRGB, alpha=False).tobytes("png"))
+ tmp.replace(target)
+ print(f'{s["folder"]}: {s["start"]}-{s["end"]} done', flush=True)
+ manifest = {"source": a.pdf.name, "page_count": len(doc), "dpi": a.dpi,
+ "page_numbering": "PDF page order from 1, not printed page numbers",
+ "filename_pattern": "page_{pdf_page:04d}.png", "sections": sections}
+ (a.out / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/tts.py b/.claude/skills/animebook/scripts/tts.py
similarity index 94%
rename from tools/tts.py
rename to .claude/skills/animebook/scripts/tts.py
index 4c9501e..9720f19 100644
--- a/tools/tts.py
+++ b/.claude/skills/animebook/scripts/tts.py
@@ -1,7 +1,9 @@
"""Generate narration audio and word-mark timings with Edge TTS.
-Usage (from project root):
- uv run --with edge-tts tools/tts.py content/ch01/narration.en.json site/ch01/audio/en
+Usage (from the project root; SKILL is this skill's folder):
+ uv run --with edge-tts $SKILL/scripts/tts.py content/ch01/narration.en.json site/ch01/audio/en
+
+Needs network access and ffprobe (from ffmpeg) for clip durations.
Narration text may contain [[mark]] tags placed before a word. The output
timings.js records each clip's duration and the time (seconds) at which the
diff --git a/CLAUDE.md b/CLAUDE.md
index 20f7ac6..85a80ad 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -20,9 +20,7 @@ AnimeBook/
├── CLAUDE.md # Agent 工作指南与目录地图
├── plan.md # 详细项目计划
├── README.md # PDF 按章节导出图片的使用说明
-├── split_book.py # PDF 每页导出为 PNG 的脚本
├── sections.json # 分组名称、章节与单元信息、PDF 页码范围
-├── requirements.txt # PDF 导出脚本的 Python 依赖
├── Everything You Need to Ace Pre-Algebra and Algebra I in One Big Fat Notebook (Jason Wang) (z-library.sk, 1lib.sk, z-lib.sk).pdf
│ # 原始参考书,641 页
├── book_pages/ # 原书书页图片;内部制作参考
@@ -59,16 +57,15 @@ AnimeBook/
├── scripts/
│ └── prepare_mascot.swift # 在 macOS 上生成透明 PNG 和 SVG 封装
├── content/chNN/ # 每章英文讲稿 narration.en.json([[mark]] 标记动画触发词)及 tts 缓存
-├── .claude/skills/animebook-chapter/ # 做章节的流程、已定约定、踩过的坑、引擎速查(新章节先读)
+├── .claude/skills/animebook/ # 从一本 PDF 到互动动画书的完整流程(英文):拆书、规划、试点章、逐章制作、审阅测试、目录与发布;
+│ # scripts/(outline、split_pages、tts、shot、check_blank)、assets/(引擎与模板)、references/
├── tools/
│ ├── tts.py # Edge TTS 生成 MP3、词级时间点与逐句字幕
-│ ├── e2e_chNN.py # 各章浏览器端到端检查(Playwright);改引擎后全部重跑
-│ └── check_blank.py # 检测开场留白:旁白已开始、画面仍为空的步骤
+│ └── e2e_chNN.py # 各章浏览器端到端检查(Playwright);改引擎后全部重跑
├── site/ # 可部署的静态站点(只部署此目录)
│ ├── index.html # 书架、书封与章节目录(同一页,hash 切换;章节数据在 UNITS;localStorage 记进度)
│ ├── lib/ # 共用引擎 engine.js / engine.css;书架数据与样式 bookshelf.js / bookshelf.css;目录页单元小图 unit-art.js
│ └── chNN/ # ch01–ch68 每章一个目录:index.html(本章步骤与题目)、audio/en/(MP3 与 timings.js)
-├── .venv/ # 现有 PDF 处理工具的 Python 虚拟环境
├── .git/ # 本地 Git 仓库,尚未配置远程
└── .DS_Store # macOS 自动生成的目录信息
```
@@ -107,19 +104,14 @@ SVG 将 PNG 以 data URL 嵌入,单个文件自包含;仍然是位图,放
## 现有工具
-查看章节分组:
+制作工具都在技能 `.claude/skills/animebook/scripts/` 里(下面用 `$SKILL` 指这个目录)。查看章节分组、按章导出书页与文字层:
```sh
-.venv/bin/python split_book.py --list
+uv run --with pymupdf $SKILL/scripts/split_pages.py *.pdf --list
+uv run --with pymupdf $SKILL/scripts/split_pages.py *.pdf --text-only # 只导出每章 text.md(读书页先读它,省 token)
```
-重新导出书页到新的目录:
-
-```sh
-.venv/bin/python split_book.py --dpi 200 --output book_pages_200dpi
-```
-
-安装和其他导出参数见 `README.md`。已有图片通常可以直接使用,不必重复导出。`.venv/` 服务于现有 PDF 工具,不是已确定的网站开发环境。
+已有图片通常可以直接使用,不必重复导出。本书的网站在 `site/` 根目录(书架也在这里);以后的新书放在 `site/<书名>/`,见技能的 `references/site.md`。改动 `site/lib/engine.*` 中通用的部分时,同步更新技能的 `assets/engine/`。
本地预览(音频需要 HTTP,不能双击打开):
@@ -132,7 +124,7 @@ python3 -m http.server 8765 -d site # 打开 http://localhost:8765/
修改讲稿后重新生成语音(只重做改动过的步骤,需联网):
```sh
-uv run --with edge-tts tools/tts.py content/chNN/narration.en.json site/chNN/audio/en
+uv run --with edge-tts $SKILL/scripts/tts.py content/chNN/narration.en.json site/chNN/audio/en
```
讲稿中的 `[[mark]]` 名称必须与 `index.html` 中该步使用的 `m('mark')` 一致。
diff --git a/README.md b/README.md
index dd8b52b..15ad8a3 100644
--- a/README.md
+++ b/README.md
@@ -1,31 +1,14 @@
-# 按章节导出电子书图片
+# AnimeBook
-运行脚本,将本目录的 PDF 按章节拆成文件夹,每页保存为一张 PNG:
+把一本书(PDF)做成带动画、语音和互动练习的网页书。第一本是 *Pre-Algebra & Algebra*,68 章,网站在 `site/`。
-```sh
-python3 -m venv .venv
-.venv/bin/python -m pip install -r requirements.txt
-.venv/bin/python split_book.py
-```
-
-输出在 `book_pages/`:
-
-- `00_cover/`:封面、版权页、扉页(PDF 第 1–4 页)
-- `01_preface/`:前言(第 5–6 页)
-- `02_contents/`:目录和之后的空白页(第 7–13 页)
-- `ch01/` 到 `ch68/`:各章正文、练习和答案;单元标题页归入该单元第一章
-- `98_index/`:索引(第 632–640 页)
-- `99_back_matter/`:末尾推荐页(第 641 页)
+完整制作流程、脚本、引擎与模板都在技能 `.claude/skills/animebook/`(英文,从 `SKILL.md` 读起)。本书的计划与进度见 `plan.md`,目录地图与约定见 `CLAUDE.md`。
-文件名如 `page_0014.png`,数字是从 1 开始的 **PDF 原始页序**,不是书页上印刷的页码。所有 641 页各导出一次,包含空白页。
-
-`sections.json` 保存章节名称和页码范围,依据本书 PDF 书签生成并核对。调整分组时可编辑此文件;脚本会检查所有页码连续且不遗漏。`book_pages/manifest.json` 记录本次导出的分组和分辨率。
-
-默认 150 DPI;提高到 200 DPI 会增加图片大小和导出时间:
+常用命令(`SKILL=.claude/skills/animebook`):
```sh
-.venv/bin/python split_book.py --list
-.venv/bin/python split_book.py --dpi 200 --output book_pages_200dpi
+uv run --with pymupdf $SKILL/scripts/outline.py book.pdf # 看 PDF 书签,生成 sections.json
+uv run --with pymupdf $SKILL/scripts/split_pages.py book.pdf # 按章导出书页图片和 text.md
+python3 -m http.server 8765 -d site # 本地预览
+uv run --with playwright tools/e2e_ch01.py # 某章端到端测试
```
-
-目录里有多本 PDF 时可以显式传入文件路径。输出目录已有文件时脚本会停止;需要重新生成同名图片可加 `--overwrite`,它会覆盖图片,不会清理额外文件。
diff --git a/plan.md b/plan.md
index c053209..75300a7 100644
--- a/plan.md
+++ b/plan.md
@@ -60,7 +60,7 @@
- `book_pages/ch01/` 至 `book_pages/ch68/`:68 章的书页图片。单元标题页并入该单元的第一章。
- 其他分组:封面、前言、目录、索引、末尾推荐页。
- `sections.json`:章节标题、单元归属和 PDF 页码边界。
-- `split_book.py`、`requirements.txt`:现有 PDF 导出工具与依赖。
+- 拆书工具已并入技能:`.claude/skills/animebook/scripts/outline.py`(由 PDF 书签生成 `sections.json`)与 `split_pages.py`(按章导出书页图片和文字层 `text.md`)。
- `README.md`:上述工具的使用说明。
现有 Python 环境服务于 PDF 处理,不代表已经选定网站技术栈。
@@ -122,7 +122,7 @@
用户明确指出问题出现在开场:旁白已经开始讲解,主画面却还没有内容,属于编排留白。后续动画审查重点检查开场的画面承接,需要时更早呈现主题、相关数学对象、算式或关键文字,再随旁白展开逐步标注、图形变化和计算推演。用户确认正常转场与思考停顿没有问题,保留这些停顿,不要求画面持续运动;适当增加的动画效果仍应服务于数学讲解。
-开场留白已处理(2026-10-03):`tools/check_blank.py` 逐步检测“旁白已开始、画面仍为空”的时长,全书原有 267 步超过 1 秒(中位 2.8 秒,最长 8.6 秒)。引擎在每步清空画面后,若 0.8 秒内没有新内容出现,就把开场一组(首个出现对象之后 1.2 秒内的全部动作)整体前移到 0.4 秒,即上一画面淡出完毕时,后续动作仍按词的时间点;某步不需要时可在步骤上写 `lead: false`。处理后全书在 0.6 秒阈值下检测为零,267 个开场画面逐一截图核对,1–68 章端到端测试全部通过。
+开场留白已处理(2026-10-03):`check_blank.py`(现位于技能 `scripts/`)逐步检测“旁白已开始、画面仍为空”的时长,全书原有 267 步超过 1 秒(中位 2.8 秒,最长 8.6 秒)。引擎在每步清空画面后,若 0.8 秒内没有新内容出现,就把开场一组(首个出现对象之后 1.2 秒内的全部动作)整体前移到 0.4 秒,即上一画面淡出完毕时,后续动作仍按词的时间点;某步不需要时可在步骤上写 `lead: false`。处理后全书在 0.6 秒阈值下检测为零,267 个开场画面逐一截图核对,1–68 章端到端测试全部通过。
### 6.2 制作前先有可检查的分镜
@@ -459,7 +459,7 @@
最终 Skill 开源分享的方向已确认,不以盈利为目标。封装重点是让其他使用者也能制作有教学价值的动画课程;具体许可证和发布方式尚未确定。
-现有 `.claude/skills/animebook-chapter/` 已覆盖单章制作流程,是可复用部分的基础。候选封装范围是从参考教材分析、章节规划、分镜与讲稿,到动画、小测、语音生成、审阅检查和静态站点交付;具体范围尚待确定。
+技能第一版已完成(2026-10-03):`.claude/skills/animebook/`,英文,覆盖从一本 PDF 到完整互动书的全流程:入门询问、拆书(书签生成章节表、按章导出图片与文字层)、全书规划、试点章、逐章循环(读文字层→分镜→讲稿与语音→画面→截图审阅→留白检测→端到端测试→登记)、目录页与单元小图、书架与发布。脚本在 `scripts/`,引擎与模板(章节页、书本封面目录页、单元小图、讲稿、测试、BOOK.md)在 `assets/`,细节在 `references/`(authoring、engine、review、site)。原则:流程固定,设计与动画留给模型发挥;第一版只用代码绘图,不用外部图片;省 token(每章新上下文、先读文字层、截图看拼图、不读引擎源码)。新书放在 `site/<书名>/`,各自带一份引擎;书架 `bookshelf.js` 已支持这类条目。下一步由用户用该技能独立尝试第二本书,检验可复用性。
设计时区分三类资源:Skill 中的制作与检查规则,可随 Skill 提供的引擎、模板和工具,以及每本书各自的目录、内容、音频、进度与章节产物。网站可通过书架统一收录多本书。当前参考书的 PDF、书页图片和已生成课程不作为通用 Skill 的内置教材。教学与视觉经验应区分通用原则和本书约定,避免把固定章节数、知识点或数学约定套到其他教材上。
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index 0c8f80e..0000000
--- a/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-PyMuPDF==1.28.2
diff --git a/site/lib/bookshelf.js b/site/lib/bookshelf.js
index 9f4f2b2..e6f7eef 100644
--- a/site/lib/bookshelf.js
+++ b/site/lib/bookshelf.js
@@ -1,6 +1,8 @@
/* The public bookshelf. Add real, published books here; no build step required.
* This first book shares index.html with its contents, so its counts and saved
* place come from the rendered chapter cards, never a second chapter list.
+ * A book in its own folder (site/<slug>/) gives href '<slug>/' and its counts
+ * (chapters, units) instead of contents.
*/
'use strict';
(() => {
@@ -35,11 +37,11 @@
</svg>`;
const container = document.getElementById('shelf-books');
for (const [index, book] of books.entries()) {
- const contents = document.querySelector(book.contents);
- const chapters = contents.querySelectorAll('.ch');
- const units = contents.querySelectorAll('.unit').length;
- const last = contents.querySelector('.ch.last');
- const finished = contents.querySelectorAll('.ch.done').length;
+ const contents = book.contents && document.querySelector(book.contents);
+ const chapters = contents ? contents.querySelectorAll('.ch') : { length: book.chapters };
+ const units = contents ? contents.querySelectorAll('.unit').length : book.units;
+ const last = contents?.querySelector('.ch.last');
+ const finished = contents ? contents.querySelectorAll('.ch.done').length : 0;
const row = el('article', 'shelf-book');
row.style.setProperty('--book-index', index);
const display = el('div', 'book-display');
@@ -54,7 +56,7 @@
title.append(el('span', '', book.coverTitle[0]), el('i', '', book.coverTitle[1]));
front.append(title);
const picture = el('span', 'book-picture');
- picture.innerHTML = artwork;
+ picture.innerHTML = book.artwork || artwork; // each book may bring its own small SVG cover picture
front.append(picture, el('span', 'book-cover-bottom', 'Watch · Explore · Try'));
cover.append(front);
display.append(cover, el('span', 'shelf-plank'));
@@ -67,7 +69,7 @@
const facts = el('p', 'book-facts', `${chapters.length} chapters · ${units} units · Narrated lessons`);
info.append(facts);
const features = el('ul', 'book-features');
- for (const text of ['Ideas drawn step by step', 'Quick checks inside the animation', 'Practice you can play with']) {
+ for (const text of book.features || ['Ideas drawn step by step', 'Quick checks inside the animation', 'Practice you can play with']) {
const li = el('li', '', text);
li.prepend(el('span', 'feature-tick', '↗'));
features.append(li);
diff --git a/split_book.py b/split_book.py
deleted file mode 100644
index 523b61a..0000000
--- a/split_book.py
+++ /dev/null
@@ -1,93 +0,0 @@
-#!/usr/bin/env python3
-"""按 sections.json 的 PDF 页码分组,将每页渲染为 PNG。"""
-
-import argparse
-import json
-from pathlib import Path
-
-try:
- import pymupdf
-except ImportError:
- raise SystemExit("请先安装依赖:.venv/bin/python -m pip install -r requirements.txt")
-
-
-ROOT = Path(__file__).resolve().parent
-
-
-def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("pdf", nargs="?", type=Path, help="省略时使用脚本目录内唯一的 PDF")
- parser.add_argument("--sections", type=Path, default=ROOT / "sections.json")
- parser.add_argument("--output", type=Path, default=ROOT / "book_pages")
- parser.add_argument("--dpi", type=int, default=150, help="图片分辨率,默认 150")
- parser.add_argument("--list", action="store_true", help="只查看分组,不导出图片")
- parser.add_argument("--overwrite", action="store_true", help="允许重新渲染并覆盖同名图片")
- args = parser.parse_args()
- if args.dpi <= 0:
- parser.error("DPI 必须大于 0")
- if args.pdf is None:
- pdfs = sorted(p for p in ROOT.iterdir() if p.suffix.lower() == ".pdf")
- if len(pdfs) != 1:
- parser.error("请指定 PDF 路径;自动查找需要目录内恰好有一本 PDF")
- args.pdf = pdfs[0]
-
- sections = json.loads(args.sections.read_text(encoding="utf-8"))
- with pymupdf.open(args.pdf) as doc:
- # 页码从 1 开始,以 PDF 文件的实际页序为准。
- next_page = 1
- folders = set()
- for section in sections:
- folder = section["folder"]
- start, end = section["start"], section["end"]
- if not folder or folder in {".", ".."} or "/" in folder or "\\" in folder:
- parser.error(f"无效文件夹名:{folder!r}")
- if folder in folders:
- parser.error(f"重复文件夹名:{folder}")
- if not isinstance(start, int) or not isinstance(end, int):
- parser.error(f"页码必须为整数:{folder}")
- if start != next_page or end < start or end > len(doc):
- parser.error(f"页码不连续、重叠或越界:{folder} ({start}-{end})")
- folders.add(folder)
- next_page = end + 1
- if next_page != len(doc) + 1:
- parser.error("分组必须覆盖整本 PDF 的每一页")
-
- print(f"共 {len(doc)} 页,{len(sections)} 个文件夹,{args.dpi} DPI", flush=True)
- if args.list:
- for s in sections:
- print(f'{s["folder"]}: {s["start"]}-{s["end"]} {s["title"]}')
- return
- if args.output.exists() and any(args.output.iterdir()) and not args.overwrite:
- parser.error("输出目录已有文件;请换 --output 路径,或使用 --overwrite 重新导出")
-
- args.output.mkdir(parents=True, exist_ok=True)
- manifest = {
- "source": args.pdf.resolve().name,
- "page_count": len(doc),
- "dpi": args.dpi,
- "format": "png",
- "page_numbering": "PDF 页序,从 1 开始;不是书页印刷页码",
- "filename_pattern": "page_{pdf_page:04d}.png",
- "sections": sections,
- }
- for s in sections:
- directory = args.output / s["folder"]
- directory.mkdir(parents=True, exist_ok=True)
- for page_number in range(s["start"], s["end"] + 1):
- page = doc[page_number - 1]
- pixmap = page.get_pixmap(dpi=args.dpi, colorspace=pymupdf.csRGB, alpha=False)
- target = directory / f"page_{page_number:04d}.png"
- # 先写临时文件,避免中断时留下半张图片。
- temporary = target.with_suffix(".tmp")
- temporary.write_bytes(pixmap.tobytes("png"))
- temporary.replace(target)
- print(f'{s["folder"]}: {s["start"]}-{s["end"]} 已完成', flush=True)
-
- (args.output / "manifest.json").write_text(
- json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
- )
- print(f"完成:{args.output.resolve()}", flush=True)
-
-
-if __name__ == "__main__":
- main()
diff --git a/tools/check_blank.py b/tools/check_blank.py
deleted file mode 100644
index dc5b6da..0000000
--- a/tools/check_blank.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Find opening blanks: narration has started but the picture is still empty.
-
- python3 -m http.server 8765 -d site &
- uv run --with playwright tools/check_blank.py # every chapter
- uv run --with playwright tools/check_blank.py ch05 ch06 # some chapters
- LIMIT=0.6 uv run --with playwright tools/check_blank.py # stricter
-
-Prints chapter, beat index, beat id, empty from, empty until, seconds, for each lesson beat whose
-picture stays empty longer than LIMIT (default 1 s) near its start. Question beats are skipped.
-No output means no opening blank.
-"""
-import asyncio, sys, json
-from playwright.async_api import async_playwright
-LIMIT = float(__import__("os").environ.get("LIMIT", "1.0"))
-JS = r"""
-(i) => {
- seek(i, false);
- const b = BEATS[i], tm = TIMINGS[b.id];
- const first = (tm.cues[0] || [0])[0];
- // A leaf is visible if its box has size, nothing hides it, and the opacity product up to the scene is > .05.
- const vis = () => {
- let n = 0;
- for (const e of scene.querySelectorAll('text,path,circle,rect,ellipse,line,polygon')) {
- if (e.closest('.qlayer')) continue;
- let o = 1, x = e;
- while (x && x !== scene) { o *= +(x.getAttribute('opacity') ?? 1); if (x.style && x.style.visibility === 'hidden') o = 0; x = x.parentNode; }
- if (o < .05) continue;
- const r = e.getBoundingClientRect();
- if (r.width < 2 && r.height < 2) continue;
- n++;
- }
- return n;
- };
- const out = [];
- for (let t = 0; t <= Math.min(tm.dur, 12); t += .2) { P.t = t; evalTo(t); out.push([+t.toFixed(1), vis()]); }
- return { id: b.id, ask: !!b.ask, first, dur: tm.dur, out };
-}
-"""
-async def main(chs):
- async with async_playwright() as p:
- b = await p.chromium.launch(); pg = await b.new_page(viewport={"width": 1600, "height": 960})
- rows = []
- for ch in chs:
- await pg.goto(f"http://localhost:8765/{ch}/index.html?beat=0&t=0"); await pg.wait_for_timeout(300)
- n = await pg.evaluate("BEATS.length")
- for i in range(n):
- r = await pg.evaluate(JS, i)
- if r["ask"] or r["id"] in ("finish",): continue
- # blank = the longest run of empty frames that starts before 3 s, measured from the first word
- empty = [t for t, c in r["out"] if c == 0]
- if not empty: continue
- start = max(empty[0], r["first"])
- end = next((t for t, c in r["out"] if t > empty[0] and c > 0), r["dur"])
- gap = end - start
- if gap > LIMIT and empty[0] < 3: rows.append((ch, i, r["id"], round(start, 1), round(end, 1), round(gap, 1)))
- for row in rows: print(*row)
- await b.close()
-chs = sys.argv[1:] or [f"ch{n:02d}" for n in range(1, 69)]
-asyncio.run(main(chs))