Skip to content

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

feat: engine-v2.1 and Skill fixes from a three-book test run

yzr2df2e1ddbeaa
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index 334bb68..fa827f4 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -47,7 +47,7 @@ site/<book>/ the static book (only this is delivered)
chNN/index.html, audio/<lang>/ a lesson, its beat MP3s + timings.js
```
-A picture book adds `books/<book>/story.md` (the user's telling, verbatim), `storyboard.md` and `art/` (`sets.js` with the set sketches, generated pictures, `painted.json`, `costs.tsv`); its `site/<book>/lib/` holds the paper kit (`paper.js`, `cast.js`, `shared.js` from `assets/templates/picture-book/`) and `img/` the baked sets, props and puppet pieces; each episode `chNN/` has one script per scene and `audio/<lang>/`, `audio/sfx/`, `audio/bgm/`.
+A picture book adds `books/<book>/story.md` (the user's telling, verbatim), `storyboard.md` and `art/` (`sets.js` with the set sketches, generated pictures, `painted.json`, `costs.tsv`); its `site/<book>/lib/` holds the paper kit (`paper.js`, `cast.js`, `shared.js` from `assets/templates/picture-book/`, which needs engine-v2.1 or later) and `img/` the baked sets, props and puppet pieces; each episode `chNN/` has one script per scene and `audio/<lang>/`, `audio/sfx/`, `audio/bgm/`.
`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access (or Kokoro, local: `uv run --python 3.12 --with kokoro`), github.com for `engine.py` when the repository's `engine/` folder is not at hand, and Playwright browsers (`uv run --with playwright playwright install chromium firefox`; where Playwright's Chromium does not run, set `CHROME` to an installed Chrome, Chromium, Brave or Edge). Preview: `python3 SKILL/scripts/serve.py 8765 site` (no browser caching).
@@ -58,7 +58,7 @@ A picture book adds `books/<book>/story.md` (the user's telling, verbatim), `sto
Start with intake whenever `books/<book>/style.json` does not exist yet; reuse answers and approvals already given.
1. **Intake** ([intake.md](references/intake.md)), a short conversation: find the PDF with the user (a story goes to [stories.md](references/stories.md)), split it, say what the book is, agree on one chapter to try and a tier, start the book folder, settle the look the way that tier needs, agree which model does which step, and write `style.json`.
- - Split: `uv run --with pymupdf SKILL/scripts/outline.py books/<book>/book.pdf`; use `--level N -o books/<book>/sections.json` at chapter depth. For a PDF without usable chapter bookmarks, inspect `split_pages.py … --pages 1-12 --out books/<book>/pages`, then write the map from its contents (schema: `outline.py --help`). Extract chapter text with `split_pages.py … --sections books/<book>/sections.json --out books/<book>/pages --text-only`.
+ - Split: `uv run --with pymupdf SKILL/scripts/outline.py books/<book>/book.pdf`; use `--level N -o books/<book>/sections.json` at chapter depth. A chapter bookmark that points outside its neighbours is moved to the page holding its title or dropped, with a warning: look at those chapters' pages. For a PDF without usable chapter bookmarks, inspect `split_pages.py … --pages 1-12 --out books/<book>/pages`, then write the map from its contents (schema: `outline.py --help`). Extract chapter text with `split_pages.py … --sections books/<book>/sections.json --out books/<book>/pages --text-only`.
- Start the book folder with [site.md](references/site.md#start-a-book-folder) before showing the user any frames; build agreed shared components once into the book's library ([assets.md](references/assets.md)) and list them in `style.json`.
2. **Pilot.** Make the chosen chapter through the chapter loop and deliver it for the user's judgement. Fold their feedback into `style.json` and record the chapter under `approved`.
3. **Remaining chapters and finish**, when the user wants the whole book: write `chapters.md`, produce chapters sequentially (see *Context*), complete cover text, contents and unit sketches using [site.md](references/site.md). Deliver the static book folder, its entry URL for local preview and any unresolved issues.
@@ -84,16 +84,16 @@ All in `SKILL/scripts/`; each prints its usage with `--help` (run it with the `u
| For | Scripts |
|---|---|
-| Every book | `serve.py` preview without caching · `engine.py` sync the engine into books · `tts.py` narration and word times · `lint.py` static checks · `shot.py` beat screenshots · `strip.py` storyboard sheets and motion strips · `check_blank.py` empty openings · `still.py` stretches where nothing moves · `perf.py` Firefox frame times · `export.py` MP4 and `.srt` |
-| Lessons | `outline.py` and `split_pages.py` page map and chapter text · `overlap.py` arrows through text · `sprites.py` image processing steps |
-| Picture books | `mouths.py` mouth shapes · `join.py` one clip per scene · `sfx.py` synthesized effects · `bake_sets.py` set layers · `bake_puppets.py` puppet bitmaps · `paint.py` / `paint_openai.py` image-model pictures · `painted.py` place them in the book |
+| Every book | `serve.py` preview without caching · `engine.py` sync the engine into books · `tts.py` narration and word times · `lint.py` static checks · `shot.py` beat screenshots · `strip.py` storyboard sheets and motion strips · `still.py` stretches where nothing moves · `perf.py` Firefox frame times · `export.py` MP4 and `.srt` |
+| Lessons | `outline.py` and `split_pages.py` page map and chapter text · `check_blank.py` empty openings · `overlap.py` arrows through text · `sprites.py` image processing steps |
+| Picture books | `mouths.py` mouth shapes · `level.py` even loudness · `join.py` one clip per scene · `sfx.py` synthesized effects · `playlog.py` sounds and captions against the picture · `bake_sets.py` set layers · `bake_puppets.py` puppet bitmaps · `paint.py` / `paint_openai.py` image-model pictures · `painted.py` place them in the book |
| Course options | `refs.py` verified citations · `items.py` question bank · `scorm.py` LMS package |
`silence.py`, `ledger.py` and `browsers.py` are helpers the others import.
## Context
-- Keep intake and the pilot in the main conversation. Afterwards, when subagents are available, coordinate each chapter as a team: a fresh worker per step of the chapter loop, each on the model the user chose for that step (`models` in `style.json`), chapters one after another ([team.md](references/team.md)); a picture book splits by scene instead ([team.md](references/team.md#picture-books)). Without subagents, run the same loop in the current agent with file-based state.
+- Talk with the user from the main conversation: intake, and every sheet and choice of the pilot. When subagents are available, chapters are made as a team: a fresh worker per step of the chapter loop, each on the model the user chose for that step (`models` in `style.json`), chapters one after another; a picture book splits by scene instead. The main conversation coordinates the pilot, since the user sees its sheets; later chapters are best coordinated from a fresh session ([team.md](references/team.md)). Without subagents, run the same loop in the current agent with file-based state.
- A worker needs little besides this Skill and `style.json`: the user's words, the look, the approved chapters to watch and read, the element library. A brief adds the chapter, its pages, the step's inputs and outputs and any current user request. Workers reply in a few lines; the coordinator registers the chapter.
- Use the engine API and inspect individual functions when needed; copy assets rather than reading their full source as instructions.
- Keep `style.json` current and short. Chapter status, errata and historical feedback stay in `chapters.md` and `chapters/chNN.md`.
diff --git a/.claude/skills/papermorph/assets/templates/e2e.py b/.claude/skills/papermorph/assets/templates/e2e.py
index ff29b23..befd876 100644
--- a/.claude/skills/papermorph/assets/templates/e2e.py
+++ b/.claude/skills/papermorph/assets/templates/e2e.py
@@ -8,7 +8,8 @@ the answers, practice and finish card. Copy to tools/<book>/e2e_chNN.py and fill
import asyncio, os
from playwright.async_api import async_playwright
URL = os.environ.get("URL", "http://localhost:8765/BOOK/ch01/")
-# Question beat id -> keys for each question in turn: '1'..'9' picks a choice; '=a,b' fills the boxes and checks.
+# Question beat id -> one step per question in turn: '1'..'9' picks a choice; '=a,b' fills the boxes and checks;
+# '#2;1+3' answers a grid (rows split by ';', each row's columns counted from 1, '+' for several, '#2;;1' a row left empty) and checks.
ANSWERS = {"q1": ["=7"], "final1": ["1"]}
# The frame reached by seeking straight to t equals the one reached by stepping through the beat (replays are exact).
@@ -21,11 +22,14 @@ SAME_FRAME = r"""
}
"""
# The open quiz card: prompt width and lines, every control inside the card, card bottom on the 900-high stage.
+# Lines count the prompt's prose: a table, figure or picture in the prompt is taken out of its height.
CARD = r"""
() => {
const st = document.getElementById('stage').getBoundingClientRect(), k = st.width / 1600;
- const c = document.querySelector('.card.quiz'), cr = c.getBoundingClientRect(), pr = c.querySelector('.prompt').getBoundingClientRect();
- const lines = pr.height / (parseFloat(getComputedStyle(c.querySelector('.prompt')).lineHeight) * k);
+ const c = document.querySelector('.card.quiz'), pe = c.querySelector('.prompt'), cr = c.getBoundingClientRect(), pr = pe.getBoundingClientRect();
+ const blocks = [...pe.querySelectorAll('table, figure, img')].filter(e => !e.parentElement.closest('table, figure'));
+ const prose = pr.height - blocks.reduce((s, e) => s + e.getBoundingClientRect().height, 0);
+ const lines = prose / (parseFloat(getComputedStyle(pe).lineHeight) * k);
const ctl = [...c.querySelectorAll('.opt, input.box, .btn:not([hidden])')].map(b => b.getBoundingClientRect());
const inside = b => b.width > 0 && b.left >= cr.left - 1 && b.right <= cr.right + 1 && b.top >= cr.top - 1 && b.bottom <= cr.bottom + 1;
return { promptW: pr.width / k, lines, ok: ctl.length > 0 && ctl.every(inside), bottom: (cr.bottom - st.top) / k };
@@ -71,6 +75,11 @@ async def main():
if s.startswith("="):
for j, v in enumerate(s[1:].split(",")): await pg.locator(".card input.box").nth(j).fill(v)
await key("Enter")
+ elif s.startswith("#"):
+ rows = pg.locator(".card.quiz .grid .row")
+ for r, cols in enumerate(s[1:].split(";")):
+ for c in filter(None, cols.split("+")): await rows.nth(r).locator(".opt").nth(int(c) - 1).click() # '' = a row left empty
+ await key("Enter")
else: await key(s)
assert "Correct" in await pg.inner_text(".card .fb"), (bid, s)
await key("Enter"); await pg.wait_for_timeout(250)
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js
index 61b144c..c41a4aa 100644
--- a/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/cast.js
@@ -1,16 +1,31 @@
/* cast.js — the puppets, in the flat cut-paper style of South Park: a big round head straight on the body, two
touching eyes, a mouth low on the face, mitten hands. Built at the feet (0, 0) facing us. They turn by sliding the
- face to one side (look -1 … 1), as that show does; the paper pieces never deform.
+ face to one side (look -1 … 1), as that show does; the paper pieces never deform, except that a sleeve stretches with
+ reach and a seated shin with the seat's height.
pose(o, f): x, y, s; look (face slide), eyeX/eyeY (pupils, -1 … 1), lids (0 open … 1 shut; .55 is deadpan), shut
(blink), mouth (a Rhubarb shape or an expression below), brow (0 none, <0 angry, >0 worried), headR, bob, squash,
- armL/armR (degrees, + raises outward; 0 hangs at the side), legL/legR (degrees), sit (hide legs), hold (prop key).
+ armL/armR (degrees, + raises outward; 0 hangs at the side), reachL/reachR (arm length, 1 rest: the sleeve stretches,
+ the mitten slides along it), legL/legR (degrees, + swings outward), lean (degrees, the body about the hip, + leans to
+ screen right), headY (+ lowers the head), sit (true: the legs and shadow hidden, for a seat whose front reaches the
+ coat; a number H, up to the shape's legH - 12 (34 on the kid): on a seat H units above the feet, the lap and knees
+ towards us and the shins down to the ground at y), hold/holdL (prop key in the screen-right / screen-left hand).
+ A hand raised above the chin and in from its shoulder, towards the face, is drawn in front of the head (a cup at the
+ lips, a hand on the chin, a reach across to the far side of the head); an arm raised out to the side (a wave, a cheer,
+ a scratch at its own side of the head) stays behind it. armFrontL/armFrontR (true / false) override that.
+ aim(o, 'L' | 'R', [x, y]) → { arm, reach, far, armR, reachR } (or armL, reachL): the values that put that hand on a
+ point in the parent's coordinates for pose o; spread it into the pose (pose({ ...o, ...kid.aim(o, 'R', pt) })) or tween
+ arm and reach from rest. far > 1.25 means the point is out of reach by that factor: lean, step closer or move the point.
+ point(o, name) → [x, y]: where 'mouth', 'chin', 'capL'/'capR' (the sides of the head at the temples) or a head-local
+ [x, y] of the shape is for pose o, in the parent's coordinates. A held thing hangs from the mitten's centre, so aim
+ at the point minus its own offset (a cup whose rim is 40 units above the hand: [mouth x, mouth y + 40·s]).
To add a character: write another entry in SHAPES (copy `kid` and change the numbers: sx/sy the shoulder, hipX the
hip, body and head outlines, eyes [x, y, rx, ry], mouth [x, y], slide how far the face moves, hair [colour, path],
- optional glasses/hat/extra/legH/cheeks/chin), then a one-line builder like kidPuppet below. A grown-up is a taller
- body (legH 96, sy and the head moved up). Colours (coat, stripe, pants, skin) are options of the builder, so one shape
+ optional glasses/hat/extra/legH/armH/browUp/cheeks/chin), then a one-line builder like kidPuppet below. A grown-up is a taller
+ body (legH 96, sy and the head moved up) with longer arms (armH 100 reaches a table). Colours (coat, stripe, pants, skin, cuff) are options of the builder, so one shape
serves many characters. An animal or anything not built like a kid gets its own builder with the same contract
- (build in g, bakeAll(g), return { g, pose(o, f) }) — see spKid for the pattern. */
+ (build in g, bakeAll(g), return { g, aim, point, pose(o, f) }) — see spKid for the pattern; aimArm and rotPt below do
+ the geometry for any shoulder and head. */
'use strict';
const SP_INK = '#1d1a1a';
// How far a shut eye's lid comes down: .9 leaves the lid line showing (a full lid, 1, leaves two blank skin ovals).
@@ -48,25 +63,48 @@ const SHAPES = {
};
let spClip = 0;
-const REST_SP = { x: 0, y: 0, s: 1, look: 0, eyeX: 0, eyeY: 0, lids: 0, shut: false, mouth: 'X', brow: 0, headR: 0, bob: 0, squash: 0,
- armL: 0, armR: 0, legL: 0, legR: 0, sit: false, hold: null, holdL: null };
+// A point rotated by deg about (cx, cy), SVG-style (y down, + clockwise).
+const rotPt = ([x, y], deg, cx = 0, cy = 0) => { const a = deg * Math.PI / 180, dx = x - cx, dy = y - cy; return [cx + dx * Math.cos(a) - dy * Math.sin(a), cy + dx * Math.sin(a) + dy * Math.cos(a)]; };
+// The arm angle that points a hand at [px, py] (parent coordinates) for pose o. pin is the shoulder in the puppet's units,
+// pivot the lean's centre, drop the body's shift (seated), rest the arm's rest angle, len the hand's distance from the shoulder.
+function aimArm(o, side, [px, py], { pin, pivot, drop = 0, rest, len }) {
+ const s = o.s ?? 1, [qx, qy] = rotPt(pin, o.lean || 0, ...pivot);
+ const sx = (o.x || 0) + s * qx, sy = (o.y || 0) + s * (qy + (o.bob || 0) + drop);
+ const th = Math.atan2(-(px - sx), py - sy) * 180 / Math.PI - (o.lean || 0);
+ const far = Math.hypot(px - sx, py - sy) / (len * s), arm = side === 'L' ? th - rest : -rest - th, reach = Math.min(1.25, Math.max(.6, far));
+ return { arm, reach, far, shoulder: [sx, sy], ['arm' + side]: arm, ['reach' + side]: reach };
+}
+const REST_SP = { x: 0, y: 0, s: 1, look: 0, eyeX: 0, eyeY: 0, lids: 0, shut: false, mouth: 'X', brow: 0, headR: 0, headY: 0, lean: 0, bob: 0, squash: 0,
+ armL: 0, armR: 0, reachL: 1, reachR: 1, armFrontL: undefined, armFrontR: undefined, legL: 0, legR: 0, sit: false, hold: null, holdL: null };
// holds: { key: svg } drawn in the hand of the screen-right arm (hold) or screen-left arm (holdL), at the mitten centre
-function spKid(parent, shape, { skin = '#f7d9bb', coat = UNIFORM.coat, stripe = UNIFORM.stripe, pants = UNIFORM.pants, holds = {} } = {}) {
+function spKid(parent, shape, { skin = '#f7d9bb', coat = UNIFORM.coat, stripe = UNIFORM.stripe, pants = UNIFORM.pants, cuff = null, holds = {} } = {}) {
const S = typeof shape === 'string' ? SHAPES[shape] : shape, g = mk('g', {}, parent), id = 'spc' + (++spClip);
- const legH = S.legH || 46, [hx, hy, hrx, hry] = S.head, [ex, ey, erx, ery] = S.eyes, [mx, my] = S.mouth;
- const arm = side => `<g data-p="arm${side}"><g filter="url(#paper)"><rect x="-14" y="-6" width="28" height="64" rx="13" fill="${coat}"/>
- <path d="M${side === 'R' ? 7 : -7},-2 v56" stroke="${stripe}" stroke-width="5"/>
- <circle cy="72" r="18" fill="#f2efe6"/><ellipse cx="${side === 'R' ? -14 : 14}" cy="62" rx="7" ry="10" fill="#f2efe6"/></g>
- ${Object.entries(holds).map(([k, s]) => `<g data-p="hold${side}_${k}" transform="translate(0,72)">${s}</g>`).join('')}</g>`;
+ const legH = S.legH || 46, armH = S.armH || 64, hand = armH + 8, [hx, hy, hrx, hry] = S.head, [ex, ey, erx, ery] = S.eyes, [mx, my] = S.mouth;
+ const browY = ey - ery - (S.browUp ?? 12), R = side => side === 'R' ? 1 : -1;
+ // a sleeve, then a knitted cuff and a mitten with its thumb towards the body; the mitten slides along the sleeve (reach)
+ const arm = side => `<g data-p="arm${side}"><g data-p="sleeve${side}"><g filter="url(#paper)"><rect x="-14" y="-6" width="28" height="${armH}" rx="13" fill="${coat}"/>
+ <path d="M${7 * R(side)},-2 v${armH - 8}" stroke="${stripe}" stroke-width="5"/></g></g>
+ <g data-p="mitt${side}"><g filter="url(#paper)"><rect x="-16" y="${hand - 24}" width="32" height="10" rx="4" fill="${cuff || coat}"/>
+ <path d="M-10,${hand - 23} v8 M-3,${hand - 23} v8 M4,${hand - 23} v8 M11,${hand - 23} v8" stroke="#00000030" stroke-width="2"/>
+ <rect x="-17" y="${hand - 16}" width="34" height="34" rx="15" fill="#f2efe6"/><ellipse cx="${-17 * R(side)}" cy="${hand - 6}" rx="7" ry="10" fill="#f2efe6"/>
+ <path d="M${-9 * R(side)},${hand + 4} q${9 * R(side)},6 ${18 * R(side)},0" stroke="#cfc9bb" stroke-width="2" fill="none"/></g></g>
+ ${Object.entries(holds).map(([k, s]) => `<g data-p="hold${side}_${k}" transform="translate(0,${hand})">${s}</g>`).join('')}</g>`;
const leg = side => `<g data-p="leg${side}"><g filter="url(#paper)"><rect x="${-S.legW / 2}" y="0" width="${S.legW}" height="${legH}" rx="6" fill="${pants}"/>
- <ellipse cx="${side === 'R' ? 6 : -6}" cy="${legH - 2}" rx="${S.shoe}" ry="11" fill="#1f1d1d"/></g></g>`;
+ <ellipse cx="${6 * R(side)}" cy="${legH - 2}" rx="${S.shoe}" ry="11" fill="#1f1d1d"/></g></g>`;
+ // seated on a seat of a given height: a shin that stretches down from the knee and a shoe of its own, so the shoe never stretches
+ const shin = side => `<g data-p="leg${side}S"><g data-p="shin${side}"><g filter="url(#paper)"><rect x="${-S.legW / 2}" y="0" width="${S.legW}" height="50" rx="6" fill="${pants}"/></g></g>
+ <g data-p="shoe${side}"><g filter="url(#paper)"><ellipse cx="${6 * R(side)}" cy="0" rx="${S.shoe}" ry="11" fill="#1f1d1d"/></g></g></g>`;
+ // the thighs seen end on: a lap and two knees towards us, which is what makes a figure from the front read as sitting
+ const lap = `<g data-p="lap"><g filter="url(#paper)"><rect x="${-S.hipX * 1.5 - S.legW / 2 - 10}" y="${-legH - 2}" width="${3 * S.hipX + S.legW + 20}" height="26" rx="13" fill="${pants}"/>
+ ${[-1, 1].map(k => `<ellipse cx="${k * S.hipX * 1.5}" cy="${-legH + 20}" rx="${S.legW * .8}" ry="19" fill="${pants}"/><ellipse cx="${k * S.hipX * 1.5 - 3}" cy="${-legH + 13}" rx="${S.legW * .42}" ry="7" fill="#ffffff" opacity=".13"/>
+ <path d="M${k * S.hipX * 1.5 - S.legW * .7},${-legH + 30} q${S.legW * .7},10 ${S.legW * 1.4},0" stroke="#00000033" stroke-width="3" fill="none"/>`).join('')}</g></g>`;
const eye = sx => `<ellipse cx="${sx * ex}" cy="${ey}" rx="${erx}" ry="${ery}"`;
// a soft shadow on the ground, a little to the right: the painted sets are lit from the left
- g.innerHTML = `<ellipse data-p="shadow" cx="${S.sx * .18}" cy="-2" rx="${S.sx + 34}" ry="16" fill="url(#spShadow)"/><g data-p="all"><g data-p="legs">${leg('L')}${leg('R')}</g>
+ g.innerHTML = `<ellipse data-p="shadow" cx="${S.sx * .18}" cy="-2" rx="${S.sx + 34}" ry="16" fill="url(#spShadow)"/><g data-p="all"><g data-p="legs">${leg('L')}${leg('R')}</g><g data-p="legsS">${shin('L')}${shin('R')}</g>
<g data-p="body"><g filter="url(#paper)"><path d="${S.body}" fill="${coat}"/>
<path d="M-24,${S.sy - 22} L0,${S.sy + 8} L24,${S.sy - 22}" fill="none" stroke="${stripe}" stroke-width="7" stroke-linejoin="round"/>
${S.extra || `<path d="M0,${S.sy + 8} V-40" stroke="#26478f" stroke-width="3"/>`}</g></g>
- ${arm('L')}${arm('R')}
+ ${lap}${arm('L')}${arm('R')}
<g data-p="head"><g filter="url(#paper)"><ellipse cx="${hx}" cy="${hy}" rx="${hrx}" ry="${hry}" fill="${skin}"/>
${S.chin ? `<path d="${S.chin}" fill="none" stroke="#d9a888" stroke-width="3" stroke-linecap="round"/>` : ''}</g>
<clipPath id="${id}"><ellipse cx="${hx}" cy="${hy}" rx="${hrx}" ry="${hry}"/></clipPath>
@@ -81,35 +119,57 @@ function spKid(parent, shape, { skin = '#f7d9bb', coat = UNIFORM.coat, stripe =
${eye(-1)} fill="none" stroke="${SP_INK}" stroke-width="2"/>${eye(1)} fill="none" stroke="${SP_INK}" stroke-width="2"/>
${S.glasses ? `<g fill="none" stroke="${SP_INK}" stroke-width="4.5"><circle cx="${-ex}" cy="${ey}" r="${S.glasses}"/><circle cx="${ex}" cy="${ey}" r="${S.glasses}"/>
<path d="M${-ex + S.glasses},${ey - 4} Q0,${ey - 10} ${ex - S.glasses},${ey - 4}"/></g>` : ''}
- <path data-p="browL" d="M${-ex - 16},${ey - ery - 12} L${-ex + 14},${ey - ery - 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
- <path data-p="browR" d="M${ex + 16},${ey - ery - 12} L${ex - 14},${ey - ery - 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
+ <path data-p="browL" d="M${-ex - 16},${browY} L${-ex + 14},${browY + 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
+ <path data-p="browR" d="M${ex + 16},${browY} L${ex - 14},${browY + 6}" stroke="${SP_INK}" stroke-width="4" stroke-linecap="round"/>
<use class="mouth" href="#spX" transform="translate(${mx},${my})"/></g></g>
<g data-p="hair"><g filter="url(#paper)"><path d="${S.hair[1]}" fill="${S.hair[0]}"/>${S.hat || ''}</g></g></g></g>`;
bakeAll(g);
const P = pieces(g), holdKeys = Object.keys(holds);
const legY = -(legH + 6), ery2 = ery * 2;
- return { g, S, pose(o, f) {
+ // sit: H puts the hip just over a seat H units up (the body comes down by drop; a seat above legH - 12 counts as that
+ // high, so a seated figure is never taller than it stands); sit: true leaves the body where it stands
+ const seatH = o => typeof o.sit === 'number' && o.sit > 0 ? Math.min(o.sit, legH - 12) : 0;
+ const drop = o => seatH(o) && legH - seatH(o) - 12;
+ const aim = (o, side, pt) => { o = { ...REST_SP, ...o };
+ return aimArm(o, side, pt, { pin: [S.sx * R(side), S.sy], pivot: [0, -legH], drop: drop(o), rest: 24, len: hand }); };
+ const LOCAL = { mouth: [[mx, my], 1], chin: [[hx, hy + hry], 0], capL: [[hx - hrx + 6, hy - hry * .45], 0], capR: [[hx + hrx - 6, hy - hry * .45], 0] };
+ const point = (o, name) => { o = { ...REST_SP, ...o };
+ let [pt, feat] = Array.isArray(name) ? [name, 0] : LOCAL[name];
+ pt = rotPt([pt[0] + feat * o.look * S.slide, pt[1]], o.headR, 0, S.neck);
+ pt = rotPt([pt[0], pt[1] + o.headY], o.lean, 0, -legH);
+ return [o.x + o.s * pt[0], o.y + o.s * (pt[1] + o.bob + drop(o))]; };
+ return { g, S, aim, point, pose(o, f) {
o = { ...REST_SP, ...o };
const j = k => .35 * jit(f >> 1, k); // the animator's hand: small, and held for two frames
tf(g, `translate(${(o.x + j(1) * .8).toFixed(1)},${(o.y + j(2) * .6).toFixed(1)}) scale(${o.s})`);
// squash > 0 flattens the figure on its feet (a landing, a sigh)
- tf(P.all, `translate(0,${o.bob.toFixed(1)}) scale(${(1 + .5 * o.squash).toFixed(3)},${(1 - o.squash).toFixed(3)}) rotate(${(j(3) * .4).toFixed(2)})`);
- vis(P.legs, !o.sit); vis(P.shadow, !o.sit);
- tf(P.legL, `translate(${-S.hipX},${legY}) rotate(${(o.legL + j(4) * .5).toFixed(2)})`);
- tf(P.legR, `translate(${S.hipX},${legY}) rotate(${(-o.legR + j(5) * .5).toFixed(2)})`);
+ const dy = drop(o), seated = seatH(o) > 0, Ls = seatH(o) + 12;
+ tf(P.all, `translate(0,${(o.bob + dy).toFixed(1)}) scale(${(1 + .5 * o.squash).toFixed(3)},${(1 - o.squash).toFixed(3)}) rotate(${o.lean.toFixed(2)},0,${-legH}) rotate(${(j(3) * .4).toFixed(2)})`);
+ vis(P.legs, !o.sit); vis(P.legsS, seated); vis(P.lap, seated); vis(P.shadow, !o.sit || seated);
+ if (seated) for (const k of 'LR') { tf(P['shin' + k], `scale(1,${((Ls - 4) / 50).toFixed(3)})`); tf(P['shoe' + k], `translate(0,${Ls - 2})`); }
+ for (const [L, Rt, k] of [[P.legL, P.legR, 1], [P.legLS, P.legRS, 1.5]]) { // the legs hang plumb whatever the lean; seated, from the knees, apart
+ tf(L, `translate(${-S.hipX * k},${legY}) rotate(${(o.legL - o.lean + j(4) * .5).toFixed(2)})`);
+ tf(Rt, `translate(${S.hipX * k},${legY}) rotate(${(-o.legR - o.lean + j(5) * .5).toFixed(2)})`); }
tf(P.armL, `translate(${-S.sx},${S.sy}) rotate(${(24 + o.armL + j(6) * .6).toFixed(2)})`);
tf(P.armR, `translate(${S.sx},${S.sy}) rotate(${(-24 - o.armR + j(7) * .6).toFixed(2)})`);
+ // a hand above the chin and in from its shoulder by more than half a mitten comes in front of the head; both arms
+ // are placed in one fixed order (L under R) from the pose alone, so a seek draws what playback draws
+ const front = (a, r) => (a *= Math.PI / 180, S.sy + hand * r * Math.cos(a) < hy + hry + 24 + o.headY && hand * r * Math.sin(a) < -17);
+ const fL = o.armFrontL ?? front(24 + o.armL, o.reachL), fR = o.armFrontR ?? front(24 + o.armR, o.reachR);
+ if (P.all._arms !== `${fL} ${fR}`) { P.all._arms = `${fL} ${fR}`;
+ for (const [a, up] of [[P.armL, fL], [P.armR, fR]]) up ? P.all.appendChild(a) : P.all.insertBefore(a, P.head); }
+ for (const sd of 'LR') { const r = o['reach' + sd]; tf(P['sleeve' + sd], `scale(1,${r.toFixed(3)})`); tf(P['mitt' + sd], `translate(0,${(hand * (r - 1)).toFixed(1)})`); }
for (const k of holdKeys) { vis(P[`holdR_${k}`], o.hold === k); vis(P[`holdL_${k}`], o.holdL === k);
// a held thing stays upright whatever the arm does
- tf(P[`holdR_${k}`], `translate(0,72) rotate(${(24 + o.armR).toFixed(2)})`); tf(P[`holdL_${k}`], `translate(0,72) rotate(${(-24 - o.armL).toFixed(2)})`); }
- tf(P.head, `rotate(${(o.headR + j(8) * .6).toFixed(2)},0,${S.neck})`);
+ tf(P[`holdR_${k}`], `translate(0,${(hand * o.reachR).toFixed(1)}) rotate(${(24 + o.armR).toFixed(2)})`); tf(P[`holdL_${k}`], `translate(0,${(hand * o.reachL).toFixed(1)}) rotate(${(-24 - o.armL).toFixed(2)})`); }
+ tf(P.head, `translate(0,${o.headY.toFixed(1)}) rotate(${(o.headR + j(8) * .6).toFixed(2)},0,${S.neck})`);
const lx = o.look * S.slide;
tf(P.feat, `translate(${lx.toFixed(1)},0)`); tf(P.hair, `translate(${(lx * .25).toFixed(1)},0)`);
tf(P.pupils, `translate(${(o.eyeX * erx * .5).toFixed(1)},${(o.eyeY * ery * .45).toFixed(1)})`);
tf(P.lids, `translate(0,${((o.shut ? SP_SHUT : o.lids) * ery2).toFixed(1)})`);
const b = o.brow;
vis(P.browL, b !== 0); vis(P.browR, b !== 0);
- tf(P.browL, `rotate(${(-14 * b).toFixed(1)},${-ex},${ey - ery - 9})`); tf(P.browR, `rotate(${(14 * b).toFixed(1)},${ex},${ey - ery - 9})`);
+ tf(P.browL, `rotate(${(-14 * b).toFixed(1)},${-ex},${browY + 3})`); tf(P.browR, `rotate(${(14 * b).toFixed(1)},${ex},${browY + 3})`);
const m = g.querySelector('.mouth'), href = '#sp' + (o.mouth || 'X'); if (m._m !== href) m.setAttribute('href', m._m = href);
} };
}
@@ -118,3 +178,16 @@ const kidPuppet = (p, o) => spKid(p, 'kid', o); // kidPuppet(parent, { coat, s
// A walk in the show's manner: the figure bobs on twos and the stubby legs scissor. (For feet that never slide on the
// ground, use walk() in paper.js, which also tells how far the hip has travelled.)
function spWalk(q) { const k = Math.floor(q * FPS / 2) % 2 ? 1 : -1; return { legL: 16 * k, legR: -16 * k, bob: k > 0 ? -6 : 0, armL: 8 * k, armR: -8 * k, k }; }
+// A side step for a figure that faces us while it crosses the frame (step, close, step, close): one foot stays planted
+// while the hip rides over it and the other opens out or closes in, so both legs lean outward by the same angle and the
+// ankles never cross. (walk() in paper.js is for a profile figure: its near/far legs on a front figure cross every
+// other step.) tau seconds into the walk, `period` s per step; L the hip pin to the sole (the shape's legH + 6), A the widest angle in
+// degrees. d is how far the hip has travelled, always >= 0: x = x0 + d * s going right, x0 - d * s going left; give
+// bob: drop. Sample tau on twos (Math.floor(q * 6) / 6) like everything else and keep the period a whole number of
+// 1/3 s, so a drawing lands on the widest stance between the step and the close and only one foot moves at a time.
+function spStep(tau, { L = 52, A = 20, period = 2 / 3 } = {}) {
+ tau = Math.max(0, tau);
+ const n = Math.floor(tau / period), u = tau / period - n, D = 2 * L * Math.sin(A * Math.PI / 180);
+ const a = Math.asin(D * Math.min(u, 1 - u) / L) * 180 / Math.PI;
+ return { legL: a, legR: a, d: D * (n + u), drop: L * (1 - Math.cos(a * Math.PI / 180)), u };
+}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js
index 84a6bf7..9f86244 100644
--- a/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/paper.js
@@ -41,7 +41,8 @@ const ease = x => x <= 0 ? 0 : x >= 1 ? 1 : x * x * (3 - 2 * x);
const span = (t, a, b) => ease((t - a) / (b - a));
// draw(q, f) runs once per 12 fps frame with q the frame's time; a pure function of time, like every beat clock.
-function stopClock(D, draw) { let last = null; clockRun(t => { const f = Math.floor(t * FPS + 1e-6); if (f === last) return; last = f; draw(f / FPS, f); }, D); }
+// It runs to the beat's end, through the engine's hold after D (HOLD s), so a scene poses sensibly for q up to D + HOLD.
+function stopClock(D, draw) { let last = null; clockRun(t => { const f = Math.floor(t * FPS + 1e-6); if (f === last) return; last = f; draw(f / FPS, f); }, D, { tail: true }); }
/* ---------- camera over a baked set ----------
A view {x, y, z} is the world point at the frame's centre and the zoom. Moves: to(view, t0, dur) eases each given
@@ -219,9 +220,14 @@ function trunkWipe(p, t0, dur, mode = 'in') {
const [a, b] = mode === 'in' ? [1650, -200] : [-200, -2150];
return q => { const u = Math.min(1, Math.max(0, (q - t0) / dur)); vis(g, mode === 'in' ? u > 0 : u < 1); tf(g, `translate(${(a + (b - a) * ease(u)).toFixed(0)},0)`); };
}
-// The title card at the end: a paper label that drops in on its pin. Give the words in the book's language.
-function endCard(p, t0, words = 'The End') {
- const g = prop(p, `<g filter="url(#paper)"><rect x="560" y="330" width="480" height="240" rx="14" fill="#f3e9d2"/><rect x="580" y="350" width="440" height="200" rx="8" fill="none" stroke="#c8322f" stroke-width="5"/></g>
- <text x="800" y="478" text-anchor="middle" font-family="Georgia, serif" font-size="78" font-style="italic" fill="#5a2a1e">${words}</text>${pinAt(800, 342)}`);
+// The title card at the end: a paper label that drops in on its pin, as wide as its words. Give the words in the book's
+// language; { x, y } is the card's centre (default the frame's centre), size the letters' height in px (a title too long
+// for the frame gets smaller letters). Put it where it covers nothing the last shot needs (a score, a face).
+function endCard(p, t0, words = 'The End', { x = 800, y = 450, size = 78 } = {}) {
+ const c = document.createElement('canvas').getContext('2d'), wide = s => (c.font = `italic ${s}px Georgia, serif`, c.measureText(words).width + 2.2 * s);
+ if (wide(size) > 1500) size = Math.floor(size * 1500 / wide(size));
+ const w = Math.max(480, Math.ceil(wide(size))), h = Math.round(size * 3.08), L = Math.round(x - w / 2), T = Math.round(y - h / 2);
+ const g = prop(p, `<g filter="url(#paper)"><rect x="${L}" y="${T}" width="${w}" height="${h}" rx="14" fill="#f3e9d2"/><rect x="${L + 20}" y="${T + 20}" width="${w - 40}" height="${h - 40}" rx="8" fill="none" stroke="#c8322f" stroke-width="5"/></g>
+ <text x="${x}" y="${Math.round(y + size * .36)}" text-anchor="middle" font-family="Georgia, serif" font-size="${size}" font-style="italic" fill="#5a2a1e">${words}</text>${pinAt(x, T + 12)}`);
return q => { const u = (q - t0) * FPS; vis(g, u >= 0); const d = [-60, -20, 8, -3, 0][Math.min(4, Math.max(0, Math.floor(u / 2)))]; tf(g, `translate(0,${d})`); };
}
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js b/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js
index ea7675a..f514505 100644
--- a/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js
+++ b/.claude/skills/papermorph/assets/templates/picture-book/lib/shared.js
@@ -23,7 +23,12 @@ const artSVG = (name, x, y, w, h) => `<image href="../img/props/${name}.webp" x=
in normal playback (seeking past it does not fire it). Pausing holds them; a seek stops them. They play at half volume under the voices. */
const SFX = [], sfxOn = [];
const SFX_BED = {}; // file name -> length in s, for long ambience called once (a seek into the middle starts it part-way)
-const sfx = (beat, at, name, vol = 1, bed = SFX_BED[name] || 0) => SFX.push({ beat, at, name, vol, bed });
+// A scene function runs again at every seek, replay and Home: the same effect (beat, time, name) is listed once.
+const sfx = (beat, at, name, vol = 1, bed = SFX_BED[name] || 0) => {
+ const e = SFX.find(x => x.beat === beat && x.at === at && x.name === name);
+ if (e) Object.assign(e, { vol, bed }); else SFX.push({ beat, at, name, vol, bed });
+};
+const sfxVolume = () => Math.min(1, Math.max(0, +(document.getElementById('volume')?.value ?? 1)));
let sfxLast = { i: -1, t: 0 };
function sfxTick() {
const id = BEATS[P.i]?.id, on = P.started && P.playing && !P.waiting && !P.done;
@@ -37,12 +42,15 @@ function sfxTick() {
if (on)
for (const e of SFX) if (e.beat === id && (e.at > from && e.at <= P.t || seeked && e.bed && e.at < P.t && P.t < e.at + e.bed)) {
const a = new Audio(`audio/sfx/${e.name}.mp3`);
- a.volume = .5 * e.vol * +(document.getElementById('volume')?.value ?? 1); // effects sit under the voices
+ a._vol = Math.min(1, Math.max(0, .5 * e.vol)); // effects sit under the voices (vol 2 is full volume); the slider is applied every tick below
+ a.volume = a._vol * sfxVolume();
a.playbackRate = P.rate || 1;
a.play().catch(() => {}); sfxOn.push(a); a.onended = () => sfxOn.splice(sfxOn.indexOf(a), 1);
if (e.at <= from || e.at > P.t) a.addEventListener('loadedmetadata', () => { a.currentTime = P.t - e.at; }, { once: true }); // a long bed joined mid-way
}
- for (const a of sfxOn) { a.playbackRate = P.rate || 1; if (on === a.paused && !a.ended) on ? a.play().catch(() => {}) : a.pause(); } // a pause holds them, play resumes
+ const v = sfxVolume();
+ for (const a of sfxOn) { a.playbackRate = P.rate || 1; if (a.volume !== a._vol * v) a.volume = a._vol * v; // the slider reaches effects and beds already playing
+ if (on === a.paused && !a.ended) on ? a.play().catch(() => {}) : a.pause(); } // a pause holds them, play resumes
// the music follows the playback speed too (BGM is the chapter's own list, when it has one)
if (typeof BGM !== 'undefined') for (const m of BGM) if (m.a.playbackRate !== (P.rate || 1)) m.a.playbackRate = P.rate || 1;
sfxLast = { i: P.i, t: on ? P.t : from, pend: !on && (!same || !!sfxLast.pend) };
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/scene1.js b/.claude/skills/papermorph/assets/templates/picture-book/scene1.js
index 985d0e0..16a9af6 100644
--- a/.claude/skills/papermorph/assets/templates/picture-book/scene1.js
+++ b/.claude/skills/papermorph/assets/templates/picture-book/scene1.js
@@ -13,13 +13,15 @@ function scene1(p, D) {
const dad = kidPuppet(cam.stage, { coat: '#3e7fc4', stripe: '#f4f1ea' });
sfx('scene1', .3, 'knock'); // audio/sfx/knock.mp3 (SKILL/scripts/sfx.py)
const enter = clipAt('scene1', PRE1, 's02'); // when the kid's first line starts
+ // the kid side-steps in from the left with planted feet (spStep, cast.js): whole steps (2/3 s each) that end at x 580
+ // just before the line; x comes from the distance the steps cover, so the feet never slide
+ const STEP = 2 / 3, steps = Math.max(0, Math.floor((enter - .2) / STEP)), far = spStep(steps * STEP).d;
stopClock(D, (q, f) => {
cam.apply(q, f);
- const walkIn = span(q, .1, enter - .2); // the kid walks in from the left, then stands
- const w = spWalk(q), moving = walkIn > 0 && walkIn < 1;
- kid.pose({ x: -200 + 780 * walkIn, y: 800, s: .95, look: .6, mouth: lips(q, 'scene1', PRE1, 's02', 's03'),
- ...(moving ? { legL: w.legL, legR: w.legR, bob: w.bob } : {}), shut: blinking(q, [2.4, 6.1]) }, f);
+ const w = spStep(Math.min(Math.floor(q * 6) / 6, steps * STEP)); // on twos, like everything else
+ kid.pose({ x: 580 - .95 * (far - w.d), y: 800, s: .95, look: .6, mouth: lips(q, 'scene1', PRE1, 's02', 's03'),
+ legL: w.legL, legR: w.legR, bob: w.drop, shut: blinking(q, [2.4, 6.1]) }, f);
dad.pose({ x: 1250, y: 800, s: 1, look: -.6, mouth: lips(q, 'scene1', PRE1, 's02b'), brow: q > enter ? -.3 : 0,
shut: blinking(q, [3.3]) }, f);
});
diff --git a/.claude/skills/papermorph/assets/templates/picture-book/series.html b/.claude/skills/papermorph/assets/templates/picture-book/series.html
index 4ad45d7..f36b432 100644
--- a/.claude/skills/papermorph/assets/templates/picture-book/series.html
+++ b/.claude/skills/papermorph/assets/templates/picture-book/series.html
@@ -55,7 +55,7 @@ try { done = JSON.parse(localStorage.getItem(key) || '{}').done || []; } catch {
const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
document.getElementById('episodes').innerHTML = EPISODES.map((e, i) => `<li${done.includes(+e.ch.slice(2)) ? ' class="watched"' : ''}>
<a href="${e.ch}/"><img src="${esc(e.still)}" alt="${esc(e.alt)}" loading="lazy">
- <small>Episode ${i + 1} · ${e.minutes} minutes</small><b>${esc(e.title)}</b><span>${esc(e.line)}</span></a></li>`).join('');
+ <small>Episode ${i + 1} · ${e.minutes} minute${e.minutes == 1 ? "" : "s"}</small><b>${esc(e.title)}</b><span>${esc(e.line)}</span></a></li>`).join('');
</script>
</body>
</html>
diff --git a/.claude/skills/papermorph/assets/templates/style.json b/.claude/skills/papermorph/assets/templates/style.json
index df72a84..2dbd145 100644
--- a/.claude/skills/papermorph/assets/templates/style.json
+++ b/.claude/skills/papermorph/assets/templates/style.json
@@ -14,7 +14,7 @@
},
"voice": { "engine": "edge", "voice": "en-US-AndrewMultilingualNeural", "rate": "-4%" },
"pacing": { "minutes": [6, 10], "checks": "one or two quick checks inside the lesson, practice at the end" },
- "engine": { "source": "DozenTwelve/Papermorph", "ref": "engine-v2" },
+ "engine": { "source": "DozenTwelve/Papermorph", "ref": "engine-v2.1" },
"models": { "extract": "claude-haiku-5-5", "narration": "claude-sonnet-5-5", "picture": "claude-opus-5-5", "checks": "claude-haiku-5-5", "review": "claude-sonnet-5-5", "rework": "claude-opus-5-5", "register": "claude-haiku-5-5" },
"scenes": {
"art": "pixel scenes on a dark board, characters about a third of the stage tall",
diff --git a/.claude/skills/papermorph/references/authoring.md b/.claude/skills/papermorph/references/authoring.md
index fd7bffb..9dbaf82 100644
--- a/.claude/skills/papermorph/references/authoring.md
+++ b/.claude/skills/papermorph/references/authoring.md
@@ -36,7 +36,7 @@ Before writing code, list the beats. For each lesson beat decide what the eye sh
- Write for the ear: short sentences, one idea each. Say symbols and units in words ("negative seven halves", "meters per second 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` writes `<beat>.mp3` and `timings.js` (duration, marks, captions) and caches each finished beat beside the narration JSON: moving `[[marks]]` reuses the cache, and after a failure the same command resumes rather than starting over.
+- `tts.py` writes `<beat>.mp3` and `timings.js` (duration, marks, captions) and caches each finished beat beside the narration JSON: moving `[[marks]]` reuses the cache, and after a failure the same command resumes rather than starting over. It takes a few seconds a beat, so a long chapter can outlast a tool's foreground time limit: run it in the background and wait for it before `lint.py`.
- Engine: `"engine": "edge"` (default, online) or `"kokoro"` (local, Apache 2.0; English word timings; voices such as `am_michael`, `af_heart`, `bm_george`), set at the top of the narration file with `voice` and `rate`. Keep one engine and voice per book.
## Questions
@@ -55,7 +55,7 @@ Pick the type that lets the student act on the picture itself whenever possible
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(...)`.
+- The prompt is rich text ([engine.md](engine.md#traps)).
- 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.
- The built-in numeric parser uses safe integer numerators and denominators and exact integer products for equality. For answers outside that range, use a subject-specific input and grader rather than allowing rounded values to pass.
@@ -66,4 +66,4 @@ New types are welcome when the content calls for one; each needs keyboard play (
- Follow the agreed chapter scope and order. Verify facts, calculations and answers actually used in the finished lesson; correct or replace source errors and note them in `books/<book>/chapters/chNN.md` for the user.
- Check worked examples as the subject, not only as arithmetic (a push on someone standing on the ground is not the net force).
-- Use the notation and rounding in `style.json` (`look.notation`). Record new shared decisions there.
+- Use the notation and rounding in `style.json` (`look.notation`). Record new shared decisions there. Group thousands with a no-break space (U+00A0) or the book's comma: a thin space all but vanishes in bold system fonts (150 000 000 read as 150000000).
diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.md
index b8abfe3..74abe55 100644
--- a/.claude/skills/papermorph/references/engine.md
+++ b/.claude/skills/papermorph/references/engine.md
@@ -2,7 +2,7 @@
A chapter page loads the engine and its `audio/<lang>/timings.js`, defines `CHAPTER` (including `language` when different from `en`: the audio folder), drawing helpers, `BEATS` and questions, then calls `boot()`. The engine provides the stage, drawing, timeline, question types, guide and player. Use the code's signatures if they differ from this reference. The interface text (buttons, help, cover, finish card) follows `<html lang>`: English, Russian, Chinese and Japanese are in the engine's `TRANSLATIONS`; another language needs a block there.
-Every book keeps a copy of the shared engine in `lib/` (`engine.*`, `math.js`, `volume.*`, `contents.*`, `units.*`), so the book runs on its own. The engine is not part of this skill: it lives in the `engine/` folder of the Papermorph repository (or a fork). `python3 SKILL/scripts/engine.py site` copies it into every book from the repository's `engine/` when it is at hand, otherwise from GitHub (`--check` lists copies that differ, `--from DIR|OWNER/REPO@REF` picks the source, by default the latest major release, `engine-v2`; `@main` takes the newest, a tag or commit pins it, and `engine-v1` is the last engine with the maths helpers inside `engine.js`); a book's copy is not edited by hand. An engine bug is fixed at the source, then synced. The book's own settings and style overrides live in `lib/book.css`, imported by `engine.css` and never overwritten: `--math-font` for numbers and formulas, `--progress-key` when the cover uses a key other than the default.
+Every book keeps a copy of the shared engine in `lib/` (`engine.*`, `math.js`, `volume.*`, `contents.*`, `units.*`), so the book runs on its own. The engine is not part of this skill: it lives in the `engine/` folder of the Papermorph repository (or a fork). `python3 SKILL/scripts/engine.py site` copies it into every book from the repository's `engine/` when it is at hand, otherwise from GitHub (`--check` lists copies that differ, `--from DIR|OWNER/REPO@REF` picks the source, by default the latest compatible release, `engine-v2.1`; `@main` takes the newest, a tag or commit pins it, and `engine-v1` is the last engine with the maths helpers inside `engine.js`); a book's copy is not edited by hand. This reference describes `engine-v2.1`; what an older copy lacks is marked *(v2.1)*, and syncing the book brings it. An engine bug is fixed at the source, then synced. The book's own settings and style overrides live in `lib/book.css`, imported by `engine.css` and never overwritten: `--math-font` for numbers and formulas, `--progress-key` when the cover uses a key other than the default.
The maths helpers (number lines, tiles, fraction rows, planes, chance objects, the number-set diagram, `pickPoint`, `sorter`) are in `lib/math.js`. A chapter that uses one loads `<script src="../lib/math.js"></script>` right after `engine.js`: it reads the engine's globals as it loads, so never before it and never `async`. `lint.py` names a chapter that uses one without loading it. Use the helpers that fit; draw the rest in the chapter, and move what several chapters use into the book's element library (`lib/<name>.js`, [assets.md](assets.md)) rather than into the engine copy.
@@ -13,13 +13,14 @@ The maths helpers (number lines, tiles, fraction rows, planes, chance objects, t
- 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 named `nat whole int rat irr real` (from the algebra book; give them the book's own meanings in `style.json` `look.meaning`, e.g. `const FORCE = COL.…`). Fonts: `UI` (text), `MATH` (serif unless the book's `--math-font` says otherwise).
+- **Board colour** *(v2.1)*. The board and ink colours are the palette at the top of `engine.css` (`--page --board --panel --edge --chalk --dim --faint --task --quiz --good --bad`, plus `--on-fill` for text on a coloured button (unset there, so dark) and `--vignette` for the stage's edges, and the shades between them: `--rule --track --track-ask --bar-edge --hover --veil`). A book redefines them in its `lib/book.css` under a plain `:root`; the stage, the cards, the player bar and `COL.chalk … COL.board` all follow, so a light board with dark ink is a few lines of settings (the commented example in `book.css`, shades included). `COL` reads its colours back as `#rrggbb` (colour tweens mix them) and keeps the dark board's own for one that is missing. The six hues stay in JS: a light book picks darker ones in its own `lib/<look>.js` (`Object.assign(COL, { … })`), loaded right after `engine.js` and before `math.js`, which copies the hues as it loads. Check a new palette on a frame with a question card and the captions on (`?beat=N&t=S`), not only on the picture.
## 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()` |
+| `path(parent, d, attrs, {d:0})` | path; `{d: 0}` makes it ready to be drawn on with `draw()`. A `transform` in `attrs` holds until the state moves the element (`x y s r`), which then owns the transform: to place a shape that also moves, put it in a `G()` |
| `T(parent, str, {x,y,size,fill,font,weight,anchor,o})` | text |
| `cite(parent, key, {str,x,y,size,fill,weight,anchor,o})` | a citation from `REFS` (`../refs.js`, a course option: [courses.md](courses.md)), drawn as an underlined link that opens the source in a new tab and listed on the finish card ([courses.md](courses.md#citations)) |
| `M(parent, parts, {x,y,size,fill,anchor,o,s})` | math with its baseline at y; parts are strings, `F(n,d)` fractions, `R(x, i)` roots (x may be `F(...)`, i the index), `E(exp)` exponents, `TX(tex)` LaTeX (see [LaTeX](#latex)); returns a group with `_w` (width) |
@@ -30,6 +31,7 @@ The maths helpers (number lines, tiles, fraction rows, planes, chance objects, t
| `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 (math.js) |
| `mathEl(parts, size)`, `rich([...])`, `$m(...parts)`, `$tex(tex)` | inline math in HTML (cards, prompts) |
+| `h(tag, cls, kids)` | an HTML element for a card (a table, a list): kids are strings, nodes or `rich(...)`; put it in a prompt or a message as it is |
| `texPart(el, name)` | the part `\class{name}{…}` of a TeX formula inside `el`, for `tw`/`fx` on `c_color` and `o` |
| `panel(t0)` | fade the current scene group and start a new one; call it at the start of a beat that changes the picture |
@@ -55,9 +57,9 @@ A book whose formulas need more than `M()` parts (indices, sums, matrices, accen
```
- `m('name', offset)` is the start time of the word after `[[name]]`; `D` is the clip's length. Use marks for actions tied to speech; scene entrances and transitions can use fixed offsets.
-- 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`, `soft`. Continuous motion and cameras: see below.
-- 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.
+- Tweens: `tw(e, to, t0, dur, ease)`, `prog(q => …, t0, dur, ease)` for custom motion (arcs, counters, live redraws), `show(e, t0, dur, ease)`, `hide`, `draw` (same arguments), `pop`, `pulse`, `stream`. Eases: `io`, `out`, `back`, `lin`, `soft`. Continuous motion and cameras: see below.
+- A lesson beat ends after its narration and its last tween, and holds that picture `HOLD` (0.6 s) before the next starts; an `ask` beat waits for `done()`.
+- **Opening lead-in**: if a beat calls `panel()` (before 0.5 s) and no element is revealed (faded, scaled or drawn in from nothing) 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, so the narration never runs over an empty board. It looks only at reveals: a beat that lays out part of its picture visible at once (axes, empty boxes, a set) and reveals the rest on later words still has that first group pulled to 0.4 s. When those words matter, give the beat `{ lead: false }` in its fourth slot; a camera that shows a picture from the first frame is the same case. To see where a beat's reveals land, put marks on a contact sheet: `strip.py chNN OUT idea:0.4,label,label+0.3,end --sheet storyboard --url http://localhost:8765/<book>/` (a mark plus an offset is the moment the action is timed to).
- **`pre`** in the fourth slot (`{ pre: 1.2 }`) runs the picture that many seconds before the narration starts: an action, then the line. Picture books use it on every scene.
- **The end of a film**: a chapter whose last beat asks nothing (a picture book) is finished when that beat ends: it is marked done and, with `CHAPTER.next`, offers the next chapter (Enter).
- **Seeking replays**: jumping to beat N rebuilds the scene and runs earlier beats instantly. Make `run` deterministic: create objects and schedule tweens through the timeline, with inputs from chapter data and replayed `S` state. Create interactions inside `ask`; use `fx`/`fxp` for answer effects.
@@ -67,13 +69,13 @@ A book whose formulas need more than `M()` parts (indices, sums, matrices, accen
For continuous motion (vehicles, orbits, rolling, scrolling scenery) and camera work. Everything is a pure function of the beat time, so pause, seek and `?beat=N&t=S` show the same frame.
-- `clockRun(f, D)` calls `f(t)` on every frame of the beat, `t` in seconds from its start (0..D). Write positions as functions of `t` (`x = x0 + v * t`) and share them between objects and the camera; never accumulate per-frame state.
+- `clockRun(f, D)` calls `f(t)` on every frame of the beat, `t` in seconds from its start (0..D); the beat's hold after `D` shows `f(D)`. With `clockRun(f, D, { tail: true })` *(v2.1; an older engine ignores `tail`, so the hold stands still)* it keeps calling `f` through the hold, `t` up to the beat's end (`P.end`: the later of the narration and the last tween, plus `HOLD`): use it where motion must never freeze (a film, whose next scene cuts in), and let `f` pose sensibly past `D`. A camera in a beat with a tailed `clockRun` runs on to `P.end` too, so a follow shot keeps up. Write positions as functions of `t` (`x = x0 + v * t`) and share them between objects and the camera; never accumulate per-frame state.
- `const cam = camera(parent, D, { x, y, z, r, box, bg })` makes a view onto a world group. Draw in `cam.world` in world coordinates. The view `{x, y}` is the world point shown at the centre, `z` the zoom (screen px per world px), `r` the roll in degrees. Defaults: full stage, `(800, 450)`, `z` 1 (identity, so stage coordinates still work). With `box: [x, y, w, h]` the camera draws in a framed, clipped box with background `bg` (split screen, picture-in-picture); its default zoom fits the 1600 × 900 world into the box. `cam.el` is the camera's group (fade, pop or hide it; it scales about the box centre).
- Moves, all on the beat clock: `cam.to({x, y, z, r}, t0, dur = 1, ease = soft)` blends only the keys given, from wherever the camera is at `t0`; `cam.cut(view, t0)` is a hard cut (`dur` 0); `cam.shake(amp, t0, dur, hz = 7)` is a subtle, repeatable shake (fades in and out over 0.3 s). Any key may be a function of `t`: that is a follow shot (`cam.to({ x: t => carX(t) }, 2, 1.5)` locks on over 1.5 s; `r: t => spin(t)` rolls with a rotating object). Zoom changes evenly (log scale) and keeps one world point fixed when start and end allow it.
- Parallax: `cam.layer(k, wrap)` returns a group inside the world that moves at `k` × the camera's pan (`k` < 1 far, > 1 near; zoom and roll are not scaled per layer). With `wrap = W` the layer's content repeats every `W` world px: draw one period plus the widest view, and the camera can pan any distance. Keep repeating details (dashes, tiles, trees) on a period that divides `W`, and move followed objects by multiples of `W` when they loop, so the loop is invisible.
- `cam.at(t)` returns the view at `t`; `cam.screen(wx, wy, t)` the screen position of a world point (no shake), for screen-space labels that track an object. `cam.track(label, wx, wy, t)` does that for a text label drawn outside the camera: it follows the point, stays inside the frame (or box), and fades out once the point leaves; fade it in through a wrapper group. Keep tracked labels in the safe frame this way rather than letting them clip at the edge.
- Split screen or picture-in-picture: two cameras with boxes, each with its own copy of the world built by the same function and driven by the same clock functions. Cross-fade between shots by fading one camera's `el` out and another's in.
-- Labels drawn in the world scale with the zoom; put text that must stay readable in screen space (the panel) or give world labels a size for the shot's zoom. A beat whose camera shows a picture from its first frame while its first scheduled reveal is late may need `{ lead: false }`.
+- Labels drawn in the world scale with the zoom; put text that must stay readable in screen space (the panel) or give world labels a size for the shot's zoom.
- Ease `soft` (cosine in-out) suits camera moves; `io`, `out`, `back`, `lin` or any `p => …` work too.
## Performance (Firefox)
@@ -96,7 +98,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'
- Positions: `BAND` (bottom band, y 686–886; long content can push it past the stage, so check it), `TOPR` (top right, ≤ 470 high), `RIGHT`, `SCREEN` (full-screen practice; the label names the set in the book's language, and the engine appends k of n when a quiz has several questions), `SORT_SCREEN`, or any `{x, y, w, cls: 'side'}`.
- `choice(options, right, why, wrongWhys[], onRight?)` — number keys.
- `mcq(id, onRight?)` — (course option, [courses.md](courses.md)) a whole quiz entry (`{id, prompt, build: choice(...)}`) from the chapter's item bank: `quiz(TOPR, [mcq('c-attrib'), mcq('c-cause')], done)`. Needs `items.js` (built by `scripts/items.py`) loaded after `engine.js`; an unknown id throws.
-- `blanks(rows)` — rows `{parts: [..., {box: '21'}, ...], why, hint?, fx?, test?}`; accepts −5, 3/4, 2 1/4, 0.75 as exact values; `{box, lowest: true}` demands lowest terms; `test(values)` judges the whole row (e.g. two factors in either order). Tab moves between boxes, Enter checks, Esc leaves a box.
+- `blanks(rows)` — rows `{parts: [..., {box: '21'}, ...], why, hint?, fx?, test?}`; accepts −5, 3/4, 2 1/4, 0.75 as exact values and, *(v2.1)*, with a currency sign ($60, 5 €) and thousands grouped by spaces of any kind (1 250, as [authoring.md](authoring.md) shows numbers) or, where the decimal sign is a point, by commas (1,250); `{box, lowest: true}` demands lowest terms; `test(values)` judges the whole row (e.g. two factors in either order). `hint` is one message for any wrong value in its row; when different mistakes need their own answers, split the step into rows or ask it as a `choice` with `wrongWhys`. 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). `pickPoint` and `sorter` are in math.js.
- 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.
@@ -105,7 +107,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'
## Player
-Space play/pause, ←/→ previous/next beat (Shift+←/→ during a question), Home restart, C captions (a question's narration is captioned too, above its band or beside its corner card, until the narration ends), `<`/`>` speed (0.75–1.5×, remembered), volume (remembered, except muted), F full screen, ? help. Clicking a step segment jumps to that point of the beat (`seekInto(i, frac)`); the next beat's clip preloads while one plays. `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, without captions (N is kept within the chapter's steps). With `?review` in the URL, N pauses and asks for a note on the current moment and Shift+N copies the chapter's notes, one line each with the `?beat=N&t=S` that reopens it, so a reviewer can collect notes while watching and hand them over at once. The finish card's Enter opens `CHAPTER.next`, R replays.
+Space play/pause, and once the chapter has ended replay *(v2.1)*, ←/→ previous/next beat (Shift+←/→ during a question), Home restart, C captions (a question's narration is captioned too, above its band or beside its corner card, until the narration ends), `<`/`>` speed (0.75–1.5×, remembered), volume (remembered, except muted), F full screen, ? help. Clicking a step segment jumps to that point of the beat (`seekInto(i, frac)`); the next beat's clip preloads while one plays. `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, without captions (N is kept within the chapter's steps); on a question step the answer box takes focus only once Space starts the lesson. With `?review` in the URL, N pauses and asks for a note on the current moment and Shift+N copies the chapter's notes, one line each with the `?beat=N&t=S` that reopens it, so a reviewer can collect notes while watching and hand them over at once. After the end, on the finish card or a film's last frame, Enter opens `CHAPTER.next` (replays when there is none) and R replays.
Progress is saved under `animebook:progress:<book-path>`; the cover and a picture book's series page read the same key. A book can set another key with `--progress-key` in `lib/book.css`; its cover must then read that key. Books served in different folders have separate saved places and completion lists.
@@ -116,10 +118,12 @@ Keep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head
## 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(...)`.
+- Prompts, feedback, `grid` text rows and `choice` options are rich text in HTML cards: a string is shown as written (`<` is a character, never markup, so `3 < 5` is safe), math goes in `$m(...)`, and anything richer (a table) is an element made with `h()` and passed as a part.
+- `st(e)` is the element's live state, not a copy: a helper that keeps `const s = st(e)`, then `put()`s the element off stage and tweens back to `s.x` tweens to the moved position, and the slide-in never returns. Copy the numbers first (`const { x, y } = st(e)`).
+- A `prog` or `clockRun` that redraws only when a key changes (a 12 fps frame number, a step index) must draw from the key's own value (`f / FPS`), not the exact `t` that crossed it: playing, seeking and `?beat=N&t=S` reach the same key at different `t`, and must show the same picture.
- In a JS string, double each TeX backslash (`'\\frac{a}{b}'`) or use `` String.raw`\frac{a}{b}` ``: `'\text'` is a tab followed by "ext".
- Write a formula wholly in TeX, an `eqLine` sign included (`sym: TX('\\le')`): TeX glyphs are smaller and lighter than `M()` text.
-- Prefix chapter-specific helpers when their names might collide with engine globals (`rect`, `popIn`, `eqLine`, `slot` from math.js when the chapter loads it; `fit`, `Y0`, `OV`, `camera`, `soft`, `clockRun`, `retire`, `seeking`, `BOOK`, `bookSetting`, `TX`, `texPart`, …); a redeclaration stops the page script. `lint.py` lists every clash.
+- Prefix chapter-specific helpers when their names might collide with engine globals (`rect`, `popIn`, `eqLine`, `slot` from math.js when the chapter loads it; `fit`, `Y0`, `OV`, `HOLD`, `camera`, `soft`, `clockRun`, `retire`, `seeking`, `BOOK`, `bookSetting`, `TX`, `texPart`, …); a redeclaration stops the page script. `lint.py` lists every clash.
- 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/papermorph/references/intake.md b/.claude/skills/papermorph/references/intake.md
index 6657804..881ab6c 100644
--- a/.claude/skills/papermorph/references/intake.md
+++ b/.claude/skills/papermorph/references/intake.md
@@ -86,4 +86,4 @@ Leave out blocks the tier does not use. New kinds of book add their own blocks b
Deliver the pilot with a choice: approve and make the rest of the book (recommended when it is good), approve and stop here, or one of two or three concrete changes you would make yourself. Fold the answer and any feedback into `words` and the affected block, and add an approved chapter to `approved`. Approved chapters are the strongest anchor: later chapters watch and read them as worked examples.
-When continuing, write `chapters.md` (`# | Title | Pages | Minutes | Status`: planned, ready, user-approved) and go on with the remaining chapters.
+When continuing, write `chapters.md` (a table `| # | Title | Pages | Minutes | Status |`, status planned, ready or user-approved) and go on with the remaining chapters.
diff --git a/.claude/skills/papermorph/references/painting.md b/.claude/skills/papermorph/references/painting.md
index c49248c..057ac6e 100644
--- a/.claude/skills/papermorph/references/painting.md
+++ b/.claude/skills/papermorph/references/painting.md
@@ -8,12 +8,12 @@ Paint one set two or three ways at the cheapest quality, stand the puppets in ea
## Getting the composition you need
-Puppets stand at fixed places, counters must hide the right legs, and cuts must match. The reliable way is to draw the set first as a rough SVG sketch in `books/<book>/art/sets.js` (`bake_sets.py books/<book>/art/sets.js site/<book> <set> … --ref books/<book>/art` renders each named set as one frame, `ref-<set>.png`; name the sets, since a set already baked is otherwise skipped), then ask the model to repaint *that picture* in the style of the reference: the layout survives, the look changes. Once a set is painted, `bake_sets.py` leaves it alone unless you name it. Then:
+Puppets stand at fixed places, counters must hide the right legs, and cuts must match. The reliable way is to draw the set first as a rough SVG sketch in `books/<book>/art/sets.js` (`bake_sets.py books/<book>/art/sets.js site/<book> <set> … --ref books/<book>/art` renders each named set as one frame, `ref-<set>.png`; name the sets, since a set already baked is otherwise skipped; the picture holds every layer of the set, so a layer painted on its own needs its own reference, cropped or sketched as a set of its own), then ask the model to repaint *that picture* in the style of the reference: the layout survives, the look changes. The exact geometry does not, so the places puppets and props stand at come from the painted set, not the sketch ([team.md](team.md#picture-books) says how to measure them). Once a set is painted, `bake_sets.py` leaves it alone unless you name it. Then:
- **Cut-outs for whatever people stand behind.** A counter, a cart, rows of desks, a lectern: paint each as its own picture on a transparent background and place it as a layer (`painted.py`, `cut`).
- **Variants by editing, not redrawing.** Rain and snow versions of a street, a door open and shut, a bun with a bite: edit the one picture, so a cut between versions changes only that.
- **Leave signs blank.** Image models garble text, Chinese and Japanese worst. Paint the banner, the shop sign, the blackboard empty and let `painted.py` write the words on in a real font.
-- **Paint wider than the frame.** Camera shakes and zooms see past the edge; `painted.py` pads full frames by mirroring their edges, and when something near an edge (a post box) shows twice in a close-up, `"edge": "stretch"` on that layer pads it with its own outermost pixels instead.
+- **Paint wider than the frame.** Camera shakes and zooms see past the edge; `painted.py` pads full frames by mirroring their edges (`pad`, 60 px at the sides and 34 at top and bottom), enough for a shake but not a pan: a camera that travels further zooms in enough to keep its view inside the picture (a follow shot needed about 1.4×), and when something near an edge (a post box) shows twice in a close-up, `"edge": "stretch"` on that layer pads it with its own outermost pixels instead.
Everything that comes out goes through `painted.py` (manifest `books/<book>/art/painted.json`): sets resized to the 1600×900 frame, blurred copies for close-ups, cut-outs placed, words written, props written to `img/props/`. Stand the puppets in a frame and look before going on.
@@ -21,8 +21,8 @@ Everything that comes out goes through `painted.py` (manifest `books/<book>/art/
Money is the user's, so the user sets a ceiling and sees every cent:
-- `paint.py` takes quality `low` or `medium` only. Try low first: in these books low was often good enough for the final set (about $0.02 a picture; medium about $0.02–0.03; high cost five times as much and, once used in a film, looked the same).
-- `paint.py` reads the OpenRouter key from `~/.config/openrouter/key` or `$OPENROUTER_API_KEY`. Every picture is logged with its cost (`--ledger books/<book>/art/costs.tsv`; `paint.py --total books/<book>/art/costs.tsv` sums it); before a batch, say how many pictures and what they will cost; after it, report the real balance from the provider (OpenRouter's credits page, or `GET https://openrouter.ai/api/v1/credits` with the key), not an estimate. OpenRouter refuses any image request when the balance is under one dollar.
+- `paint.py --q` is `low` or `medium` (the default; high is refused). Try `--q low` first: in these books low was often good enough for the final set (about $0.016 a picture with one reference, about $0.026 with the style picture as a second; medium about $0.02–0.03; high cost five times as much and, once used in a film, looked the same).
+- `paint.py` reads the OpenRouter key from `~/.config/openrouter/key` or `$OPENROUTER_API_KEY`. Every picture is logged with its cost (`--ledger books/<book>/art/costs.tsv`; `paint.py --total books/<book>/art/costs.tsv` sums it); before a batch, say how many pictures and what they will cost; after it, report the real balance from the provider (OpenRouter's credits page, or `GET https://openrouter.ai/api/v1/credits` with the key), not an estimate; it can lag a batch by some minutes, so read it again before reporting. OpenRouter refuses any image request when the balance is under one dollar.
- Without an OpenRouter account, `paint_openai.py` calls OpenAI's image API directly with the same arguments and ledger (key in `$OPENAI_API_KEY`, `--env FILE` or `~/.config/papermorph/.env`). OpenAI does not return a price, so its ledger lines are estimates: read the real spend from OpenAI's usage page.
- After every batch, put the pictures on one contact sheet and open it for the user (Finder, the browser), even when working on your own, so the user sees each stage.
diff --git a/.claude/skills/papermorph/references/puppets.md b/.claude/skills/papermorph/references/puppets.md
index 30245c9..4431a68 100644
--- a/.claude/skills/papermorph/references/puppets.md
+++ b/.claude/skills/papermorph/references/puppets.md
@@ -6,7 +6,7 @@ Two cast styles are on the shelf, both on the same `paper.js`: round-headed figu
## What makes it read as stop motion
-- **Twelve frames a second, on twos.** `stopClock` samples every movement into steps; the slight jerk is the style, not a defect. Big moves still ease in and out across those steps.
+- **Twelve frames a second, on twos.** `stopClock` samples every movement into steps; the slight jerk is the style, not a defect. Big moves still ease in and out across those steps. It draws through the beat's 0.6 s hold after the clip too (`clockRun`'s tail, engine-v2.1 on: [engine.md](engine.md#world-clock-and-camera)), so a scene's pose functions run to about `D + 0.6` and the frame the next scene cuts from is still alive.
- **The animator's hand.** Each frame nudges every puppet by a tiny random amount (`jit(frame, k)`, the same nudge for the same frame, so pause, seek and `?beat=N&t=S` show exactly what playback shows), and the picture flickers faintly. Keep it small: at full strength it reads as shaking; a third of a pixel-ish wobble, held for two frames, felt hand-made.
- **Paper you can feel.** Grain, torn edges and a soft drop shadow on every piece (the `#paper` filter), brass pins at the joints, and a soft contact shadow under the feet so a puppet stands on the ground, leaning the way the set's light falls.
- **Replacement, not morphing.** Mouths are swapped shapes timed to the words; a blink is two closed frames; a door opens through a few boards of different widths; a bun bitten is a different picture.
@@ -15,8 +15,10 @@ Two cast styles are on the shelf, both on the same `paper.js`: round-headed figu
- **Nobody freezes.** Whoever speaks lip-syncs; everyone blinks at their own moments, never in unison; listeners' eyes follow the speaker; reactions get a small head turn or a lid drop. A crowd glances about on its own and turns as one only when something happens (a staggered snap, a frame or two apart).
- **Turning round.** A round-headed puppet turns by sliding its face across the head (`look`), as South Park does. A profile puppet turns as a whole-body swap: the side view squashes, the whole front figure shows for the narrowest frames, and it comes out mirrored. A front head on a side body looked wrong every time.
-- **Feet don't slide.** Walks use a compass step (`walk()`): the planted foot stays put while the hip swings over it; distance is scale. Runs are on twos with a bigger bob.
-- **Hands touch what they hold.** A held prop belongs to the hand's piece; when something is handed over, both hands meet it.
+- **Feet don't slide.** A walk keeps the planted foot still while the hip rides over it, and the puppet's x comes from the distance the walk returns (`d`, in the puppet's units, times its scale), never from a separate tween. A profile figure uses the compass step `walk()` (`paper.js`): `d` grows as it goes forward, so one built facing right goes `x0 + d·s` and a mirrored one `x0 − d·s`; its `near`/`far` angles go to the near and far leg as they are. A figure that faces us while it crosses the frame side-steps with `spStep()` (`cast.js`): step out, close, both legs leaning outward, `x0 ± d·s` by the direction, a step every 2/3 s by default (keep the period a whole number of 1/3 s, so a drawn frame lands on the widest stance and only one foot moves at a time; the template's `scene1.js` walks the kid in this way); `walk()`'s angles on a front figure cross the ankles every other step. `spWalk()` is the show's quick shuffle on the spot, for short moves where nobody watches the feet. Runs are on twos with a bigger bob. Check a walk on a strip at 1/12 s: the planted shoe should not move between frames.
+- **Hands touch what they hold.** A held prop belongs to the hand's piece (`hold` is the screen-right hand, on `armR`; `holdL` the screen-left one, on `armL`); when something is handed over, both hands meet it. To put a hand on a point, ask the puppet: `aim(pose, 'R', [x, y])` gives the `armR`/`reachR` values for that pose (its result spreads straight into the pose, or tween `arm` and `reach` from rest for a gesture), and `point(pose, 'mouth' | 'chin' | 'capL' | 'capR')` says where that place of the face is for the same pose, so a cup, a scratch or a chin on a hand lands where it should through a lean, a head tilt or a seat. A held thing hangs from the mitten's centre, so aim at the point less the thing's own offset (a cup's rim above the hand). A hand raised above the chin and in towards the face (a cup at the lips, a hand on the chin, a reach across the head) is drawn in front of the head; an arm raised out to the side (a wave, a cheer) stays behind it, and so does a hand at its own side of the head, so a scratch there wants `armFrontR: true` (or `armFrontL`; `false` keeps a hand behind). `far` above 1.25 means the point is out of reach: lean in, step closer or move the point. Look at a full-size still of the moment the hand arrives.
+- **Sitting reads from the knees.** A figure that faces us looks seated only when its thighs come towards us: `sit: H` sits on a seat H units above the feet (up to the shape's `legH − 12`, 34 on the kid; a higher seat counts as that), the lap and knees towards us and the shins down to the ground at the pose's `y`. `sit: true` only hides the legs and the shadow, for a seat whose front comes up to the coat (a desk row). A still beside the standing pose should read sitting without the set.
+- **Whatever says where something is follows what is drawn.** A helper a scene asks for a position (`point()`, `aim()`, a board's square or the top of a piece the kit adds) works from the same state the drawing uses this frame, a piece being lifted or carried included, and draw order comes from the pose alone, so a seek to any frame shows what playback showed (compare a frame from playback with the same `?beat=N&t=S`).
- **Things behind things.** A counter, a cart, a desk row or a lectern sits on its own layer between puppets, so the person behind shows from the chest up (`paperCam(…, { after, stages })` puts puppet layers between set layers).
## Cameras
@@ -35,4 +37,4 @@ Paper filters are expensive live, so every finished piece is baked to a bitmap;
## Seeing your own work
-The preview server must not cache (`serve.py`). Look at contact sheets that advance the clock the way playback does (`strip.py chNN OUT scene1/0.5 --url http://localhost:8765/<book>/`; times are on the beat clock, so a scene's speech starts at its `pre`, and marks of a joined scene are named `clip.mark`), at full-size frames at the key moments, at the last frame of each scene beside the first of the next, and play the whole episode through once at speed. Some faults appear only in continuous playback (a camera layer shown once and never hidden again), so don't rely on jumps with `?t=` alone.
+The preview server must not cache (`serve.py`). Look at contact sheets that advance the clock the way playback does (`strip.py chNN OUT scene1/0.5 --url http://localhost:8765/<book>/`; times are on the beat clock, so a scene's speech starts at its `pre`, and marks of a joined scene are named `clip.mark`; `scene1:2..5/0.1@o@c` is an onion skin of one shot with the camera held still, for feet and hands), at full-size frames at the key moments (`shot.py`, beats counted from 0 or named), at the last frame of each scene beside the first of the next (`shot.py --cuts`), at the sounds against the picture (`playlog.py`), and play the whole episode through once at speed ([review.md](review.md) has the commands). Some faults appear only in continuous playback (a camera layer shown once and never hidden again), so don't rely on jumps with `?t=` alone.
diff --git a/.claude/skills/papermorph/references/review.md b/.claude/skills/papermorph/references/review.md
index 4af88ba..ba5d6c6 100644
--- a/.claude/skills/papermorph/references/review.md
+++ b/.claude/skills/papermorph/references/review.md
@@ -5,12 +5,13 @@ Serve `site/` with `python3 SKILL/scripts/serve.py 8765 site` (no browser cachin
## Watch it in motion
```sh
-uv run --with playwright --with pillow --with numpy SKILL/scripts/strip.py chNN OUT --url http://localhost:8765/<book>/ push/0.25 law3/0.5@w roll/0.2@o
+uv run --with playwright --with pillow --with numpy SKILL/scripts/strip.py chNN OUT --url http://localhost:8765/<book>/ push/0.25 law3/0.5@w roll:2..4/0.2@o walk:1..5/0.1@o@c
+uv run --with playwright --with pillow SKILL/scripts/playlog.py chNN --out OUT --url http://localhost:8765/<book>/ # picture books: sounds against picture
```
-A strip shows one beat at small steps; `@w` adds a motion WebP; `@o` adds an onion skin, the same frames laid over each other in one picture, later ones stronger, so spacing reads at a glance: even gaps are even speed, bunched ghosts are easing in or out, a ghost that jumps is a pop. Look at each action as a viewer would: do actors perform what the narration says, do props stay on the hands, does the camera move with purpose, does each frame still match the storyboard, do arrows, labels and readouts agree with the motion? Then watch a few beats live in Firefox with sound, which is how the user watches.
+A strip shows one beat at small steps; `@w` adds a motion WebP; `@o` adds an onion skin, the same frames laid over each other in one picture, later ones stronger, so spacing reads at a glance: even gaps are even speed, bunched ghosts are easing in or out, a ghost that jumps is a pop. An onion skin reads only within one shot, so give it that shot's range (`roll:2..4`, ends may be marks); `@c` draws a picture book's frames in the set's own framing, so under a pan a planted foot stays one sharp ghost and a sliding one smears. Look at each action as a viewer would: do actors perform what the narration says, do props stay on the hands, does the camera move with purpose, does each frame still match the storyboard, do arrows, labels and readouts agree with the motion? Then watch a few beats live in Firefox with sound, which is how the user watches. An agent that cannot listen plays the chapter with `playlog.py` instead: it logs when each sound and caption starts in real playback and shows the stage rebuilt by seeking to that beat time, so a clack can be checked against the piece landing and a line against the mouth that says it (a fault that only continuous playback shows will not be in those frames). `--from`/`--to` play only some beats; a lesson stops at its first question.
-Watch every beat to its end, question cards included; problems hide in the beats nobody looked at. A strip is a row of still pictures, so it cannot tell you that nothing is moving: a wave drawn once at a fixed phase looks right in every frame and is dead on screen. `uv run --with playwright --with pillow SKILL/scripts/still.py chNN --url …` lists the stretches of each beat where the stage does not change. Some holds are right (a moment to read a result); a wave, a ray of light or an actor that stands for something in motion should be moving whenever it is on screen, because the motion is what it explains.
+Watch every beat to its end, question cards included; problems hide in the beats nobody looked at. A strip is a row of still pictures, so it cannot tell you that nothing is moving: a wave drawn once at a fixed phase looks right in every frame and is dead on screen. `uv run --with playwright --with pillow SKILL/scripts/still.py chNN --url …` lists the stretches of each beat where the stage does not change. In a picture book it switches off the kit's hand jitter and flicker first (a scene's own `jit`, falling snow or a tremble, still counts as motion), so a puppet that only breathes and blinks measures about 1–1.5 and acting 2 and up (its default threshold is 1.5). Some holds are right (a moment to read a result); a wave, a ray of light or an actor that stands for something in motion should be moving whenever it is on screen, because the motion is what it explains.
## Static checks first
@@ -20,11 +21,12 @@ Watch every beat to its end, question cards included; problems hide in the beats
```sh
uv run --with playwright --with pillow SKILL/scripts/shot.py chNN --url http://localhost:8765/<book>/ --out OUT
+uv run --with playwright --with pillow SKILL/scripts/shot.py chNN --url http://localhost:8765/<book>/ --out OUT --cuts # picture books
uv run --with playwright SKILL/scripts/check_blank.py site/<book> chNN --url http://localhost:8765/<book>/
uv run --with playwright SKILL/scripts/overlap.py chNN --url http://localhost:8765/<book>/
```
-`shot.py` captures open/end frames of every beat as 4-up sheets and reports console errors. Look for an empty or unrelated opening, text over drawings or clipped at the edge, a card covering what it asks about, leftovers half faded, geometry contradicting its values, shapes inside circles or curves crossing the outline (check thin geometry on the full-size `chNN_bII_T.png`, not only the sheet), text too small at half size or too much at once, and the same idea in different colours. `check_blank.py` reports openings empty for more than a second after speech starts. `overlap.py` samples every beat and lists where an arrow runs through text or two texts collide, with times, so you can look at exactly those frames.
+`shot.py` captures open/end frames of every beat as 4-up sheets and reports console errors. Look for an empty or unrelated opening, text over drawings or clipped at the edge, a card covering what it asks about, leftovers half faded, geometry contradicting its values, shapes inside circles or curves crossing the outline (check thin geometry on the full-size `chNN_bII_T.png`, not only the sheet), text too small at half size or too much at once, and the same idea in different colours. `--cuts` puts each beat's last frame beside the next one's first, one cut a row: in a picture book, look there for jumps in place, pose, light and screen direction. `check_blank.py` reports openings empty for more than a second after speech starts. `overlap.py` samples every beat and lists where an arrow runs through text or two texts collide, with times, so you can look at exactly those frames. Both are lesson checks and skip a picture book, whose set is always there and whose words are captions.
## Smoothness
@@ -32,7 +34,7 @@ uv run --with playwright SKILL/scripts/overlap.py chNN --url http://localhost:87
## Interaction tests
-Adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`: it checks playback, that every beat replays the same frame when seeked, that quiz cards stay readable and on stage at two viewport sizes, and walks the answers, practice and finish card. Run it in Chromium and with `BROWSER=firefox`. Run existing tests of approved chapters after changing the book's engine or library.
+Adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`: it checks playback, that every beat replays the same frame when seeked, that quiz cards stay readable and on stage at two viewport sizes, and walks the answers, practice and finish card. `ANSWERS` maps each question beat to one step per question: a digit picks a choice, `=a,b` fills the boxes, `#2;1+3` answers a grid (rows split by `;`, each row's columns counted from 1, `+` for several, `#2;;1` a row left empty). Run it in Chromium and with `BROWSER=firefox`. Run existing tests of approved chapters after changing the book's engine or library.
After scoring changes, check a wrong first try stays recorded after revisiting and a restart clears it; after progress changes, check book isolation and missing or malformed stored data. Fix engine bugs at the engine source and copy them to the books with `scripts/engine.py`; book-specific settings stay in each book's `lib/book.css`.
diff --git a/.claude/skills/papermorph/references/scenes.md b/.claude/skills/papermorph/references/scenes.md
index 72bd8e2..fcafadb 100644
--- a/.claude/skills/papermorph/references/scenes.md
+++ b/.claude/skills/papermorph/references/scenes.md
@@ -15,7 +15,7 @@ Vary the composition with the content (a close-up, a wide shot, a split screen,
## Storyboard: layout first, then motion
1. With narration and beats written, place everything for one to three key moments per beat in the real page: real elements at their real sizes, positions written as the moment's values, no tweens yet.
-2. Capture those moments into one sheet (`strip.py chNN OUT force:push,dir net:add … --sheet storyboard`; times may be marks). Write one line per frame in `chapters/chNN.md`: what it says and where the eye goes. That sheet is the storyboard; composition is cheapest to change now.
+2. Capture those moments into one sheet (`strip.py chNN OUT force:push,dir net:add … --sheet storyboard --url http://localhost:8765/<book>/`; times may be marks). Write one line per frame in `chapters/chNN.md`: what it says and where the eye goes. That sheet is the storyboard; composition is cheapest to change now.
3. In the pilot the user reviews the sheet before motion is added. In later chapters it is your own check and stays as evidence in `books/<book>/review/chNN/`.
4. Add motion and camera so that the picture passes through those compositions, then compare finished frames with the sheet.
diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.md
index 310c242..7694592 100644
--- a/.claude/skills/papermorph/references/site.md
+++ b/.claude/skills/papermorph/references/site.md
@@ -42,6 +42,7 @@ For a painted look, also `cp "$PB/painted.json" "$BOOK_WORK/art/"` ([painting.md
```sh
A="$BOOK_SITE/ch01/audio/en"; N="content/$BOOK_ID/ch01/narration.en.json"
uv run --with edge-tts python "$SKILL/scripts/tts.py" "$N" "$A"
+python3 "$SKILL/scripts/level.py" "$A"/*.mp3
python3 "$SKILL/scripts/mouths.py" "$N" "$A"
python3 "$SKILL/scripts/join.py" "$A" scene1=s01,s02,s02b,s03 --words "$N"
uv run --with numpy python "$SKILL/scripts/sfx.py" "$BOOK_SITE/ch01/audio/sfx" knock
@@ -58,7 +59,7 @@ uv run --with playwright --with pillow python "$SKILL/scripts/bake_puppets.py" "
### Every book
-Use the pilot chapter's number in place of `ch01` when the pilot is not the first chapter. Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js` (a picture-book chapter also loads `mouths.js` and `shots.js` from that folder), and set `CHAPTER.language` to match (default `en`, it picks the audio folder). Set `<html lang>` in `index.html` and every chapter to the same language: the player and the contents page take their interface text from it (English, Russian, Chinese and Japanese are built into the engine; other languages fall back to English until a block is added to the engine's `TRANSLATIONS`). Take `voice` and `rate` for each narration file from `style.json`, and translate the template's own visible text (titles, lede, prompts) before the pilot.
+Use the pilot chapter's number in place of `ch01` when the pilot is not the first chapter. Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js` (a picture-book chapter also loads `mouths.js` and `shots.js` from that folder), and set `CHAPTER.language` to match (default `en`, it picks the audio folder). A chapter's minutes appear on its title screen (`CHAPTER.minutes`), its contents card and a series card; write the same number in each: the length of its audio (the `dur`s in `timings.js`) plus about 15 s for each question, rounded to whole minutes and never below 1. Set `<html lang>` in `index.html` and every chapter to the same language: the player and the contents page take their interface text from it (English, Russian, Chinese and Japanese are built into the engine; other languages fall back to English until a block is added to the engine's `TRANSLATIONS`). Take `voice` and `rate` for each narration file from `style.json`, and translate the template's own visible text (titles, lede, prompts) before the pilot.
If the book's formulas need LaTeX ([engine.md](engine.md#latex)), add MathJax (with its license) to `lib/`, and load `../lib/mathjax.js` right after `engine.js` in every chapter:
diff --git a/.claude/skills/papermorph/references/sound.md b/.claude/skills/papermorph/references/sound.md
index 3a34b47..be5b175 100644
--- a/.claude/skills/papermorph/references/sound.md
+++ b/.claude/skills/papermorph/references/sound.md
@@ -9,16 +9,16 @@ Voices carry the story; everything else sits under them. In early cuts the music
- **Mouths** follow the words: `mouths.py` turns each line's word timings into mouth shapes (a Chinese or Japanese line opens and shuts once per character), and `lips(q, scene, pre, line…)` picks the shape for the frame. Edge's word times run about a tenth of a second ahead of the sound; `mouths.py` and `join.py` move mouths and captions that much later and shut the mouth where the clip's sound stops, so a lip flap that leads or trails the voice is worth reporting.
- **One clip per scene.** `join.py` joins a scene's lines into one audio clip with short pauses, and inserts silence where the action needs room (`line@T+S`: S seconds of silence T seconds into the line, after a word's sound has ended rather than where the next word begins) or after the last line (`name:S`, a stare or a tag). Gaps for a held stare, a fly landing, a class turning round belong here, not in rushed animation. `--words` writes every word's time in the scene clip beside the narration; scene authors time actions against it (the beat clock adds the scene's `pre`).
- **One script for the whole sound.** Keep the episode's audio steps in one script beside the book's notes (`tools/<book>/audio.sh`) and rerun it after any change: lines replaced by hand, `mouths.py`, level fixes, `join.py` with its holes, any caption edits. One episode's join arguments lived only in a terminal and had to be read back out of `shots.js`.
-- **Levels.** The line the joke hangs on must not be the quietest, voices need pitches apart (a dog at 113 Hz under a 110 Hz narrator read as the same person), and peaks stay under -1 dB. A gain change goes through a limiter (`volume=3dB,alimiter=limit=0.89`) once per synthesized clip, so rerunning the script does not raise it again (remember the clip's checksum).
+- **Levels.** The line the joke hangs on must not be the quietest, voices need pitches apart (a dog at 113 Hz under a 110 Hz narrator read as the same person), and peaks stay under -1 dB. `python3 SKILL/scripts/level.py <clips>` brings clips to one loudness (`--lufs`, default -18) under a limiter (`--peak`, default -1 dB) without moving a word, and leaves an already level clip, or one under 0.4 s (a tick, a clack), as it is, so the script can be rerun; it goes in the audio script right after `tts.py` and before `join.py`. A line that must sit above the rest (a quiet old man's punchline) gets its own target and stays out of the others' list (`level.py o1.mp3 --lufs -15`), so a rerun leaves it alone too; `--gain` adds again on every run, so it suits a one-off fix, not the script.
- **Sounds a voice makes.** Animal voices that speak (a dog's "Woof!") came out best from an Edge voice shouting the word, trimmed and normalized; synthesized barks lost to them. A whispered "Shh." is shaped pink noise, not Edge's voiced "shh-uh". Write such a clip over the line's MP3 and set its `dur` in `timings.js` before joining.
## Sound effects
-`sfx.py` synthesizes effects as small MP3s, free and consistent (knock, door, creak, bell, chop, crash, coin, rain, wind, room tone, surf, gulls, crickets, steps, a dog and more; `--list` names them all). Keep them soft and natural: the first rain was a high hiss and read as scary; pink noise with patter and taps on umbrellas read as rain.
+`sfx.py` synthesizes effects as small MP3s, free and consistent (knock, door, creak, bell, chop, crash, coin, rain, wind, room tone, surf, gulls, crickets, footsteps (`patter`, `step1`), a dog and more; `--list` names them all). A sound the list lacks goes in the book's own `books/<book>/sfx_recipes.py`, passed with `--recipes`: each top-level function without required arguments is a recipe named after it, returning samples at `sfx.SR`, built from sfx's own helpers, its docstring's first line shown by `--list` (the script's header has the details). Keep them soft and natural: the first rain was a high hiss and read as scary; pink noise with patter and taps on umbrellas read as rain.
- Place an effect on the scene clock with `sfx(scene, t, name, volume)`; it plays at half volume under the voices, a pause holds it and the next scene stops it.
- Cut an effect to its shot: a six-second rain under a one-second shot spills into the next.
-- A long bed (wind, room tone) is listed in `SFX_BED` with its length, so a seek into the middle joins it part-way; a bed that loops overlaps its seams by about half a second, and room tone runs under the silences too, where its absence is heard first.
+- A long bed (wind, room tone, the 10 s `birds` of a park) is listed in `SFX_BED` with its length (`SFX_BED.birds = 10`), so a seek into the middle joins it part-way; a bed that loops overlaps its seams by about half a second, and room tone runs under the silences too, where its absence is heard first.
## Music
diff --git a/.claude/skills/papermorph/references/stories.md b/.claude/skills/papermorph/references/stories.md
index a153594..ed9892d 100644
--- a/.claude/skills/papermorph/references/stories.md
+++ b/.claude/skills/papermorph/references/stories.md
@@ -55,7 +55,7 @@ Everybody in the shot stays alive and stays there: extras blink and glance about
A first cut made in one pass looks like a first cut. What lifts an episode is watching it the way a director would, against the episodes the user already approved, and sending scenes back.
-- **Director's view**: contact sheets of the whole episode beside an approved one. Look for story-level causes, not glitches: is every object the joke hangs on given its own shot, is the cause shown before the payoff, are the reactions framed so they read, is the shot density close to the approved episodes', does a silence stay silent? Write a restaging for each scene that needs one: which shots, from where, on which word.
+- **Director's view**: contact sheets of the whole episode and its cut sheet (`shot.py --cuts`) beside an approved one (a series' first episode: beside its storyboard). Look for story-level causes, not glitches: is every object the joke hangs on given its own shot, is the cause shown before the payoff, are the reactions framed so they read, is the shot density close to the approved episodes', does a silence stay silent? Write a restaging for each scene that needs one: which shots, from where, on which word.
- **Picture and sound**: frame by frame for faces cut by the edge, popping poses, puppets passing through each other; sound for lines cut short, effects out of step, music over a silence.
- Restage the scenes from those notes, then look again; two rounds usually settle it.
@@ -65,4 +65,4 @@ With subagents the reviewers run in parallel ([team.md](team.md#picture-books));
The episode is a first cut for the user's viewing, not a finished film. Deliver its URL with what was made, the final script, the decisions the user should review (every line or moment you added), known problems, and the real cost of pictures. Once the user approves it, add it to `approved` in `style.json` and to the series page, and set the previous episode's `CHAPTER.next`: when an episode's last scene ends, the player marks it watched and offers the next one.
-The series page is the book's `index.html`, made from [series.html](../assets/templates/picture-book/series.html): one card per episode with a still, its title and a line, and a mark on episodes already watched. A still is one frame of the episode (`shot.py`, or the page at `?beat=N&t=S`) saved as a 1400×788 WebP, like the cover image.
+The series page is the book's `index.html`, made from [series.html](../assets/templates/picture-book/series.html): one card per episode with a still, its title and a line, and a mark on episodes already watched. A still is one frame of the episode saved as a 1400×788 WebP: `shot.py chNN --out books/<book>/review/stills sceneN:S --webp 1400 --name still-chNN --url http://localhost:8765/<book>/` writes it without the player's controls (beside a full-size PNG); copy the WebP to `site/<book>/img/`. The page's header shows `img/cover.webp`, a still too: the first episode's, or a frame the user picks, until the series has a picture of its own.
diff --git a/.claude/skills/papermorph/references/team.md b/.claude/skills/papermorph/references/team.md
index 368b91a..39150cd 100644
--- a/.claude/skills/papermorph/references/team.md
+++ b/.claude/skills/papermorph/references/team.md
@@ -1,6 +1,10 @@
# Making a chapter with a team of models
-After the pilot, a chapter can be made by a coordinator handing each step of the chapter loop to a fresh subagent on the model that suits it. The chapter must reach the same bar as the book's approved chapters, in the same look (`style.json`), so it sits on the shelf beside them as one book.
+A chapter can be made by a coordinator handing each step of the chapter loop to a fresh subagent on the model that suits it; for the pilot the coordinator is the main conversation, which shows the user each sheet and choice.
+
+In the pilot, the narration and first beats made at intake (by the main conversation itself, before the models are agreed) are where steps 2 and 3 start, not something to redo. The picture worker stops when the storyboard sheet is ready and replies with it; the coordinator shows the sheet to the user, then continues the same worker with the user's changes to add motion. The chapter must reach the same bar as the book's approved chapters, in the same look (`style.json`), so it sits on the shelf beside them as one book.
+
+Wherever a step below names the previous or approved chapter as its model, a new book's first chapter (or a series' first episode) has none yet: use what the user agreed at intake (the pilot frames or sheet, the storyboard, `style.json`), the Skill's templates and the books on the shelf. The first chapter the user approves becomes the model from then on.
Why this shape: one agent doing a whole chapter carries an ever larger context through every call, and long idle waits make that context expire and get written again; that, more than the model's price, makes a chapter expensive. Small workers that start from the files they need and finish quickly cost far less, and each step can use the cheapest model that does it well. On a physics book this cost about half as much per minute of narration as one strong agent doing everything, at the same quality.
@@ -8,7 +12,7 @@ Each step runs on the model the user chose for it (`models` in `style.json`, agr
## The coordinator
-You read SKILL.md and this file, look at the storyboard sheet and the workers' replies, and pass work on. You don't write the chapter, read the page code or read workers' transcripts; keeping your own context small is most of the saving. A fresh session is the best coordinator: a long conversation rereads its whole history at every step.
+You read SKILL.md and this file, look at the storyboard sheet and the workers' replies, and pass work on. You don't write the chapter, read the page code or read workers' transcripts; keeping your own context small is most of the saving. After the pilot a fresh session is the best coordinator, starting from SKILL.md, this file and `style.json`: a long conversation rereads its whole history at every step.
Start each worker in the background with a short brief: the chapter and its pages, what to read, what to write, what not to touch, the preview URL (start one server for everyone), and a reply of a few lines. Workers don't commit. Pass work on as soon as a step returns.
@@ -18,7 +22,7 @@ Start each worker in the background with a short brief: the chapter and its page
2. **Narration — middle.** From chNN.md, [authoring.md](authoring.md), `style.json` and the previous approved chapter (its beat table and narration as the worked example): decide each flagged problem (`## Errata`), choose what to teach for the book's pacing (and say what was dropped), write the beat table (what the picture shows and does, each `[[mark]]` naming the word that triggers which action, where the eye goes, new visual elements needed), all questions, the narration file, then run `tts.py` and confirm every mark is in timings.js. The plan has to be concrete enough for a different model to build from.
3. **Picture — strong.** From the plan, `style.json`, the previous approved chapter's page and the book's library: storyboard layout first, then motion, camera and questions, new shared elements in the library, a quick self-view of the busiest beats and lint. The plan is a plan, not a cage. Storyboard and motion stay in one step: split, the next worker would have to read the whole page again.
- Look at the storyboard sheet yourself when it comes back; problems visible there are cheapest to name now.
-4. **Checks — small, report-only**, in parallel with 5: lint, `check_blank.py`, `overlap.py`, `still.py`, `perf.py` in Firefox, and an e2e test adapted from the previous chapter's, in Chromium and Firefox. It reports problems with beat and time and changes only its own test.
+4. **Checks — small, report-only**, in parallel with 5: lint, `check_blank.py`, `overlap.py`, `still.py`, `perf.py` in Firefox, and an e2e test adapted from the previous chapter's (the first from `assets/templates/e2e.py`), in Chromium and Firefox. It reports problems with beat and time and changes only its own test.
5. **Review — middle**, in parallel with 4: watch every beat as [review.md](review.md) describes, against the storyboard and the approved chapters. It fixes small local problems itself and lists larger ones with beat, time and a suggested fix. Its reply opens with the beats it watched; if some are missing, send it back to finish (continuing a worker is cheaper than starting one).
6. **Rework — strong, only for real problems** left by 4 and 5: a brief listing exactly those, re-checked with strips, `still.py`, lint and e2e in both browsers.
7. **Register — small.** Give it the exact edits: the contents entry, the previous chapter's `CHAPTER.next`, chapter counts on the cover, `chapters.md` and the status line in chNN.md. Then lint and e2e.
@@ -35,13 +39,14 @@ The same shape, split by scene instead of by step. The **strong** coordinator wr
- the episode kit's API, to read and not edit: a scene that needs more from the kit asks the coordinator, so every scene gets the fix;
- each scene's `pre`, its holes and the word times to cut on;
- continuity: who stands where, facing whom, in the first and last frame of every scene, so the cuts match;
-- the style, the effects available, how to look at one's own work, and the reply (the shots with their times, the first and last frame).
+- where things are: each set's places for puppets and props, its camera ranges, what comes into view on each pan. A painted set lands some way off its sketch (a bench seat about 30 px), so measure the places on frames of the painted set (`shot.py … --clean` gives the stage alone) and check the table on frames of every set before sending the brief out (a puppet at each place, the camera at each end of its range): in one episode a table written from the sketches put an ear off frame, feet below the ground and a tree trunk hiding the wrong side, and five workers built on it;
+- the style, the effects available, how to look at one's own work, and the reply (the shots with their times, the first and last frame, what each check showed).
-One **middle** worker per scene, in parallel, writes only its own `sceneN.js` and checks it with contact sheets and full-size frames of its close-ups; a **small** worker synthesizes the sound effects from recipes.
+One **middle** worker per scene, in parallel, writes only its own `sceneN.js`; a **small** worker synthesizes the sound effects from recipes. Before replying, a scene worker runs and reports on these, each with the book's `--url` (the screenshot scripts run with reduced motion, so the workers' browsers can run at once): a strip of its scene, with time ranges and `@o@c` for walks and hands ([review.md](review.md#watch-it-in-motion)); full-size `shot.py` frames of its close-ups and of each moment a hand arrives; `shot.py --cuts sceneN` for its cuts in and out; `playlog.py --from sceneN --to sceneN`, since it cannot listen: is each effect on the frame it belongs to, each line on a moving mouth; and `still.py chNN sceneN`, saying which still stretches are meant. A brief that only asked them to look was skipped by all five workers of one episode; named commands and a reply that reports what they showed get run.
Review comes in rounds ([stories.md](stories.md#review-rounds) says what to look for):
-- **Who**: four report-only reviewers watch the episode against the approved ones: a director (**strong**) for story, comedy, staging and shots; two picture reviewers (**middle**) splitting the scenes; one (**middle**) for sound and runtime.
+- **Who**: four report-only reviewers watch the episode against the approved ones (a series' first: its storyboard and brief): a director (**strong**) for story, comedy, staging and shots; two picture reviewers (**middle**) splitting the scenes; one (**middle**) for sound and runtime.
- **Reports**: each ranked: scene, beat-clock time, what is wrong as a viewer sees it, a concrete fix. Earlier good reports serve as examples.
- **Merging**: the coordinator turns the reports into one rework list, taking the director's side where reviewers disagree, fixes the kit itself and sends scenes back to their workers.
- **Closing**: the next round starts by checking which findings were fixed; a last read-only pass counts them as fixed, partly fixed, not fixed or worse. Two or three rounds made the best episodes. The rounds come before the user watches, and what the user says then still decides.
diff --git a/.claude/skills/papermorph/scripts/check_blank.py b/.claude/skills/papermorph/scripts/check_blank.py
index 27cb429..9a2744c 100644
--- a/.claude/skills/papermorph/scripts/check_blank.py
+++ b/.claude/skills/papermorph/scripts/check_blank.py
@@ -10,6 +10,8 @@ book_dir holds the chNN folders; --url is where that folder is served. For each
(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.
Otherwise it prints one line saying none were found. Exit status 1 when something is found.
+A lesson tool: a picture book's painted set is always on stage, so a picture-book chapter (paper.js loaded) is
+skipped with a note; check its openings with strip.py and still.py.
"""
import argparse, asyncio, os, sys
from pathlib import Path
@@ -40,12 +42,15 @@ PROBE = r"""
async def main(book: Path, chapters, url):
- found = []
+ found, checked = [], []
async with async_playwright() as p:
browser = await p.chromium.launch(**exe())
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)
+ if await pg.evaluate("typeof jit === 'function'"):
+ print(f"{ch}: a picture book, skipped (check_blank is for lessons; use strip.py and still.py)"); continue
+ checked.append(ch)
for i in range(await pg.evaluate("BEATS.length")):
r = await pg.evaluate(PROBE, i)
if r["ask"] or r["id"] == "finish":
@@ -60,7 +65,7 @@ async def main(book: Path, chapters, url):
await browser.close()
for row in found:
print(*row)
- if not found: print(f"no opening blanks in {', '.join(chapters)}")
+ if not found and checked: print(f"no opening blanks in {', '.join(checked)}")
return 1 if found else 0
diff --git a/.claude/skills/papermorph/scripts/engine.py b/.claude/skills/papermorph/scripts/engine.py
index 36695d2..038bb2a 100644
--- a/.claude/skills/papermorph/scripts/engine.py
+++ b/.claude/skills/papermorph/scripts/engine.py
@@ -9,9 +9,9 @@
python3 engine.py site/stats --latex # also MathJax, for a book whose chapters use TX()
The engine is not part of this skill: it is the engine/ folder of a repository, versioned by tags (engine-v2,
-engine-v2.0.1, ...; a new major number means books may need a change), and anyone may fork it. Without --from, the
-engine/ folder here or above the target is used (a checkout of that repository), otherwise DEFAULT, the latest major
-release; the source used is printed.
+engine-v2.1, ...; a new major number means books may need a change), and anyone may fork it. Without --from, the
+engine/ folder here or above the target is used (a checkout of that repository), otherwise DEFAULT, the latest release
+compatible with this Skill (its docs and the picture-book kit); the source used is printed.
Each book keeps a full copy in lib/, so it runs on its own; fix the engine at its source and sync, never edit the
copies. lib/book.css holds the book's own settings and overrides; it is created from the default and never
overwritten. MathJax (engine/vendor/mathjax) goes only into books that ask for it with --latex; after that, a book
@@ -20,7 +20,7 @@ with lib/mathjax.js keeps it in step like the rest.
import argparse, filecmp, io, shutil, sys, tarfile, tempfile, urllib.request
from pathlib import Path
-DEFAULT = 'DozenTwelve/Papermorph@engine-v2' # moves only with a major release
+DEFAULT = 'DozenTwelve/[email protected]' # follows the latest compatible release
OWN = 'book.css'
LATEX = {'vendor/mathjax/tex-svg-full.js': 'mathjax.js', 'vendor/mathjax/LICENSE': 'mathjax-LICENSE.txt'}
diff --git a/.claude/skills/papermorph/scripts/level.py b/.claude/skills/papermorph/scripts/level.py
new file mode 100644
index 0000000..2fe06dd
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/level.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Even out the levels of clips (voices, effects): bring each to one loudness and keep its peaks under a limiter.
+
+ python3 level.py site/<book>/ch01/audio/en/*.mp3 # every clip to -18 LUFS, in place
+ python3 level.py site/<book>/ch01/audio/en/o1.mp3 o2.mp3 --gain 3 # these clips 3 dB louder (not idempotent)
+ python3 level.py CLIPS --lufs -16 --peak -1.5 --out OUT_DIR # write the results to OUT_DIR instead
+
+Needs ffmpeg. Each clip is measured (EBU R128 integrated loudness and true peak), raised or lowered to --lufs (default
+-18, a speaking voice for headphones and laptop speakers), and run through a lookahead limiter with its delay
+compensated, so the clip keeps its length and every word stays where timings.js says; the encoded result is measured
+again and redone from the original until its true peak is at most --peak dBTP (default -1). A clip already within
+0.5 dB of the target with its peak at or under --peak is left alone, so a rerun touches only the clips tts.py
+regenerated (join.py's scene*.mp3 included): put it in the episode's audio script after tts.py and before join.py
+(which joins the levelled clips). A clip shorter than 0.4 s (a tick, a clack, a pop) has no integrated loudness and is
+left as it is with a note (--gain still applies to it). Effects from sfx.py are peak-normalised, not loudness-matched;
+level them with their own --lufs if a set of them sounds uneven. Prints, per clip, the loudness and peak before and
+after. --selftest checks all this on synthetic clips.
+"""
+import argparse, json, math, os, re, subprocess, sys, tempfile
+from pathlib import Path
+
+
+def measure(f):
+ """Integrated loudness (LUFS), true peak (dBTP), duration (s) and bit rate of a clip."""
+ r = subprocess.run(["ffmpeg", "-hide_banner", "-nostats", "-i", str(f), "-af", "loudnorm=print_format=json",
+ "-f", "null", "-"], capture_output=True, text=True, check=True)
+ m = json.loads(re.search(r"\{[^{}]*\"input_i\"[^{}]*\}", r.stderr).group(0))
+ p = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration,bit_rate", "-of", "json", str(f)],
+ capture_output=True, text=True, check=True)
+ fmt = json.loads(p.stdout)["format"]
+ return float(m["input_i"]), float(m["input_tp"]), float(fmt["duration"]), int(fmt.get("bit_rate") or 64000)
+
+
+def level(f, out, gain, limit, rate):
+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(f), "-af",
+ f"volume={gain:.2f}dB,alimiter=limit={10 ** (limit / 20):.4f}:level=0:latency=1",
+ "-b:a", f"{max(32, round(rate / 1000))}k", "-f", "mp3", str(out)], check=True)
+ return measure(out)
+
+
+def one(f, dest, a):
+ """Level clip f into dest (may be f itself); returns the line to print."""
+ i, tp, dur, rate = measure(f)
+ g = a.gain if a.gain is not None else a.lufs - i
+ head = f"{f.name:16s} {i:6.1f} LUFS {tp:5.1f} dBTP"
+ skip = ("too short to measure loudness, left as is" if not math.isfinite(g) else
+ "already level" if a.gain is None and abs(g) < .6 and tp <= a.peak + .05 else None)
+ if skip: # an unmeasurable clip gets no gain; a level one is not encoded again
+ if dest != f: dest.write_bytes(f.read_bytes())
+ return f"{head} {skip}"
+ tmp = dest.with_name(f".{dest.stem}.level.tmp") # beside dest, then replaced in one step
+ try:
+ lim = a.peak - .3 # MP3 encoding overshoots the limiter; measure and redo from the original until under --peak
+ for _ in range(6):
+ i2, tp2, dur2, _ = level(f, tmp, g, lim, rate)
+ off = a.lufs - i2 if a.gain is None else 0
+ if tp2 <= a.peak and abs(off) <= .3: break
+ if tp2 > a.peak: lim -= tp2 - a.peak + .2
+ if abs(off) > .3: g += off # the limiter took some of the loudness
+ os.replace(tmp, dest)
+ finally:
+ tmp.unlink(missing_ok=True)
+ warn = f" WARNING length {dur:.3f} -> {dur2:.3f} s" if abs(dur2 - dur) > .03 else ""
+ warn += f" WARNING peak {tp2:.1f} over {a.peak}" if tp2 > a.peak else ""
+ return f"{head} -> {i2:6.1f} LUFS {tp2:5.1f} dBTP ({g:+.1f} dB){warn}"
+
+
+def selftest():
+ """A 0.1 s tick, a 3 s clip whose clicks the limiter must hold, and a quiet one: the tick untouched, the others at target and under the ceiling with
+ their lengths kept, and a rerun leaves every file as it was."""
+ with tempfile.TemporaryDirectory() as d:
+ d = Path(d)
+ for name, src in (("tick", "sine=f=2000:d=0.1"), ("spiky", "aevalsrc='0.1*sin(2*PI*220*t)+0.95*lt(mod(t,0.5),0.003)':d=3"),
+ ("quiet", "sine=f=220:d=2.5,volume=-30dB")):
+ subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", src, "-ac", "1", "-ar", "44100", "-b:a", "64k",
+ str(d / f"{name}.mp3")], check=True)
+ clips = sorted(d.glob("*.mp3"))
+ before = {f: (f.read_bytes(), measure(f)) for f in clips}
+ a = argparse.Namespace(lufs=-18, gain=None, peak=-1)
+ print("\n".join(one(f, f, a) for f in clips))
+ assert (d / "tick.mp3").read_bytes() == before[d / "tick.mp3"][0], "a short clip is left alone"
+ after = {f: f.read_bytes() for f in clips}
+ for f in clips:
+ i, tp, dur, _ = measure(f)
+ assert abs(dur - before[f][1][2]) < .03, (f.name, "length")
+ if f.stem != "tick": assert abs(i + 18) < .6 and tp <= -1, (f.name, i, tp)
+ print("\n".join(one(f, f, a) for f in clips))
+ assert all(f.read_bytes() == after[f] for f in clips), "a rerun changes nothing"
+ assert not list(d.glob(".*")), "no temp files left"
+ print("level.py selftest passed")
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("clips", nargs="*", type=Path)
+ ap.add_argument("--lufs", type=float, default=-18, help="target integrated loudness (default -18)")
+ ap.add_argument("--gain", type=float, help="add this many dB instead of matching --lufs")
+ ap.add_argument("--peak", type=float, default=-1, help="ceiling for the encoded true peak in dBTP (default -1)")
+ ap.add_argument("--out", type=Path, help="write here instead of replacing the clips")
+ ap.add_argument("--selftest", action="store_true", help="check the levelling on synthetic clips")
+ a = ap.parse_args()
+ if a.selftest: return selftest()
+ if not a.clips: ap.error("give the clips to level")
+ if a.out:
+ a.out.mkdir(parents=True, exist_ok=True)
+ for f in a.clips:
+ print(one(f, (a.out / f.name) if a.out else f, a), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/.claude/skills/papermorph/scripts/lint.py b/.claude/skills/papermorph/scripts/lint.py
index da4277c..05c9853 100644
--- a/.claude/skills/papermorph/scripts/lint.py
+++ b/.claude/skills/papermorph/scripts/lint.py
@@ -30,6 +30,8 @@ ENGINE_FILES = {'engine.js', 'math.js', 'volume.js', 'contents.js', 'units.js'}
LOCAL = re.compile(r'[,(]\s*([A-Za-z_$][\w$]*)\s*=(?![=>])') # a, name = … or (p, name = 1): declared in a list
PARAMS = re.compile(r'function\s*[\w$]*\s*\(([^)]*)\)|\(([^()]*)\)\s*=>|([A-Za-z_$][\w$]*)\s*=>') # parameters
METHOD = re.compile(r'^\s*([A-Za-z_$][\w$]*)\s*\([^()]*\)\s*\{', re.M) # name(a, b) { … } in an object
+DESTRUCT = re.compile(r'(?:const|let|var)\s*([\[{][^;]*?[\]}])\s*(?:=|of\b|in\b)') # const {a, b: c, d = 1} = …, for (const [x, y] of …)
+DKEY = re.compile(r'[A-Za-z_$][\w$]*\s*:|=[^,\]}]*') # in a pattern, a key (b: c declares c) and a default (= 1) declare nothing
USE = re.compile(r'(?<![\w$.])([A-Za-z_$][\w$]*)(?![\w$])(?!\s*:)') # a name, not a property or an object key
@@ -114,7 +116,7 @@ def words(s):
def lint_chapter(ch, content, out):
err = lambda kind, msg: out.append(('E', kind, f'{ch.name}: {msg}'))
warn = lambda kind, msg: out.append(('W', kind, f'{ch.name}: {msg}'))
- html = (ch / 'index.html').read_text(encoding='utf-8')
+ html = re.sub(r'<!--.*?-->', '', (ch / 'index.html').read_text(encoding='utf-8'), flags=re.S) # a commented-out <script> loads nothing
inline = '\n'.join(INLINE.findall(html))
# globals: every script the page loads, in order
seen, own = {}, [inline] # own: the chapter's code and the book's scripts, not the engine's
@@ -143,6 +145,7 @@ def lint_chapter(ch, content, out):
code = [depth0(text)[0] for text in own]
local = {m.group(2) for c in code for m in DECL.finditer(c)} | {n for c in code for n in LOCAL.findall(c)}
local |= {n for c in code for n in METHOD.findall(c)}
+ local |= {n for c in code for d in DESTRUCT.findall(c) for n in re.findall(r'[A-Za-z_$][\w$]*', DKEY.sub(' ', d))}
local |= {n for c in code for p in PARAMS.findall(c) for n in re.findall(r'[A-Za-z_$][\w$]*', ''.join(p))}
used = sorted({w for c in code for w in USE.findall(c)} & names - local)
if used:
diff --git a/.claude/skills/papermorph/scripts/outline.py b/.claude/skills/papermorph/scripts/outline.py
index d376972..45992c1 100644
--- a/.claude/skills/papermorph/scripts/outline.py
+++ b/.claude/skills/papermorph/scripts/outline.py
@@ -10,7 +10,11 @@ title pages are put at the start of its first chapter, and "chapter_start" keeps
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.
+not by printed page numbers. A chapter bookmark that points outside the pages between
+its neighbours (a wrong target, e.g. page 1) is moved to the first page in that gap whose
+text contains its title (after "Chapter N:"; a page of the chapter before that mentions it
+wins too), or dropped so the chapter before it runs on; either way a warning names it: check
+that chapter's pages by hand. Two chapters on one page stop with "Fix by hand".
Without usable chapter bookmarks, render the contents using split_pages.py book.pdf
--pages 1-12, then write sections.json from those pages. Its JSON array covers every
@@ -21,6 +25,7 @@ Adjust boundaries to the actual PDF; start/end are inclusive PDF page numbers.
"""
import argparse
import json
+import re
import sys
from pathlib import Path
@@ -30,6 +35,32 @@ FLAT_PDF_HINT = ("Render contents with split_pages.py book.pdf --pages 1-12, "
"then write sections.json from them (schema: outline.py --help).")
+def repair(chapters, doc):
+ """Chapter bookmarks outside the longest run of rising pages (a wrong target): moved to the first page between
+ their neighbours whose text holds the title, or dropped (the chapter before runs on). Each repair is a warning."""
+ pages = [p for _, _, p in chapters]
+ best = [] # best[k]: the longest run of pages that ends at bookmark k, never falling (two on a page: fix by hand)
+ for k, p in enumerate(pages):
+ best.append(max((best[j] for j in range(k) if pages[j] <= p), key=len, default=[]) + [k])
+ keep = set(max(best, key=len))
+ out = []
+ for k, (i, title, page) in enumerate(chapters):
+ if k in keep:
+ out.append((i, title, page)); continue
+ lo = out[-1][2] if out else 0
+ hi = next((pages[j] for j in range(k + 1, len(pages)) if j in keep), len(doc) + 1)
+ key = " ".join(re.sub(r"^\s*(chapter|ch\.?)?\s*\d+[.:]?\s*", "", title, flags=re.I).split()).lower()
+ found = next((p for p in range(lo + 1, hi) if key and key in " ".join(doc[p - 1].get_text().split()).lower()), None)
+ if found:
+ print(f"WARNING bookmark {title!r} points to page {page}, outside {lo}-{hi}: "
+ f"put at page {found}, the first there that holds its title. Check it.", file=sys.stderr)
+ out.append((i, title, found))
+ else:
+ print(f"WARNING bookmark {title!r} points to page {page}, outside {lo}-{hi}, and its title is on no page "
+ "there: dropped, the chapter before runs on. Check it.", file=sys.stderr)
+ return out
+
+
def main():
# Captured output (a pipe) uses the system code page on Windows; bookmark titles may be any language.
for stream in (sys.stdout, sys.stderr):
@@ -56,6 +87,7 @@ def main():
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}.")
+ chapters = repair(chapters, doc)
# 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)
diff --git a/.claude/skills/papermorph/scripts/overlap.py b/.claude/skills/papermorph/scripts/overlap.py
index 1363912..4afcb23 100644
--- a/.claude/skills/papermorph/scripts/overlap.py
+++ b/.claude/skills/papermorph/scripts/overlap.py
@@ -8,6 +8,8 @@ Points every 3 px along each visible arrow (shaft and head, widened by half the
box of each visible text (getBBox trimmed to the glyph band, tested in the text's own, possibly rotated, frame).
Text pairs count when their ink boxes overlap by more than 4 px on every axis. Hits are merged into time ranges per
beat and element pair; look at those frames with strip.py. Runs in Firefox.
+A lesson tool: picture-book scenes have no SVG text or arrows (captions are HTML, signs are painted), so a
+picture-book chapter (paper.js loaded) is skipped with a note.
"""
import argparse, asyncio, json, sys
from playwright.async_api import async_playwright
@@ -86,8 +88,9 @@ MEASURE = r"""
async def run(pg, base, ch, step, only):
await pg.goto(f"{base}{ch}/?beat=0&t=0"); await pg.wait_for_timeout(800)
+ if await pg.evaluate("typeof jit === 'function'"): return None
beats = await pg.evaluate("BEATS.map(b => [b.id, !!b.ask])")
- res = {}
+ res = {"": len([1 for bid, ask in beats if not ask and (not only or bid in only)])} # beats sampled
for i, (bid, ask) in enumerate(beats):
if ask or (only and bid not in only): continue
hits = await pg.evaluate(MEASURE, [i, step])
@@ -116,10 +119,13 @@ async def main():
errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))
allres = {}
for ch in args:
- res = allres[ch] = await run(pg, base, ch, step, only)
+ res = await run(pg, base, ch, step, only)
+ if res is None:
+ print(f"== {ch}: a picture book, skipped (overlap.py is for lessons: films have no SVG text or arrows)"); continue
+ n = res.pop(""); allres[ch] = res
na = sum(1 for rows in res.values() for r in rows if r["kind"] == "arrow")
nt = sum(1 for rows in res.values() for r in rows if r["kind"] == "text")
- print(f"== {ch}: {na} arrow/text, {nt} text/text pairs in {len(res)} beats")
+ print(f"== {ch}: {na} arrow/text, {nt} text/text pairs, in {len(res)} of {n} beats sampled")
for bid, rows in res.items():
for r in rows:
rg = ", ".join(f"{a:g}" if a == c else f"{a:g}-{c:g}" for a, c in r["ranges"])
diff --git a/.claude/skills/papermorph/scripts/painted.py b/.claude/skills/papermorph/scripts/painted.py
index 5855037..366f7ed 100644
--- a/.claude/skills/papermorph/scripts/painted.py
+++ b/.claude/skills/papermorph/scripts/painted.py
@@ -11,7 +11,8 @@ opaque part and placed by its left x, bottom y and width, so characters can stan
parallax factor as in the sketch (1, the puppets' plane, if left out). The padding mirrors the picture's edges; a layer
with "edge": "stretch" repeats its outermost pixels instead (when something near the edge, a post box, would show
twice). Words for signs and boards
-(the model leaves them blank) are written onto the picture. Props go to SITE/img/props/<name>.webp. Run bake_sets.py
+(the model leaves them blank) are written onto the picture. sets.js is rewritten after each set, so if a set fails the
+sets before it are done and the rest keep their old files and entries. Props go to SITE/img/props/<name>.webp. Run bake_sets.py
first (it rewrites sets.js); run this again after any change. Paths in the manifest are relative to the manifest.
{
@@ -112,9 +113,8 @@ def main(manifest, site):
for n, im in made:
im.save(out / f'{n}.webp', quality=88, method=6)
im.filter(ImageFilter.GaussianBlur(6)).save(out / f'{n}-soft.webp', quality=80, method=6)
- sets[name] = entry
- sets_js.parent.mkdir(parents=True, exist_ok=True)
- sets_js.write_text('window.SETS = ' + json.dumps(sets) + ';\n')
+ sets[name] = entry # sets.js follows each finished set, so a later failure leaves files and entries in step
+ tmp = sets_js.with_suffix('.tmp'); tmp.write_text('window.SETS = ' + json.dumps(sets) + ';\n'); tmp.replace(sets_js)
props = pathlib.Path(site) / 'img/props'; props.mkdir(parents=True, exist_ok=True)
for name, src in m.get('props', {}).items():
im = tight(Image.open(base / src).convert('RGBA')); im.thumbnail((800, 800), Image.LANCZOS)
diff --git a/.claude/skills/papermorph/scripts/playlog.py b/.claude/skills/papermorph/scripts/playlog.py
new file mode 100644
index 0000000..0a0dcd8
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/playlog.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Play a chapter headless in real time and log every sound start and caption line with its beat time, plus a frame
+at each: checking sound against picture without ears.
+
+ uv run --with playwright --with pillow playlog.py ch01 --out OUT --url http://localhost:8765/<book>/
+ ... --rate 1.5 play faster (effects and voices follow the speed; beat times stay the same)
+ ... --from scene3 start at that beat (index from 0 or id) instead of the beginning
+ ... --to scene3 stop when that beat ends instead of at the end (--from scene3 --to scene3: one scene)
+
+Prints and writes OUT/chNN_playlog.txt, one event a line, and OUT/chNN_playlog.jpg, the stage at each event's beat
+time with its label (four a row):
+
+ scene1 0.60 voice en/scene1.mp3
+ scene1 1.12 line Every afternoon, the old man plays chess in the park.
+ scene1 8.41 sfx clack vol 0.50
+
+voice/sfx/bgm: an audio file started playing (its folder under audio/ names the kind; vol is the element's volume
+when it started, the slider at 1). line: the caption changed (captions are switched on for the run). An effect
+listed twice at one moment plays twice. Look at each frame: is the clack on the frame where the piece lands, the
+slurp where the cup is at the mouth, the line where that character's mouth moves? Effects fire only in normal
+playback, never on a seek, which is why this plays the chapter instead of seeking it. Chromium; if it cannot play
+sound, the engine runs on wall time and the log says so (times are then still beat times).
+"""
+import argparse, asyncio, io, sys
+from pathlib import Path
+from playwright.async_api import async_playwright
+from browsers import exe
+from PIL import Image, ImageDraw
+
+HOOK = r"""
+window.__log = [];
+try { localStorage.setItem('captions', '1'); } catch {}
+const play0 = HTMLMediaElement.prototype.play;
+HTMLMediaElement.prototype.play = function () {
+ try {
+ if (this.paused && !this.muted && typeof P !== 'undefined' && P.playing) { // a real start (not a resume of a playing clip, not the silent unlock)
+ const src = decodeURI(new URL(this.currentSrc || this.src, location.href).pathname).replace(/^.*?\/audio\//, '');
+ __log.push({ kind: /^sfx\//.test(src) ? 'sfx' : /^bgm\//.test(src) ? 'bgm' : 'voice', what: src.replace(/^(sfx|bgm)\//, '').replace(/\.mp3$/, ''),
+ i: P.i, t: P.t, vol: this.volume });
+ }
+ } catch {}
+ return play0.apply(this, arguments);
+};
+addEventListener('DOMContentLoaded', () => {
+ const c = document.getElementById('caption'); if (!c) return;
+ let last = '';
+ new MutationObserver(() => { const s = c.hidden ? '' : c.textContent.trim();
+ if (s && s !== last && P.playing) __log.push({ kind: 'line', what: s, i: P.i, t: P.t }); last = s; })
+ .observe(c, { childList: true, characterData: true, subtree: true, attributes: true });
+});
+"""
+
+
+async def main(a):
+ a.out.mkdir(parents=True, exist_ok=True)
+ async with async_playwright() as p:
+ x = exe(); x["args"] = list({*x.get("args", []), "--autoplay-policy=no-user-gesture-required"})
+ b = await p.chromium.launch(**x)
+ pg = await b.new_page(viewport={"width": 1600, "height": 960}, reduced_motion="reduce")
+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))
+ await pg.add_init_script(HOOK)
+ url = f"{a.url}{a.chapter}/index.html"
+ await pg.goto(url); await pg.wait_for_timeout(1000)
+ ids = await pg.evaluate("BEATS.map(b => b.id)")
+ def beat(s):
+ if s.isdigit() and int(s) < len(ids): return int(s)
+ if s in ids: return ids.index(s)
+ sys.exit(f"no beat {s!r}: give an index from 0 to {len(ids) - 1} or one of {', '.join(ids)}")
+ first, last = beat(a.start), beat(a.end) if a.end else len(ids) - 1
+ if last < first: sys.exit(f"--to {a.end} comes before --from {a.start}")
+ total = await pg.evaluate(f"BEATS.slice({first}, {last + 1}).reduce((s, b) => s + (b.pre || 0) + TIMINGS[b.id].dur + 1, 0)")
+ if first: await pg.goto(f"{url}?beat={first}&t=0"); await pg.wait_for_timeout(1000)
+ await pg.keyboard.press("Space"); await pg.wait_for_timeout(200) # a real key press: the browser lets it start sound
+ if a.rate != 1: await pg.evaluate(f"typeof setSpeed === 'function' ? setSpeed({a.rate}) : (P.rate = {a.rate})")
+ print(f"playing {a.chapter} from {ids[first]} to {ids[last]}, about {total / a.rate:.0f} s", flush=True)
+ waited, stop = 0, f"P.done || P.waiting || P.i > {last}"
+ while not await pg.evaluate(stop) and waited < total / a.rate + 30:
+ await pg.wait_for_timeout(250); waited += .25
+ log, afail = await pg.evaluate(f"[__log.filter(e => e.i <= {last}), P.afail]")
+ if not await pg.evaluate(f"P.done || P.i > {last}"): print(f"did not reach the end of {ids[last]} (a question waits, or it stalled)")
+ # the frames: each beat rebuilt once and its clock run forward, as playback reaches it
+ shots = []
+ await pg.add_style_tag(content=".paused-mark { display: none !important; }") # the frames are taken paused
+ for e in sorted(log, key=lambda e: (e["i"], e["t"])):
+ if not shots or shots[-1][0]["i"] != e["i"]:
+ await pg.evaluate(f"seek({e['i']}, false)")
+ await pg.evaluate(f"P.t = {e['t']}; evalTo({e['t']})"); await pg.wait_for_timeout(120)
+ r = await pg.evaluate("(() => { const r = document.getElementById('stage').getBoundingClientRect(); return {x: r.x, y: r.y, width: r.width, height: r.height}; })()")
+ shots.append((e, Image.open(io.BytesIO(await pg.screenshot(clip=r))).convert("RGB").resize((400, 225))))
+ await b.close()
+ lines = [f"{ids[e['i']]:10} {e['t']:6.2f} {e['kind']:5} {e['what']}" + (f" vol {e['vol']:.2f}" if e['kind'] == 'sfx' else '') for e, _ in shots]
+ if afail: lines.append("note: sound did not play in this browser; the clock ran on wall time")
+ (a.out / f"{a.chapter}_playlog.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
+ print("\n".join(lines))
+ if shots:
+ S = Image.new("RGB", (1600, 225 * ((len(shots) + 3) // 4)), (20, 30, 27))
+ for k, (e, im) in enumerate(shots):
+ d = ImageDraw.Draw(im); label = f"{ids[e['i']]} {e['t']:.2f} {e['kind']} {e['what'][:40]}"
+ d.rectangle((0, 0, 7 * len(label) + 8, 16), fill=(0, 0, 0)); d.text((4, 3), label, fill=(255, 230, 120))
+ S.paste(im, ((k % 4) * 400, (k // 4) * 225))
+ S.save(a.out / f"{a.chapter}_playlog.jpg", quality=84)
+ print(f"{len(shots)} events | log and frames in {a.out}" + (f" | PAGE ERRORS: {errs[:5]}" if errs else ""))
+ return 1 if errs else 0
+
+
+if __name__ == "__main__":
+ for stream in (sys.stdout, sys.stderr):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("chapter", help="chapter folder under --url, e.g. ch01")
+ ap.add_argument("--out", type=Path, required=True, help="folder for the log and the frames")
+ ap.add_argument("--url", default="http://localhost:8765/")
+ ap.add_argument("--rate", type=float, default=1, help="playback speed (the player offers .75, 1, 1.25, 1.5)")
+ ap.add_argument("--from", dest="start", default="0", help="first beat, index from 0 or id")
+ ap.add_argument("--to", dest="end", help="last beat, index from 0 or id (default: the last)")
+ a = ap.parse_args()
+ a.url = a.url if a.url.endswith("/") else a.url + "/"
+ sys.exit(asyncio.run(main(a)))
diff --git a/.claude/skills/papermorph/scripts/sfx.py b/.claude/skills/papermorph/scripts/sfx.py
index dbe2b36..4d87bac 100644
--- a/.claude/skills/papermorph/scripts/sfx.py
+++ b/.claude/skills/papermorph/scripts/sfx.py
@@ -4,21 +4,31 @@
uv run --with numpy python sfx.py site/<book>/ch01/audio/sfx knock door rain # these effects, OUT_DIR/<name>.mp3
uv run --with numpy python sfx.py site/<book>/ch01/audio/sfx all # every recipe
uv run --with numpy python sfx.py --list # names with a one-line description
+ uv run --with numpy python sfx.py OUT_DIR splat --recipes books/<book>/sfx_recipes.py # with the book's own recipes
+ uv run --with numpy python sfx.py --selftest # checks the --recipes loading
Needs ffmpeg. Every file is faded (5 ms) and peak-normalised to -3 dBFS; each recipe is seeded by its name, so a name
always renders the same sound. Play them from a chapter with sfx(beat, seconds, 'name', volume) (paper-cutout kit,
-shared.js), which plays them at half volume under the voices.
-
-Add a recipe: write a function that returns a float array at SR, built from the small toolkit below (t_of, unit, place,
-lp1/hp1/bpf filters, pluck, pink, drops), and list it in RECIPES. Keep them soft and natural: a hard high hiss reads
-as "scary rain" and a bare sine as a phone, so layer a low thump under a click, shape every sound with a decay, and
-listen before using one. Recipes: sting growl gulp door tick bell whoosh fly violin crickets chair (character and
-house sounds), knock chop bang bonk thud crash (wood, axe, glass, a wardrobe door), plop sniff chomp burp lick bark
-(eating and a dog), chime beep card coin (a convenience store), rain and rain-short (gentle rain), creak latch sash
-shutter flap clang scrape (doors, windows, a shutter, cardboard, a steel bowl), inhale inhale-short (a breath in),
-patter patter1 step1 (light steps, one step, a grown-up's shoe), honk gulls gull1 (a penguin or goose, seagulls,
-one gull), crack clop (a whip, hooves), bark-big woof-mf yip (a big dog, a smothered bark, a puppy), and beds:
-wind (8 s), surf (30 s), room (3 s room tone that tiles every 2.6 s).
+shared.js), which plays them at half volume under the voices. Even out voices and effects afterwards with level.py.
+
+A book's own recipes: --recipes FILE.py (repeatable) imports FILE; every top-level function in it that takes no
+required argument and whose name does not start with _ becomes a recipe (underscores in the name become hyphens; the
+docstring's first line is its --list line; a book recipe replaces a built-in of the same name). Build them from this
+module (`from sfx import SR, t_of, unit, place, smooth, lp1, hp1, bpf, pluck, pink, drops, noise`; draw randomness
+from `noise(n)` or `sfx.rng`, which is seeded per recipe) and keep them in the book's folder, not in a copy of this script.
+
+Add a recipe here: write a function that returns a float array at SR, built from the small toolkit below (t_of, unit,
+place, smooth, lp1/hp1/bpf filters, pluck, pink, drops), and list it in RECIPES. Keep them soft and natural: a hard
+high hiss reads as "scary rain" and a bare sine as a phone, so layer a low thump under a click, shape every sound with
+a decay, and listen before using one. Recipes: sting growl gulp door tick bell whoosh fly violin crickets chair
+(character and house sounds), knock chop bang bonk thud crash (wood, axe, glass, a wardrobe door), clack chalk page
+(a game piece set down, a chalk line, a page turned), plop sniff chomp burp lick slurp hmph bark (eating, drinking, a
+nose, a dog), laugh applause (a person laughing, a small audience clapping), splash pop boing (water, a cork, a
+spring), chime beep card coin (a convenience store), rain and rain-short (gentle rain), creak latch sash shutter flap
+clang scrape (doors, windows, a shutter, cardboard, a steel bowl), inhale inhale-short (a breath in), patter patter1
+step1 (light steps, one step, a grown-up's shoe), honk gulls gull1 (a penguin or goose, seagulls, one gull), crack
+clop (a whip, hooves), bark-big woof-mf yip (a big dog, a smothered bark, a puppy), and beds: wind (8 s), surf (30 s),
+room (3 s room tone that tiles every 2.6 s), birds (10 s park with distant birds; 0.4 s fades, tiles every 9.6 s).
"""
import math
import os
@@ -106,7 +116,13 @@ def drops(n, rate, fc, q, decay, lo, hi):
return y
-noise = lambda n: rng.standard_normal(n)
+def noise(n):
+ return rng.standard_normal(n)
+
+
+def smooth(x, n=40):
+ """Moving average over n samples: a soft, cheap low-pass that keeps the length."""
+ return np.convolve(x, np.ones(n) / n, mode="same")
def sting():
@@ -641,10 +657,131 @@ def woof_mf():
return y
+def clack():
+ """A wooden game piece set down on a wooden board: a dry click, a short hollow ring, a tiny settle, 0.25 s."""
+ y, t = np.zeros(int(.25 * SR)), t_of(.12)
+ click = unit(smooth(hp1(noise(len(t)), 1800), 4) * np.exp(-t / .0012))
+ ring = unit(bpf(noise(len(t)), 1250, q=9) * np.exp(-t / .022))
+ body = unit(np.sin(2 * np.pi * 520 * t) * np.exp(-t / .018))
+ place(y, .55 * click + .7 * ring + .35 * body, .005)
+ place(y, .18 * ring[:int(.05 * SR)] * np.exp(-t[:int(.05 * SR)] / .01), .04) # the felt base settles
+ return y
+
+
+def chalk():
+ """A chalk line on wood or a board, 0.55 s: a gritty scratch with a faint squeak riding on it."""
+ t = t_of(.55)
+ grit = smooth(bpf(noise(len(t)), 2000, q=2.2), 10) * np.repeat(rng.uniform(.35, 1, int(np.ceil(.55 / .006))), int(.006 * SR))[:len(t)]
+ f = 2300 + 260 * np.sin(2 * np.pi * 3 * t) + 80 * noise(len(t)).cumsum() / SR
+ squeak = np.sin(2 * np.pi * np.cumsum(f) / SR) * (.5 + .5 * np.sin(2 * np.pi * 45 * t)) ** 2
+ env = np.minimum(t / .03, 1) * np.minimum((.55 - t) / .08, 1)
+ return (unit(grit) * .8 + unit(squeak) * .22) * env
+
+
+def slurp():
+ """A sip of something hot, 0.7 s: an airy suck rising in pitch, a little bubbly."""
+ t = t_of(.7)
+ air = bpf(noise(len(t)), 700 + 1300 * (t / .7) ** .7, q=2.5)
+ bub = .55 + .45 * np.sign(np.sin(2 * np.pi * np.cumsum(32 + 20 * rng.random(len(t))) / SR))
+ return unit(smooth(air * bub)) * np.sin(np.pi * t / .7) ** .7
+
+
+def hmph():
+ """A small offended 'hmph' through the nose, 0.4 s: a short low hum under a breath out."""
+ t = t_of(.4)
+ s = 2 * ((np.cumsum(175 - 55 * t / .4) / SR) % 1) - 1
+ hum = bpf(s, 260, q=2) + .25 * bpf(s, 1100, q=4)
+ breath = smooth(bpf(noise(len(t)), 650, q=1.6), 24)
+ return (unit(hum) * .7 + unit(breath) * .6) * np.minimum(t / .012, 1) * np.exp(-t / .11)
+
+
+def birds(dur=10.0):
+ """A park in the afternoon, 10 s bed: a soft far wash with a few distant birds; 0.4 s fades, so tiles every 9.6 s overlap."""
+ t = t_of(dur)
+ n = len(t)
+ f = np.fft.rfftfreq(n, 1 / SR)
+ f[0] = 1
+ wash = unit(np.fft.irfft(np.fft.rfft(noise(n)) / np.sqrt(f) * (f > 60) / (1 + (f / 900) ** 2), n)) * .35
+ y = np.zeros(n)
+ for _ in range(int(.9 * dur)): # phrases of two to five chirps
+ at, f0, g = rng.uniform(.3, dur - 1), rng.uniform(3000, 4800), rng.uniform(.25, .6)
+ for k in range(rng.integers(2, 6)):
+ d = rng.uniform(.05, .11)
+ c = t_of(d)
+ sweep = f0 * (1 + .25 * np.sin(np.pi * c / d)) * rng.uniform(.92, 1.08)
+ place(y, np.sin(2 * np.pi * np.cumsum(sweep) / SR) * np.sin(np.pi * c / d) ** 2 * g, min(at + k * rng.uniform(.12, .2), dur - .3))
+ y = bpf(y, 3800, q=.8) # distance takes the edge off
+ return (wash + unit(y) * .5) * np.minimum(t / .4, 1) * np.minimum((dur - t) / .4, 1)
+
+
+def laugh():
+ """A warm laugh, 1.2 s: five breathy 'ha's falling in pitch and getting softer."""
+ y = np.zeros(int(1.2 * SR))
+ for k in range(5):
+ d = .13 - .008 * k
+ t = t_of(d)
+ ph = np.cumsum(240 - 18 * k - 40 * t / d) / SR
+ src = 2 * (ph % 1) - 1
+ voiced = bpf(src, 750, q=3) + .7 * bpf(src, 1200, q=4) + .25 * bpf(src, 2600, q=5)
+ h = bpf(noise(len(t)), 1400, q=1) * np.exp(-t / .02) # the breathy 'h' at each onset
+ env = np.minimum(t / .015, 1) * np.minimum((d - t) / .04, 1)
+ place(y, (unit(voiced) + .5 * unit(h)) * env * (1 - .13 * k), .02 + k * .19)
+ return y
+
+
+def applause(dur=3.0):
+ """A small audience clapping, 3 s: many hands at their own pace, swelling in and dying away."""
+ t = t_of(dur)
+ y = np.zeros(len(t))
+ for _ in range(18): # 18 people clapping 3-5 times a second
+ rate, at, fc = rng.uniform(3, 5), rng.uniform(0, .4), rng.uniform(1100, 2200)
+ while at < dur - .1:
+ c = t_of(.05)
+ place(y, unit(bpf(noise(len(c)), fc, q=1.3)) * np.exp(-c / .008) * rng.uniform(.5, 1), at)
+ at += rng.normal(1 / rate, .02)
+ return y * np.minimum(t / .3, 1) * np.minimum((dur - t) / 1.2, 1)
+
+
+def splash():
+ """Something dropped into water, 0.9 s: a low plunge, a spray of noise and droplets falling back."""
+ t = t_of(.9)
+ n = len(t)
+ plunge = lp1(noise(n), 400) * np.exp(-t / .08)
+ spray = bpf(noise(n), 1800, q=.8) * np.minimum(t / .01, 1) * np.exp(-t / .18)
+ y = unit(plunge) * .7 + unit(spray) * .6 + unit(drops(n, 40, 1500, 6, .01, .3, 1)) * .3 * np.exp(-t / .5)
+ return y
+
+
+def page():
+ """A page turned, 0.5 s: a papery swish that rises and lands with a soft flap."""
+ t = t_of(.5)
+ crinkle = np.repeat(rng.uniform(.4, 1, int(np.ceil(.5 / .008))), int(.008 * SR))[:len(t)]
+ swish = unit(bpf(noise(len(t)), 1200 + 2400 * t / .5, q=1.1)) * crinkle * np.sin(np.pi * t / .5) ** 1.5
+ k = t_of(.06)
+ place(swish, unit(bpf(noise(len(k)), 500, q=1.2)) * np.exp(-k / .015) * .6, .42)
+ return swish
+
+
+def pop():
+ """A cork or a bubble popping, 0.2 s: a click and a quick hollow drop in pitch."""
+ t = t_of(.2)
+ tone = np.sin(2 * np.pi * np.cumsum(700 * np.exp(-t / .03) + 250) / SR) * np.exp(-t / .03)
+ return unit(tone) + .5 * unit(hp1(noise(len(t)), 2500) * np.exp(-t / .0015))
+
+
+def boing():
+ """A spring, 0.8 s: a low twang whose pitch wobbles fast and settles."""
+ t = t_of(.8)
+ f = 170 * (1 + .35 * np.exp(-t / .25) * np.sin(2 * np.pi * 11 * t))
+ ph = 2 * np.pi * np.cumsum(f) / SR
+ return unit(np.sin(ph) + .3 * np.sin(2 * ph)) * np.minimum(t / .005, 1) * np.exp(-t / .3)
+
+
RECIPES = {name: globals()[name] for name in (
"sting growl gulp door tick bell whoosh fly violin crickets chair knock chop bang bonk thud crash plop sniff "
"chomp burp lick bark chime beep card coin rain creak latch clang shutter sash flap scrape inhale wind room "
- "honk gulls surf patter step1 crack clop gull1 yip").split()}
+ "honk gulls surf patter step1 crack clop gull1 yip clack chalk slurp hmph birds laugh applause splash page pop "
+ "boing").split()}
RECIPES["bark-big"] = bark_big
RECIPES["woof-mf"] = woof_mf
RECIPES["rain-short"] = lambda: rain(1.15, .12)
@@ -674,24 +811,88 @@ def write_mp3(path, y):
"-b:a", "128k", str(path)], check=True)
-def main(argv):
+def load_recipes(path):
+ """Import a book's recipe file and add its recipes to RECIPES; returns their names."""
+ import importlib.util
+ import inspect
+ sys.modules.setdefault("sfx", sys.modules[__name__]) # `import sfx` in the file gets this module, not a second copy
+ spec = importlib.util.spec_from_file_location(f"sfx_book_{zlib.crc32(os.path.abspath(path).encode())}", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ added = []
+ for name, fn in vars(mod).items():
+ if name.startswith("_") or not inspect.isfunction(fn) or fn.__module__ != mod.__name__:
+ continue
+ if any(p.default is p.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)
+ for p in inspect.signature(fn).parameters.values()):
+ continue # a helper that needs arguments, not a recipe
+ RECIPES[name.replace("_", "-")] = fn
+ added.append(name.replace("_", "-"))
+ return added
+
+
+def render(name):
global rng
- if argv == ["--list"]:
+ rng = np.random.default_rng(zlib.crc32(name.encode()))
+ return RECIPES[name]()
+
+
+BOOK_TEST = '''import numpy as np
+from sfx import SR, t_of, unit, noise
+def _hidden():
+ return np.zeros(10)
+def helper(x):
+ return x
+def tap_tap(dur=.1):
+ "Two taps."
+ return unit(noise(len(t_of(dur))))
+def knock():
+ "A book's own knock."
+ return np.ones(SR // 10)
+'''
+
+
+def selftest():
+ """--recipes: a book file's recipes register (helpers and imports do not), override built-ins, render repeatably."""
+ with tempfile.TemporaryDirectory() as d:
+ f = os.path.join(d, "book.py")
+ with open(f, "w") as fh:
+ fh.write(BOOK_TEST)
+ assert load_recipes(f) == ["tap-tap", "knock"]
+ assert "helper" not in RECIPES and "_hidden" not in RECIPES and "unit" not in RECIPES
+ a, b = render("tap-tap"), render("tap-tap")
+ assert len(a) == 4410 and np.array_equal(a, b)
+ assert np.all(render("knock") == 1)
+ print("sfx selftest ok")
+
+
+def main(argv):
+ import argparse
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("out", nargs="?", help="folder for <name>.mp3 (the chapter's audio/sfx)")
+ ap.add_argument("names", nargs="*", help="recipe names, or all")
+ ap.add_argument("--recipes", action="append", default=[], metavar="FILE.py", help="a book's own recipes")
+ ap.add_argument("--list", action="store_true", help="print the recipe names with a one-line description")
+ ap.add_argument("--selftest", action="store_true", help="check the --recipes loading")
+ a = ap.parse_args(argv)
+ if a.selftest:
+ return selftest()
+ for f in a.recipes:
+ load_recipes(f)
+ if a.list:
for name, fn in RECIPES.items():
doc = (fn.__doc__ or "").strip().splitlines()
print(f"{name:14s}{doc[0] if doc else ''}")
return
- if len(argv) < 2 or argv[0] in ("-h", "--help"):
- print(__doc__)
- sys.exit(0 if argv[:1] in (["-h"], ["--help"]) else 2)
- out, names = argv[0], (list(RECIPES) if argv[1:] == ["all"] else argv[1:])
+ if not a.out or not a.names:
+ ap.error("give an output folder and recipe names (or all)")
+ names = list(RECIPES) if a.names == ["all"] else a.names
unknown = [n for n in names if n not in RECIPES]
if unknown:
sys.exit(f"unknown: {', '.join(unknown)} (sfx.py --list)")
- os.makedirs(out, exist_ok=True)
+ os.makedirs(a.out, exist_ok=True)
for name in names:
- rng = np.random.default_rng(zlib.crc32(name.encode()))
- write_mp3(os.path.join(out, name + ".mp3"), RECIPES[name]())
+ write_mp3(os.path.join(a.out, name + ".mp3"), render(name))
print("wrote", name)
diff --git a/.claude/skills/papermorph/scripts/shot.py b/.claude/skills/papermorph/scripts/shot.py
index 2e8f464..af1db1e 100644
--- a/.claude/skills/papermorph/scripts/shot.py
+++ b/.claude/skills/papermorph/scripts/shot.py
@@ -1,28 +1,46 @@
#!/usr/bin/env python3
-"""Screenshot beats of a chapter for review, plus contact sheets of four shots each.
+"""Screenshot beats of a chapter for review, plus contact sheets of four shots each; cut sheets and clean stills.
- uv run --with playwright --with pillow shot.py ch07 # every beat at 1.2 s (open) and its end
- uv run --with playwright --with pillow shot.py ch07 --moments mid # add the middle of every beat
- 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
+ uv run --with playwright --with pillow shot.py ch07 --out OUT # every beat at 1.2 s (open) and its end
+ uv run --with playwright --with pillow shot.py ch07 --out OUT --moments mid # add the middle of every beat
+ uv run --with playwright --with pillow shot.py ch07 --out OUT 3:end 5:4.5 scene2:mid # chosen moments
+ uv run --with playwright --with pillow shot.py ch01 --out OUT --cuts # cut sheet of a picture book
+ uv run --with playwright --with pillow shot.py ch01 --out OUT --cuts scene3 # only the cuts into and out of scene3
+ uv run --with playwright --with pillow shot.py ch01 --out books/<book>/review/stills 2:9 --webp 1400 --name still-ch01 # copy the .webp to site/<book>/img/
+ ... --url http://localhost:8765/<book>/
-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.
+A moment is BEAT:TIME. BEAT is the beat's index in BEATS counted from 0 (the player shows BEAT+1) or its id;
+TIME is seconds on the beat clock, open (1.2 s), mid (half the beat) or end (the beat's last frame, P.end - 0.05:
+the picture the next beat cuts from). Writes OUT/chNN_bII_T.png and OUT/chNN_sheet_T_K.png (2x2, half size; open
+the sheets first). --out is required: give each review its own folder (books/<book>/review/...).
+
+ --clean the stage alone: no player bar, captions, cards or notes, cropped to the 1600x900 stage
+ --cuts [BEAT ...] a cut sheet, OUT/chNN_cuts.jpg: for every beat boundary, the last frame of the beat beside the
+ first frame of the next (clean), one boundary a row; with beats, only the boundaries into and out of
+ them (OUT/chNN_cuts_BEAT.jpg). Look for jumps in place, pose, light and screen direction
+ --webp W also write each shot as a W-wide 16:9 WebP (implies --clean): a series-page still or a cover
+ (stories.md: 1400 wide); --name NAME names it OUT/NAME.webp (one moment only)
+
+Uses ?beat=N&t=0, then sets the beat clock to the moment, as playback would reach it. The page runs with reduced
+motion, which stops the CSS-only motion that runs on the wall clock (page cross-fades, cards sliding in, the mascot):
+a shot is the same picture however busy the machine is, so several runs at once (parallel scene workers) are safe.
"""
-import argparse, asyncio
+import argparse, asyncio, io
import sys
from pathlib import Path
from playwright.async_api import async_playwright
from browsers import exe
-from PIL import Image
+from PIL import Image, ImageDraw
+
+CLEAN = """#bar, #caption, #ui, #soundNote, #help, #cover, .paused-mark { display: none !important; }
+#frame { border-radius: 0 !important; box-shadow: none !important; }"""
async def main(a):
a.out.mkdir(parents=True, exist_ok=True)
async with async_playwright() as p:
b = await p.chromium.launch(**exe())
- pg = await b.new_page(viewport={"width": 1600, "height": 960})
+ pg = await b.new_page(viewport={"width": 1600, "height": 960}, reduced_motion="reduce")
errs = []
pg.on("pageerror", lambda e: errs.append(str(e)))
# a desktop browser ($CHROME) also asks the server for /favicon.ico, which is not the book's
@@ -31,26 +49,67 @@ async def main(a):
await pg.goto(base + "?beat=0&t=0"); await pg.wait_for_timeout(500)
if errs:
print("page errors:", errs); await b.close(); return 1
- n = await pg.evaluate("BEATS.length")
- durs = await pg.evaluate("BEATS.map(b => (b.pre || 0) + TIMINGS[b.id].dur)") # a picture book's scene starts `pre` s before its speech
- specs = a.specs or [f"{i}:{t}" for t in ("open", "end", *a.moments) 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)
+ ids = await pg.evaluate("BEATS.map(b => b.id)")
+
+ async def grab(i, t, clean):
+ """The picture of beat i at t (seconds, open, mid, end) as an RGB image, and the time used."""
+ await pg.goto(f"{base}?beat={i}&t=0"); await pg.wait_for_timeout(300)
+ end = await pg.evaluate("P.end")
+ sec = {"open": 1.2, "end": end - .05, "mid": end / 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)
+ await pg.evaluate(f"P.t = {sec}; evalTo({sec})")
+ if clean: await pg.add_style_tag(content=CLEAN)
+ await pg.wait_for_timeout(450)
+ clip = await pg.evaluate("(() => { const r = document.getElementById('stage').getBoundingClientRect(); return {x: r.x, y: r.y, width: r.width, height: r.height}; })()") if clean else None
+ im = Image.open(io.BytesIO(await pg.screenshot(clip=clip))).convert("RGB")
+ return (im.resize((1600, 900), Image.LANCZOS) if clean else im), sec # stage pixels = stage coordinates
+
+ def beat(s):
+ if s.isdigit() and int(s) < len(ids): return int(s)
+ if s in ids: return ids.index(s)
+ sys.exit(f"no beat {s!r}: give an index from 0 to {len(ids) - 1} or one of {', '.join(ids)}")
+
+ groups, clean = {}, a.clean or bool(a.webp)
+ specs = a.specs or ([] if a.cuts is not None else [f"{i}:{t}" for t in ("open", "end", *a.moments) for i in range(len(ids))])
+ if a.name and not a.webp: sys.exit("--name names the --webp still: give --webp too")
+ if a.name and len(specs) != 1: sys.exit("--name names one moment: give exactly one BEAT:TIME")
+ for s in specs:
+ i, t = s.rsplit(":", 1); i = beat(i)
+ im, _ = await grab(i, t, clean)
f = a.out / f"{a.chapter}_b{i:02d}_{t}.png"
- await pg.screenshot(path=str(f))
+ im.save(f)
groups.setdefault(t, []).append(f)
- live = await pg.evaluate("typeof bakedJobs === 'undefined' ? 0 : bakedJobs.size")
+ if a.webp:
+ w = a.out / f"{a.name or f.stem}.webp"
+ im.resize((a.webp, round(a.webp * 9 / 16)), Image.LANCZOS).save(w, quality=88); print("still", w)
+ if a.cuts is not None:
+ rows, only = [], {beat(s) for s in a.cuts}
+ for i in range(len(ids) - 1):
+ if only and not only & {i, i + 1}: continue
+ (x, tx), (y, ty) = await grab(i, "end", True), await grab(i + 1, "0.05", True)
+ pair = Image.new("RGB", (1608, 450), (20, 30, 27))
+ for k, (im, label) in enumerate(((x, f"{ids[i]} end t={tx:.2f}"), (y, f"{ids[i + 1]} start t={ty:.2f}"))):
+ pair.paste(im.resize((800, 450)), (k * 808, 0)); ImageDraw.Draw(pair).text((k * 808 + 8, 6), label, fill=(255, 230, 120))
+ rows.append(pair)
+ if rows:
+ S = Image.new("RGB", (1608, 458 * len(rows)), (20, 30, 27))
+ for k, r in enumerate(rows): S.paste(r, (0, k * 458))
+ f = a.out / f"{a.chapter}_cuts{''.join('_' + ids[i] for i in sorted(only))}.jpg"
+ S.save(f, quality=86); print("cut sheet", f)
+ # pieces a picture book bakes in the browser: missing from img/puppets/baked.js (key hash = its file name there)
+ live = await pg.evaluate("typeof bakedJobs === 'undefined' ? [] : [...bakedJobs.keys()].map(k => { const i = k.indexOf('|'), "
+ "html = k.slice(i + 1); return [keyHash(k), k.slice(0, i), (html.match(/data-p=\"([^\"]+)\"/) || [])[1] "
+ "|| html.replace(/\\s+/g, ' ').slice(0, 70)]; })")
await b.close()
- if live: print(f"{live} paper pieces were baked live in the page: run bake_puppets.py")
+ if live:
+ print(f"{len(live)} paper pieces were baked live in the page: run bake_puppets.py. Pieces (hash, box x y w h, data-p or the start of its SVG):")
+ for h, box, svg in live: print(f" {h} {box:18} {svg}")
for t, fs in groups.items():
+ if len(fs) < 2: continue
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))
+ im = Image.open(f); sheet.paste(im.resize((800, 800 * im.height // im.width)), ((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)
return 1 if errs else 0
@@ -63,11 +122,16 @@ if __name__ == "__main__":
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("chapter", help="chapter folder under --url, e.g. ch07")
ap.add_argument("specs", nargs="*",
- help="moments as BEAT:TIME; BEAT is the index in BEATS from 0 (the player shows BEAT+1), "
+ help="moments as BEAT:TIME; BEAT is the index in BEATS from 0 (the player shows BEAT+1) or the beat id, "
"TIME is seconds, open, mid or end; e.g. 3:end 5:4.5 (default: every beat at open and end)")
ap.add_argument("--moments", nargs="*", default=[], choices=["mid"], help="extra moments for every beat")
ap.add_argument("--url", default="http://localhost:8765/")
- ap.add_argument("--out", type=Path, default=Path("/tmp/animebook-shots"))
+ ap.add_argument("--out", type=Path, required=True, help="folder for the shots, e.g. books/<book>/review/chNN-shots")
+ ap.add_argument("--clean", action="store_true", help="the stage alone, no player UI")
+ ap.add_argument("--cuts", nargs="*", metavar="BEAT", help="cut sheet: each beat's last frame beside the next one's first; "
+ "with beats, only the cuts into and out of them")
+ ap.add_argument("--webp", type=int, metavar="W", help="also save each shot as a W-wide 16:9 WebP (clean)")
+ ap.add_argument("--name", help="file name (without .webp) for the one --webp still")
a = ap.parse_args()
a.url = a.url if a.url.endswith("/") else a.url + "/"
sys.exit(asyncio.run(main(a)))
diff --git a/.claude/skills/papermorph/scripts/still.py b/.claude/skills/papermorph/scripts/still.py
index d73886b..a6fd89a 100644
--- a/.claude/skills/papermorph/scripts/still.py
+++ b/.claude/skills/papermorph/scripts/still.py
@@ -4,9 +4,12 @@
uv run --with playwright --with pillow still.py ch15 --url http://localhost:8765/science/ [beat ...] [--min 3]
Prints, per lesson beat, the stretches of at least --min seconds whose consecutive frames differ by less than
---thr (mean absolute pixel difference, 0-255, on a small grey copy of the stage; default 0.03 for a lesson, 2 for a
-picture book, whose puppets jitter and flicker on every frame even when nothing acts). Strips and onion skins cannot
-show that nothing moves; this can. A stretch is worth a look, not automatically wrong: a held moment can be right.
+--thr (mean absolute pixel difference, 0-255, on a small grey copy of the stage). In a picture book the kit's hand
+jitter (`jit` called from the book's lib/, not the camera's shake) and the exposure flicker are switched off while
+measuring; a scene's own `jit` (snowfall, a tremble) keeps working, so what is left is the film as played, less the hand:
+a breathing, blinking puppet that does nothing else measures about 1-1.5, real acting 2 and up (The Chess Dog,
+2026-10-23). Defaults: 0.03 for a lesson, 1.5 for a picture book. Strips and onion skins cannot show that nothing
+moves; this can. A stretch is worth a look, not automatically wrong: a held moment can be right.
"""
import argparse, asyncio, io
from playwright.async_api import async_playwright
@@ -19,14 +22,28 @@ ap.add_argument("--step", type=float, default=1); ap.add_argument("--min", type=
ap.add_argument("--thr", type=float)
a = ap.parse_args()
URL = a.url.rstrip("/") + f"/{a.chapter}/"
+# The kit's hand jitter is jit() called from a puppet in the book's lib/ (cast.js, paper.js); the camera's shake is
+# jit() from cam.apply, and scenes call jit() for layout and acting (ch01's snowflakes, ch06's trembling dog): those
+# keep their values. ponytail: tells callers apart by the stack (slow, measuring only); a kit flag would be cheaper.
+STEADY = r"""(() => {
+ if (typeof jit !== 'function') return false;
+ const j0 = jit;
+ window.jit = (f, k) => {
+ const at = new Error().stack.split('\n').find(l => /https?:/.test(l)) || '';
+ return /\/lib\/[^/]+\.js/.test(at) && !/\bapply\b/.test(at) ? 0 : j0(f, k);
+ };
+ if (typeof FLICKER !== 'undefined') FLICKER.style.display = 'none';
+ return true;
+})()"""
async def main():
async with async_playwright() as p:
b = await p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0})
- pg = await b.new_page(viewport={"width": 1600, "height": 960})
+ pg = await b.new_page(viewport={"width": 1600, "height": 960}, reduced_motion="reduce")
await pg.goto(URL + "?beat=0&t=0"); await pg.wait_for_timeout(800)
ids = await pg.evaluate("BEATS.map(b => b.id)"); asks = await pg.evaluate("BEATS.map(b => !!b.ask)")
- thr = a.thr if a.thr is not None else (2 if await pg.evaluate("typeof jit === 'function'") else .03) # paper.js jitters
+ film = await pg.evaluate(STEADY)
+ thr = a.thr if a.thr is not None else (1.5 if film else .03)
r = await pg.evaluate("(() => { const r = document.getElementById('stage').getBoundingClientRect(); return {x: r.x, y: r.y, width: r.width, height: r.height}; })()")
for i, bid in enumerate(ids):
if asks[i] or (a.beats and bid not in a.beats): continue
diff --git a/.claude/skills/papermorph/scripts/strip.py b/.claude/skills/papermorph/scripts/strip.py
index 91734d5..4b01bc7 100644
--- a/.claude/skills/papermorph/scripts/strip.py
+++ b/.claude/skills/papermorph/scripts/strip.py
@@ -9,6 +9,11 @@
push/0.25@w also a motion WebP of the beat (0.25 s steps)
push/0.2@o also an onion skin: the strip's frames laid over each other in one picture, later ones
stronger; even gaps between ghosts mean even speed, bunched ghosts slow-in or slow-out
+ push:4..6/0.2@o a time range of the beat instead of all of it (ends may be marks: dir..dir+1.5). An onion
+ skin is only readable inside one shot: give it the range of that shot, never across a cut
+ walk:2..5/0.1@o@c @c: camera off. Every frame is drawn in the set's own framing (a picture book's paperCam at
+ its base view, no pan, zoom or shake), so a follow shot or a cut within one set no longer
+ moves the background: a planted foot is one sharp ghost, a sliding foot a smear
--sheet storyboard put every frame into one sheet OUT/storyboard.jpg (layout-first storyboard)
Without --sheet each beat gets OUT/strip_<beat>.jpg (onion skins OUT/onion_<beat>.jpg). Frames are labelled "beat t" and shown at 1/3 size, four
@@ -26,6 +31,17 @@ def sheet(ims, path, cols=4):
for k, im in enumerate(ims): S.paste(im, ((k % cols) * W, (k // cols) * H))
S.save(path, quality=84)
+CAMERA_OFF = r"""() => { // paperCam: a set layer is image > layer g > world > view; base view = no transforms
+ for (const im of scene.querySelectorAll('image[href*="img/sets/"]')) {
+ const layer = im.parentNode, view = layer.parentNode.parentNode;
+ layer.removeAttribute('transform'); view.removeAttribute('transform');
+ }
+}"""
+
+def mean_diff(a, b):
+ import numpy as np
+ return float(np.abs(np.asarray(a.convert("L"), dtype=np.float32) - np.asarray(b.convert("L"), dtype=np.float32)).mean())
+
def onion_skin(ims):
"""Frames over a common background: what stays still is the per-pixel median; what moved is painted from
each frame, earliest faintest."""
@@ -42,25 +58,28 @@ async def main(a):
tmp = Path(tempfile.mkdtemp()) / "f.png"
async with async_playwright() as p:
b = await (p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0}) if a.browser == "firefox" else p.chromium.launch(**exe()))
- pg = await b.new_page(viewport={"width": 1600, "height": 960})
+ pg = await b.new_page(viewport={"width": 1600, "height": 960}, reduced_motion="reduce") # no wall-clock CSS motion
errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))
await pg.goto(f"{a.url}{a.chapter}/?beat=0&t=0"); await pg.wait_for_timeout(800)
at = {"i": -1, "t": 0.0}
+ cam = {"off": False}
async def shot(t, scale):
if t < at["t"]: # tweens that have finished stay finished: going back needs the beat rebuilt
await pg.evaluate(f"seek({at['i']}, false)")
at["t"] = t
- await pg.evaluate(f"P.t = {t}; evalTo({t})"); await pg.wait_for_timeout(60)
+ await pg.evaluate(f"P.t = {t}; evalTo({t})")
+ if cam["off"]: await pg.evaluate(CAMERA_OFF)
+ await pg.wait_for_timeout(60)
r = await pg.evaluate("(() => { const r = document.getElementById('stage').getBoundingClientRect(); return [r.x, r.y, r.width, r.height]; })()")
await pg.screenshot(path=str(tmp), clip={"x": r[0], "y": r[1], "width": r[2], "height": r[3]})
im = Image.open(tmp).convert("RGB")
return im.resize((im.width // scale, im.height // scale))
allims = []
for spec in a.specs:
- m = re.fullmatch(r"(.+?)((?:@[wo])*)", spec); spec, flags = m[1], m[2]
- webp, onion = "@w" in flags, "@o" in flags
- m = re.fullmatch(r"([^:/]+)(?::(.+)|/([\d.]+))?", spec)
- if not m: sys.exit(f"bad spec {spec!r}")
+ m = re.fullmatch(r"(.+?)((?:@[woc])*)", spec); spec, flags = m[1], m[2]
+ webp, onion, cam["off"] = "@w" in flags, "@o" in flags, "@c" in flags
+ m = re.fullmatch(r"([^:/]+)(?::([^/]+))?(?:/([\d.]+))?", spec)
+ if not m or (m[2] and m[3] and ".." not in m[2]): sys.exit(f"bad spec {spec!r}")
bid, moments, step = m.groups()
i = await pg.evaluate(f"BEATS.findIndex(b => b.id === '{bid}')")
if i < 0: sys.exit(f"no beat {bid!r}")
@@ -74,20 +93,25 @@ async def main(a):
if mk: sys.exit(f"no mark {mk[1]!r} in {bid}")
return float(x)
st = float(step or 1)
- ts = [when(x) for x in moments.split(",")] if moments else [k * st for k in range(int(dur / st) + 1)]
+ t0, t1 = (when(x) for x in moments.split("..")) if moments and ".." in moments else (0, dur)
+ ts = ([when(x) for x in moments.split(",")] if moments and ".." not in moments
+ else [t0 + k * st for k in range(int((t1 - t0) / st + 1e-6) + 1)])
ims, raw = [], []
for t in ts:
im = await shot(t, 3); raw.append(im.copy())
ImageDraw.Draw(im).text((6, 4), f"{bid} t={t:.2f}", fill=(255, 230, 120)); ims.append(im)
if onion:
+ cuts = [f"{ts[k]:.2f}" for k in range(1, len(raw)) if mean_diff(raw[k - 1], raw[k]) > 30]
+ if cuts: print(f" {bid}: the picture jumps at t={', '.join(cuts)} (a cut or a pan?): the onion skin blends "
+ "shots; give it the range of one shot, or @c for a pan")
skin = onion_skin([await shot(t, 2) for t in ts] if len(ts) > 1 else raw)
- ImageDraw.Draw(skin).text((8, 6), f"{bid} onion t={ts[0]:.2f}..{ts[-1]:.2f}, {len(ts)} frames", fill=(255, 230, 120))
+ ImageDraw.Draw(skin).text((8, 6), f"{bid} onion t={ts[0]:.2f}..{ts[-1]:.2f}, {len(ts)} frames{', camera off' if cam['off'] else ''}", fill=(255, 230, 120))
skin.save(out / f"onion_{bid}.jpg", quality=86)
if a.sheet: allims += ims
else: sheet(ims, out / f"strip_{bid}.jpg")
if webp:
- fr, t = [], 0.0
- while t <= dur:
+ fr, t = [], t0
+ while t <= t1 + 1e-6:
fr.append(await shot(t, 2)); t += .25
fr[0].save(out / f"motion_{bid}.webp", save_all=True, append_images=fr[1:], duration=250, loop=0, quality=60)
print(bid, len(ims), "frames")
diff --git a/.claude/skills/papermorph/scripts/tts.py b/.claude/skills/papermorph/scripts/tts.py
index 0e5c274..758fc0e 100644
--- a/.claude/skills/papermorph/scripts/tts.py
+++ b/.claude/skills/papermorph/scripts/tts.py
@@ -143,7 +143,8 @@ def split_marks(raw):
def time_at(clean, words, estimate=False):
"""Return f(pos): start time of the first spoken word at or after char pos. The voice's word list can stop
- short of the text; with estimate, a position past its last word is timed at the speaking rate so far."""
+ short of the text; with estimate, a position past its last word is timed at the speaking rate so far (seconds
+ per character within sentences) plus the voice's mean pause at each sentence end on the way."""
cursor, located = 0, []
for t, w in words:
i = clean.find(w, cursor)
@@ -151,11 +152,17 @@ def time_at(clean, words, estimate=False):
continue
located.append((i, t))
cursor = i + len(w)
+ ends = lambda a, b: len(SENTENCE_END.findall(clean, a, b))
+ pairs = list(zip(located, located[1:]))
+ inner = [(i1 - i0, t1 - t0) for (i0, t0), (i1, t1) in pairs if not ends(i0, i1)]
+ rate = sum(d for _, d in inner) / max(sum(c for c, _ in inner), 1) if inner else located[-1][1] / max(located[-1][0], 1) if located else 0
+ gaps = [t1 - t0 - (i1 - i0) * rate for (i0, t0), (i1, t1) in pairs if ends(i0, i1)]
+ pause = max(0, sum(gaps) / len(gaps)) if gaps else .4 # ponytail: a guess when the clip shows no sentence end
def at(pos):
t = next((t for i, t in located if i >= pos), None)
if t is None and estimate and located:
i, t = located[-1]
- t += (pos - i) * t / max(i, 1)
+ t += (pos - i) * rate + ends(i, pos) * pause
return None if t is None else round(t, 3)
return at
@@ -169,13 +176,14 @@ def mark_times(clean, marks, words):
return out
+SENTENCE_END = re.compile(r"[.?!]\s+|[。!?]\s*")
ABBREV = re.compile(r"(?<![\w.])(?:Mr|Mrs|Ms|Dr|Prof|St|vs|approx|e\.g|i\.e|cf)\.$")
def caption_cues(clean, words):
"""One cue per sentence: [start seconds, sentence]."""
at, cues, start = time_at(clean, words, estimate=True), [], 0
- for m in list(re.finditer(r"[.?!]\s+|[。!?]\s*", clean)) + [None]:
+ for m in list(SENTENCE_END.finditer(clean)) + [None]:
if m and ABBREV.search(clean, 0, m.start() + 1): # "Mr. Lee", "e.g. a lot" go on
continue
end = m.end() if m else len(clean)
diff --git a/README.md b/README.md
index 4417a12..2b929f0 100644
--- a/README.md
+++ b/README.md
@@ -74,7 +74,7 @@ python3 .claude/skills/papermorph/scripts/engine.py site
python3 .claude/skills/papermorph/scripts/engine.py site --from you/your-fork@main
```
-Engine versions are tags (`engine-v2`, then `engine-v2.0.1` for fixes); a new major number means a book may need a change, described in its [release notes](https://github.com/DozenTwelve/Papermorph/releases). Outside this repository, `engine.py` syncs from the latest major release, now `engine-v2`. Since `engine-v2` the maths helpers (number lines, tiles, planes, the number-set diagram) are in `lib/math.js`: a chapter that uses them loads `../lib/math.js` right after `engine.js`, and `lint.py` names the chapters that need it. `--from DozenTwelve/Papermorph@engine-v1` keeps the earlier engine.
+Engine versions are tags (`engine-v2`, `engine-v2.1`, …); a new major number means a book may need a change, described in its [release notes](https://github.com/DozenTwelve/Papermorph/releases). Outside this repository, `engine.py` syncs from the latest compatible release, now `engine-v2.1`. Since `engine-v2` the maths helpers (number lines, tiles, planes, the number-set diagram) are in `lib/math.js`: a chapter that uses them loads `../lib/math.js` right after `engine.js`, and `lint.py` names the chapters that need it. `--from DozenTwelve/Papermorph@engine-v1` keeps the earlier engine.
## Video and LMS export
diff --git a/engine/book.css b/engine/book.css
index 5d49bfb..1d09772 100644
--- a/engine/book.css
+++ b/engine/book.css
@@ -4,6 +4,12 @@
:root {
--math-font: "Avenir Next", Arial, sans-serif; face for numbers and formulas (default: a serif, see engine.js)
--progress-key: "progress"; localStorage key shared with the cover (default: one per book folder)
+ --page: #e9e5d8; --board: #fbfaf5; --panel: #fff; --edge: #d8d2c0; a light board: the palette at the top of
+ --chalk: #1d1d1f; --dim: #6a6a6e; --faint: #c4bfae; engine.css, redefined; the stage, cards,
+ --task: #e2589b; --quiz: #1f6fc5; --good: #3f8a1d; --bad: #d9473a; bar and COL follow (#rrggbb for the ink
+ --on-fill: #fff; --vignette: rgba(90, 70, 30, .08); color-scheme: light; and board colours COL reads)
+ --rule: #ece8e0; --track: #e6e2d5; --track-ask: #cfdeeb; and the shades between them
+ --bar-edge: #eae6da; --hover: #efede6; --veil: #e9e5d8;
}
Style overrides go here too. They come before the engine's rules, so make each selector more specific than the
engine's, e.g. ':root .card.band' for '.card.band'. */
diff --git a/engine/engine.css b/engine/engine.css
index b65752d..3e6079a 100644
--- a/engine/engine.css
+++ b/engine/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/engine/engine.js b/engine/engine.js
index f24936a..6ad6d52 100644
--- a/engine/engine.js
+++ b/engine/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/engine/volume.css b/engine/volume.css
index 195fe1f..106dd36 100644
--- a/engine/volume.css
+++ b/engine/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/elementary-algebra/lib/engine.css b/site/elementary-algebra/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/elementary-algebra/lib/engine.css
+++ b/site/elementary-algebra/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/elementary-algebra/lib/engine.js b/site/elementary-algebra/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/elementary-algebra/lib/engine.js
+++ b/site/elementary-algebra/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/elementary-algebra/lib/volume.css b/site/elementary-algebra/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/elementary-algebra/lib/volume.css
+++ b/site/elementary-algebra/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/joke-collection/lib/engine.css b/site/joke-collection/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/joke-collection/lib/engine.css
+++ b/site/joke-collection/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/joke-collection/lib/engine.js b/site/joke-collection/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/joke-collection/lib/engine.js
+++ b/site/joke-collection/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/joke-collection/lib/volume.css b/site/joke-collection/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/joke-collection/lib/volume.css
+++ b/site/joke-collection/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/little-red-riding-hood/lib/engine.css b/site/little-red-riding-hood/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/little-red-riding-hood/lib/engine.css
+++ b/site/little-red-riding-hood/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/little-red-riding-hood/lib/engine.js b/site/little-red-riding-hood/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/little-red-riding-hood/lib/engine.js
+++ b/site/little-red-riding-hood/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/little-red-riding-hood/lib/volume.css b/site/little-red-riding-hood/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/little-red-riding-hood/lib/volume.css
+++ b/site/little-red-riding-hood/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/math-notebook/lib/engine.css b/site/math-notebook/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/math-notebook/lib/engine.css
+++ b/site/math-notebook/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/math-notebook/lib/engine.js b/site/math-notebook/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/math-notebook/lib/engine.js
+++ b/site/math-notebook/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/math-notebook/lib/volume.css b/site/math-notebook/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/math-notebook/lib/volume.css
+++ b/site/math-notebook/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/physics-notebook/lib/book.css b/site/physics-notebook/lib/book.css
index 3a498c5..1fe41ea 100644
--- a/site/physics-notebook/lib/book.css
+++ b/site/physics-notebook/lib/book.css
@@ -11,6 +11,7 @@
--task: #e89a00; --quiz: #2d8fd0; --good: #2f9a5c; --bad: #d9473a;
--ui: "Patrick Hand", "Avenir Next", "Segoe UI", sans-serif;
--math-font: "Patrick Hand", "Avenir Next", sans-serif;
+ --hover: #eee9de; /* the volume control under the pointer */
color-scheme: light;
}
/* Lined paper with a red margin: one static image (CSS gradients here cost Firefox ~20 ms a frame under camera moves). */
diff --git a/site/physics-notebook/lib/engine.css b/site/physics-notebook/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/physics-notebook/lib/engine.css
+++ b/site/physics-notebook/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/physics-notebook/lib/engine.js b/site/physics-notebook/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/physics-notebook/lib/engine.js
+++ b/site/physics-notebook/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/physics-notebook/lib/volume.css b/site/physics-notebook/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/physics-notebook/lib/volume.css
+++ b/site/physics-notebook/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/science/lib/engine.css b/site/science/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/science/lib/engine.css
+++ b/site/science/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/science/lib/engine.js b/site/science/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/science/lib/engine.js
+++ b/site/science/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/science/lib/volume.css b/site/science/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/science/lib/volume.css
+++ b/site/science/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }
diff --git a/site/three-little-pigs/lib/engine.css b/site/three-little-pigs/lib/engine.css
index b65752d..3e6079a 100644
--- a/site/three-little-pigs/lib/engine.css
+++ b/site/three-little-pigs/lib/engine.css
@@ -1,11 +1,20 @@
@import url(volume.css);
@import url(book.css); /* this book's own settings and overrides (not shared), before the rules below */
-:root {
+/* The palette. lib/book.css may redefine any of it in its own ':root' (this one has no specificity), e.g. a light board
+ with dark ink: the stage, COL in engine.js, the cards and the player bar all follow. Colours are #rrggbb. The last
+ lines are shades between those colours, written out so the dark board stays exact: a palette of its own sets them too
+ (the light set in book.css). */
+:where(:root) {
--page: #0f1613; --board: #1d2b27; --panel: #22322d; --edge: #3a5047;
--chalk: #ece8dc; --dim: #9aaba3; --faint: #5d7068;
--task: #f0b45a; --quiz: #86c9e8; --good: #8fd6b0; --bad: #f08c7a;
--ui: "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+ --vignette: rgba(0, 0, 0, .35); /* the stage's darkened edges; a light board wants a faint, warm one */
color-scheme: dark;
+ --rule: #2e433b; /* lines between answer rows */
+ --track: #2f4640; --track-ask: #2d4a57; /* the player bar's steps, and its question steps */
+ --bar-edge: #2a3b35; --hover: #2b3f36; /* the bar's top line, the volume control under the pointer */
+ --veil: #0a100e; /* behind the help panel and the captions */
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; overflow: hidden; background: var(--page); }
@@ -18,11 +27,11 @@ button[hidden] { display: none; }
#frame { position: absolute; left: 50%; top: 50%; width: 1600px; height: 960px; transform: translate(-50%, -50%) scale(var(--k, .5));
border-radius: 20px; overflow: hidden; background: var(--board); box-shadow: 0 0 0 1px var(--edge), 0 30px 80px rgba(0, 0, 0, .45); }
#stage { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: block;
- background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, rgba(0,0,0,.35)), var(--grain, none), #1d2b27; }
+ background: radial-gradient(75% 75% at 50% 45%, rgba(0,0,0,0) 60%, var(--vignette)), var(--grain, none), var(--board); }
#ui { position: absolute; left: 0; top: 0; width: 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 { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--page) 50%, transparent); border: 0; }
.cover[hidden] { display: none; }
.cover > div { display: flex; flex-direction: column; align-items: center; }
.cover-k { margin: 0 0 10px; text-align: center; font-size: 22px; font-weight: 600; letter-spacing: .14em; text-transform: uppercase; color: var(--quiz); }
@@ -36,10 +45,10 @@ button[hidden] { display: none; }
.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; }
+.paused-mark div { padding: 14px 30px; border-radius: 999px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 22px; }
/* Question cards inside the picture. */
-.card { position: absolute; padding: 20px 26px; border-radius: 20px; background: 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 { position: absolute; padding: 20px 26px; border-radius: 20px; background: color-mix(in srgb, var(--panel) 97%, transparent); border: 1.5px solid var(--edge); border-left: 7px solid var(--quiz); box-shadow: 0 14px 44px rgba(0, 0, 0, .35); }
.card.band { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; grid-template-areas: "pic head body acts" "pic fb body acts"; column-gap: 28px; align-items: center; align-content: center; min-height: 150px; }
.band .mascot { grid-area: pic; }
.band .head { grid-area: head; align-self: end; }
@@ -55,8 +64,8 @@ button[hidden] { display: none; }
.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[aria-pressed="true"] { background: var(--c, var(--chalk)); border-color: var(--c, var(--chalk)); color: var(--on-fill, #1b2320); font-weight: 600; }
+.opt.good { border-color: var(--good); box-shadow: 0 0 0 3px color-mix(in srgb, var(--good) 35%, transparent); }
.opt.bad { border-color: var(--bad); color: var(--bad); }
.opt:disabled { cursor: default; }
.fb { margin-top: 8px; font-size: 22px; line-height: 1.4; color: var(--chalk); }
@@ -72,10 +81,10 @@ button[hidden] { display: none; }
.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.go { background: var(--quiz); color: var(--on-fill, #10242e); } /* --on-fill: text on a coloured fill */
.btn:disabled { background: var(--edge); color: var(--dim); cursor: default; }
-.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid #2e433b; }
+.grid .row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 34px; gap: 16px; align-items: center; padding: 5px 0 5px 12px; border-bottom: 1px solid var(--rule); }
.grid .num { display: flex; justify-content: flex-end; align-items: center; font-size: 26px; }
.grid.text .row { grid-template-columns: minmax(0, 1fr) auto 34px; }
.grid.text .num { justify-content: flex-start; }
@@ -96,17 +105,17 @@ button[hidden] { display: none; }
.tok { cursor: grab; touch-action: none; } /* a finger drags the chip instead of scrolling the page */
/* Controls strip, part of the frame. */
-#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: #16211d; border-top: 1px solid #2a3b35; }
+#bar { position: absolute; left: 0; top: 900px; width: 1600px; height: 60px; display: flex; align-items: center; gap: 10px; padding: 0 20px; background: color-mix(in srgb, var(--page) 50%, var(--board)); border-top: 1px solid var(--bar-edge); }
.icon { width: 44px; height: 44px; border-radius: 50%; border: 1px solid var(--edge); background: var(--panel); display: grid; place-items: center; flex: none; padding: 0; }
.icon svg { width: 18px; height: 18px; fill: var(--chalk); }
.icon .i-pause { display: none; }
.is-playing .icon .i-play { display: none; }
.is-playing .icon .i-pause { display: block; }
.segs { flex: 1; display: flex; gap: 4px; height: 30px; align-items: center; min-width: 0; margin: 0 8px; }
-.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: #2f4640; border: 0; padding: 0; overflow: hidden; }
+.seg { position: relative; display: block; min-width: 0; height: 8px; border-radius: 4px; background: var(--track); border: 0; padding: 0; overflow: hidden; }
.seg:hover { height: 12px; }
.seg i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; background: var(--chalk); }
-.seg.ask { background: #2d4a57; }
+.seg.ask { background: var(--track-ask); }
.seg.ask i { background: var(--quiz); }
.step { width: 300px; flex: none; color: var(--dim); font-size: 19px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; text-align: right; }
/* Keep the control strip usable without scaling down its touch targets. */
@@ -121,9 +130,9 @@ button[hidden] { display: none; }
.segs { order: 1; }
.segs { min-width: 80px; margin: 0; }
}
-.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: rgba(15, 22, 19, .85); color: var(--dim); font-size: 19px; }
+.sound-note { position: absolute; left: 24px; top: 20px; margin: 0; padding: 8px 18px; border-radius: 12px; background: color-mix(in srgb, var(--page) 85%, transparent); color: var(--dim); font-size: 19px; }
.sound-note[hidden] { display: none; }
-.blanks .brow { padding: 8px 0; border-bottom: 1px solid #2e433b; }
+.blanks .brow { padding: 8px 0; border-bottom: 1px solid var(--rule); }
.blanks .brow:last-child { border-bottom: 0; }
.blanks .bline { line-height: 64px; white-space: nowrap; }
.blanks .mark { display: inline-block; margin-left: 14px; font-weight: 700; }
@@ -131,8 +140,8 @@ button[hidden] { display: none; }
.blanks .mark.bad { color: var(--bad); }
.blanks .why { font-size: 19px; color: var(--dim); line-height: 1.35; }
.blanks .why:empty { display: none; }
-.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: rgba(236, 232, 220, .07); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
-.box:focus { outline: none; background: rgba(134, 201, 232, .16); }
+.box { height: 52px; margin: 0 6px; padding: 0 6px; border: 0; border-bottom: 3px solid var(--quiz); border-radius: 8px 8px 0 0; background: color-mix(in srgb, var(--chalk) 7%, transparent); color: var(--chalk); font: 32px var(--math-font, "STIX Two Text", "Cambria Math", "Iowan Old Style", Palatino, Georgia, serif); text-align: center; vertical-align: -6px; }
+.box:focus { outline: none; background: color-mix(in srgb, var(--quiz) 16%, transparent); }
.box.good { border-color: var(--good); }
.box.bad { border-color: var(--bad); }
.box:disabled { opacity: 1; }
@@ -140,8 +149,8 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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); }
+.grid .row.cur { background: color-mix(in srgb, var(--chalk) 5%, transparent); box-shadow: inset 4px 0 var(--quiz); }
+.help { position: absolute; left: 0; top: 0; width: 1600px; height: 900px; display: grid; place-items: center; background: color-mix(in srgb, var(--veil) 72%, transparent); }
.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; }
@@ -155,7 +164,7 @@ kbd { display: inline-block; min-width: 1.5em; padding: 0 .4em; margin-left: .5e
.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 { position: absolute; left: 50%; bottom: 78px; transform: translateX(-50%); width: max-content; max-width: 1180px; padding: 10px 24px; border-radius: 14px; background: color-mix(in srgb, var(--veil) 82%, transparent); color: var(--chalk); font-size: 28px; line-height: 1.35; text-align: center; pointer-events: none; }
.caption[hidden] { display: none; }
.icon.cc { font-size: 15px; font-weight: 700; color: var(--dim); }
.icon.cc[aria-pressed="true"] { background: var(--chalk); border-color: var(--chalk); color: var(--board); }
diff --git a/site/three-little-pigs/lib/engine.js b/site/three-little-pigs/lib/engine.js
index f24936a..6ad6d52 100644
--- a/site/three-little-pigs/lib/engine.js
+++ b/site/three-little-pigs/lib/engine.js
@@ -250,13 +250,19 @@ document.body.insertAdjacentHTML('afterbegin', `<div id="frame">
/* ---------- drawing helpers ---------- */
const NS = 'http://www.w3.org/2000/svg';
-const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
- chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
const UI = '"Avenir Next","Segoe UI","Helvetica Neue",Arial,sans-serif';
// Book settings (lib/book.css, next to engine.css and imported by it): --math-font for numbers and formulas,
// --progress-key for the localStorage key the cover and chapters share.
const BOOK = getComputedStyle(document.documentElement);
const bookSetting = name => BOOK.getPropertyValue(name).trim().replace(/^(["'])([^"']*)\1$/, '$2'); // unquote a lone string only
+// The board and ink colours come from the palette in engine.css, which lib/book.css may redefine (a light board):
+// the picture, the cards and the player bar then agree. The six hues are the chapters' meanings, set in JS.
+const COL = { nat: '#f4a48c', whole: '#86c9e8', int: '#f3c95c', rat: '#e8a0c8', irr: '#8fd6b0', real: '#bba8ee',
+ chalk: '#ece8dc', dim: '#9aaba3', faint: '#5d7068', task: '#f0b45a', good: '#8fd6b0', bad: '#f08c7a', board: '#1d2b27' };
+{ // a canvas reads any CSS colour back as #rrggbb, the form colour tweens mix; a missing or bad one keeps the default
+ const c = document.createElement('canvas').getContext('2d');
+ for (const k of ['chalk', 'dim', 'faint', 'task', 'good', 'bad', 'board']) { c.fillStyle = COL[k]; c.fillStyle = bookSetting('--' + k) || COL[k]; COL[k] = c.fillStyle; }
+}
const MATH = bookSetting('--math-font') || '"STIX Two Text","Cambria Math","Iowan Old Style",Palatino,Georgia,serif';
const NAME = { nat: translate('natural'), whole: translate('whole'), int: translate('integers'), rat: translate('rational'), irr: translate('irrational'), real: translate('real') };
// Card positions inside the 1600×900 picture.
@@ -280,7 +286,8 @@ function put(e, o) { Object.assign(st(e), o); render(e); return e; }
// Unchanged transform/opacity are not rewritten: per-frame updates of still elements cost repaints (notably in Firefox).
function render(e) {
const s = e._st, tf = s.x || s.y || s.s !== 1 || s.r ? `translate(${s.x},${s.y}) rotate(${s.r}) scale(${s.s})` : null;
- if (tf !== e._tf) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
+ // _tf starts unset: an element never moved keeps a transform attribute it was made with
+ if (tf !== (e._tf ?? null)) { if (tf) e.setAttribute('transform', tf); else e.removeAttribute('transform'); e._tf = tf; }
if (s.o !== e._o) { e.setAttribute('opacity', s.o); e._o = s.o; }
if (s.d !== undefined) {
e.setAttribute('stroke-dashoffset', 1 - s.d);
@@ -576,9 +583,9 @@ 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 show = (e, t0, dur = .5, ease) => tw(e, { o: 1 }, t0, dur, ease);
+const hide = (e, t0, dur = .5, ease) => tw(e, { o: 0 }, t0, dur, ease);
+const draw = (e, t0, dur = .9, ease) => tw(e, { d: 1 }, t0, dur, ease);
const pop = (e, t0) => tw(e, { s: 1, o: 1 }, t0, .45, back);
function pulse(e, t0, k = 1.7) { tw(e, { s: k }, t0, .22, out); tw(e, { s: 1 }, t0 + .22, .4); }
function stream(t, str, t0, dur) { prog(q => { t.textContent = str.slice(0, Math.round(q * str.length)); }, t0, dur, lin); }
@@ -606,8 +613,11 @@ function evalTo(t, list = TW) {
/* ---------- world clock and camera ---------- */
const soft = p => (1 - Math.cos(Math.PI * p)) / 2; // gentle in-out, for camera moves
// Continuous motion: f(t) runs on every frame of the beat with t in seconds from its start (0..D).
-// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame.
-const clockRun = (f, D) => { f(0); prog(q => f(q * D), 0, D, lin); };
+// Keep f a pure function of t, so pause, seek and ?beat=N&t=S show the same frame. A beat holds its picture for HOLD s
+// after its narration and last tween; with { tail: true } f keeps running through that hold (t up to the beat's end)
+// instead of freezing at D, for motion that never stops, as in a film. A camera runs through the hold too when anything
+// in its beat does (its tail is 'follow'), so a follow shot keeps up with a tailed subject.
+const clockRun = (f, D, { tail = false } = {}) => { f(0); const w = { t0: 0, dur: D, ease: lin, tail }; w.pf = q => f(q * w.dur); TW.push(w); };
// A camera looks at a world group through the stage (or a box, for split screen and picture-in-picture).
// The view {x, y, z, r} is the world point at the centre, the zoom (screen px per world px) and the roll in degrees.
// Moves are keyed on the beat clock: to(view, t0, dur, ease) blends each given key from its value at t0; a key may be a
@@ -676,7 +686,7 @@ function camera(p, D, { box, x = 800, y = 450, z, r = 0, bg = COL.board } = {})
put(el, { x: Math.min(bx + bw - m - h, Math.max(bx + m + h, sx)), y: sy, o: Math.max(0, 1 - away / 80) });
},
};
- clockRun(apply, D);
+ clockRun(apply, D, { tail: 'follow' });
return cam;
}
@@ -1063,9 +1073,12 @@ const grid = (items, cols, { multi = true, text = false } = {}) => (body, api) =
};
};
// 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, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
+// Accepts −, – or - as the sign, a currency sign before or after ($5, -$5, 5 €), thousands grouped by spaces (any kind)
+// or, where the decimal sign is a point, by commas, and a decimal comma when DECIMAL_SIGN is ','. Never evaluates the text as code.
function rat(str) {
- let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ');
+ let t = String(str).trim().replace(/^[−–]/, '-').replace(/\s+/g, ' ').replace(/^(-?) ?\p{Sc} ?|(?<=\d) ?\p{Sc}$/gu, '$1');
+ const group = DECIMAL_SIGN === ',' ? ' ' : '[, ]'; // one kind of separator throughout: 1,000 000 is not a number
+ t = t.replace(new RegExp(`^(-?\\d{1,3})(${group})(\\d{3}(?:\\2\\d{3})*)(?=$|[.,])`), (_, head, sep, rest) => head + rest.split(sep).join(''));
if (DECIMAL_SIGN === ',') t = t.replace(/^(-?\d+),(\d+)$/, '$1.$2'); // 0,75 where the decimal sign is a comma
let m = t.match(/^(-?)(\d+)(?:\.(\d+))?$/);
if (m) { const d = 10 ** (m[3] || '').length, n = (m[1] ? -1 : 1) * (Number(m[2]) * d + Number(m[3] || 0)); return Number.isSafeInteger(n) && Number.isSafeInteger(d) ? [n, d] : null; }
@@ -1126,7 +1139,8 @@ const blanks = rowsIn => (body, api) => {
if (ok && !r.played) { r.played = true; r.it.fx?.(); }
return ok;
};
- requestAnimationFrame(() => all[0]?.focus({ preventScroll: true }));
+ // not on the frame ?beat=N opens before the lesson has started: there Space starts it rather than typing a space
+ requestAnimationFrame(() => { if (P.started) all[0]?.focus({ preventScroll: true }); });
return {
check() {
const right = rows.filter(judge).length, done = right === rows.length;
@@ -1161,8 +1175,12 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && !pre) leadIn();
TW.sort((a, c) => a.t0 - c.t0);
- return Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + .6;
+ const end = Math.max(pre + tm.dur, ...TW.map(w => w.t0 + w.dur)) + HOLD;
+ const tail = TW.some(w => w.tail === true);
+ for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
+ return end;
}
+const HOLD = .6;
// A beat that clears the picture must not leave it empty while the narration has started.
// If nothing appears before LEAD_MAX, the opening group (every tween that starts within LEAD_GROUP s of the
// first reveal) moves earlier so it begins at LEAD_AT, just after the old panel has faded. Later steps keep their word timing.
@@ -1229,7 +1247,7 @@ function start(i, play) {
};
const b = BEATS[i];
if (b.ask) b.ask(() => {
- if (P.i !== i) return;
+ if (P.i !== i || P.done) return;
evalTo(Infinity);
if (i + 1 < BEATS.length) start(i + 1, true);
else { P.done = true; setPlaying(false); filmDone(); }
@@ -1282,10 +1300,13 @@ function beatDone() {
// counts as done, and CHAPTER.next is offered over that frame. Seeking or replaying clears the button with the cards.
function filmDone() {
progress(p => { p.done = [...new Set([...(p.done || []), CHAPTER.number])]; });
+ document.activeElement?.blur(); // a last question's Continue keeps focus, and Enter would press it again
+ // as on the finish card: Enter opens the next chapter (or replays), R and Space replay
+ const go = () => { if (CHAPTER.next) location.href = CHAPTER.next; else restart(); };
+ P.keys = e => e.key === 'Enter' ? (go(), true) : isShortcut(e, 'r') ? (restart(), true) : false;
if (!CHAPTER.next) return;
const next = h('button', 'btn go', [translate('nextChapter'), kbd('Enter')]);
- next.onclick = () => { location.href = CHAPTER.next; };
- P.keys = e => e.key === 'Enter' ? (next.onclick(), true) : false; // not focused, so Space still replays
+ next.onclick = go;
const c = card({ x: 0, y: 770, w: 0, cls: 'side' }, 'next');
Object.assign(c.style, { left: 'auto', right: '40px', width: 'auto' });
c.append(h('div', 'acts', [next]));
@@ -1376,10 +1397,15 @@ function setCaptions(on, save = true) {
if (save) try { localStorage.setItem('captions', on ? '1' : '0'); } catch {}
}
setCaptions(captions, false); // only the reader's own choice is stored, so a book can still pick the first-time default
-function hideCover() { P.started = true; $('cover').hidden = true; }
+function hideCover() {
+ P.started = true; $('cover').hidden = true;
+ // a question that ?beat=N opened before the start (its box waited unfocused, so Space started) now takes the typing
+ if (BEATS[P.i].ask) $('ui').querySelector('input.box:not(:disabled)')?.focus({ preventScroll: true });
+}
function togglePlay() {
if (!P.started) { hideCover(); return setPlaying(true); }
- if (P.waiting || P.done) return;
+ if (P.done) return restart(); // the end of a film (or of a chapter whose last step is a question): play again
+ if (P.waiting) return;
setPlaying(!P.playing);
}
const back1 = () => seek(P.t > 2.5 || P.i === 0 ? P.i : P.i - 1);
@@ -1388,7 +1414,7 @@ $('cover').onclick = togglePlay;
$('stage').addEventListener('click', e => {
if (e.target.closest('a.cite')) { if (P.playing && !P.waiting) setPlaying(false); return; } // opening a source pauses the lesson
const b = BEATS[P.i];
- if (!b.ask && !e.target.closest('.qlayer')) togglePlay();
+ if (!b.ask && !P.done && !e.target.closest('.qlayer')) togglePlay(); // a tap on a finished film's last frame does nothing
});
const citeObs = new MutationObserver(ms => { for (const m of ms) for (const n of m.addedNodes) autoCite(n); });
citeObs.observe(scene, { childList: true, subtree: true });
@@ -1440,7 +1466,7 @@ document.addEventListener('keydown', e => {
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;
+ const free = e.shiftKey || !P.keys || P.done; // after the end no question holds the arrows
let used = true;
if (k === ' ') togglePlay();
else if (k === 'ArrowLeft' && free) back1();
@@ -1479,7 +1505,11 @@ function boot() {
progress(p => { p.last = CHAPTER.number; });
document.getElementById('stage').setAttribute('aria-label', translate('stageLabelTitled', { title: CHAPTER.title }));
const film = !BEATS.some(b => b.ask); // a picture book: no questions, so no "lesson" or "quick checks" on its cover
- if (film) { $('coverGo').textContent = translate('startFilm'); $('help').querySelector('.help-cols > :last-child').hidden = true; }
+ if (film) { // the help lists no question keys and needs no column titles
+ $('coverGo').textContent = translate('startFilm');
+ const shift = [...$('help').querySelectorAll('dt')].find(e => e.textContent.startsWith('Shift'));
+ for (const e of [$('help').querySelector('.help-cols > :last-child'), $('help').querySelector('h3'), shift, shift.nextElementSibling]) e.hidden = true;
+ }
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
diff --git a/site/three-little-pigs/lib/volume.css b/site/three-little-pigs/lib/volume.css
index 195fe1f..106dd36 100644
--- a/site/three-little-pigs/lib/volume.css
+++ b/site/three-little-pigs/lib/volume.css
@@ -3,7 +3,7 @@
border: 1px solid var(--edge); border-radius: 999px; background: var(--panel); color: var(--chalk); transition: width .18s ease; }
.volume .icon { width: 42px; height: 42px; border: 0; background: transparent; }
.volume:hover, .volume:focus-within { width: 166px; gap: 10px; padding-right: 12px; }
-.volume:hover { background: #2b3f36; border-color: var(--faint); }
+.volume:hover { background: var(--hover, #2b3f36); border-color: var(--faint); }
.volume:has(:focus-visible) { outline: 2px solid var(--task); outline-offset: 3px; }
.volume .icon:focus-visible { outline: none; }
.volume input { appearance: none; flex: none; width: 0; height: 42px; margin: 0; opacity: 0; background: transparent; cursor: pointer; }