Skip to content

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

feat(engine): engine-v2.7, internals in a closure, silent beats, minDur, ?lengths

yzr64fe833ee8db
diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.md
index 11400e0..59e62cb 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 compatible release, `engine-v2.6`; `@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.6`; what an older copy lacks is marked *(v2.1)*, *(v2.2)*, *(v2.3)*, *(v2.4)*, *(v2.4.1)*, *(v2.4.2)*, *(v2.5)* or *(v2.6)*, 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.
+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.7`; `@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.7`; what an older copy lacks is marked *(v2.1)*, *(v2.2)*, *(v2.3)*, *(v2.4)*, *(v2.4.1)*, *(v2.4.2)*, *(v2.5)*, *(v2.6)* or *(v2.7)*, 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.
@@ -62,9 +62,12 @@ 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(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 (tailed `clockRun`s and cameras run to that end and do not set it *(v2.6)*: hold a picture longer with a plain run, `prog(() => {}, 0, D + 1)`); an `ask` beat waits for `done()`. An `ask` is any `done => …` that calls `done()` once; `quiz()` is the usual one, and a film's own handler can listen on the stage instead ([documentary.md](documentary.md#interactive-moments)). A `done()` kept from an earlier start of the same beat (the reader stepped back and replayed it) no longer counts *(v2.4.1)*; a chapter's own handler that acts later can compare `P.gen`, which every start of a beat changes.
+- A lesson beat ends after its narration and its last tween, and holds that picture `HOLD` (0.6 s) before the next starts (tailed `clockRun`s and cameras run to that end and do not set it *(v2.6)*: hold a picture longer with a plain run, `prog(() => {}, 0, D + 1)`, or `minDur`, below); an `ask` beat waits for `done()`. An `ask` is any `done => …` that calls `done()` once; `quiz()` is the usual one, and a film's own handler can listen on the stage instead ([documentary.md](documentary.md#interactive-moments)). A `done()` kept from an earlier start of the same beat (the reader stepped back and replayed it) no longer counts *(v2.4.1)*; a chapter's own handler that acts later can compare `P.gen`, which every start of a beat changes.
+- **Beats lengthen without a word**: any tween that ends after `D` (a push to `D + .6`, a helper's `clockRun(f, 30)`) lengthens the beat by as much. `?lengths` in the URL *(v2.7)* prints in the console each beat's voice (`pre` + clip), its length on screen and the time past voice + `HOLD`; read it after a change, and recut the music after any change in length. A helper that does not know the beat's `D` runs to the beat's end with `clockRun(f, 0, { tail: true })`, which never lengthens it.
- **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, or a camera shows a picture from the first frame, give the beat `{ lead: false }` in its fourth slot; when every opening in the chapter is timed by hand (a documentary), set `CHAPTER.lead = false` *(v2.2)* instead. 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.
+- **`minDur`** in the fourth slot (`{ minDur: 9.4 }`) *(v2.7)* is the least the whole beat lasts, hold included, as `?lengths` reports it: two mirrored beats (two answers treated alike) get the longer one's length.
+- **`dur`** in the fourth slot (`{ dur: 2 }`) *(v2.7)* makes a beat with no narration: no clip and no `TIMINGS` entry (the engine adds `{ dur, marks: {}, cues: [], silent: true }`), the picture runs `dur` seconds on wall time, then holds. A wordless card (a series card, an end card) needs no silence clip. A beat with a `TIMINGS` entry ignores `dur`.
- **`hold`** in the fourth slot of an `ask` beat in a film (`CHAPTER.film`) is read only by `export.py`: the seconds the video holds the waiting picture before it plays on as if the reader had acted (1.5 by default). The page ignores it.
- **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.
@@ -91,6 +94,7 @@ Firefox repaints SVG on the main thread and is the slowest common browser for th
- Large shapes under a big camera zoom or roll are expensive: a filled `<circle>` scaled 6× and rotating cost about 200 ms a frame in Firefox, while the same picture as one `<image>` cost about 3 ms. Prefer one image for a big detailed object (a planet, a map), and few elements over many small ones (merge cells into one path per colour, or use an image).
- Write per-frame attributes and text only when they change (`render()` already skips unchanged transform and opacity). A panel replaced at the start of a beat leaves the page after its fade, and at once while seeking *(v2.6)*; one replaced later in a beat is set to `display: none`. A removed node measures as nothing (`getBBox`, `getComputedTextLength` give 0, `getSubStringLength` throws) and its ids no longer resolve (`url(#…)`, `<use href>`): keep what a later beat measures or refers to outside a panel.
- Pixel-art sprites: draw `<image>` with `style="image-rendering: pixelated"` at an integer scale, and pre-scale the file (nearest neighbour) so it stays crisp where the style is ignored.
+- A `<canvas>` in a `foreignObject` is re-rastered on every frame in Gecko when a parent group scales or moves it: a canvas map pushed by a scaled wrapper got slower, not faster. Move a canvas through its own view (redraw it from `t`), or hold it still and move what lies over it; never scale its parent.
- Cross-fading two full-screen cameras costs a long frame: fade only the incoming one in over the outgoing one, then hide the old.
- A question card's entrance after a busy scene can hitch; measure it with `perf.py`.
@@ -114,7 +118,7 @@ quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'
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); a beat's last caption clears a second after its narration, so it does not sit on a closing title *(v2.4.2)*; a line in another language with a `sub` (`tts.py`, `eleven.py`) shows its subtitle even with captions off *(v2.4.1)*, `<`/`>` speed (0.75–1.5×, remembered), volume (remembered, except muted), F full screen *(v2.5)*: the stage fills the screen, and the controls lie over its foot, showing while the pointer moves or a key is pressed, while paused and while the pointer is on them (a touch screen, with no hover, keeps them under the stage); full screen also turns the screen to the stage's orientation where the browser can lock it (Android, not iOS), and on a phone held across the stage, starting the chapter goes full screen that way, so a landscape lesson is not a strip on an upright phone, ? help (it lists the question keys only in a chapter with questions, and a film with questions can leave them out with `CHAPTER.questionKeys = false` when its moments have their own controls *(v2.6)*). 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`. In a hidden tab (another tab or window in front) a timer keeps the clock going, so the chapter plays on from beat to beat *(v2.3.1; an older engine stops at the end of the beat until the tab is shown again)*. `?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.
-**Sound effects and music** *(v2.2)*, in films only: in a chapter with a question, `sfx()` and `music()` are silent, unless the chapter sets `CHAPTER.film = true` *(v2.3)*: a film with interactive moments (a documentary where the reader fires a rifle). There, while a question beat waits for the reader after its narration, the music plays on (it rises to 70 %, as in a lead-in) and is not pulled back for the time it ran on, and a click on its step bar seeks into it like any other beat; the next beat's tracks take over as usual (`fade` 0 is a cut). `sfx(beat, t, name, vol)` plays `audio/sfx/<name>.mp3` when that beat's clock passes `t` in normal playback (a seek past it fires nothing), at half volume (vol 2 is full); effects are fetched and decoded when `sfx()` is called, before the first click *(v2.6)*; one still loading when it is due plays late, from its start, for up to a second. A long ambience listed in `SFX_BED` with its length (`SFX_BED.birds = 10`) is joined part-way after a seek. `music(file, beats, gain, fade)` is a looping track under the listed beats (all of them by default). Its place is the length of its earlier beats as they really ran plus the clock; a beat under music gives back from its closing hold the time the clock stood still (a clip getting going), so the film keeps the music's time *(v2.4)*. It ducks to 30 % for the whole beat, voice or not, and rises to 70 % only in the `pre` lead-in of the beats in `window.MUSIC_UP_IN_PRE` (`true` for all); it crossfades over `fade` s (0.8; 0 is a cut), and `window.MUSIC_OFF = { beat: t => true }` fades it out for a moment. Both go through one Web Audio graph started by the reader's first touch, click or key, so ducks, fades and the volume slider reach them on phones too (on iOS the slider does not reach the narration). A pause holds the music's level and a seek stops the effects. When a clip loading or buffering holds the clock, the music runs on, then eases back (5 % slower or faster), or jumps back once if it is more than a second out. Safari and every iOS browser stall a media element at each speed change, so there the music keeps the film's speed and is put back by a seek once it is a quarter second out, aimed ahead by the lag it showed after the last one *(v2.4.1)*. `export.py` reads `SFX`, `BGM` and these settings and mixes the film by the same rules.
+**Sound effects and music** *(v2.2)*, in films only: in a chapter with a question, `sfx()` and `music()` are silent, unless the chapter sets `CHAPTER.film = true` *(v2.3)*: a film with interactive moments (a documentary where the reader fires a rifle). There, while a question beat waits for the reader after its narration, the music plays on (it rises to 70 %, as in a lead-in) and is not pulled back for the time it ran on, and a click on its step bar seeks into it like any other beat; the next beat's tracks take over as usual (`fade` 0 is a cut). `sfx(beat, t, name, vol)` plays `audio/sfx/<name>.mp3` when that beat's clock passes `t` in normal playback (a seek past it fires nothing), at half volume (vol 2 is full); effects are fetched and decoded when `sfx()` is called, before the first click *(v2.6)*; one still loading when it is due plays late, from its start, for up to a second. A long ambience listed in `SFX_BED` with its length (`SFX_BED.birds = 10`) is joined part-way after a seek. `music(file, beats, gain, fade)` is a looping track under the listed beats (all of them by default; called above `BEATS`, it takes them all when `boot()` runs *(v2.7)*, and a listed id that `BEATS` lacks is named in a console warning). Its place is the length of its earlier beats as they really ran plus the clock; a beat under music gives back from its closing hold the time the clock stood still (a clip getting going), so the film keeps the music's time *(v2.4)*. It ducks to 30 % for the whole beat, voice or not, and rises to 70 % only in the `pre` lead-in of the beats in `window.MUSIC_UP_IN_PRE` (`true` for all); it crossfades over `fade` s (0.8; 0 is a cut), and `window.MUSIC_OFF = { beat: t => true }` fades it out for a moment. Both go through one Web Audio graph started by the reader's first touch, click or key, so ducks, fades and the volume slider reach them on phones too (on iOS the slider does not reach the narration). A pause holds the music's level and a seek stops the effects. When a clip loading or buffering holds the clock, the music runs on, then eases back (5 % slower or faster), or jumps back once if it is more than a second out. Safari and every iOS browser stall a media element at each speed change, so there the music keeps the film's speed and is put back by a seek once it is a quarter second out, aimed ahead by the lag it showed after the last one *(v2.4.1)*. `export.py` reads `SFX`, `BGM` and these settings and mixes the film by the same rules.
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.
@@ -130,7 +134,7 @@ Keep `<link rel="expect" href="#bar" blocking="render">` in every chapter's head
- 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`, `HOLD`, `camera`, `soft`, `clockRun`, `retire`, `seeking`, `BOOK`, `bookSetting`, `TX`, `texPart`, …); a redeclaration stops the page script. `lint.py` lists every clash, each name of a `const a = 1, b = 2` included.
+- **Global names.** The engine keeps its own state and helpers in a closure *(v2.7)*: a chapter may use any other name (`clock`, `fit`, `frame`, `last`, `ui`, `segs`, …; an older engine declared those too), and the engine calls its own functions: replacing one from outside (`window.start = …`) no longer reaches the engine; watch `P` instead. The names it puts in global scope are the API: `TRANSLATIONS PORTRAIT SW SH LANGUAGE translate DECIMAL_SIGN isShortcut NS UI BOOK bookSetting COL MATH NAME BAND RIGHT TOPR SCREEN SORT_SCREEN $m mk st put render G path T cite ctx2d textW F R E TX $tex texGraphic texPart OV M chip tokens layRow collapse mathEl io out back lin tw prog show hide draw pop pulse stream mix evalTo soft clockRun camera scene S AXIS X Y0 num reset tick dot arrow panel retire header fx fxp finishFx pulseFx shakeFx floatText TF $ kbd sources uiW SCORE h rich card mascotEl quiz qlayer keyAct choice mcq tap tapEls pickEls grid rat gcd lowest blanks SND P HOLD clearCards seek seekInto start setSpeed setPlaying setCaptions hideCover restart boot ENGINE seeking captions finishCard BOOK_PROGRESS_KEY progress`, plus the window properties `sfx music SFX SFX_BED BGM MathJax`. A chapter that declares one of them again stops with an error; prefix chapter helpers that would (`rect`, `popIn`, `eqLine`, `slot` from math.js too, when the chapter loads it). `lint.py` lists every clash, each name of a `const a = 1, b = 2` included. `finishCard` and `progress` stay assignable for `scorm-bridge.js`, which wraps them.
- 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/scripts/engine.py b/.claude/skills/papermorph/scripts/engine.py
index 77fc9df..0e74ded 100644
--- a/.claude/skills/papermorph/scripts/engine.py
+++ b/.claude/skills/papermorph/scripts/engine.py
@@ -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/[email protected]' # follows the latest compatible 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/engine/engine.js b/engine/engine.js
index 65f7780..b59277b 100644
--- a/engine/engine.js
+++ b/engine/engine.js
@@ -4,6 +4,13 @@
// A fast follow-up navigation can abort the incoming page transition.
addEventListener('pagereveal', e => e.viewTransition?.ready.catch(() => {}));
+// The engine's state and helpers live in one closure. Only the names declared at the end of this file are global (the
+// API that chapters, math.js, book libraries and the scripts use), so a chapter may name its own helpers anything else
+// (clock, fit, frame, last, ui, …).
+let seeking = false; // true while seek() replays the beats before its target
+let captions = false; // the reader's captions setting (C)
+const ENGINE = (() => {
+
/* ---------- interface language ---------- */
// The page's <html lang> picks the interface text; CHAPTER.language picks the audio folder. Set both alike.
// A value is a string or plural forms { one, few, many, other } chosen by vars.n. Missing keys fall back to English.
@@ -735,7 +742,6 @@ function panel(t0) {
// Take a beat's old picture away on wall time: a 150 ms fade, then out of rendering. On the beat clock the fade would
// wait for the new clip's audio to start (a few hundred ms in Firefox) with the old, frozen scene still showing.
// While seeking, the pictures passed on the way were never seen: they go at once.
-let seeking = false;
// It then leaves the page: a long film otherwise keeps every earlier beat's picture (a documentary's maps: megabytes).
function retire(e) {
if (seeking) { e.remove(); return; }
@@ -1187,6 +1193,7 @@ const blanks = rowsIn => (body, api) => {
When a clip loading or buffering holds the film's clock, the music runs on and then eases back (5 % slower or faster),
or jumps back once if it is more than a second out. */
const SND = { sfx: [], bed: {}, bgm: [], len: [], on: [], wait: [], buf: {}, ctx: null, out: null, last: { i: -1, t: 0 }, duck: .3 };
+const everyBeat = () => { try { return BEATS.map(b => b.id); } catch { return undefined; } }; // undefined until BEATS is defined
// window properties, not declarations: a book with its own older sfx() or BGM declares them over these
Object.assign(window, { SFX: SND.sfx, SFX_BED: SND.bed, BGM: SND.bgm,
sfx(beat, at, name, vol = 1, bed = SND.bed[name] || 0) {
@@ -1194,7 +1201,8 @@ Object.assign(window, { SFX: SND.sfx, SFX_BED: SND.bed, BGM: SND.bgm,
if (e) Object.assign(e, { vol, bed }); else SND.sfx.push({ beat, at, name, vol, bed });
sfxLoad(name);
},
- music(file, beats = BEATS.map(b => b.id), gain = 1, fade = .8) {
+ // without beats, every beat: boot() fills them in when music() comes before BEATS
+ music(file, beats = everyBeat(), gain = 1, fade = .8) {
const m = { n: file, beats, gain, fade, v: 0, a: Object.assign(new Audio(file), { preload: 'auto', loop: true, volume: 0 }) };
SND.bgm.push(m);
if (SND.ctx) bgmWire(m);
@@ -1326,8 +1334,9 @@ function runBeat(i) {
b.run(m, pre + tm.dur);
if (S.cleared && b.lead !== false && CHAPTER.lead !== false && !pre) leadIn(); // CHAPTER.lead false: no beat gets one (a film)
TW.sort((a, c) => a.t0 - c.t0);
- // runs that last to the end anyway (tails, follow cameras) do not set it: only the narration and the other tweens do
- const end = Math.max(pre + tm.dur, ...TW.filter(w => !w.tail).map(w => w.t0 + w.dur)) + HOLD;
+ // runs that last to the end anyway (tails, follow cameras) do not set it: only the narration and the other tweens do,
+ // and minDur, the least the whole beat lasts (two mirrored beats run the same seconds)
+ const end = Math.max(Math.max(pre + tm.dur, ...TW.filter(w => !w.tail).map(w => w.t0 + w.dur)) + HOLD, b.minDur || 0);
const tail = TW.some(w => w.tail === true);
for (const w of TW) if (w.tail === true || tail && w.tail === 'follow') w.dur = end - w.t0;
return SND.len[i] = end; // the music places itself by how long each beat really runs
@@ -1389,16 +1398,18 @@ function start(i, play) {
P.end = runBeat(i);
evalTo(0);
const a = P.audio = beatClip(i, true);
- a.volume = +($('volume')?.value ?? 1);
- a.playbackRate = P.rate;
- // An aborted or superseded load (fast stepping, a reload) is not a failure: only a real error for the current clip
- // shows the note, and the note goes away as soon as a clip plays.
- a.onerror = () => { if (P.audio === a && a.error && a.error.code !== MediaError.MEDIA_ERR_ABORTED) soundFailed(); };
- a.onplaying = () => {
- if (P.audio !== a) return;
- $('soundNote').hidden = true;
- if (P.afail) { P.afail = false; a.currentTime = Math.max(0, P.t - (BEATS[P.i].pre || 0)); } // sound came back late: rejoin the picture where it is
- };
+ if (a) { // a beat with no narration ({ dur }) has no clip: wall time drives its clock
+ a.volume = +($('volume')?.value ?? 1);
+ a.playbackRate = P.rate;
+ // An aborted or superseded load (fast stepping, a reload) is not a failure: only a real error for the current clip
+ // shows the note, and the note goes away as soon as a clip plays.
+ a.onerror = () => { if (P.audio === a && a.error && a.error.code !== MediaError.MEDIA_ERR_ABORTED) soundFailed(); };
+ a.onplaying = () => {
+ if (P.audio !== a) return;
+ $('soundNote').hidden = true;
+ if (P.afail) { P.afail = false; a.currentTime = Math.max(0, P.t - (BEATS[P.i].pre || 0)); } // sound came back late: rejoin the picture where it is
+ };
+ }
const b = BEATS[i];
if (b.ask) b.ask(() => {
if (P.gen !== gen || P.done) return;
@@ -1411,6 +1422,7 @@ function start(i, play) {
}
// The next beat's clip starts loading while this one plays, so a slow connection does not stall between beats.
function beatClip(i, take) {
+ if (TIMINGS[BEATS[i].id]?.silent) return null;
// the clip's length rides on the URL: regenerated narration gets a new address, so a browser cache cannot pair new
// timings with an old clip
const src = `audio/${CHAPTER.language || 'en'}/${BEATS[i].id}.mp3?v=${TIMINGS[BEATS[i].id]?.dur ?? ''}`;
@@ -1558,7 +1570,7 @@ function placeCaption(asking) {
const [bottom, left, width] = at.split('|'), s = $('caption').style;
Object.assign(s, { bottom: bottom && bottom + 'px', left: left && left + 'px', maxWidth: width && width + 'px' });
}
-let captions = false, capText = '';
+let capText = '';
try { captions = localStorage.getItem('captions') === '1'; } catch {}
function setCaptions(on, save = true) {
captions = on;
@@ -1681,17 +1693,15 @@ fit();
// Start the lesson once the chapter page has defined CHAPTER and BEATS.
// ?beat=N&t=S opens a paused frame, for reviewing a single moment.
-// Per-book progress shared with the cover/contents at the parent URL folder.
-const BOOK_PROGRESS_KEY = bookSetting('--progress-key') || 'animebook:progress:' + new URL('../', location.href).pathname;
-function progress(f) {
- try {
- const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');
- const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
- p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];
- f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));
- } catch {}
-}
function boot() {
+ // a beat with no narration: { dur } in its fourth slot stands in for its clip and its TIMINGS entry
+ window.TIMINGS ??= {};
+ for (const b of BEATS) if (!TIMINGS[b.id] && b.dur != null) TIMINGS[b.id] = { dur: b.dur, marks: {}, cues: [], silent: true };
+ for (const m of SND.bgm) { // music() above BEATS plays under every beat
+ m.beats ??= BEATS.map(b => b.id);
+ const lost = m.beats.filter(id => !BEATS.some(b => b.id === id));
+ if (lost.length) console.warn(`music('${m.n}'): no beat ${lost.join(', ')} in BEATS`);
+ }
$('coverK').textContent = translate('chapterNumber', { n: CHAPTER.label ?? CHAPTER.number });
$('coverT').textContent = CHAPTER.title;
$('bHome').href = `../#ch${String(CHAPTER.number).padStart(2, '0')}`;
@@ -1706,6 +1716,14 @@ function boot() {
$('coverMeta').textContent = translate(film ? 'aboutMinutesFilm' : 'aboutMinutes', { n: num(CHAPTER.minutes) });
buildSegs();
const qs = new URLSearchParams(location.search);
+ if (qs.has('lengths')) { // each beat's voice against its length on screen: a tween or a run past the voice lengthens it
+ reset(); seeking = true;
+ try { for (let k = 0; k < BEATS.length; k++) { runBeat(k); evalTo(Infinity); } } finally { seeking = false; }
+ console.log(`?lengths: beat, voice (pre + clip), on screen (hold included), and the time past voice + ${HOLD} s hold\n` + BEATS.map((b, i) => {
+ const v = (b.pre || 0) + TIMINGS[b.id].dur, over = SND.len[i] - HOLD - v;
+ return `${b.id.padEnd(16)} ${v.toFixed(2).padStart(6)} ${SND.len[i].toFixed(2).padStart(6)}${over > .005 ? ` +${over.toFixed(2)}` : ''}`;
+ }).join('\n'));
+ }
if (qs.has('beat')) {
$('cover').hidden = true;
seek(Math.max(0, Math.min(BEATS.length - 1, qs.get('beat') | 0)), false);
@@ -1718,3 +1736,51 @@ function boot() {
// one (a tab playing sound keeps its timers). Its ticks come late, so they may move the clock further at once.
setInterval(() => { if (document.hidden) frameStep(performance.now(), 1.5); }, 250);
}
+return { TRANSLATIONS, PORTRAIT, SW, SH, LANGUAGE, translate, DECIMAL_SIGN, isShortcut, NS, UI, BOOK, bookSetting,
+ COL, MATH, NAME, BAND, RIGHT, TOPR, SCREEN, SORT_SCREEN, $m, mk, st, put, render, G, path, T, cite, ctx2d, textW, F,
+ R, E, TX, $tex, texGraphic, texPart, OV, M, chip, tokens, layRow, collapse, mathEl, io, out, back, lin, tw, prog,
+ show, hide, draw, pop, pulse, stream, mix, evalTo, soft, clockRun, camera, scene, S, AXIS, X, Y0, num, reset, tick,
+ dot, arrow, panel, retire, header, fx, fxp, finishFx, pulseFx, shakeFx, floatText, TF, $, kbd, sources, uiW, SCORE,
+ h, rich, card, mascotEl, quiz, qlayer, keyAct, choice, mcq, tap, tapEls, pickEls, grid, rat, gcd, lowest, blanks,
+ SND, P, HOLD, clearCards, seek, seekInto, start, setSpeed, setPlaying, setCaptions, hideCover, restart, boot,
+ finishCard };
+})();
+
+// The API, one global each: lint.py reads these declarations, and a chapter that declares one of them again stops
+// with an error, as before.
+const TRANSLATIONS = ENGINE.TRANSLATIONS, PORTRAIT = ENGINE.PORTRAIT, SW = ENGINE.SW, SH = ENGINE.SH,
+ LANGUAGE = ENGINE.LANGUAGE, translate = ENGINE.translate, DECIMAL_SIGN = ENGINE.DECIMAL_SIGN,
+ isShortcut = ENGINE.isShortcut, NS = ENGINE.NS, UI = ENGINE.UI, BOOK = ENGINE.BOOK,
+ bookSetting = ENGINE.bookSetting, COL = ENGINE.COL, MATH = ENGINE.MATH, NAME = ENGINE.NAME, BAND = ENGINE.BAND,
+ RIGHT = ENGINE.RIGHT, TOPR = ENGINE.TOPR, SCREEN = ENGINE.SCREEN, SORT_SCREEN = ENGINE.SORT_SCREEN, $m = ENGINE.$m,
+ mk = ENGINE.mk, st = ENGINE.st, put = ENGINE.put, render = ENGINE.render, G = ENGINE.G, path = ENGINE.path,
+ T = ENGINE.T, cite = ENGINE.cite, ctx2d = ENGINE.ctx2d, textW = ENGINE.textW, F = ENGINE.F, R = ENGINE.R,
+ E = ENGINE.E, TX = ENGINE.TX, $tex = ENGINE.$tex, texGraphic = ENGINE.texGraphic, texPart = ENGINE.texPart,
+ OV = ENGINE.OV, M = ENGINE.M, chip = ENGINE.chip, tokens = ENGINE.tokens, layRow = ENGINE.layRow,
+ collapse = ENGINE.collapse, mathEl = ENGINE.mathEl, io = ENGINE.io, out = ENGINE.out, back = ENGINE.back,
+ lin = ENGINE.lin, tw = ENGINE.tw, prog = ENGINE.prog, show = ENGINE.show, hide = ENGINE.hide, draw = ENGINE.draw,
+ pop = ENGINE.pop, pulse = ENGINE.pulse, stream = ENGINE.stream, mix = ENGINE.mix, evalTo = ENGINE.evalTo,
+ soft = ENGINE.soft, clockRun = ENGINE.clockRun, camera = ENGINE.camera, scene = ENGINE.scene, S = ENGINE.S,
+ AXIS = ENGINE.AXIS, X = ENGINE.X, Y0 = ENGINE.Y0, num = ENGINE.num, reset = ENGINE.reset, tick = ENGINE.tick,
+ dot = ENGINE.dot, arrow = ENGINE.arrow, panel = ENGINE.panel, retire = ENGINE.retire, header = ENGINE.header,
+ fx = ENGINE.fx, fxp = ENGINE.fxp, finishFx = ENGINE.finishFx, pulseFx = ENGINE.pulseFx, shakeFx = ENGINE.shakeFx,
+ floatText = ENGINE.floatText, TF = ENGINE.TF, $ = ENGINE.$, kbd = ENGINE.kbd, sources = ENGINE.sources,
+ uiW = ENGINE.uiW, SCORE = ENGINE.SCORE, h = ENGINE.h, rich = ENGINE.rich, card = ENGINE.card,
+ mascotEl = ENGINE.mascotEl, quiz = ENGINE.quiz, qlayer = ENGINE.qlayer, keyAct = ENGINE.keyAct,
+ choice = ENGINE.choice, mcq = ENGINE.mcq, tap = ENGINE.tap, tapEls = ENGINE.tapEls, pickEls = ENGINE.pickEls,
+ grid = ENGINE.grid, rat = ENGINE.rat, gcd = ENGINE.gcd, lowest = ENGINE.lowest, blanks = ENGINE.blanks,
+ SND = ENGINE.SND, P = ENGINE.P, HOLD = ENGINE.HOLD, clearCards = ENGINE.clearCards, seek = ENGINE.seek,
+ seekInto = ENGINE.seekInto, start = ENGINE.start, setSpeed = ENGINE.setSpeed, setPlaying = ENGINE.setPlaying,
+ setCaptions = ENGINE.setCaptions, hideCover = ENGINE.hideCover, restart = ENGINE.restart, boot = ENGINE.boot;
+// Hooks: scorm-bridge.js wraps these two, and the engine calls progress() through this global.
+let finishCard = ENGINE.finishCard;
+// Per-book progress shared with the cover/contents at the parent URL folder.
+const BOOK_PROGRESS_KEY = bookSetting('--progress-key') || 'animebook:progress:' + new URL('../', location.href).pathname;
+function progress(f) {
+ try {
+ const saved = JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY) || '{}');
+ const p = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
+ p.done = Array.isArray(p.done) ? p.done.filter(n => Number.isInteger(n) && n > 0) : [];
+ f(p); localStorage.setItem(BOOK_PROGRESS_KEY, JSON.stringify(p));
+ } catch {}
+}