diff --git a/.claude/hooks/stage_log.py b/.claude/hooks/stage_log.py index e0793e1..c91c13b 100644 --- a/.claude/hooks/stage_log.py +++ b/.claude/hooks/stage_log.py @@ -3,6 +3,8 @@ After every Read, Grep, Glob or Bash call, if a new piece is in a design stage (the newest proj/*/brief.md whose status line says Stage: interview, brief, concepts or storyboard), append one JSON line to proj//access.jsonl: time, stage, mode, tool and the paths touched (for Bash, the command). tools/check_stage_reads.py reads the logs. +Bash commands made only of git bookkeeping (add, commit, push, status) plus cd/echo are skipped: they read no piece +content, and logging them left the log dirty after every commit. Other git commands (show, diff, log) are logged. Any error is swallowed: the hook must never get in the way of the session. """ import json, os, re, sys, time, glob @@ -28,6 +30,16 @@ def piece_in_design(root): return best +BOOKKEEPING = re.compile(r'^(cd\b|echo\b|git\s+(add|commit|push|status)\b)') + + +def bookkeeping_only(cmd): + # Drop quoted text (commit messages) first, then every segment must be bookkeeping. + bare = re.sub(r'"(?:\\.|[^"\\])*"|\'[^\']*\'', '""', cmd) + segments = [s.strip() for s in re.split(r'&&|\|\||;|\||\n', bare)] + return all(not s or BOOKKEEPING.match(s) for s in segments) + + def rel(root, p): if not p: return p @@ -42,6 +54,8 @@ def main(): tool = ev.get('tool_name', '') if tool not in ('Read', 'Grep', 'Glob', 'Bash'): return + if tool == 'Bash' and bookkeeping_only(str((ev.get('tool_input') or {}).get('command', ''))): + return found = piece_in_design(root) if not found: return diff --git a/README.md b/README.md index 582017d..82dcd01 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Start sound for the music. Move the mouse to see the controls. | `players/danbury-academies-clock.html` | The Academies film below with a wall clock and a session timer, for a classroom screen | | `players/sanctioned-corporate-calm.html` | Sanctioned Corporate Calm: a 20-minute seamless study loop built from the Academies film's tunes, with a wall clock and a session timer | | `players/gen-player.html` | The generative library below as one self-contained file (USB-stick ready) | +| `players/essay-demo.html` | The motion-essay engine in the kit (for ProofEr): shader scenes (bars from zero, a dot tally, proportional and nested areas) built from data rows, quiet transitions, words over the picture from per-language tracks (English, draft Spanish), a quiet drone, a sources chapter with links. Lays out for phones held upright too. Placeholder words and made-up numbers, labelled so. Built by `tools/build_essay_demo.py` | - **Generative motion library:** double-click **`gen/player.html`**. Press **G** for the gallery of ready-made cartridges (Truchet tiles, 3D dot meshes, dot swarms that fly into words, flow fields, Julia sets, tunnels, @@ -89,6 +90,7 @@ so they run from Thonny or any editor's Run button, or from a terminal (`python3 | The **Academies film and the Sanctioned Corporate Calm study loop, with a wall clock + timer** | `tools/build_academies_clock.py` (re-run after any change to either master in `academies-film/`) | `dist/danbury-academies-clock.html`, `dist/sanctioned-corporate-calm.html` | | A **self-contained gen player** to put on a USB stick | `python3 gen/build.py` | `gen/dist/gen-player.html` | | **One gen cartridge as its own HTML and/or an MP4 with its music** | run `tools/gen_export.py` (pick cartridge + folder) | the folder you picked | +| The **motion essay demo** (the kit's essay engine) | `tools/build_kit.py`, then `tools/build_essay_demo.py` | `dist/essay-demo.html` | The first build downloads the open-source fonts (SIL OFL, from Google Fonts' GitHub) and caches them; after that, everything is offline. `tools/build.py` needs `pip install fonttools brotli`. @@ -165,7 +167,7 @@ the project: the reusable parts are already here, so a new piece is mostly a sho | `proj//` | One piece's brief, copy and sources (`cdrom`, `pltw`, `cs`, `ex`, `ssr`, `academies`) | | `living/`, `jukebox/` | The living-poster engine and the jukebox page | | `engine/` | The starter timeline engine the Academies film grew from; `engine/src/audio/dsp.js` is the DSP everything uses | -| `kit/` | Engine parts packaged for other projects (the lens, the DSP), versioned, with sha256s in `kit/KIT.json`; built by `tools/build_kit.py`, never edited by hand | +| `kit/` | Engine parts packaged for other projects (the lens, the DSP, the motion-essay engine), versioned, with sha256s in `kit/KIT.json`; built by `tools/build_kit.py`, never edited by hand | | `academies-film/` | The finished Academies hallway film | | `fonts/` | Downloaded open-source fonts and their licenses | diff --git a/STATUS.md b/STATUS.md index b1e2a4f..543834e 100644 --- a/STATUS.md +++ b/STATUS.md @@ -3,7 +3,7 @@ > **Visitors:** this is the project's working log, kept for the people and AI assistants working on it. For what > EOMD is and how to use it, start with [README.md](README.md). -_Last updated: Nov 28, 2026 (kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its +_Last updated: Dec 1, 2026 (kit v0.4.0, ProofEr's review fixes: drone audible on small speakers at −28 LUFS, bigger laptop type, text never over data; kit v0.3.0, ProofEr's addendum: portrait layouts, pause button, per-language text tracks, data-row sequences, drone bed, sources chapter; kit v0.2.0: the motion-essay engine for ProofEr: beat model + fixed-step clock, essay player shell, test hooks + `engine/tools/essay-qa.js`, plain-WebGL2 scene host + compositor with the lens on a GPU texture, 4 scenes, 6 transitions, HTML text with a WCAG check; demo at `players/essay-demo.html`. Nov 28: kit v0.1.0: `kit/` + `tools/build_kit.py` for ProofEr; both repos are AGPLv3, so no licence obstacle; video-essay plan in `TODO.md`; lens upgraded: 6-level glow, halation, AgX/ACES, grade, dither; engine audio fallback renders in slices and works when the worker is blocked. Nov 27: optional WebGL2 lens finish, ideas taken from the Q-Day player; before that Nov 21: CD-ROM link options `?start=`, `?go`, `?airship`; before that Nov 4: fresh-eyes review added to the design stages; Academies film: clock + timer version). Each piece's history, limits and open questions live in its folder's `STATUS.md`; repo-wide history in `notes/history.md`._ ## Pieces @@ -15,7 +15,7 @@ folder's `STATUS.md`; repo-wide history in `notes/history.md`._ | CSE hallway loop (new, full creative) | Done; published Oct 25 (`players/cse-loop.html`) | ES/PT check; real-TV check | `proj/cse-loop/STATUS.md` | | PLTW CSE promo | r2 published ("cheesy as hell, but exactly what I asked for") | The PLTW test below | `proj/pltw/STATUS.md` | | Engine lens finish (`engine/src/fx/lens.js`) | Built Nov 27, upgraded Nov 28; in the engine's dev, kiosk, stills and MP4 paths; off by default | Not yet seen on a real TV; not yet inlined in CD-ROM, living or gen | -| Video essays (Q-Day / Last Boring Slide level) | Planned: `TODO.md`. Decided Nov 28: EOMD builds the engine as a versioned kit; ProofEr hosts motion essays (TODO §0) | Kit v0.1.0 built (`kit/`, `tools/build_kit.py`); next: ProofEr's sync script against it, then the GPU scene layer | +| Video essays (Q-Day / Last Boring Slide level) | Kit v0.4.0 (Dec 1; v0.3.0 + ProofEr's review fixes): the essay engine (`engine/src/essay/`, `engine/src/gl/`, `engine/src/audio/bed.js`) with ProofEr's addendum for holocaust-by-country (portrait, text tracks, data-row sequences, drone bed, sources). Demo `players/essay-demo.html` (placeholder words, made-up numbers, EN + DRAFT ES track). EOMD builds the engine; ProofEr hosts motion essays (TODO §0) | Bryan tries the new bed on phone and laptop speakers; ProofEr syncs 0.4.0; next here (`TODO.md` top): GPU letter type, sound hits, essay MP4. Not yet seen on a real GPU, phone or TV (tested in SwiftShader) | | gen library (incl. Dust Type) | Working; `tools/gen_export.py` | Check Dust Type knobs | `gen/STATUS.md` | | Jukebox | 15 cartridges | Redesign its look | `jukebox/STATUS.md` | diff --git a/TODO.md b/TODO.md index 58034f2..ba7984b 100644 --- a/TODO.md +++ b/TODO.md @@ -12,6 +12,31 @@ background beds, presenter tools). Take their mechanisms, never their look or mu - Engine audio renders in slices on the main thread (`P.steps`, `P.runAsync`, `DHS.audio.renderAsync`). A blocked worker now falls back to it instead of going silent. +**Kit v0.2.0 (Dec 1, 2026): the essay engine.** Beat model + fixed-step clock (§2), essay player shell (§5), test +hooks + `engine/tools/essay-qa.js` (§6), WebGL2 toolkit, scene host, render-to-texture compositor and lens on a GPU +texture (§1), six transitions (§1), HTML text over the picture (§3), and a demo essay with placeholder content +(`players/essay-demo.html`, built by `tools/build_essay_demo.py`). Sources: `engine/src/essay/`, `engine/src/gl/`. + +**Kit v0.3.0 (Dec 1, 2026): ProofEr's addendum** for its first motion essay (holocaust-by-country, watched on +viewers' own laptops, tablets and phones): portrait layouts for every scene and text position (QA at 390×844 and +1920×1080), plays by itself with an always-visible pause button (Space), words as per-language JSON tracks with +holds per language (`engine/src/essay/track.js`), data-row scene templates and the `nested` scene, one quiet drone +bed (`engine/src/audio/bed.js`, ffmpeg-checked), a sources chapter with working links, and a takeaway. + +**Kit v0.4.0 (Dec 1, 2026): fixes from ProofEr's review.** The bed moved up into what small speakers play (−28 LUFS, +small-speaker check), small type got bigger on laptops, and text can no longer cover data marks (checked; a side +layout for phones held sideways). + +**Next, in order** (not started): +1. **GPU letter-by-letter type** (§3). +2. **Sound hits and effects** (§4); beds that know the cut. One drone bed is done (v0.3.0). +3. **MP4 export of an essay** (§6): `tools/html_to_mp4.py` stepping the fixed clock via `EOMD_ESSAY.at(t)`, with the + bed rendered offline (`DHS.bed.steps`). +4. Adaptive quality and warm-up (§5); linked/portal transitions and scene snapshots (§1); scrambled headlines (§3). + +**Dropped from the essay player (ProofEr, Dec 1):** presenter notes (N), the second window (P) and the scene grid +(O). Essays play by themselves; revisit only if a presented talk comes along. + Ordered by what unblocks the most. Each item says where it would live. "Essay player" means the player shell EOMD builds for the kit (§0), which ProofEr uses for motion essays. @@ -28,9 +53,9 @@ videos blur the line between interactive scrollytelling and video." Not yet: see **v0.1.0 built Nov 28** (lens, DSP with `P.steps`/`P.runAsync`; `tools/build_kit.py`, CI check): add each part below as it lands: - the lens; - - the GPU toolkit, scene host and shader scene cartridges (§1); + - the GPU toolkit, scene host and shader scene cartridges (§1): **v0.2.0**; - the DSP and sliced synthesis (`P.steps`, `P.runAsync`); - - the beat model and essay player shell (§2, §5); + - the beat model and essay player shell (§2, §5): **v0.2.0**; - GPU type (§3) and sound hits and beds (§4). Every file needs only the `DHS` namespace. - [ ] **`kit/KIT.json`: the kit's manifest, agreed with ProofEr (Nov 28).** ProofEr's sync script is being written @@ -76,8 +101,8 @@ videos blur the line between interactive scrollytelling and video." Not yet: see the kit. - **ProofEr:** anything sourced: infographics, scrolling data essays, and motion essays. - **Test:** if a piece's claims need sources, it's ProofEr, however much it moves. -- [ ] **No three.js.** The Last Boring Slide bundles it. Rebuild everything below in plain WebGL2, as the lens is. - Confirm this rule and add it to `engine/CLAUDE.md`. +- [x] **No three.js.** The Last Boring Slide bundles it. Everything is plain WebGL2, as the lens is; the rule is in + `engine/CLAUDE.md` (Dec 1). **Merge triggers.** Re-merge into one repo with two front doors ("motion piece", "sourced piece") sharing one method folder and one engine when any of these happens: @@ -89,18 +114,22 @@ Merging means keeping each front door's first-question context small (EOMD's is tokens today). ## 1. The picture: GPU scenes and how they join -- [ ] **Shader scenes.** Each scene is one fragment shader over the whole screen: +- [x] **Shader scenes** (v0.2.0: `engine/src/gl/gl.js` preamble, `scenes.js` with field, bars, tally, areas and a + plain fallback). Each scene is one fragment shader over the whole screen: - it gets time, a smoothed beat value, the mouse, and one or two data values; - a shared GLSL preamble gives hash, value noise, fbm, distance-field shapes (box, capsule, torus, smooth min) and a fake studio light for reflections; - this is the "real object under studio light" look with no image files. Both files do this. Lives in: `engine/src/gl/` (new), with a fallback scene when a shader won't build. -- [ ] **Render-to-texture compositor.** Draw the outgoing and incoming scenes into two buffers, run a transition +- [x] **Render-to-texture compositor** (v0.2.0: `engine/src/gl/host.js`; `DHS.lens.create(knobs, { gl })` + + `drawTexture`). Draw the outgoing and incoming scenes into two buffers, run a transition shader between them, then the lens. - The lens gets an entry point that takes a GPU texture, so GPU scenes skip the 2D upload and keep their full floating-point range (AgX and halation work properly on real highlights). - Canvas 2D scenes keep working through the upload path. -- [ ] **Transition library**, with timing as a function of transition progress: +- [ ] **Transition library**, with timing as a function of transition progress. **v0.2.0 has six** (cut, crossfade, + dip, wipe, dissolve, push; `engine/src/gl/transitions.js`), each measured at 0 or 1 flashes a second. Still to + take, as mechanisms only: - from Q-Day: collapse (cell dissolve), ripple, tile flip, zoom-blur warp, slices. Q-Day also lists lens, glass, liquid, cube and burn, but never wrote them; - from The Last Boring Slide: fold, wash, flaps, slam (paper fibres), daybreak, line, tear, portal-in and @@ -117,14 +146,14 @@ tokens today). shaders. ## 2. Time, beats and pacing -- [ ] **Beat model.** A scene is a list of beats, each with `dur`, `delay` and `hold`. +- [x] **Beat model** (v0.2.0: `engine/src/essay/beats.js`; back runs 2.4× faster in the player). A scene is a list of beats, each with `dur`, `delay` and `hold`. - Each beat has its own 0→1 progress that eases forward and runs back 2.4× faster when you go back. - `s.k(beat, t0, t1, ease)` times a move inside a beat. - It plays by itself (dur + hold, then next) or follows clicks. Lives in: the essay player. -- [ ] **Reading-time pacing.** A beat's hold comes from its word count (Q-Day: 2.6 s + 0.31 s a word, kept between +- [x] **Reading-time pacing** (v0.2.0). A beat's hold comes from its word count (Q-Day: 2.6 s + 0.31 s a word, kept between 5.2 and 16 s). Client copy stays word for word; only the timing comes from the words. -- [ ] **A pure function of time where possible.** Both files build up progress from frame to frame. For an MP4 and a +- [x] **A pure function of time where possible** (v0.2.0: `DHS.beats.clock`, `DHS.beats.rng`). Both files build up progress from frame to frame. For an MP4 and a seamless loop, the essay player needs a fixed-step clock (1/60 s) that seek and export can replay exactly, and a seeded random generator in place of `Math.random`. @@ -136,7 +165,8 @@ tokens today). - arrival styles: rise, blur, type, fade, scatter, track, drop, by letter, word or line, with stagger; - it can also sit inside a 3D scene. Lives in: `engine/src/gl/type.js`; later the gen `type` layer. -- [ ] **HTML text over the picture** (Q-Day's way, for long copy and sources): +- [x] **HTML text over the picture** (Q-Day's way, for long copy and sources). v0.2.0: `engine/src/essay/text.js`, all + but the scrambled headlines: - named positions (corners, centre, quote, chapter card, giant number); - a soft dark patch behind the text instead of glows; - words fading in one by one, and headlines that arrive scrambled and resolve; @@ -165,15 +195,16 @@ tokens today). Yield inside long instrument notes if it shows on a slow machine. ## 5. Player, presenter and performance -- [ ] **Essay player shell:** +- [x] **Essay player shell** (v0.2.0: `engine/src/essay/player.js`; right-click goes back; no sound yet): - start screen with Begin with sound / Begin silently; - controls hidden until the mouse moves, fading after 3 s (both files use less); - progress bar with gaps between chapters; - keyboard, swipe and right-click to go back; plays by itself (A); black screen (.); help card (?); - `#scene-beat` links that work with the back button. -- [ ] **Presenter tools:** notes for every beat (N), notes in a second window kept in step (P), a grid of all scenes +- [ ] **Presenter tools** (dropped for essays, Dec 1: see the top of this file): notes for every beat (N), notes in a second window kept in step (P), a grid of all scenes with thumbnails (O), and a talk timer. -- [ ] **Fill the screen without black bars:** lay out in 1920×1080 design units and widen the view to the screen's +- [x] **Fill the screen without black bars** (essays, v0.2.0/0.3.0: the GL canvas fills the screen and scenes lay out + for its shape, portrait included; the 2D runtime still letterboxes): lay out in 1920×1080 design units and widen the view to the screen's shape (`engine/src/player/runtime.js` letterboxes today). - [ ] **Quality that adapts.** - Render-scale steps 1 / 0.84 / 0.70 / 0.58: drop a step after about 1.2 s of slow frames, climb back only after @@ -183,15 +214,16 @@ tokens today). - [ ] **Warm-up:** a loading bar that runs every scene and transition once, off-screen, before the show (no stutter at the first cut). Scenes far from the current one shrink their buffers to 2×2 pixels; the next two scenes warm up ahead. -- [ ] **No WebGL2:** the text and sound still play, with a plain note on screen (both files do this). +- [x] **No WebGL2:** the text and sound still play, with a plain note on screen (both files do this). ## 6. Export and QA -- [ ] **Test hooks for stepped and essay players:** `seek(scene, beat, t)`, `trans(scene, p)` and `perf(scene)`, +- [x] **Test hooks for essay players** (v0.2.0: `window.EOMD_ESSAY`, `engine/tools/essay-qa.js`; stepped players + still use `?manual` + `advance()`): `seek(scene, beat, t)`, `trans(scene, p)` and `perf(scene)`, returning repeatable stills of any beat or any point in a transition. Used by fresh-eyes review (`brief/CRAFT.md` §11) and by `tools/html_to_mp4.py`. - [ ] **MP4 of an essay:** play by itself at a fixed step, capture frames, and lay in the offline render of the event log, frame-exact. Extends `tools/html_to_mp4.py`. -- [ ] **Fresh-eyes review of transitions:** stills at 0.25, 0.5 and 0.75 of every transition, plus a flash-rate +- [x] **Fresh-eyes review of transitions** (v0.2.0: `essay-qa.js` writes the stills and measures flashes): stills at 0.25, 0.5 and 0.75 of every transition, plus a flash-rate check. ## 7. Roll out what's already built diff --git a/engine/CLAUDE.md b/engine/CLAUDE.md index 2182486..95f490b 100644 --- a/engine/CLAUDE.md +++ b/engine/CLAUDE.md @@ -6,8 +6,15 @@ inside `engine/`, e.g. `node tools/build-player.js`). - `engine/src/audio/dsp.js` is the DSP every player uses: a change to it follows the regression rule in `audio/CLAUDE.md`. -- `engine/src/fx/lens.js` and `engine/src/audio/dsp.js` are copied into `kit/` for ProofEr: after changing either, run - `tools/build_kit.py` and commit `kit/` too (CI fails on a stale copy). A release also bumps `kit/KIT.json`'s version - and adds a `kit/CHANGELOG.md` section. +- Kit sources (copied into `kit/` for ProofEr): `src/fx/lens.js`, `src/audio/dsp.js`, `src/audio/bed.js`, + `src/essay/*.js` (beats, text tracks, player shell, words layer), `src/gl/*.js` (WebGL2 toolkit, scenes, transitions, compositor), `tools/essay-qa.js` and + `tools/render-bed.js`. + After changing any, run `tools/build_kit.py` and commit `kit/` too (CI fails on a stale copy). A release also bumps + `kit/KIT.json`'s version and adds a `kit/CHANGELOG.md` section. +- **No three.js, no libraries:** everything is plain WebGL2 in the `DHS` namespace, single-offline-HTML friendly. +- The motion-essay engine: `src/essay/beats.js` keeps the whole essay a pure function of the playhead; scene shaders + write linear light and lay out for portrait too; words live in per-language tracks, never in shaders; + transitions change each part of the screen once. Check with `tools/essay-qa.js` at 1920 1080 and 390 844. The demo + essay is `essay-demo/` (placeholder content only; real essays and their figures live in ProofEr). - `engine/tools/html_to_mp4.py` is the original MP4 script; use `tools/html_to_mp4.py` instead. - Don't open `engine/` for living-poster or jukebox work (only `dsp.js`, for DSP internals). diff --git a/engine/essay-demo/dev.html b/engine/essay-demo/dev.html new file mode 100644 index 0000000..c5e4883 --- /dev/null +++ b/engine/essay-demo/dev.html @@ -0,0 +1,29 @@ + + + + + + + Placeholder Motion Essay (dev) + + + + + + + + + + + + + + + + + + + diff --git a/engine/essay-demo/essay.js b/engine/essay-demo/essay.js new file mode 100644 index 0000000..f75816c --- /dev/null +++ b/engine/essay-demo/essay.js @@ -0,0 +1,42 @@ +/* DEMO ESSAY: placeholder content only. It shows what the kit's essay engine does; ProofEr owns real essays, their + copy, figures and design. Every number here is MADE UP and labelled so on screen; no real figures belong here + (they live in ProofEr's checked figures table). The words are in tracks/.json, not in this file. */ +// Made-up rows: what a per-country data row looks like (part2 of row B is missing on purpose: drawn as no figure) +const ROWS = [ + { id: 'a', name: 'Placeholder country A', total: 1000, part1: 600, part2: 300 }, + { id: 'b', name: 'Placeholder country B', total: 400, part1: 120, part2: null }, +]; +// prettier-ignore +const ESSAY = { + lang: 'en', + lens: { bloom: 0.12, threshold: 0.85, streak: 0, fringe: 0.3, vignette: 0.28, grain: 0.015, tone: 'none' }, + sound: { bed: { seed: 7 } }, // the default bed: -28 LUFS, body in 250 Hz-2 kHz so small speakers play it + // a scene template: each data row becomes a short run of scenes (its words: track text "country#1", "country#2") + templates: { + country: { + steps: [ + { scene: 'bars', fields: ['total', 'part1', 'part2'], data: { grow: 1 }, transition: { type: 'crossfade', dur: 2.2 }, + beats: [{ dur: 1.2 }, { dur: 3.2 }, { dur: 1.6, focus: 1 }] }, + { scene: 'nested', fields: ['total', 'part1'], data: { grow: 0 }, transition: { type: 'dissolve', dur: 2.2 }, + beats: [{ dur: 3 }] }, + ], + }, + }, + scenes: [ + { id: 'opening', chapter: 'opening', scene: 'field', data: { tint: [0.9, 0.86, 0.8] }, transition: { type: 'dip', dur: 2 }, + beats: [{ dur: 2.4 }, { dur: 1.6 }] }, + { sequence: 'country', rows: ROWS, scale: 'all', transition: { type: 'crossfade', dur: 2.2 } }, + { id: 'tally', chapter: 'part1', scene: 'tally', transition: { type: 'wipe', dur: 1.8 }, + data: { count: 640, cols: 40, grow: 1, box: [0.4, 0.3, 0.94, 0.76] }, + beats: [{ dur: 1.2 }, { dur: 6, ease: 'linear' }] }, + { id: 'areas', chapter: 'part2', scene: 'areas', transition: { type: 'dissolve', dur: 2.4 }, + data: { values: [100, 400, 25] }, + beats: [{ dur: 2.6 }, { dur: 1.4 }] }, + { id: 'quote', chapter: 'part2', scene: 'field', data: { tint: [0.75, 0.8, 0.9], drift: 0.4 }, transition: { type: 'push', dur: 2 }, + beats: [{ dur: 2 }] }, + { id: 'sources', chapter: 'sources', type: 'sources', perPage: 3, data: { tint: [0.8, 0.8, 0.8], drift: 0.2 }, + transition: { type: 'dip', dur: 2 } }, + { id: 'takeaway', chapter: 'close', scene: 'field', data: { tint: [0.9, 0.86, 0.8], drift: 0.2 }, transition: { type: 'crossfade', dur: 2.4 }, + beats: [{ dur: 2.4 }] }, + ], +}; diff --git a/engine/essay-demo/tracks/en.json b/engine/essay-demo/tracks/en.json new file mode 100644 index 0000000..b9a5ca5 --- /dev/null +++ b/engine/essay-demo/tracks/en.json @@ -0,0 +1,120 @@ +{ + "lang": "en", + "name": "English", + "title": "Placeholder Motion Essay", + "subtitle": "A demo of the EOMD kit. The words and numbers are placeholders, not facts.", + "chapters": { + "opening": "Opening", + "part1": "Part one", + "part2": "Part two", + "sources": "Sources", + "close": "Close" + }, + "fields": { "total": "Placeholder total", "part1": "Placeholder part 1", "part2": "Placeholder part 2" }, + "text": { + "opening": { + "1": [{ "pos": "chapter", "kind": "chapter", "text": "Placeholder chapter title" }], + "2": [ + { + "pos": "center", + "kind": "body", + "text": "This sentence stands in for the opening line of an essay. A real essay brings its own words, word for word." + } + ] + }, + "country": { "chapter": "{name}" }, + "country#1": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Three made-up values for {name}. Each bar starts at zero; all rows share one scale." + } + ], + "3": [{ "pos": "top-left", "kind": "body", "text": "One bar is brought forward while the others step back." }], + "note": "Made-up placeholder numbers" + }, + "country#2": { + "1": [ + { + "pos": "top-left", + "kind": "body", + "text": "A made-up part of {part1} inside a made-up whole of {total}. The areas are proportional." + } + ], + "note": "Made-up placeholder numbers" + }, + "tally": { + "1": [ + { "pos": "bottom-left", "kind": "number", "text": "640" }, + { "pos": "bottom-left", "kind": "body", "text": "A made-up count, one dot for each unit." } + ], + "2": [ + { + "pos": "top-right", + "kind": "body", + "text": "The dots arrive slowly, at a steady pace, so the number has time to register." + } + ], + "note": "Made-up placeholder count: one dot is one unit" + }, + "areas": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "Areas, not widths" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "A circle with four times the value has four times the area, so it is twice as wide, not four times." + } + ], + "labels": ["Placeholder X", "Placeholder Y", "Placeholder Z"], + "note": "Made-up placeholder numbers" + }, + "quote": { + "1": [ + { + "pos": "quote", + "kind": "quote", + "text": "“A placeholder quotation sits here, set apart from the running text, with room around it.”" + }, + { "pos": "quote", "kind": "source", "text": "Placeholder source, placeholder date" } + ] + }, + "sources": { + "1": [{ "kind": "headline", "text": "Sources" }], + "2": [{ "kind": "headline", "text": "Sources (continued)" }] + }, + "takeaway": { + "1": [ + { + "pos": "center", + "kind": "takeaway", + "text": "A placeholder takeaway: the one sentence a viewer should leave with." + } + ] + } + }, + "sources": [ + { + "title": "Placeholder source one", + "url": "https://example.org/placeholder-source-1", + "note": "A short explanation of what this source supports goes here." + }, + { + "title": "Placeholder source two", + "url": "https://example.org/placeholder-source-2", + "note": "Each title is a working link in the HTML player." + }, + { + "title": "Placeholder source three", + "url": "https://example.org/placeholder-source-3", + "note": "The site's name is shown too, for anyone watching a recording." + }, + { + "title": "Placeholder source four", + "url": "https://example.org/placeholder-source-4", + "note": "A long list is split across pages, each held long enough to read." + } + ] +} diff --git a/engine/essay-demo/tracks/es.json b/engine/essay-demo/tracks/es.json new file mode 100644 index 0000000..265a76b --- /dev/null +++ b/engine/essay-demo/tracks/es.json @@ -0,0 +1,157 @@ +{ + "lang": "es", + "name": "Español", + "draft": true, + "title": "Ensayo animado de muestra", + "subtitle": "Una demostración del kit de EOMD. Las palabras y los números son de muestra, no son datos reales.", + "ui": { + "begin": "Empezar", + "withSound": "Empezar con sonido", + "silently": "Empezar sin sonido", + "pause": "Pausa", + "play": "Reproducir", + "playAgain": "Ver de nuevo", + "next": "Siguiente", + "back": "Atrás", + "keys": "Teclas", + "close": "Cerrar", + "fullscreen": "Pantalla completa", + "soundOn": "Sonido activado", + "soundOff": "Sonido desactivado", + "soundLoading": "Preparando el sonido…", + "auto": "Se reproduce solo", + "waits": "Espera clics", + "part": "parte {n} de {total}", + "pressKeys": "Pulsa ? para ver las teclas", + "language": "Idioma", + "progress": "Progreso", + "noGL": "Esta pantalla no puede mostrar las imágenes en movimiento. Las palabras y los números se siguen viendo.", + "noData": "sin dato", + "help": [ + ["Espacio, K", "Pausa o reproducir"], + ["Clic, →", "Siguiente"], + ["Clic derecho, ←", "Atrás"], + ["Deslizar", "Siguiente o atrás"], + ["A", "Se reproduce solo o espera clics"], + ["M", "Sonido sí o no"], + [".", "Pantalla negra"], + ["F", "Pantalla completa"], + ["Inicio, Fin", "Primera o última parte"], + ["?", "Esta tarjeta"] + ] + }, + "chapters": { + "opening": "Inicio", + "part1": "Primera parte", + "part2": "Segunda parte", + "sources": "Fuentes", + "close": "Cierre" + }, + "fields": { "total": "Total de muestra", "part1": "Parte 1 de muestra", "part2": "Parte 2 de muestra" }, + "text": { + "opening": { + "1": [{ "pos": "chapter", "kind": "chapter", "text": "Título de capítulo de muestra" }], + "2": [ + { + "pos": "center", + "kind": "body", + "text": "Esta frase ocupa el lugar de la primera línea de un ensayo. Un ensayo real trae sus propias palabras, tal cual." + } + ] + }, + "country": { "chapter": "{name}" }, + "country#1": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Tres valores inventados para {name}. Cada barra empieza en cero; todas las filas comparten una escala." + } + ], + "3": [{ "pos": "top-left", "kind": "body", "text": "Una barra pasa al frente mientras las demás se apartan." }], + "note": "Números de muestra inventados" + }, + "country#2": { + "1": [ + { + "pos": "top-left", + "kind": "body", + "text": "Una parte inventada de {part1} dentro de un total inventado de {total}. Las áreas son proporcionales." + } + ], + "note": "Números de muestra inventados" + }, + "tally": { + "1": [ + { "pos": "bottom-left", "kind": "number", "text": "640" }, + { "pos": "bottom-left", "kind": "body", "text": "Un recuento inventado, un punto por unidad." } + ], + "2": [ + { + "pos": "top-right", + "kind": "body", + "text": "Los puntos llegan despacio, a un ritmo constante, para que el número tenga tiempo de calar." + } + ], + "note": "Recuento de muestra inventado: un punto es una unidad" + }, + "areas": { + "1": [{ "pos": "top-left", "kind": "headline", "text": "Áreas, no anchos" }], + "2": [ + { + "pos": "top-left", + "kind": "body", + "text": "Un círculo con el cuádruple del valor tiene el cuádruple del área, así que es el doble de ancho, no el cuádruple." + } + ], + "labels": ["Muestra X", "Muestra Y", "Muestra Z"], + "note": "Números de muestra inventados" + }, + "quote": { + "1": [ + { + "pos": "quote", + "kind": "quote", + "text": "«Aquí va una cita de muestra, separada del texto, con espacio a su alrededor.»" + }, + { "pos": "quote", "kind": "source", "text": "Fuente de muestra, fecha de muestra" } + ] + }, + "sources": { + "1": [{ "kind": "headline", "text": "Fuentes" }], + "2": [{ "kind": "headline", "text": "Fuentes (continuación)" }] + }, + "takeaway": { + "1": [ + { + "pos": "center", + "kind": "takeaway", + "text": "Una conclusión de muestra: la frase que el espectador debería llevarse." + } + ] + } + }, + "sources": [ + { + "title": "Fuente de muestra uno", + "url": "https://example.org/placeholder-source-1", + "note": "Aquí va una breve explicación de lo que respalda esta fuente." + }, + { + "title": "Fuente de muestra dos", + "url": "https://example.org/placeholder-source-2", + "note": "Cada título es un enlace que funciona en el reproductor HTML." + }, + { + "title": "Fuente de muestra tres", + "url": "https://example.org/placeholder-source-3", + "note": "También se muestra el nombre del sitio, para quien vea una grabación." + }, + { + "title": "Fuente de muestra cuatro", + "url": "https://example.org/placeholder-source-4", + "note": "Una lista larga se reparte en páginas, cada una el tiempo necesario para leerla." + } + ] +} diff --git a/engine/src/audio/bed.js b/engine/src/audio/bed.js new file mode 100644 index 0000000..3522bad --- /dev/null +++ b/engine/src/audio/bed.js @@ -0,0 +1,272 @@ +/* BED: one quiet generative ambient drone (near silence) for an essay, made with EOMD's DSP (DHS.dsp) in the page. + A seamless loop: every partial and every slow swell has a whole number of cycles in the loop, the air (filtered + noise) and the room are processed circularly, so the loop point can't be heard. Normalised to a loudness target + (BS.1770 integrated, LUFS) and true-peak limited (default ceiling -1.5 dBTP). Same seed and knobs, same samples. + + const out = DHS.dsp.drain(DHS.bed.steps(knobs)); // { L, R, sr, seconds, lufs, truePeakDb, gainDb } + result.smallSpeakerLufs: loudness above 300 Hz (what a phone or laptop speaker plays); keep it within ~6 dB of lufs + DHS.bed.renderAsync(knobs).then(...) // in a worker; or in ~8 ms slices on the main thread + const sound = DHS.bed.sound(knobs); // the essay player's sound hook (DHS.essay.mount opts.sound) + sound.prepare() starts rendering now (the player calls it when it mounts) + sound.start(audioContext) when rendered, loops it with a slow fade in + sound.update(t, playing) fades out on pause, back in on play + sound.setMuted(on) the player's sound button + Needs DHS.dsp (audio/dsp.js). Hits and effects are not here yet (kit TODO). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + // The character (Bryan): "music that sounds the way the Memorial to the Murdered Jews of Europe in Berlin looks": + // austere, grey, even, slowly shifting, no melody, nothing that swells into drama. So: a fixed open chord (fifths + // and a ninth, no third), every tone held the whole time, levels and overtones drifting a little and against each + // other so the total stays even. It is made for small speakers first: the body sits in about 250 Hz to 2 kHz. + const DEFAULTS = { + seed: 7, + seconds: 30, // loop length + sr: 48000, + root: 62, // MIDI note of the lowest body tone (62 = D4, 294 Hz): where phone and laptop speakers play + chord: [0, 7, 12, 14, 19], // semitones above the root: D4 A4 D5 E5 A5 + partials: [1, 0.32, 0.16, 0.07, 0.035], // levels of each tone's harmonics 1..5 (soft overtones, a grey tone) + shift: 0.3, // how far tone levels and overtones drift (0 = still; small keeps it even) + low: 0.35, // optional weight: the root two octaves down (D2) for headphones; never carries the sound; 0 = off + air: 0.3, // breath of band-passed noise around 1-3 kHz (0 = none) + brightness: 3600, // lowpass on the tones, Hz + lufs: -28, // integrated loudness target: quiet, under the words, but audible on small speakers + ceiling: -1.5, // true-peak ceiling, dBTP + room: 0.3, // reverb send + fade: 4, // seconds of fade in when sound starts + measure: false, // true: also measure the exact true peak (slow; tools/render-bed.js sets it for the ffmpeg check) + }; + + // a sine from a table (fast, and the same in the page, the worker and Node) + const TBL = 4096, + SIN = new Float32Array(TBL + 1); + for (let i = 0; i <= TBL; i++) SIN[i] = Math.sin((2 * Math.PI * i) / TBL); + const sinT = (ph) => { + const x = (ph - Math.floor(ph)) * TBL, + i = x | 0; + return SIN[i] + (SIN[i + 1] - SIN[i]) * (x - i); + }; + + // Small-speaker check: loudness of what a phone or laptop speaker can play (above 300 Hz, 4th-order highpass) + // next to the full-band loudness. Within about 6 dB means the bed doesn't live only in the bass. + function* smallSpeaker(bus, sr) { + const P = DHS.dsp; + const hp = yield* P.steps.circular(bus, () => { + const a = P.rbjHighpass(300, 0.7071, sr), + b = P.rbjHighpass(300, 0.7071, sr), + c = P.rbjHighpass(300, 0.7071, sr), + d = P.rbjHighpass(300, 0.7071, sr); + return (l, r) => [b(a(l)), d(c(r))]; + }); + return yield* P.steps.lufs(hp, sr); + } + + function* steps(knobs = {}) { + const P = DHS.dsp, + k = Object.assign({}, DEFAULTS, knobs); + const sr = k.sr, + N = Math.round(k.seconds * sr), + L = N / sr, + TAU = Math.PI * 2; + const rnd = P.rng(k.seed); + const bus = P.bus(N); + // whole cycles in the loop, so nothing jumps at the loop point + const cyc = (f) => Math.max(1, Math.round(f * L)) / L; + const n = k.chord.length; + for (let v = 0; v < n; v++) { + const f = cyc(P.mtof(k.root + k.chord[v])), + beat = (1 + v) / L, // a second copy this far above: a very slow grey beating, no vibrato + ph = (rnd() + 1) * Math.PI, + drift = ((v + 0.5) / n) * 2 * Math.PI, // phases spread round the circle: as one tone fades, another rises + amp = 0.22 / (1 + v * 0.35), + pan = ((v % 2 ? 1 : -1) * (0.15 + 0.1 * v)) / 1.5; + const hs = k.partials.map((w, h) => ({ w, f: cyc(f * (h + 1)), ph: rnd() })); + const buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr, + u = t / L; + // the change is mostly in the overtones (the grey shifts); levels drift by at most shift/2 (about 1.5 dB) + const lv = 1 - k.shift * 0.25 * (1 - Math.cos(2 * Math.PI * u + drift)); + const tone = 1 + k.shift * Math.sin(2 * Math.PI * 2 * u + drift + ph); + let x = 0.2 * sinT((f + beat) * t + ph); // faint, so the beating shimmers instead of swelling + for (let h = 0; h < hs.length; h++) x += hs[h].w * (h ? tone : 1) * sinT(hs[h].f * t + hs[h].ph); + buf[i] = x * amp * lv; + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, pan); + } + // the optional low layer: weight on headphones, far below the body's level on small speakers + if (k.low > 0) { + const f = cyc(P.mtof(k.root - 24)), + buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr; + buf[i] = k.low * 0.22 * (sinT(f * t) + 0.25 * sinT(2 * f * t)); + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, 0); + } + // tone colour + const body = yield* P.steps.circular(bus, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness, 0.5, sr), b(r, k.brightness, 0.5, sr)]; + }); + // air: noise band-passed round 1.8 kHz (circular, so its filter state is continuous across the loop) + if (k.air > 0) { + const air = P.bus(N); + for (let i = 0; i < N; i++) { + air.L[i] = rnd() * k.air * 0.25; + air.R[i] = rnd() * k.air * 0.25; + } + yield; + const f = yield* P.steps.circular(air, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, 1800, 0.55, sr, 'bp'), b(r, 1800, 0.55, sr, 'bp')]; + }); + P.mixInto(body, f); + } + let out = body; + if (k.room > 0) { + const wet = yield* P.steps.circular(out, P.reverb({ sr, size: 0.86, damp: 0.5, lp: k.brightness * 3 })); + P.mixInto(out, wet, k.room * 2.5); + } + // loudness target, then the true-peak limiter. The tones are lowpassed, so the true peak sits within a few dB of + // the sample peak: when the sample peak is more than 6 dB under the ceiling the limiter can't act, and its + // (slow) oversampled pass is skipped. + const measured = yield* P.steps.lufs(out, sr); + const gainDb = k.lufs - measured, + g = P.db(gainDb); + let peak = 0; + for (let i = 0; i < N; i++) { + out.L[i] *= g; + out.R[i] *= g; + peak = Math.max(peak, Math.abs(out.L[i]), Math.abs(out.R[i])); + } + yield; + let limited = false; + if (P.todb(peak) > k.ceiling - 6) { + out = (yield* P.steps.limit(out, sr, P.db(k.ceiling))).bus; + limited = true; + } + return { + L: out.L, + R: out.R, + sr, + seconds: L, + lufs: yield* P.steps.lufs(out, sr), // measured again after the gain (and the limiter, if it ran) + smallSpeakerLufs: yield* smallSpeaker(out, sr), + samplePeakDb: P.todb(peak), + truePeakDb: k.measure ? P.todb(P.truePeak(out)) : null, + limited, + gainDb, + }; + } + + // In a page where the kit files are inlined, the bed renders in a background worker made from their own text, so + // a busy or slow page (big screen, slow GPU, phone) can't starve it. Where workers are blocked, or the scripts + // were loaded by src (dev pages), it renders on the main thread in ~8 ms slices. + const SELF = G.document && G.document.currentScript ? G.document.currentScript.textContent : ''; + const inWorker = (knobs) => + new Promise((resolve, reject) => { + const dsp = G.document && Array.from(G.document.scripts).find((x) => x.textContent.includes('(DHS.dsp = {})')); + if (!SELF || !dsp || !G.Worker || !G.Blob || !G.URL) return reject(new Error('no worker sources')); + const code = + dsp.textContent + + '\n' + + SELF + + '\nonmessage=(e)=>{const r=DHS.dsp.drain(DHS.bed.steps(e.data));postMessage(r,[r.L.buffer,r.R.buffer]);};'; + const url = G.URL.createObjectURL(new G.Blob([code], { type: 'text/javascript' })); + let w; + try { + w = new G.Worker(url); + } catch (err) { + G.URL.revokeObjectURL(url); + return reject(err); + } + const done = () => { + w.terminate(); + G.URL.revokeObjectURL(url); + }; + w.onmessage = (e) => { + done(); + resolve(Object.assign(e.data, { via: 'worker' })); + }; + w.onerror = (e) => { + done(); + e.preventDefault && e.preventDefault(); + reject(new Error('worker failed')); + }; + w.postMessage(knobs || {}); + }); + const renderAsync = (knobs) => + inWorker(knobs).catch(() => + DHS.dsp.runAsync(steps(knobs), { budgetMs: 8 }).then((r) => Object.assign(r, { via: 'main thread' })) + ); + + // The essay player's sound hook. Rendering takes a second or two of sliced work after "Begin with sound". + function sound(knobs = {}) { + const k = Object.assign({}, DEFAULTS, knobs); + const S = { ctx: null, gain: null, src: null, muted: false, playing: false, status: 'idle', result: null }; + const level = () => (S.muted || !S.playing ? 0 : 1); + const ramp = (secs) => { + if (!S.gain) return; + const now = S.ctx.currentTime; + S.gain.gain.cancelScheduledValues(now); + S.gain.gain.setValueAtTime(S.gain.gain.value, now); + S.gain.gain.linearRampToValueAtTime(level(), now + secs); + }; + // start rendering before anyone asks (the player calls this when it mounts): by the time the viewer has read + // the start screen the bed is usually ready + let job = null; + S.prepare = () => { + if (!job) { + S.status = 'rendering'; + job = renderAsync(k); + } + return job; + }; + S.start = (ctx) => { + if (S.ctx) return; + S.ctx = ctx; + if (ctx.state === 'suspended') ctx.resume(); + return S.prepare().then( + (r) => { + S.result = r; + const b = ctx.createBuffer(2, r.L.length, r.sr); + b.copyToChannel(r.L, 0); + b.copyToChannel(r.R, 1); + S.gain = ctx.createGain(); + S.gain.gain.value = 0; + S.gain.connect(ctx.destination); + S.src = ctx.createBufferSource(); + S.src.buffer = b; + S.src.loop = true; + S.src.connect(S.gain); + S.src.start(); + S.status = 'playing'; + ramp(k.fade); + }, + (err) => { + S.status = 'failed'; + console.warn('bed: no sound', err); + } + ); + }; + S.update = (t, playing) => { + if (playing !== S.playing) { + S.playing = playing; + ramp(playing ? 1.5 : 0.6); + } + }; + S.setMuted = (m) => { + S.muted = !!m; + ramp(0.5); + }; + return S; + } + + DHS.bed = { DEFAULTS, steps, renderAsync, sound }; +})(globalThis); diff --git a/engine/src/essay/beats.js b/engine/src/essay/beats.js new file mode 100644 index 0000000..395dbf7 --- /dev/null +++ b/engine/src/essay/beats.js @@ -0,0 +1,231 @@ +/* BEATS: the time model of an essay. A scene is a list of beats; each beat has + delay seconds of quiet before it starts arriving + dur seconds it takes to arrive (its progress runs 0 -> 1, eased) + hold seconds it stays before the next beat (default: reading time from its words) + Scenes are joined by transitions that take their own time (the outgoing scene stays at its last beat, the incoming + one at its first beat's progress 0). Everything is a pure function of the playhead t (seconds from the start): + seek, stills and an MP4 export replay exactly. No Math.random: use DHS.beats.rng(seed). + + const TL = DHS.beats.compile(essay, { transDur: (type) => 1.2 }); + const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } + const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek + + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words + (a beat can change the limits with reading: { max: 40 }, as a page of sources does). + The words themselves are never changed; only the timing comes from them. + + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const clamp = (x, a, b) => (x < a ? a : x > b ? b : x); + const clamp01 = (x) => clamp(x, 0, 1); + + // Ease curves, all f(0) = 0 and f(1) = 1 + const EASE = { + linear: (x) => x, + in: (x) => x * x * x, + out: (x) => 1 - (1 - x) ** 3, + inOut: (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2), + sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x), + slow: (x) => 1 - (1 - x) ** 5, // long, gentle settle: the default for a solemn essay + }; + const ease = (e) => (typeof e === 'function' ? e : EASE[e] || EASE.slow); + + // ---- reading time + const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; + const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; + // words in a beat: text blocks, plus the titles and notes of a sources list + const blockWords = (x) => + typeof x === 'string' + ? countWords(x) + : countWords(x.text) + (x.items || []).reduce((n, it) => n + countWords(it.title) + countWords(it.note), 0); + const beatWords = (b) => (b.text || []).reduce((n, x) => n + blockWords(x), 0); + const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); + + // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names + const hash = (...parts) => { + let h = 2166136261; + const s = parts.join('\u0001'); + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return h >>> 0; + }; + const rng = (seed) => { + let a = (typeof seed === 'number' ? seed : hash(seed)) >>> 0; + const r = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + r.range = (lo, hi) => lo + (hi - lo) * r(); + r.int = (lo, hi) => Math.floor(lo + (hi - lo + 1) * r()); + r.pick = (arr) => arr[Math.floor(r() * arr.length)]; + return r; + }; + + // ---- the timeline + // essay: { scenes: [{ id, chapter, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text }] }] } + // opts.transDur(type): a transition's default length (the essay player passes the transition library's) + function compile(essay, opts = {}) { + const transDur = opts.transDur || (() => 1); + const reading = Object.assign({}, READING, opts.reading || {}); + const scenes = []; + let t = 0; + essay.scenes.forEach((sc, i) => { + const tr = typeof sc.transition === 'string' ? { type: sc.transition } : Object.assign({}, sc.transition || {}); + tr.type = tr.type || (i ? 'crossfade' : 'dip'); + tr.dur = tr.type === 'cut' ? 0 : tr.dur != null ? tr.dur : transDur(tr.type); + const S = { index: i, id: sc.id || 's' + (i + 1), chapter: sc.chapter || '', start: t, trans: tr, beats: [] }; + t += tr.dur; + S.body = t; + (sc.beats && sc.beats.length ? sc.beats : [{}]).forEach((b, j) => { + const words = beatWords(b); + const B = { + index: j, + delay: b.delay != null ? b.delay : 0, + dur: b.dur != null ? b.dur : 1.6, + hold: + b.hold != null + ? b.hold + : Math.max( + readingHold(words, b.reading ? Object.assign({}, reading, b.reading) : reading), + j === 0 && !words ? 1.5 : 0 + ), + ease: ease(b.ease), + words, + start: t, + }; + B.arrive = B.start + B.delay; + B.shown = B.arrive + B.dur; + B.end = B.shown + B.hold; + t = B.end; + S.beats.push(B); + }); + S.end = t; + scenes.push(S); + }); + const total = t; + + // the chapters, in order, with their time spans (for the progress bar) + const chapters = []; + scenes.forEach((S) => { + const last = chapters[chapters.length - 1]; + if (last && last.name === S.chapter) last.end = S.end; + else chapters.push({ name: S.chapter, start: S.start, end: S.end, scene: S.index }); + }); + + const sceneAt = (t) => { + let lo = 0, + hi = scenes.length - 1; + while (lo < hi) { + const m = (lo + hi + 1) >> 1; + if (scenes[m].start <= t) lo = m; + else hi = m - 1; + } + return lo; + }; + + // reduced motion: arrivals take at most `quick` seconds (same timeline length, so links and seeks still match) + function at(t, o = {}) { + t = clamp(t, 0, total); + const i = sceneAt(t), + S = scenes[i]; + const quick = o.reduced ? 0.35 : Infinity; + let beat = -1; + const raw = S.beats.map((B, j) => { + if (t >= B.arrive) beat = j; + return clamp01((t - B.arrive) / Math.max(1e-6, Math.min(B.dur, quick))); + }); + if (t < S.body) beat = -1; + else if (beat < 0) beat = 0; + const p = raw.map((r, j) => S.beats[j].ease(r)); + const trans = + t < S.body && S.trans.dur > 0 + ? { + type: S.trans.type, + from: i - 1, + to: i, + p: clamp01((t - S.start) / S.trans.dur), + dur: S.trans.dur, + fromT: i ? t - scenes[i - 1].body : 0, + } + : null; + const B = beat >= 0 ? S.beats[beat] : null; + return { + t, + total, + scene: i, + id: S.id, + chapter: S.chapter, + beat, + beatT: B ? t - B.start : 0, + sceneT: t - S.body, + raw, + p, + trans, + // progress of a move inside a beat: k(beat, 0.2, 0.8, 'out') runs 0 -> 1 while the beat goes 20% -> 80% + k: (j, t0 = 0, t1 = 1, e = 'inOut') => ease(e)(clamp01(((raw[j] || 0) - t0) / Math.max(1e-6, t1 - t0))), + }; + } + + // time of a beat's moments: 'start', 'arrive', 'shown' (fully in, hold begins), 'end' + const timeOf = (i, j = 0, where = 'shown') => { + const S = scenes[clamp(i, 0, scenes.length - 1)]; + if (j < 0) return S.start; + return S.beats[clamp(j, 0, S.beats.length - 1)][where]; + }; + // flat list of beats in order: [{ scene, beat }], for next/back + const flat = []; + scenes.forEach((S) => S.beats.forEach((B) => flat.push({ scene: S.index, beat: B.index, B }))); + const flatIndex = (t) => { + let k = 0; + for (let n = 0; n < flat.length; n++) if (flat[n].B.start <= t + 1e-9) k = n; + return k; + }; + const sceneIndex = (idOrIndex) => + typeof idOrIndex === 'number' + ? clamp(idOrIndex, 0, scenes.length - 1) + : scenes.findIndex((S) => S.id === idOrIndex); + + return { scenes, chapters, total, at, timeOf, flat, flatIndex, sceneIndex, sceneAt }; + } + + // Fixed-step clock: real time goes in, whole 1/fps steps come out, so frame rate never changes what is shown + // at a given t, and an export stepping at 1/60 s sees exactly the frames a viewer saw. + function clock(fps = 60) { + let base = 0, + n = 0, + acc = 0; + return { + fps, + get t() { + return base + n / fps; + }, + // a seek lands exactly on t; steps continue from there in whole 1/fps steps + set(t) { + base = t; + n = 0; + acc = 0; + }, + // dt in seconds of real time (capped, so a sleeping tab doesn't jump); rate: 1 forward, -2.4 rewinding + advance(dt, rate = 1) { + acc += Math.min(Math.max(dt, 0), 0.25) * rate; + const k = acc >= 0 ? Math.floor(acc * fps + 1e-9) : Math.ceil(acc * fps - 1e-9); + n += k; + acc -= k / fps; + return k; + }, + step(k = 1) { + n += k; + }, + }; + } + + DHS.beats = { EASE, READING, countWords, beatWords, readingHold, hash, rng, compile, clock, clamp, clamp01 }; +})(globalThis); diff --git a/engine/src/essay/player.js b/engine/src/essay/player.js new file mode 100644 index 0000000..4e3b119 --- /dev/null +++ b/engine/src/essay/player.js @@ -0,0 +1,782 @@ +/* ESSAY PLAYER: the shell around a motion essay (a sourced essay that plays like a film). It owns time, controls and + links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses + DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). + + DHS.essay.start(essay, { root: document.body }) // loads the language tracks, then mounts; or: + const E = DHS.essay.mount(essay, { root, tracks: { en: {...} }, sound }); + essay: { lang, lens: knobs | null, sound: { bed: knobs } | null, autoplay, templates, scenes: [{ id, chapter, + scene: 'bars', data: {...}, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold }] }] } + The words come from per-language tracks (DHS.essayTrack: JSON keyed by scene id and beat; ?lang=es picks one, + and a language menu appears when there are several). Holds follow the active language's words. + + Viewer controls: + Space, K, the round button (top right, always shown) pause / play + click, Right arrow, Page Down, Enter, swipe left next beat (finishes the current one first) + right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) + A play by itself (the default) / wait for clicks M sound on / off . black screen F full screen + ? help card + Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. + Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. + + Sound (optional): essay.sound = { bed: knobs } plays DHS.bed's quiet drone; or opts.sound = { start(audioContext), + update(t, playing), setMuted(on), status }. With sound, the start screen offers "Begin with sound" and "Begin + silently", and the sound button (M) turns it on or off at any time; without it, just "Begin". + + Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), + E.flashCheck(scene), E.contrast(), E.layoutCheck(), E.setLang(lang). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + screen (what the stills and MP4 tools use). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const CSS = ` +.eo-root{position:fixed;inset:0;background:var(--eo-bg,#050506);color:var(--eo-ink,#f3f0e8);overflow:hidden; + font-family:var(--eo-font,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif);-webkit-tap-highlight-color:transparent; + user-select:none;-webkit-user-select:none;touch-action:none} +.eo-root.eo-nogl{background:var(--eo-fallback-bg,radial-gradient(120% 90% at 50% 40%,#1b1c22 0%,#08080a 70%))} +.eo-gl{position:absolute;inset:0;width:100%;height:100%;display:block} +.eo-black{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;transition:opacity .6s} +.eo-black.on{opacity:1} +.eo-ui{position:absolute;left:0;right:0;bottom:0;padding:0 max(16px,env(safe-area-inset-right)) max(14px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left)); + opacity:1;transition:opacity .5s;background:linear-gradient(transparent,rgba(0,0,0,.55));padding-top:40px} +.eo-root:not(.eo-on) .eo-ui{display:none} +.eo-idle .eo-ui{opacity:0;pointer-events:none}.eo-idle{cursor:none} +.eo-bar{display:flex;gap:6px;height:18px;align-items:center;cursor:pointer} +.eo-seg{position:relative;height:4px;background:rgba(255,255,255,.22);border-radius:2px;overflow:hidden} +.eo-seg i{position:absolute;inset:0;right:auto;background:var(--eo-accent,#e9e4d8);width:0} +.eo-row{display:flex;align-items:center;gap:10px;margin-top:6px;font-size:14px} +.eo-row button,.eo-start button,.eo-help button{font:inherit;color:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.28); + border-radius:6px;padding:7px 12px;cursor:pointer;min-height:36px} +.eo-row button:hover,.eo-start button:hover{background:rgba(255,255,255,.18)} +.eo-row button:focus-visible,.eo-start button:focus-visible,.eo-help button:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-where{flex:1;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.eo-start,.eo-help{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column; + text-align:center;padding:max(24px,env(safe-area-inset-top)) 24px max(24px,env(safe-area-inset-bottom));background:rgba(5,5,6,.82)} +.eo-start h1{font-family:var(--eo-display,inherit);font-weight:500;font-size:clamp(28px,5vw,64px);margin:0 0 .3em;max-width:20ch;line-height:1.1} +.eo-start p{margin:0 0 1.6em;opacity:.8;max-width:46ch;font-size:clamp(15px,1.6vw,20px);line-height:1.45} +.eo-start .eo-go{display:flex;gap:12px;flex-wrap:wrap;justify-content:center} +.eo-start button{font-size:18px;padding:12px 22px} +.eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} +.eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-pp{position:absolute;top:max(12px,env(safe-area-inset-top));right:max(12px,env(safe-area-inset-right));width:48px;height:48px;border-radius:50%; + display:none;align-items:center;justify-content:center;padding:0;cursor:pointer;color:var(--eo-ink,#f3f0e8);background:rgba(0,0,0,.45); + border:1px solid rgba(255,255,255,.35);opacity:.75;transition:opacity .3s} +.eo-pp svg{fill:currentColor}.eo-pp:hover,.eo-pp:focus-visible{opacity:1}.eo-pp:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-on .eo-pp{display:flex} +.eo-lang{font:inherit;color:inherit;background:#111114;border:1px solid rgba(255,255,255,.28);border-radius:6px;padding:6px 8px;min-height:36px} +.eo-langrow{margin-top:1.2em} +@media (max-width:600px){.eo-row{flex-wrap:wrap}.eo-where{flex-basis:100%;order:-1}.eo-row button{padding:6px 9px}} +.eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} +.eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} +.eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} +.eo-help dt{font-weight:600;white-space:nowrap}.eo-help dd{margin:0;opacity:.85} +.eo-note{position:absolute;top:max(14px,env(safe-area-inset-top));left:50%;transform:translateX(-50%);max-width:min(560px,90vw); + background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.25);border-radius:8px;padding:10px 14px;font-size:14px;line-height:1.4;text-align:center} +.eo-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} +@media (prefers-reduced-motion: reduce){.eo-ui,.eo-black{transition:none}} +`; + + const el = (tag, cls, parent, html) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (html != null) e.innerHTML = html; + if (parent) parent.appendChild(e); + return e; + }; + const esc = (s) => + String(s == null ? '' : s).replace( + /[&<>"]/g, + (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] + ); + + // button and note words when DHS.essayTrack isn't inlined (it holds the full list, translatable per track) + const FALLBACK_UI = { + begin: 'Begin', + withSound: 'Begin with sound', + silently: 'Begin silently', + pause: 'Pause', + play: 'Play', + playAgain: 'Play again', + next: 'Next', + back: 'Back', + keys: 'Keys', + close: 'Close', + fullscreen: 'Full screen', + soundOn: 'Sound on', + soundOff: 'Sound off', + soundLoading: 'Preparing sound\u2026', + auto: 'Plays by itself', + waits: 'Waits for clicks', + part: 'part {n} of {total}', + pressKeys: 'Press ? for keys', + language: 'Language', + progress: 'Progress', + noGL: "This screen can't draw the moving pictures. The words and numbers still play.", + help: [ + ['Space', 'Pause or play'], + ['Click, \u2192', 'Next'], + ['Right-click, \u2190', 'Back'], + ['?', 'This card'], + ], + }; + + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. + function plainText(root, TL, essay) { + const box = el('div', '', root); + box.style.cssText = + 'position:absolute;left:8vw;right:8vw;bottom:18vh;font-size:clamp(18px,2.2vw,30px);line-height:1.4'; + let last = ''; + return { + render(s) { + const sc = essay.scenes[s.scene], + b = sc.beats && sc.beats[Math.max(0, s.beat)]; + const html = + b && !s.trans + ? (b.text || []).map((x) => '

' + esc(typeof x === 'string' ? x : x.text) + '

').join('') + : ''; + if (html !== last) box.innerHTML = last = html; + }, + boxes: () => [], + hideGlyphs() {}, + }; + } + + // series: one array of cell luminances (0..1) per frame at `fps`. A change is a swing of at least 0.1 from the last + // turning point with the darker side under 0.8; a flash is a pair of opposing changes (WCAG 2.3.1). + // Returns the most flashes in any one second in any cell, and the biggest frame-to-frame step. + function flashCount(series, fps = 60) { + let maxPerSecond = 0, + maxStep = 0; + const cells = series.length ? series[0].length : 0; + for (let c = 0; c < cells; c++) { + const changes = []; + let ext = series[0][c], + dir = 0; + for (let f = 1; f < series.length; f++) { + const v = series[f][c]; + maxStep = Math.max(maxStep, Math.abs(v - series[f - 1][c])); + if ((dir > 0 && v > ext) || (dir < 0 && v < ext)) + ext = v; // still moving the same way + else if (Math.abs(v - ext) >= 0.1 && Math.min(v, ext) < 0.8) { + changes.push(f); + dir = v > ext ? 1 : -1; + ext = v; + } + } + for (let a = 0; a < changes.length; a++) { + let b = a; + while (b + 1 < changes.length && changes[b + 1] - changes[a] < fps) b++; + maxPerSecond = Math.max(maxPerSecond, Math.floor((b - a + 1) / 2)); + } + } + return { maxPerSecond, maxStep }; + } + + function mount(source, opts = {}) { + const B = DHS.beats, + Tk = DHS.essayTrack; + const root = el('div', 'eo-root', opts.root || doc.body); + if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; + const params = new URLSearchParams(G.location ? G.location.search : ''); + const manual = params.has('manual'); + const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; + const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + + // ---- words: the language's track, resolved into plain scenes (sequences expanded, sources paged) + const tracks = opts.tracks || (Tk ? Tk.fromPage(doc) : {}); + const langs = Object.keys(tracks); + let lang = Tk ? Tk.pick(tracks, params.get('lang'), source.lang) : source.lang || 'en'; + const resolveLang = (l) => { + const R = Tk ? Tk.resolve(source, tracks[l] || {}) : { essay: source, ui: FALLBACK_UI, warnings: [] }; + R.warnings.forEach((w) => console.warn('essay:', w)); + return R; + }; + let R = resolveLang(lang), + essay = R.essay, + ui = R.ui; + root.lang = lang; + + // ---- picture + const canvas = el('canvas', 'eo-gl', root); + canvas.setAttribute('aria-hidden', 'true'); + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', source.lens || null) : null; + const host = + DHS.gl && DHS.gl.host && params.get('gl') !== '0' + ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) + : null; + const transDur = (type) => + DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; + + const textRoot = el('div', 'eo-textroot', root); + textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; + const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once + live.setAttribute('aria-live', 'polite'); + const black = el('div', 'eo-black', root); + const note = el('div', 'eo-note', root); + note.setAttribute('role', 'status'); + note.hidden = true; + const nogl = () => { + root.classList.add('eo-nogl'); + canvas.style.display = 'none'; + note.hidden = false; + }; + + // ---- sound: the essay's drone bed (DHS.bed) unless the page passes its own hook + const sound = + opts.sound || (source.sound && DHS.bed && DHS.dsp ? DHS.bed.sound(source.sound.bed || source.sound) : null); + if (sound && sound.prepare && !manual) sound.prepare().then(() => setSoundLabel()); + + // ---- controls + const ui0 = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui0); + bar.setAttribute('role', 'slider'); + bar.tabIndex = -1; + const row = el('div', 'eo-row', ui0); + const bBack = el('button', '', row, '←'); + const bNext = el('button', '', row, '→'); + const where = el('div', 'eo-where', row); + const bSound = sound ? el('button', '', row) : null; + const langSel = langs.length > 1 ? el('select', 'eo-lang', row) : null; + const bAuto = el('button', '', row); + const bHelp = el('button', '', row, '?'); + const bFull = el('button', '', row); + // the pause button stays on screen while the essay plays (controls fade; this doesn't) + const bPP = el('button', 'eo-pp', root); + const help = el('div', 'eo-help', root); + help.hidden = true; + const start = el('div', 'eo-start', root); + if (manual) { + start.hidden = true; + root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves + } + if (langSel) + langs.forEach((l) => { + const o = el('option', '', langSel); + o.value = l; + o.textContent = (tracks[l].name || l) + (tracks[l].draft ? ' (draft)' : ''); + }); + + // ---- state + const clock = B.clock(60); + const st = { + started: manual, + playing: !manual, + auto: source.autoplay !== false, + rate: 1, + stopAt: null, + target: null, + dirty: true, + audio: null, + soundOn: false, + nav: false, + }; + let TL, text, segs; + + const label = (b, txt, aria) => { + b.textContent = txt; + if (aria) b.setAttribute('aria-label', aria); + }; + const setAuto = (a) => { + st.auto = a; + label(bAuto, a ? ui.auto : ui.waits); + bAuto.setAttribute('aria-pressed', String(a)); + }; + const PP_PAUSE = + ''; + const PP_PLAY = + ''; + const setPlaying = (p) => { + st.playing = p; + const end = TL && clock.t >= TL.total; + bPP.innerHTML = p ? PP_PAUSE : PP_PLAY; + bPP.setAttribute('aria-label', p ? ui.pause : end ? ui.playAgain : ui.play); + bPP.title = bPP.getAttribute('aria-label') + ' (Space)'; + }; + const setSoundLabel = () => { + if (!bSound) return; + const busy = sound.status === 'rendering'; + label(bSound, busy ? ui.soundLoading : st.soundOn ? ui.soundOn : ui.soundOff); + bSound.setAttribute('aria-pressed', String(st.soundOn)); + }; + + // (re)build everything that holds words: timeline, words layer, progress bar, labels, start screen, help card + const build = () => { + TL = B.compile(essay, { transDur }); + textRoot.innerHTML = ''; + text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + bar.innerHTML = ''; + bar.setAttribute('aria-label', ui.progress); + segs = TL.chapters.map((c) => { + const sg = el('div', 'eo-seg', bar); + sg.style.flex = String(Math.max(0.001, c.end - c.start)); + sg.title = essay.scenes[c.scene].chapterName || c.name; + return { c, sg, fill: el('i', '', sg) }; + }); + label(bBack, '←', ui.back); + label(bNext, '→', ui.next); + label(bHelp, '?', ui.keys); + label(bFull, ui.fullscreen); + if (langSel) { + langSel.value = lang; + langSel.setAttribute('aria-label', ui.language); + } + setAuto(st.auto); + setPlaying(st.playing); + setSoundLabel(); + note.textContent = ui.noGL; + help.innerHTML = + ``; + help.querySelector('button').onclick = () => toggleHelp(false); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${sound ? `` : ``}
` + + (langSel ? '
' : '') + + `${esc(ui.pressKeys)}`; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + if (langSel) { + const s2 = langSel.cloneNode(true); + s2.value = lang; + s2.onchange = () => setLang(s2.value); + start.querySelector('.eo-langrow').appendChild(s2); + } + lastKey = ''; + if (host && host.ok) host.setEssay(essay); + st.dirty = true; + }; + + const S = () => TL.at(clock.t, { reduced: reduced() }); + const fi = () => TL.flatIndex(clock.t); + + const jump = (t) => { + clock.set(t); + st.target = null; + st.rate = 1; + st.dirty = true; + }; + // next: finish the current beat; else play the next one in (its scene's transition first) + const next = () => { + const F = TL.flat, + k = fi(), + cur = F[k].B; + st.target = null; + st.rate = 1; + if (clock.t < cur.shown - 1e-3) jump(cur.shown); + else if (k + 1 < F.length) { + const n = F[k + 1]; + jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); + st.stopAt = st.auto ? null : n.B.shown; + } else jump(TL.total); + st.nav = true; + setPlaying(true); + }; + // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) + const back = () => { + const F = TL.flat, + k = Math.max(0, fi() - 1); + const to = F[k].B.shown; + if (to >= clock.t) return jump(to); + st.nav = true; + if ((clock.t - to) / 2.4 > 3 || reduced()) jump(to); + else { + st.target = to; + st.rate = -2.4; + } + st.stopAt = st.auto ? null : to; + setPlaying(true); + }; + const togglePlay = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + wake(); + }; + const goBeat = (i, j, where2 = 'shown') => { + jump(TL.timeOf(i, j, where2)); + st.stopAt = null; + }; + const fromHash = () => { + const m = /^#(.+)-(\d+)$/.exec((G.location && G.location.hash) || ''); + if (!m) return false; + const i = TL.sceneIndex(decodeURIComponent(m[1])); + if (i < 0) return false; + goBeat(i, +m[2] - 1); + return true; + }; + // switch language at the same scene and beat (the timeline changes: holds follow the new words) + const setLang = (l) => { + if (!tracks[l] || l === lang) return; + const s = S(), + id = s.id, + beat = Math.max(0, s.beat); + lang = l; + R = resolveLang(l); + essay = R.essay; + ui = R.ui; + root.lang = l; + build(); + const i = TL.sceneIndex(id); + goBeat(i < 0 ? 0 : i, beat); + if (G.history && G.location && !manual) { + const u = new URL(G.location.href); + u.searchParams.set('lang', l); + G.history.replaceState(null, '', u.toString()); + } + draw(); + }; + if (langSel) langSel.onchange = () => setLang(langSel.value); + + // ---- sound + const ensureAudio = () => { + if (!sound || st.audio) return; + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + const pr = sound.start(st.audio); + setSoundLabel(); + if (pr && pr.then) pr.then(setSoundLabel); + } catch (err) { + console.warn('essay: no sound', err); + } + }; + const setSound = (on) => { + if (!sound) return; + st.soundOn = on; + if (on) ensureAudio(); + if (sound.setMuted) sound.setMuted(!on); + setSoundLabel(); + }; + + // ---- the frame + let lastKey = '', + lastLive = ''; + const draw = () => { + const s = S(); + if (host && host.ok) host.render(s); + text.render(s); + segs.forEach( + ({ c, fill }) => + (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') + ); + bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); + const key = TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); + if (key !== lastKey && st.started) { + lastKey = key; + const sc = TL.scenes[s.scene], + spec = essay.scenes[s.scene]; + where.textContent = + (spec.chapterName ? spec.chapterName + ' · ' : '') + + ui.part.replace('{n}', s.scene + 1).replace('{total}', TL.scenes.length); + if (G.history && G.location && !manual) { + const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); + if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); + } + st.nav = false; + const b = spec.beats && spec.beats[Math.max(0, s.beat)]; + // the sources list is read where it is (its links are real); the live region says the rest once + const said = b + ? (b.text || []) + .filter((x) => !x.items) + .map((x) => (typeof x === 'string' ? x : x.text)) + .join(' ') + : ''; + if (said && said !== lastLive) live.textContent = lastLive = said; + } + if (sound && st.audio && sound.update) sound.update(s.t, st.playing && st.soundOn); + }; + + let prev = 0; + const frame = (now) => { + G.requestAnimationFrame(frame); + const dt = prev ? (now - prev) / 1000 : 0; + prev = now; + if (st.started && st.playing) { + const before = clock.t; + clock.advance(dt, st.rate); + if (st.target != null && clock.t <= st.target) { + clock.set(st.target); + st.target = null; + st.rate = 1; + if (!st.auto) setPlaying(false); + } + if (st.stopAt != null && clock.t >= st.stopAt && st.rate > 0) { + clock.set(st.stopAt); + st.stopAt = null; + setPlaying(false); + } + // waiting for clicks: stop when the current beat is fully shown + if (!st.auto && st.rate > 0 && st.stopAt == null) { + const cur = TL.flat[fi()].B; + if (before < cur.shown && clock.t >= cur.shown) { + clock.set(cur.shown); + setPlaying(false); + } + } + if (clock.t >= TL.total) { + clock.set(TL.total); + setPlaying(false); + } + if (clock.t !== before) st.dirty = true; + } + if (st.dirty) { + st.dirty = false; + draw(); + } + }; + + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600 either way round) + const resize = () => { + const r = root.getBoundingClientRect(); + const big = Math.max(r.width, r.height), + small = Math.min(r.width, r.height); + const d = Math.min(2, G.devicePixelRatio || 1, 2560 / Math.max(1, big), 1600 / Math.max(1, small)); + if (host && host.ok) host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d))); + if (text.resize) text.resize(r.width, r.height); + st.dirty = true; + }; + G.addEventListener('resize', resize); + + // ---- input + let idleT = 0; + const wake = () => { + root.classList.remove('eo-idle'); + G.clearTimeout(idleT); + idleT = G.setTimeout(() => { + if (help.hidden && st.started) root.classList.add('eo-idle'); + }, 3000); + }; + // only a real move wakes the controls (browsers send a mousemove when the page changes under a still pointer) + let mx = null, + my = null; + root.addEventListener('mousemove', (e) => { + const moved = mx != null && Math.abs(e.clientX - mx) + Math.abs(e.clientY - my) > 2; + mx = e.clientX; + my = e.clientY; + if (moved) wake(); + }); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start,.eo-pp,a,select'); + root.addEventListener('click', (e) => { + if (!st.started || inUI(e) || e.pointerType === 'touch') return; + next(); + }); + root.addEventListener('contextmenu', (e) => { + if (!st.started || inUI(e)) return; + e.preventDefault(); + back(); + }); + let tx = null, + ty = 0; + root.addEventListener('touchstart', (e) => { + tx = e.touches[0].clientX; + ty = e.touches[0].clientY; + }); + root.addEventListener('touchend', (e) => { + if (tx == null || !st.started) return; + const t = e.changedTouches[0], + dx = t.clientX - tx, + dy = t.clientY - ty; + tx = null; + if (inUI(e)) return; + if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) dx < 0 ? next() : back(); + else wake(); // a tap shows the controls + }); + const toggleHelp = (on = help.hidden) => { + help.hidden = !on; + if (on) help.querySelector('button').focus(); + wake(); + }; + const fullscreen = () => { + if (doc.fullscreenElement) doc.exitFullscreen(); + else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); + }; + G.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey || !st.started) return; + const k = e.key, + tag = e.target.tagName; + if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); + if ((tag === 'BUTTON' || tag === 'A') && (k === ' ' || k === 'Enter')) return; + if (tag === 'SELECT') return; + const act = { + ' ': togglePlay, + k: togglePlay, + K: togglePlay, + ArrowRight: next, + PageDown: next, + Enter: next, + ArrowLeft: back, + PageUp: back, + Backspace: back, + a: () => setAuto(!st.auto), + A: () => setAuto(!st.auto), + m: () => setSound(!st.soundOn), + M: () => setSound(!st.soundOn), + '.': () => black.classList.toggle('on'), + f: fullscreen, + F: fullscreen, + '?': () => toggleHelp(), + h: () => toggleHelp(), + Home: () => goBeat(0, 0), + End: () => goBeat(TL.scenes.length - 1, 1e9), + }[k]; + if (act) { + e.preventDefault(); + act(); + wake(); + } + }); + bBack.onclick = () => back(); + bNext.onclick = () => next(); + bPP.onclick = togglePlay; + bAuto.onclick = () => setAuto(!st.auto); + bHelp.onclick = () => toggleHelp(); + bFull.onclick = fullscreen; + if (bSound) bSound.onclick = () => setSound(!st.soundOn); + bar.addEventListener('click', (e) => { + let t = 0; + for (const { c, sg } of segs) { + const sr = sg.getBoundingClientRect(); + if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) + t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); + } + const k = TL.flatIndex(t); + st.nav = true; + goBeat(TL.flat[k].scene, TL.flat[k].beat, 'shown'); + }); + G.addEventListener('popstate', () => fromHash()); + G.addEventListener('hashchange', () => fromHash()); + + const begin = (withSound) => { + start.hidden = true; + st.started = true; + root.classList.add('eo-on'); + if (withSound) setSound(true); + if (!fromHash()) jump(0); + setPlaying(true); + fullscreen(); + wake(); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way + }; + + // ---- test hooks: repeatable stills of any beat or any point in a transition + const E = { + get TL() { + return TL; + }, + get essay() { + return essay; + }, + get lang() { + return lang; + }, + langs, + host, + sound, + // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, + // or 'shown' (fully in) / 'end' (the last frame of its hold) + seek(scene, beat = 0, t = 'shown') { + const i = TL.sceneIndex(scene), + Sc = TL.scenes[i]; + if (beat < 0) jump(Sc.start); + else { + const b = Sc.beats[Math.min(beat, Sc.beats.length - 1)]; + jump(t === 'shown' ? b.shown : t === 'end' ? b.end - 1e-3 : b.start + t); + } + setPlaying(false); + draw(); + return E.state(); + }, + // the transition into scene `scene` at progress p (0..1) + trans(scene, p) { + const Sc = TL.scenes[TL.sceneIndex(scene)]; + jump(Sc.start + B.clamp01(p) * Sc.trans.dur * 0.99999); + setPlaying(false); + draw(); + return E.state(); + }, + at(t) { + jump(t); + setPlaying(false); + draw(); + return E.state(); + }, + // ms per frame for a scene (waiting for the GPU each frame), drawn n times at its last beat + perf(scene, n = 60) { + if (!host || !host.ok) return null; + E.seek(scene, 1e9, 'shown'); + const s = S(); + const t0 = G.performance.now(); + for (let f = 0; f < n; f++) { + host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); + host.finish(); + } + return (G.performance.now() - t0) / n; + }, + // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps + // from 0.5 s before to 0.5 s after; flashes counted per cell of a 16 x 9 grid (DHS.essay.flashCount) + flashCheck(scene, cols = 16, rows = 9) { + if (!host || !host.ok) return null; + const Sc = TL.scenes[TL.sceneIndex(scene)], + t0 = Math.max(0, Sc.start - 0.5), + t1 = Math.min(TL.total, Sc.body + 0.5), + n = Math.round((t1 - t0) * 60); + const series = []; + for (let f = 0; f <= n; f++) { + host.render(TL.at(t0 + f / 60, { reduced: reduced() })); + series.push(host.lumaGrid(cols, rows)); + } + const { maxPerSecond, maxStep } = flashCount(series); + draw(); + return { maxPerSecond, maxStep, frames: series.length, pass: maxPerSecond <= 3 }; + }, + state() { + const s = S(); + return { + t: s.t, + total: TL.total, + scene: s.scene, + id: s.id, + beat: s.beat, + trans: s.trans, + gl: !!(host && host.ok), + reduced: reduced(), + lang, + playing: st.playing, + sound: sound ? sound.status : null, + }; + }, + textBoxes: () => text.boxes(), + contrast: () => (text.contrast ? text.contrast() : []), + layoutCheck: () => (text.layoutCheck ? text.layoutCheck() : []), + hideGlyphs: (on) => text.hideGlyphs(on), + next, + back, + begin, + setAuto, + setLang, + setSound, + togglePlay, + }; + G.EOMD_ESSAY = E; + + build(); + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; + resize(); + setPlaying(st.playing); + if (manual) draw(); + G.requestAnimationFrame(frame); + return E; + } + + // Loads the language tracks (inline JSON, or data-src when served over http), then mounts. + const start = async (essay, opts = {}) => { + const tracks = opts.tracks || (DHS.essayTrack ? await DHS.essayTrack.load(doc) : {}); + return mount(essay, Object.assign({}, opts, { tracks })); + }; + + DHS.essay = { mount, start, flashCount }; +})(globalThis); diff --git a/engine/src/essay/text.js b/engine/src/essay/text.js new file mode 100644 index 0000000..1e0ecd6 --- /dev/null +++ b/engine/src/essay/text.js @@ -0,0 +1,474 @@ +/* ESSAY TEXT: the words over the picture, in HTML (sharp at any size, selectable by screen readers through the + player's live region, and still there without WebGL2). A beat's text is a list of blocks: + { pos, kind, text } + pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, + bottom-right. Several blocks of one beat at one position stack (a big number and its caption). + sources: a list of { title, url, note }; titles are working links (http/https), with their site shown + kind body, headline, chapter, quote, source, number, note, takeaway (the closing statement), sources + The text is shown exactly as written; only its timing comes from it. + + Timing (a pure function of t, so seeks and stills match playback): + - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, + about 0.09 s apart, closer for long text so all are in by the end of the beat's dur; a number arrives whole); + - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new + text fades in), or until the scene ends (they fade out in the first 40% of the next transition); + - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. + Behind each group is a soft dark patch (a dark rounded box with soft edges, no glow) so the words hold on any picture. + Data labels from the scene (DHS.gl.sceneLabels: values, categories, the placeholder note) are drawn here too. + + const X = DHS.essayText.create(root, timeline, essay, { reduced, host }); + X.render(state); X.resize(w, h); X.boxes(); X.hideGlyphs(on); + X.contrast() -> [{ key, text, kind, ratio, need, against, pass }] WCAG contrast of each visible group against + the brightest and darkest picture pixels under it, with the patch composited in + Restyle with CSS variables on the player root: --eo-ink, --eo-font, --eo-display, --eo-serif, --eo-patch. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; + const PATCH = { + sources: 0.6, + takeaway: 0.45, + body: 0.55, + headline: 0.5, + chapter: 0.42, + quote: 0.5, + source: 0.55, + number: 0.45, + note: 0.55, + label: 0.68, + }; + const CSS = ` +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-pos{position:absolute;display:grid} +.eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} +.eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} +.eo-pos{z-index:0;isolation:isolate} +.eo-p-middle{left:50%;top:50%;transform:translate(-50%,-50%);width:min(30em,84vw);text-align:center} +.eo-g.eo-gp-quote{text-align:left} +.eo-p-lower-third{left:var(--m);right:var(--m);bottom:var(--mb);max-width:40em} +.eo-p-top-left{left:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-top-right{right:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-bottom-left{left:var(--m);bottom:var(--mb);width:min(28em,52vw)} +.eo-p-bottom-right{right:var(--m);bottom:var(--mb);width:min(28em,52vw);text-align:right} +.eo-b{margin:0}.eo-b+.eo-b{margin-top:.5em} +.eo-k-body{font-size:var(--eo-body,clamp(18px,1.1vw + 1.1vmin,34px));line-height:1.42;font-weight:400} +.eo-k-headline{font-family:var(--eo-display,inherit);font-size:clamp(26px,2vw + 2vmin,60px);line-height:1.12;font-weight:600;letter-spacing:-.01em} +.eo-k-chapter{font-family:var(--eo-display,inherit);font-size:clamp(30px,2.6vw + 2.4vmin,76px);line-height:1.1;font-weight:500;letter-spacing:.01em} +.eo-k-quote{font-family:var(--eo-serif,Georgia,"Times New Roman",serif);font-style:italic;font-size:clamp(22px,1.5vw + 1.5vmin,44px);line-height:1.35} +.eo-k-source{font-size:clamp(14px,.6vw + .8vmin,20px);line-height:1.4;opacity:.92} +.eo-k-number{font-family:var(--eo-display,inherit);font-size:clamp(44px,5vw + 4vmin,150px);line-height:1;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.02em} +.eo-w{display:inline-block;will-change:opacity} +.eo-hide .eo-w,.eo-hide .eo-lb{color:transparent!important} +.eo-lb{position:absolute;left:0;top:0;white-space:nowrap;font-size:clamp(13px,.5vw + .9vmin,22px);font-variant-numeric:tabular-nums;padding:.25em .6em; + border-radius:.8em; + background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} +.eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} +.eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} +.eo-text a{pointer-events:auto;color:inherit;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:.18em} +.eo-text a:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:3px;border-radius:2px} +.eo-p-sources{left:var(--m);top:var(--mt);bottom:var(--mb);width:min(44em,90vw);align-content:start} +.eo-src{margin:.4em 0 0;padding-left:1.3em;font-size:clamp(15px,.55vw + .9vmin,22px);line-height:1.38} +.eo-src li{margin:0 0 .75em} +.eo-src-title{font-weight:600} +.eo-src-site{font-size:.86em} +.eo-src-note{display:block;margin-top:.15em} +.eo-k-takeaway{font-family:var(--eo-display,inherit);font-size:clamp(26px,2.2vw + 2.2vmin,64px);line-height:1.2;font-weight:500} +/* landscape screens 600 px tall or more (laptops at arm's length, TVs; not phones held sideways): labels, notes, + source lines and the sources list get a floor tied to the screen's height, so they read at 1366x768 and 1920x1080 + (about 2.4% of the height for a label). Phone sizes don't change. */ +@media (orientation:landscape) and (min-height:600px){ + .eo-lb{font-size:max(clamp(16px,.5vw + .9vmin,22px),2.4vh)} + .eo-lb.eo-k-value{font-size:max(clamp(18px,.7vw + 1vmin,26px),2.8vh)} + .eo-lb.eo-k-note{font-size:max(clamp(14px,.4vw + .8vmin,17px),2vh)} + .eo-k-source{font-size:max(clamp(16px,.6vw + .8vmin,20px),2.1vh)} + .eo-src{font-size:max(clamp(17px,.55vw + .9vmin,22px),2.6vh)}} +/* very wide screens (phones held sideways, ultrawide monitors; aspect 1.9 and up): the data takes the right 55% + (DHS.gl.band), so corner text stacks in a left column */ +@media (orientation:landscape) and (min-aspect-ratio:19/10){ + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right,.eo-p-lower-third{left:var(--m);right:auto;width:min(28em,40vw);text-align:left} + .eo-pos>.eo-g{padding:.6em 1em}} +/* portrait phones and tablets: corner positions go full width (the data band sits between them) */ +@media (orientation:portrait){.eo-text{--m:max(6vw,env(safe-area-inset-left));--mt:max(6vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(4vh,env(safe-area-inset-bottom)) + 92px)} + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m);text-align:left} + .eo-p-middle{width:88vw}.eo-pos>.eo-g{padding:.7em 1em}} +`; + + const el = (tag, cls, parent) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (parent) parent.appendChild(e); + return e; + }; + const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x); + const smooth = (x) => ((x = clamp01(x)), x * x * (3 - 2 * x)); + + function create(root, TL, essay, opts = {}) { + const reduced = opts.reduced || (() => false), + host = opts.host; + if (!doc.getElementById('eo-text-css')) { + const st = el('style', '', doc.head); + st.id = 'eo-text-css'; + st.textContent = CSS; + } + const layer = el('div', 'eo-text', root); + let W = 1, + H = 1; + + // build every scene's groups once + const scenes = essay.scenes.map((spec, i) => { + const S = TL.scenes[i], + box = el('div', '', layer); + box.style.display = 'none'; + const posEls = {}, + groups = []; + (spec.beats || []).forEach((b, j) => { + const byPos = {}; + (b.text || []).forEach((x) => { + const blk = typeof x === 'string' ? { text: x } : x; + const pos = blk.pos || 'lower-third'; + (byPos[pos] = byPos[pos] || []).push(blk); + }); + Object.keys(byPos).forEach((pos) => { + // center, chapter and quote share the middle of the screen: a later one there replaces an earlier one + const slot = SLOT[pos] || pos; + if (!posEls[slot]) posEls[slot] = el('div', 'eo-pos eo-p-' + slot, box); + const g = el('div', 'eo-g eo-gp-' + pos, posEls[slot]), + patch = el('div', 'eo-patch', g); + const kind0 = byPos[pos][0].kind || 'body'; + const alpha = Math.max(...byPos[pos].map((x) => PATCH[x.kind || 'body'] || 0.5)); + patch.style.setProperty('--a', String(alpha)); + const words = [], + blocks = []; + // exact text: words become spans, the whitespace between them is kept as it was + const addWords = (parent, str, kind) => { + const bw = []; + String(str == null ? '' : str) + .split(/(\s+)/) + .forEach((part) => { + if (!part) return; + if (/^\s+$/.test(part)) return parent.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', parent); + w.textContent = part; + words.push({ el: w, whole: kind === 'number', last: '' }); + bw.push(w); + }); + blocks.push({ kind, text: String(str), words: bw }); + }; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body'; + if (blk.items) { + // a sources list: each title is a working link (http and https only), its site, and a short note + const ol = el('ol', 'eo-b eo-src', g); + blk.items.forEach((it) => { + const li = el('li', '', ol), + ok = /^https?:\/\//i.test(it.url || ''); + const t = el(ok ? 'a' : 'span', 'eo-src-title', li); + if (ok) { + t.href = it.url; + t.target = '_blank'; + t.rel = 'noopener noreferrer'; + } + addWords(t, it.title, 'source-title'); + if (ok) { + li.appendChild(doc.createTextNode(' ')); + addWords( + el('span', 'eo-src-site', li), + new URL(it.url).hostname.replace(/^www\./, ''), + 'source-site' + ); + } + if (it.note) addWords(el('span', 'eo-src-note', li), it.note, 'source-note'); + }); + return; + } + addWords(el('p', 'eo-b eo-k-' + kind, g), blk.text, kind); + }); + // the sources list is read by screen readers where it is (links); other words come from the live region + if (!byPos[pos].some((b) => b.items)) g.setAttribute('aria-hidden', 'true'); + groups.push({ + pos: slot, + beat: j, + g, + patch, + words, + blocks, + alpha, + kind: kind0, + text: byPos[pos].map((x) => x.text).join(' '), + start: S.beats[j].arrive, + reveal: Math.max(1.2, S.beats[j].dur), + out: null, + last: '', + }); + }); + }); + // when each group leaves: the next group at the same position, or the next scene's transition + const nextS = TL.scenes[i + 1]; + groups.forEach((gr, k) => { + const later = groups.slice(k + 1).find((x) => x.pos === gr.pos && x.beat > gr.beat); + if (later) gr.out = [later.start, later.start + 0.5]; + else if (nextS) + gr.out = + nextS.trans.dur > 0 + ? [nextS.start, nextS.start + 0.4 * nextS.trans.dur] + : [nextS.start - 1e-6, nextS.start]; + else gr.out = null; // the last scene's words stay to the end + }); + return { box, groups, labels: [], lbBox: el('div', '', box) }; + }); + + const setOp = (o, e, v) => { + const s = v.toFixed(3); + if (o.last !== s) { + e.style.opacity = s; + o.last = s; + } + }; + const groupOp = (gr, t) => { + const red = reduced(); + if (t < gr.start) return 0; + const inn = red ? clamp01((t - gr.start) / 0.3) : 1; + return gr.out ? inn * (1 - smooth((t - gr.out[0]) / Math.max(1e-6, gr.out[1] - gr.out[0]))) : inn; + }; + const drawScene = (i, t, s, labelFade, p) => { + const sc = scenes[i], + red = reduced(); + sc.box.style.display = ''; + sc.groups.forEach((gr) => { + const op = groupOp(gr, t); + setOp(gr, gr.g, op); + gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; + const n = gr.words.length, + // every word is in by the time the beat has arrived (a long sources list reveals faster) + stag = red ? 0 : Math.min(0.09, Math.max(0, gr.reveal - 0.6) / Math.max(1, n - 1)); + gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); + }); + // data labels + const spec = essay.scenes[i]; + const L = DHS.gl && DHS.gl.sceneLabels ? DHS.gl.sceneLabels(spec, p, W / H) : []; + while (sc.labels.length < L.length) + sc.labels.push({ el: el('div', 'eo-lb', sc.lbBox), last: '', txt: null, pos: '' }); + sc.labels.forEach((lb, k) => { + const d = L[k]; + if (!d) return (lb.el.style.display = 'none'); + lb.el.style.display = ''; + if (lb.txt !== d.text) lb.el.textContent = lb.txt = d.text; + lb.el.className = 'eo-lb eo-k-' + d.kind; + const x = (d.x / (W / H) + 0.5) * W, + y = (0.5 - d.y) * H, + ax = d.align === 'right' ? '-100%' : d.align === 'left' ? '0' : '-50%'; + const pos = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px) translate(${ax},-50%)`; + if (lb.pos !== pos) lb.el.style.transform = lb.pos = pos; + lb.data = d; + setOp(lb, lb.el, d.alpha * labelFade); + }); + }; + let shown = new Set(); + const X = { + render(s) { + const now = new Set([s.scene]); + if (s.trans && s.trans.from >= 0) now.add(s.trans.from); + shown.forEach((i) => !now.has(i) && (scenes[i].box.style.display = 'none')); + shown = now; + if (s.trans && s.trans.from >= 0) { + const f = s.trans.from; + drawScene( + f, + s.t, + s, + 1 - smooth(s.trans.p / 0.4), + TL.scenes[f].beats.map(() => 1) + ); + } + drawScene(s.scene, s.t, s, s.trans ? smooth((s.trans.p - 0.6) / 0.4) : 1, s.p); + }, + resize(w, h) { + W = Math.max(1, w); + H = Math.max(1, h); + }, + hideGlyphs(on) { + layer.classList.toggle('eo-hide', !!on); + }, + // visible groups and labels with their screen rectangles (CSS pixels) + boxes() { + const out = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) { + const pr = gr.patch.getBoundingClientRect(); + // one entry per paragraph: a big number and its small caption need different ratios + gr.blocks.forEach((b, n) => { + if (!b.words.length) return; + const wr = b.words.map((w) => w.getBoundingClientRect()); + out.push({ + key: i + ':' + gr.beat + ':' + gr.pos + ':' + n, + text: b.text, + kind: b.kind, + rect: b.words[0].parentNode.getBoundingClientRect(), + patch: pr, + alpha: gr.alpha * +gr.last, + words: wr, + el: b.words[0], + }); + }); + } + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) { + const r = lb.el.getBoundingClientRect(); + out.push({ + key: i + ':label:' + k, + text: lb.txt, + kind: lb.data.kind, + rect: r, + patch: r, + alpha: PATCH.label * +lb.last, + words: [r], + el: lb.el, + }); + } + }); + }); + return out; + }, + // problems a viewer would see: words or labels on top of each other, cut off at the screen's edge, or text + // panels covering the scene's data marks (DHS.gl.sceneMarks) + layoutCheck() { + const rootR = layer.getBoundingClientRect(), + out = []; + const items = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) + items.push({ + key: i + ':' + gr.beat + ':' + gr.pos, + text: gr.text, + r: gr.g.getBoundingClientRect(), + scene: i, + }); + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) + items.push({ key: i + ':label:' + k, text: lb.txt, r: lb.el.getBoundingClientRect(), label: true }); + }); + }); + // text panels over the scene's data marks (bars, dots, circles): none may be hidden + const W0 = rootR.width, + H0 = rootR.height, + asp = W0 / H0; + shown.forEach((i) => { + const marks = DHS.gl && DHS.gl.sceneMarks ? DHS.gl.sceneMarks(essay.scenes[i], asp) : []; + const px = (x) => rootR.left + (x / asp + 0.5) * W0, + py = (y) => rootR.top + (0.5 - y) * H0; + items + .filter((it) => !it.label && it.scene === i) + .forEach((it) => { + const r = { left: it.r.left + 6, right: it.r.right - 6, top: it.r.top + 6, bottom: it.r.bottom - 6 }; + const hit = marks.some((m) => { + if (m.cx != null) { + // circle against rectangle: the rectangle's nearest point to the centre + const cx = px(m.cx), + cy = py(m.cy), + rr = m.r * H0; + const nx = Math.max(r.left, Math.min(cx, r.right)), + ny = Math.max(r.top, Math.min(cy, r.bottom)); + return (nx - cx) ** 2 + (ny - cy) ** 2 < rr * rr; + } + return r.left < px(m.r) && px(m.l) < r.right && r.top < py(m.b) && py(m.t) < r.bottom; + }); + if (hit) out.push({ problem: 'covers data', a: it.text }); + }); + }); + // groups have padding round their words: shrink them a little so touching patches aren't counted + const pad = (r, p) => ({ left: r.left + p, right: r.right - p, top: r.top + p, bottom: r.bottom - p }); + items.forEach((a, n) => { + const r = a.r; + if ( + r.left < rootR.left - 1 || + r.top < rootR.top - 1 || + r.right > rootR.right + 1 || + r.bottom > rootR.bottom + 1 + ) + out.push({ problem: 'off screen', a: a.text }); + items.slice(n + 1).forEach((b) => { + const A = pad(a.r, a.label ? 2 : 10), + Bb = pad(b.r, b.label ? 2 : 10); + if (A.left < Bb.right && Bb.left < A.right && A.top < Bb.bottom && Bb.top < A.bottom) + out.push({ problem: 'overlap', a: a.text, b: b.text }); + }); + }); + return out; + }, + contrast() { + const px = host && host.ok ? host.pixels() : null; + const rootR = layer.getBoundingClientRect(); + const sx = px ? px.w / rootR.width : 1, + sy = px ? px.h / rootR.height : 1; + const lum = DHS.gl.relLum, + con = DHS.gl.contrast; + // with no picture (no WebGL2), the fallback background's lightest colour + const fallback = [0x1b, 0x1c, 0x22]; + return X.boxes().map((b) => { + const cs = G.getComputedStyle(b.el), + ink = cs.color.match(/[\d.]+/g).map(Number); + // the text's own opacity (fades, dimmed labels, a lighter source line), up to the layer + let op = 1; + for (let e = b.el; e && e !== layer; e = e.parentElement) op *= +G.getComputedStyle(e).opacity; + const size = parseFloat(cs.fontSize), + bold = +cs.fontWeight >= 600; + const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5; + let worst = Infinity, + against = '', + lo = Infinity, + hi = -Infinity; + const samples = []; + b.words.forEach((r) => { + const step = Math.max(1, Math.floor(Math.min(r.width, r.height) / 6)); + for (let y = r.top; y <= r.bottom; y += step) + for (let x = r.left; x <= r.right; x += step) { + // inside the patch box the patch is solid (its soft edge lies outside, past the words) + const inside = x >= b.patch.left && x <= b.patch.right && y >= b.patch.top && y <= b.patch.bottom; + const a = inside ? b.alpha : 0; + let c = fallback; + if (px) { + const X0 = Math.min(px.w - 1, Math.max(0, Math.round((x - rootR.left) * sx))), + Y0 = Math.min(px.h - 1, Math.max(0, Math.round((y - rootR.top) * sy))); + const k = ((px.h - 1 - Y0) * px.w + X0) * 4; + c = [px.data[k], px.data[k + 1], px.data[k + 2]]; + } + const bg = c.map((v) => v * (1 - a)); + const l = lum(bg[0], bg[1], bg[2]); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + samples.push([bg, l]); + } + }); + samples.forEach(([bg, l]) => { + // text drawn at opacity op over this pixel (CSS blends in sRGB) + const t = ink.slice(0, 3).map((v, i) => v * op + bg[i] * (1 - op)); + const r = con(lum(t[0], t[1], t[2]), l); + if (r < worst) { + worst = r; + against = l >= (lo + hi) / 2 ? 'brightest' : 'darkest'; + } + }); + return { + key: b.key, + text: b.text, + kind: b.kind, + ratio: worst, + need, + against, + opacity: +op.toFixed(3), + pass: worst >= need, + }; + }); + }, + }; + return X; + } + + DHS.essayText = { create, PATCH }; +})(globalThis); diff --git a/engine/src/essay/track.js b/engine/src/essay/track.js new file mode 100644 index 0000000..cd4f80f --- /dev/null +++ b/engine/src/essay/track.js @@ -0,0 +1,240 @@ +/* TRACK: an essay's on-screen words as a separate track, one JSON per language, never baked into the picture. + The essay file holds the structure (scenes, scene templates, data rows, timing); a track holds the words, keyed + by scene id and beat number. Reading-time holds are computed from the active track's words, so each language + gets its own pacing. Copy is shown exactly as written; numbers come from the data, formatted for the language. + + A track: + { + "lang": "en", "draft": false, draft: a translation nobody has checked yet (shown in the console) + "title": "...", "subtitle": "...", + "ui": { "begin": "Begin", ... }, player buttons and notes (DHS.essayTrack.UI has every key) + "chapters": { "opening": "Opening" }, chapter names by chapter id + "fields": { "population": "Population" }, data field names, used as chart labels + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }], "2": [ ... ] }, + "bars": { "1": [ ... ], "labels": ["A", "B"], "note": "Source: ..." }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] } + }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }] + } + "country#1" is step 1 of the scene template "country": {field} in its text is filled from each data row. + + Scene entries in the essay that this expands: + { sequence: 'country', rows: [row, ...], scale: 'row' | 'all', transition } + one short run of scenes per row from essay.templates.country.steps: [{ scene, fields, data, beats, + transition }]. A step's chart values are row[field] for its fields (a missing field stays missing, never + zero); scale 'all' puts every row on one scale (comparable bars across countries). + { id: 'sources', type: 'sources', perPage: 3 } + the sources chapter: the track's sources, perPage to a beat, as a list with working links. + + DHS.essayTrack.resolve(essay, track) -> { essay (plain scenes with text), ui, warnings } + DHS.essayTrack.fromPage(document) -> { lang: track } from + +``` + +The essay holds the structure, the data and the timing; the tracks hold every word: + +```js +const ESSAY = { + lang: 'en', // used when no track matches the viewer + lens: { bloom: 0.12, streak: 0, vignette: 0.28 }, // or null for no lens + sound: { bed: { lufs: -28 } }, // or null: no sound, the start screen says "Begin" + templates: { + country: { steps: [ + { scene: 'bars', fields: ['population', 'murdered', 'survived'], data: { grow: 1 }, beats: [{ dur: 1.2 }, { dur: 3 }] }, + { scene: 'nested', fields: ['population', 'murdered'], transition: 'dissolve', beats: [{ dur: 3 }] }, + ] }, + }, + scenes: [ + { id: 'opening', chapter: 'opening', scene: 'field', transition: { type: 'dip', dur: 2 }, beats: [{ dur: 2.4 }] }, + { sequence: 'country', rows: ROWS, scale: 'all' }, // one short run of scenes per data row + { id: 'sources', chapter: 'sources', type: 'sources', perPage: 3 }, + { id: 'takeaway', chapter: 'close', scene: 'field', beats: [{ dur: 2.4 }] }, + ], +}; +``` + +```json +{ "lang": "en", "title": "...", "subtitle": "...", + "chapters": { "opening": "Opening", "sources": "Sources" }, + "fields": { "population": "Population", "murdered": "Murdered", "survived": "Survived" }, + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }] }, + "country": { "chapter": "{name}" }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "Source: ..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] }, + "takeaway": { "1": [{ "pos": "center", "kind": "takeaway", "text": "..." }] } }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }], + "ui": { "begin": "..." } } +``` + +- A beat: `dur` (seconds to arrive), `delay`, `hold` (default: reading time from the active language's words), + `ease`, and for data scenes `focus`. Its words are the track's `text[sceneId][beatNumber]`, shown exactly as + written; `{field}` in a template step's words is filled from the row (numbers formatted for the language). +- A row's missing value (`null`) is drawn as nothing and labelled with `ui.noData`, never as zero. `scale: 'all'` + puts every row on one scale. +- Text positions: `center`, `chapter`, `quote` (these share the middle), `lower-third`, `top-left`, `top-right`, + `bottom-left`, `bottom-right` (full width on portrait screens; a left column on very wide ones, aspect 1.9 and up). Kinds: `body`, `headline`, `chapter`, `quote`, + `source`, `number`, `note`, `takeaway`. Restyle with CSS variables on `.eo-root`: `--eo-ink`, `--eo-bg`, + `--eo-font`, `--eo-display`, `--eo-serif`, `--eo-accent`. +- `?lang=es` picks a track; with several tracks a language menu appears. A track marked `"draft": true` shows as + "(draft)" in the menu and is reported in the console. +- A new scene is a cartridge in `DHS.gl.scenes` (`frag`, `layout(data, aspect)`, `labels`, `marks`); lay it out for + every shape (`DHS.gl.band(aspect)` is the shared data area: landscape, portrait, side) and report its data with + `marks` so the check can see text covering it. A new transition is a shader in + `DHS.gl.transitions`. The comments at the top of `gl/scenes.js` and `gl/transitions.js` give the contract. +- Before review, at both shapes: `node tools/essay-qa.js essay.html out-wide/ 1920 1080` and + `node tools/essay-qa.js essay.html out-phone/ 390 844` (add `lang=es` as a fifth argument for another track). + Each writes the stills and a pass/fail report: flashes, WCAG contrast, overlaps and cut-off words, the sound bed + starting and its small-speaker check, text covering data marks, page errors. The bed's loudness: + `node tools/render-bed.js bed.wav` (prints the full-band and above-300-Hz loudness; within 6 dB passes), then + `ffmpeg -nostats -i bed.wav -filter_complex ebur128=peak=true:framelog=quiet -f null -`. +- EOMD's demo essay (`engine/essay-demo/`, built by `tools/build_essay_demo.py` into `players/essay-demo.html`) shows + every part with placeholder words and made-up numbers, in English and a draft Spanish track. + +### The lens and the DSP + ```js // Lens over a 2D canvas: knobs from DHS.lens.DEFAULTS; null when it's off or can't start const L = DHS.lens.attach(canvas, { bloom: 0.25, tone: 'none' }); @@ -27,6 +111,9 @@ function frame(t) { drawScene(ctx, t); if (L && L.ok) L.draw(canvas, t); } +// Lens on a GPU texture in your own WebGL2 context (linear light, no upload) +const L2 = DHS.lens.create({ bloom: 0.2 }, { gl }); +L2.drawTexture(texture, width, height, t); // Sound made on the main thread without freezing the page: write the render as a generator of P.steps const P = DHS.dsp; diff --git a/kit/audio/bed.js b/kit/audio/bed.js new file mode 100644 index 0000000..2bf1565 --- /dev/null +++ b/kit/audio/bed.js @@ -0,0 +1,274 @@ +/* EOMD kit: audio/bed.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/audio/bed.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* BED: one quiet generative ambient drone (near silence) for an essay, made with EOMD's DSP (DHS.dsp) in the page. + A seamless loop: every partial and every slow swell has a whole number of cycles in the loop, the air (filtered + noise) and the room are processed circularly, so the loop point can't be heard. Normalised to a loudness target + (BS.1770 integrated, LUFS) and true-peak limited (default ceiling -1.5 dBTP). Same seed and knobs, same samples. + + const out = DHS.dsp.drain(DHS.bed.steps(knobs)); // { L, R, sr, seconds, lufs, truePeakDb, gainDb } + result.smallSpeakerLufs: loudness above 300 Hz (what a phone or laptop speaker plays); keep it within ~6 dB of lufs + DHS.bed.renderAsync(knobs).then(...) // in a worker; or in ~8 ms slices on the main thread + const sound = DHS.bed.sound(knobs); // the essay player's sound hook (DHS.essay.mount opts.sound) + sound.prepare() starts rendering now (the player calls it when it mounts) + sound.start(audioContext) when rendered, loops it with a slow fade in + sound.update(t, playing) fades out on pause, back in on play + sound.setMuted(on) the player's sound button + Needs DHS.dsp (audio/dsp.js). Hits and effects are not here yet (kit TODO). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + // The character (Bryan): "music that sounds the way the Memorial to the Murdered Jews of Europe in Berlin looks": + // austere, grey, even, slowly shifting, no melody, nothing that swells into drama. So: a fixed open chord (fifths + // and a ninth, no third), every tone held the whole time, levels and overtones drifting a little and against each + // other so the total stays even. It is made for small speakers first: the body sits in about 250 Hz to 2 kHz. + const DEFAULTS = { + seed: 7, + seconds: 30, // loop length + sr: 48000, + root: 62, // MIDI note of the lowest body tone (62 = D4, 294 Hz): where phone and laptop speakers play + chord: [0, 7, 12, 14, 19], // semitones above the root: D4 A4 D5 E5 A5 + partials: [1, 0.32, 0.16, 0.07, 0.035], // levels of each tone's harmonics 1..5 (soft overtones, a grey tone) + shift: 0.3, // how far tone levels and overtones drift (0 = still; small keeps it even) + low: 0.35, // optional weight: the root two octaves down (D2) for headphones; never carries the sound; 0 = off + air: 0.3, // breath of band-passed noise around 1-3 kHz (0 = none) + brightness: 3600, // lowpass on the tones, Hz + lufs: -28, // integrated loudness target: quiet, under the words, but audible on small speakers + ceiling: -1.5, // true-peak ceiling, dBTP + room: 0.3, // reverb send + fade: 4, // seconds of fade in when sound starts + measure: false, // true: also measure the exact true peak (slow; tools/render-bed.js sets it for the ffmpeg check) + }; + + // a sine from a table (fast, and the same in the page, the worker and Node) + const TBL = 4096, + SIN = new Float32Array(TBL + 1); + for (let i = 0; i <= TBL; i++) SIN[i] = Math.sin((2 * Math.PI * i) / TBL); + const sinT = (ph) => { + const x = (ph - Math.floor(ph)) * TBL, + i = x | 0; + return SIN[i] + (SIN[i + 1] - SIN[i]) * (x - i); + }; + + // Small-speaker check: loudness of what a phone or laptop speaker can play (above 300 Hz, 4th-order highpass) + // next to the full-band loudness. Within about 6 dB means the bed doesn't live only in the bass. + function* smallSpeaker(bus, sr) { + const P = DHS.dsp; + const hp = yield* P.steps.circular(bus, () => { + const a = P.rbjHighpass(300, 0.7071, sr), + b = P.rbjHighpass(300, 0.7071, sr), + c = P.rbjHighpass(300, 0.7071, sr), + d = P.rbjHighpass(300, 0.7071, sr); + return (l, r) => [b(a(l)), d(c(r))]; + }); + return yield* P.steps.lufs(hp, sr); + } + + function* steps(knobs = {}) { + const P = DHS.dsp, + k = Object.assign({}, DEFAULTS, knobs); + const sr = k.sr, + N = Math.round(k.seconds * sr), + L = N / sr, + TAU = Math.PI * 2; + const rnd = P.rng(k.seed); + const bus = P.bus(N); + // whole cycles in the loop, so nothing jumps at the loop point + const cyc = (f) => Math.max(1, Math.round(f * L)) / L; + const n = k.chord.length; + for (let v = 0; v < n; v++) { + const f = cyc(P.mtof(k.root + k.chord[v])), + beat = (1 + v) / L, // a second copy this far above: a very slow grey beating, no vibrato + ph = (rnd() + 1) * Math.PI, + drift = ((v + 0.5) / n) * 2 * Math.PI, // phases spread round the circle: as one tone fades, another rises + amp = 0.22 / (1 + v * 0.35), + pan = ((v % 2 ? 1 : -1) * (0.15 + 0.1 * v)) / 1.5; + const hs = k.partials.map((w, h) => ({ w, f: cyc(f * (h + 1)), ph: rnd() })); + const buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr, + u = t / L; + // the change is mostly in the overtones (the grey shifts); levels drift by at most shift/2 (about 1.5 dB) + const lv = 1 - k.shift * 0.25 * (1 - Math.cos(2 * Math.PI * u + drift)); + const tone = 1 + k.shift * Math.sin(2 * Math.PI * 2 * u + drift + ph); + let x = 0.2 * sinT((f + beat) * t + ph); // faint, so the beating shimmers instead of swelling + for (let h = 0; h < hs.length; h++) x += hs[h].w * (h ? tone : 1) * sinT(hs[h].f * t + hs[h].ph); + buf[i] = x * amp * lv; + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, pan); + } + // the optional low layer: weight on headphones, far below the body's level on small speakers + if (k.low > 0) { + const f = cyc(P.mtof(k.root - 24)), + buf = new Float32Array(N); + for (let i = 0; i < N; i++) { + const t = i / sr; + buf[i] = k.low * 0.22 * (sinT(f * t) + 0.25 * sinT(2 * f * t)); + if ((i & 32767) === 32767) yield; + } + P.write(bus, buf, 0, 1, 0); + } + // tone colour + const body = yield* P.steps.circular(bus, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, k.brightness, 0.5, sr), b(r, k.brightness, 0.5, sr)]; + }); + // air: noise band-passed round 1.8 kHz (circular, so its filter state is continuous across the loop) + if (k.air > 0) { + const air = P.bus(N); + for (let i = 0; i < N; i++) { + air.L[i] = rnd() * k.air * 0.25; + air.R[i] = rnd() * k.air * 0.25; + } + yield; + const f = yield* P.steps.circular(air, () => { + const a = P.svf(), + b = P.svf(); + return (l, r) => [a(l, 1800, 0.55, sr, 'bp'), b(r, 1800, 0.55, sr, 'bp')]; + }); + P.mixInto(body, f); + } + let out = body; + if (k.room > 0) { + const wet = yield* P.steps.circular(out, P.reverb({ sr, size: 0.86, damp: 0.5, lp: k.brightness * 3 })); + P.mixInto(out, wet, k.room * 2.5); + } + // loudness target, then the true-peak limiter. The tones are lowpassed, so the true peak sits within a few dB of + // the sample peak: when the sample peak is more than 6 dB under the ceiling the limiter can't act, and its + // (slow) oversampled pass is skipped. + const measured = yield* P.steps.lufs(out, sr); + const gainDb = k.lufs - measured, + g = P.db(gainDb); + let peak = 0; + for (let i = 0; i < N; i++) { + out.L[i] *= g; + out.R[i] *= g; + peak = Math.max(peak, Math.abs(out.L[i]), Math.abs(out.R[i])); + } + yield; + let limited = false; + if (P.todb(peak) > k.ceiling - 6) { + out = (yield* P.steps.limit(out, sr, P.db(k.ceiling))).bus; + limited = true; + } + return { + L: out.L, + R: out.R, + sr, + seconds: L, + lufs: yield* P.steps.lufs(out, sr), // measured again after the gain (and the limiter, if it ran) + smallSpeakerLufs: yield* smallSpeaker(out, sr), + samplePeakDb: P.todb(peak), + truePeakDb: k.measure ? P.todb(P.truePeak(out)) : null, + limited, + gainDb, + }; + } + + // In a page where the kit files are inlined, the bed renders in a background worker made from their own text, so + // a busy or slow page (big screen, slow GPU, phone) can't starve it. Where workers are blocked, or the scripts + // were loaded by src (dev pages), it renders on the main thread in ~8 ms slices. + const SELF = G.document && G.document.currentScript ? G.document.currentScript.textContent : ''; + const inWorker = (knobs) => + new Promise((resolve, reject) => { + const dsp = G.document && Array.from(G.document.scripts).find((x) => x.textContent.includes('(DHS.dsp = {})')); + if (!SELF || !dsp || !G.Worker || !G.Blob || !G.URL) return reject(new Error('no worker sources')); + const code = + dsp.textContent + + '\n' + + SELF + + '\nonmessage=(e)=>{const r=DHS.dsp.drain(DHS.bed.steps(e.data));postMessage(r,[r.L.buffer,r.R.buffer]);};'; + const url = G.URL.createObjectURL(new G.Blob([code], { type: 'text/javascript' })); + let w; + try { + w = new G.Worker(url); + } catch (err) { + G.URL.revokeObjectURL(url); + return reject(err); + } + const done = () => { + w.terminate(); + G.URL.revokeObjectURL(url); + }; + w.onmessage = (e) => { + done(); + resolve(Object.assign(e.data, { via: 'worker' })); + }; + w.onerror = (e) => { + done(); + e.preventDefault && e.preventDefault(); + reject(new Error('worker failed')); + }; + w.postMessage(knobs || {}); + }); + const renderAsync = (knobs) => + inWorker(knobs).catch(() => + DHS.dsp.runAsync(steps(knobs), { budgetMs: 8 }).then((r) => Object.assign(r, { via: 'main thread' })) + ); + + // The essay player's sound hook. Rendering takes a second or two of sliced work after "Begin with sound". + function sound(knobs = {}) { + const k = Object.assign({}, DEFAULTS, knobs); + const S = { ctx: null, gain: null, src: null, muted: false, playing: false, status: 'idle', result: null }; + const level = () => (S.muted || !S.playing ? 0 : 1); + const ramp = (secs) => { + if (!S.gain) return; + const now = S.ctx.currentTime; + S.gain.gain.cancelScheduledValues(now); + S.gain.gain.setValueAtTime(S.gain.gain.value, now); + S.gain.gain.linearRampToValueAtTime(level(), now + secs); + }; + // start rendering before anyone asks (the player calls this when it mounts): by the time the viewer has read + // the start screen the bed is usually ready + let job = null; + S.prepare = () => { + if (!job) { + S.status = 'rendering'; + job = renderAsync(k); + } + return job; + }; + S.start = (ctx) => { + if (S.ctx) return; + S.ctx = ctx; + if (ctx.state === 'suspended') ctx.resume(); + return S.prepare().then( + (r) => { + S.result = r; + const b = ctx.createBuffer(2, r.L.length, r.sr); + b.copyToChannel(r.L, 0); + b.copyToChannel(r.R, 1); + S.gain = ctx.createGain(); + S.gain.gain.value = 0; + S.gain.connect(ctx.destination); + S.src = ctx.createBufferSource(); + S.src.buffer = b; + S.src.loop = true; + S.src.connect(S.gain); + S.src.start(); + S.status = 'playing'; + ramp(k.fade); + }, + (err) => { + S.status = 'failed'; + console.warn('bed: no sound', err); + } + ); + }; + S.update = (t, playing) => { + if (playing !== S.playing) { + S.playing = playing; + ramp(playing ? 1.5 : 0.6); + } + }; + S.setMuted = (m) => { + S.muted = !!m; + ramp(0.5); + }; + return S; + } + + DHS.bed = { DEFAULTS, steps, renderAsync, sound }; +})(globalThis); diff --git a/kit/essay/beats.js b/kit/essay/beats.js new file mode 100644 index 0000000..c570009 --- /dev/null +++ b/kit/essay/beats.js @@ -0,0 +1,233 @@ +/* EOMD kit: essay/beats.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/beats.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* BEATS: the time model of an essay. A scene is a list of beats; each beat has + delay seconds of quiet before it starts arriving + dur seconds it takes to arrive (its progress runs 0 -> 1, eased) + hold seconds it stays before the next beat (default: reading time from its words) + Scenes are joined by transitions that take their own time (the outgoing scene stays at its last beat, the incoming + one at its first beat's progress 0). Everything is a pure function of the playhead t (seconds from the start): + seek, stills and an MP4 export replay exactly. No Math.random: use DHS.beats.rng(seed). + + const TL = DHS.beats.compile(essay, { transDur: (type) => 1.2 }); + const s = TL.at(t); // { t, scene, beat, beatT, raw[], p[], trans, k(beat, t0, t1, ease) } + const C = DHS.beats.clock(); C.advance(realDt); C.t // fixed 1/60 s steps; C.set(t) to seek + + Reading time (Q-Day's rule): hold = 2.6 s + 0.31 s a word, kept between 5.2 and 16 s, for a beat with words + (a beat can change the limits with reading: { max: 40 }, as a page of sources does). + The words themselves are never changed; only the timing comes from them. + + Standalone: needs only the DHS namespace. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + + const clamp = (x, a, b) => (x < a ? a : x > b ? b : x); + const clamp01 = (x) => clamp(x, 0, 1); + + // Ease curves, all f(0) = 0 and f(1) = 1 + const EASE = { + linear: (x) => x, + in: (x) => x * x * x, + out: (x) => 1 - (1 - x) ** 3, + inOut: (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2), + sine: (x) => 0.5 - 0.5 * Math.cos(Math.PI * x), + slow: (x) => 1 - (1 - x) ** 5, // long, gentle settle: the default for a solemn essay + }; + const ease = (e) => (typeof e === 'function' ? e : EASE[e] || EASE.slow); + + // ---- reading time + const READING = { base: 2.6, perWord: 0.31, min: 5.2, max: 16 }; + const countWords = (s) => (String(s || '').match(/\S+/g) || []).length; + // words in a beat: text blocks, plus the titles and notes of a sources list + const blockWords = (x) => + typeof x === 'string' + ? countWords(x) + : countWords(x.text) + (x.items || []).reduce((n, it) => n + countWords(it.title) + countWords(it.note), 0); + const beatWords = (b) => (b.text || []).reduce((n, x) => n + blockWords(x), 0); + const readingHold = (n, r = READING) => (n > 0 ? clamp(r.base + r.perWord * n, r.min, r.max) : 0); + + // ---- seeded random (mulberry32) and a string hash (FNV-1a) to make seeds from names + const hash = (...parts) => { + let h = 2166136261; + const s = parts.join('\u0001'); + for (let i = 0; i < s.length; i++) { + h ^= s.charCodeAt(i); + h = Math.imul(h, 16777619); + } + return h >>> 0; + }; + const rng = (seed) => { + let a = (typeof seed === 'number' ? seed : hash(seed)) >>> 0; + const r = () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + r.range = (lo, hi) => lo + (hi - lo) * r(); + r.int = (lo, hi) => Math.floor(lo + (hi - lo + 1) * r()); + r.pick = (arr) => arr[Math.floor(r() * arr.length)]; + return r; + }; + + // ---- the timeline + // essay: { scenes: [{ id, chapter, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold, text }] }] } + // opts.transDur(type): a transition's default length (the essay player passes the transition library's) + function compile(essay, opts = {}) { + const transDur = opts.transDur || (() => 1); + const reading = Object.assign({}, READING, opts.reading || {}); + const scenes = []; + let t = 0; + essay.scenes.forEach((sc, i) => { + const tr = typeof sc.transition === 'string' ? { type: sc.transition } : Object.assign({}, sc.transition || {}); + tr.type = tr.type || (i ? 'crossfade' : 'dip'); + tr.dur = tr.type === 'cut' ? 0 : tr.dur != null ? tr.dur : transDur(tr.type); + const S = { index: i, id: sc.id || 's' + (i + 1), chapter: sc.chapter || '', start: t, trans: tr, beats: [] }; + t += tr.dur; + S.body = t; + (sc.beats && sc.beats.length ? sc.beats : [{}]).forEach((b, j) => { + const words = beatWords(b); + const B = { + index: j, + delay: b.delay != null ? b.delay : 0, + dur: b.dur != null ? b.dur : 1.6, + hold: + b.hold != null + ? b.hold + : Math.max( + readingHold(words, b.reading ? Object.assign({}, reading, b.reading) : reading), + j === 0 && !words ? 1.5 : 0 + ), + ease: ease(b.ease), + words, + start: t, + }; + B.arrive = B.start + B.delay; + B.shown = B.arrive + B.dur; + B.end = B.shown + B.hold; + t = B.end; + S.beats.push(B); + }); + S.end = t; + scenes.push(S); + }); + const total = t; + + // the chapters, in order, with their time spans (for the progress bar) + const chapters = []; + scenes.forEach((S) => { + const last = chapters[chapters.length - 1]; + if (last && last.name === S.chapter) last.end = S.end; + else chapters.push({ name: S.chapter, start: S.start, end: S.end, scene: S.index }); + }); + + const sceneAt = (t) => { + let lo = 0, + hi = scenes.length - 1; + while (lo < hi) { + const m = (lo + hi + 1) >> 1; + if (scenes[m].start <= t) lo = m; + else hi = m - 1; + } + return lo; + }; + + // reduced motion: arrivals take at most `quick` seconds (same timeline length, so links and seeks still match) + function at(t, o = {}) { + t = clamp(t, 0, total); + const i = sceneAt(t), + S = scenes[i]; + const quick = o.reduced ? 0.35 : Infinity; + let beat = -1; + const raw = S.beats.map((B, j) => { + if (t >= B.arrive) beat = j; + return clamp01((t - B.arrive) / Math.max(1e-6, Math.min(B.dur, quick))); + }); + if (t < S.body) beat = -1; + else if (beat < 0) beat = 0; + const p = raw.map((r, j) => S.beats[j].ease(r)); + const trans = + t < S.body && S.trans.dur > 0 + ? { + type: S.trans.type, + from: i - 1, + to: i, + p: clamp01((t - S.start) / S.trans.dur), + dur: S.trans.dur, + fromT: i ? t - scenes[i - 1].body : 0, + } + : null; + const B = beat >= 0 ? S.beats[beat] : null; + return { + t, + total, + scene: i, + id: S.id, + chapter: S.chapter, + beat, + beatT: B ? t - B.start : 0, + sceneT: t - S.body, + raw, + p, + trans, + // progress of a move inside a beat: k(beat, 0.2, 0.8, 'out') runs 0 -> 1 while the beat goes 20% -> 80% + k: (j, t0 = 0, t1 = 1, e = 'inOut') => ease(e)(clamp01(((raw[j] || 0) - t0) / Math.max(1e-6, t1 - t0))), + }; + } + + // time of a beat's moments: 'start', 'arrive', 'shown' (fully in, hold begins), 'end' + const timeOf = (i, j = 0, where = 'shown') => { + const S = scenes[clamp(i, 0, scenes.length - 1)]; + if (j < 0) return S.start; + return S.beats[clamp(j, 0, S.beats.length - 1)][where]; + }; + // flat list of beats in order: [{ scene, beat }], for next/back + const flat = []; + scenes.forEach((S) => S.beats.forEach((B) => flat.push({ scene: S.index, beat: B.index, B }))); + const flatIndex = (t) => { + let k = 0; + for (let n = 0; n < flat.length; n++) if (flat[n].B.start <= t + 1e-9) k = n; + return k; + }; + const sceneIndex = (idOrIndex) => + typeof idOrIndex === 'number' + ? clamp(idOrIndex, 0, scenes.length - 1) + : scenes.findIndex((S) => S.id === idOrIndex); + + return { scenes, chapters, total, at, timeOf, flat, flatIndex, sceneIndex, sceneAt }; + } + + // Fixed-step clock: real time goes in, whole 1/fps steps come out, so frame rate never changes what is shown + // at a given t, and an export stepping at 1/60 s sees exactly the frames a viewer saw. + function clock(fps = 60) { + let base = 0, + n = 0, + acc = 0; + return { + fps, + get t() { + return base + n / fps; + }, + // a seek lands exactly on t; steps continue from there in whole 1/fps steps + set(t) { + base = t; + n = 0; + acc = 0; + }, + // dt in seconds of real time (capped, so a sleeping tab doesn't jump); rate: 1 forward, -2.4 rewinding + advance(dt, rate = 1) { + acc += Math.min(Math.max(dt, 0), 0.25) * rate; + const k = acc >= 0 ? Math.floor(acc * fps + 1e-9) : Math.ceil(acc * fps - 1e-9); + n += k; + acc -= k / fps; + return k; + }, + step(k = 1) { + n += k; + }, + }; + } + + DHS.beats = { EASE, READING, countWords, beatWords, readingHold, hash, rng, compile, clock, clamp, clamp01 }; +})(globalThis); diff --git a/kit/essay/player.js b/kit/essay/player.js new file mode 100644 index 0000000..41b8407 --- /dev/null +++ b/kit/essay/player.js @@ -0,0 +1,784 @@ +/* EOMD kit: essay/player.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/player.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* ESSAY PLAYER: the shell around a motion essay (a sourced essay that plays like a film). It owns time, controls and + links; the picture (DHS.gl.host) and the words (DHS.essayText) draw what it tells them. Needs DHS.beats; uses + DHS.gl.host and DHS.essayText when they are inlined, and still plays the words without them (or without WebGL2). + + DHS.essay.start(essay, { root: document.body }) // loads the language tracks, then mounts; or: + const E = DHS.essay.mount(essay, { root, tracks: { en: {...} }, sound }); + essay: { lang, lens: knobs | null, sound: { bed: knobs } | null, autoplay, templates, scenes: [{ id, chapter, + scene: 'bars', data: {...}, transition: 'crossfade' | { type, dur }, beats: [{ dur, delay, hold }] }] } + The words come from per-language tracks (DHS.essayTrack: JSON keyed by scene id and beat; ?lang=es picks one, + and a language menu appears when there are several). Holds follow the active language's words. + + Viewer controls: + Space, K, the round button (top right, always shown) pause / play + click, Right arrow, Page Down, Enter, swipe left next beat (finishes the current one first) + right-click, Left arrow, Page Up, Backspace, swipe back (runs back 2.4x faster than it came) + A play by itself (the default) / wait for clicks M sound on / off . black screen F full screen + ? help card + Home / End first / last beat; #scene-beat links (e.g. #bars-2) open at that beat; the back button works. + Controls are hidden until the mouse moves or the screen is tapped, and fade after 3 s. + + Sound (optional): essay.sound = { bed: knobs } plays DHS.bed's quiet drone; or opts.sound = { start(audioContext), + update(t, playing), setMuted(on), status }. With sound, the start screen offers "Begin with sound" and "Begin + silently", and the sound button (M) turns it on or off at any time; without it, just "Begin". + + Test hooks (stills, fresh-eyes review, MP4): E.seek(scene, beat, t), E.trans(scene, p), E.perf(scene), E.state(), + E.flashCheck(scene), E.contrast(), E.layoutCheck(), E.setLang(lang). Also on window.EOMD_ESSAY. Add ?manual to the URL to start paused with no start + screen (what the stills and MP4 tools use). */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const CSS = ` +.eo-root{position:fixed;inset:0;background:var(--eo-bg,#050506);color:var(--eo-ink,#f3f0e8);overflow:hidden; + font-family:var(--eo-font,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif);-webkit-tap-highlight-color:transparent; + user-select:none;-webkit-user-select:none;touch-action:none} +.eo-root.eo-nogl{background:var(--eo-fallback-bg,radial-gradient(120% 90% at 50% 40%,#1b1c22 0%,#08080a 70%))} +.eo-gl{position:absolute;inset:0;width:100%;height:100%;display:block} +.eo-black{position:absolute;inset:0;background:#000;opacity:0;pointer-events:none;transition:opacity .6s} +.eo-black.on{opacity:1} +.eo-ui{position:absolute;left:0;right:0;bottom:0;padding:0 max(16px,env(safe-area-inset-right)) max(14px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left)); + opacity:1;transition:opacity .5s;background:linear-gradient(transparent,rgba(0,0,0,.55));padding-top:40px} +.eo-root:not(.eo-on) .eo-ui{display:none} +.eo-idle .eo-ui{opacity:0;pointer-events:none}.eo-idle{cursor:none} +.eo-bar{display:flex;gap:6px;height:18px;align-items:center;cursor:pointer} +.eo-seg{position:relative;height:4px;background:rgba(255,255,255,.22);border-radius:2px;overflow:hidden} +.eo-seg i{position:absolute;inset:0;right:auto;background:var(--eo-accent,#e9e4d8);width:0} +.eo-row{display:flex;align-items:center;gap:10px;margin-top:6px;font-size:14px} +.eo-row button,.eo-start button,.eo-help button{font:inherit;color:inherit;background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.28); + border-radius:6px;padding:7px 12px;cursor:pointer;min-height:36px} +.eo-row button:hover,.eo-start button:hover{background:rgba(255,255,255,.18)} +.eo-row button:focus-visible,.eo-start button:focus-visible,.eo-help button:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-where{flex:1;opacity:.85;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.eo-start,.eo-help{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column; + text-align:center;padding:max(24px,env(safe-area-inset-top)) 24px max(24px,env(safe-area-inset-bottom));background:rgba(5,5,6,.82)} +.eo-start h1{font-family:var(--eo-display,inherit);font-weight:500;font-size:clamp(28px,5vw,64px);margin:0 0 .3em;max-width:20ch;line-height:1.1} +.eo-start p{margin:0 0 1.6em;opacity:.8;max-width:46ch;font-size:clamp(15px,1.6vw,20px);line-height:1.45} +.eo-start .eo-go{display:flex;gap:12px;flex-wrap:wrap;justify-content:center} +.eo-start button{font-size:18px;padding:12px 22px} +.eo-start small{margin-top:1.6em;opacity:.6;font-size:13px} +.eo-help[hidden],.eo-start[hidden],.eo-note[hidden]{display:none} +.eo-pp{position:absolute;top:max(12px,env(safe-area-inset-top));right:max(12px,env(safe-area-inset-right));width:48px;height:48px;border-radius:50%; + display:none;align-items:center;justify-content:center;padding:0;cursor:pointer;color:var(--eo-ink,#f3f0e8);background:rgba(0,0,0,.45); + border:1px solid rgba(255,255,255,.35);opacity:.75;transition:opacity .3s} +.eo-pp svg{fill:currentColor}.eo-pp:hover,.eo-pp:focus-visible{opacity:1}.eo-pp:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:2px} +.eo-on .eo-pp{display:flex} +.eo-lang{font:inherit;color:inherit;background:#111114;border:1px solid rgba(255,255,255,.28);border-radius:6px;padding:6px 8px;min-height:36px} +.eo-langrow{margin-top:1.2em} +@media (max-width:600px){.eo-row{flex-wrap:wrap}.eo-where{flex-basis:100%;order:-1}.eo-row button{padding:6px 9px}} +.eo-help .eo-card{background:#111114;border:1px solid rgba(255,255,255,.2);border-radius:10px;padding:22px 26px;text-align:left;max-width:520px;font-size:15px;line-height:1.5} +.eo-help h2{margin:0 0 .6em;font-size:18px;font-weight:600} +.eo-help dl{display:grid;grid-template-columns:auto 1fr;gap:4px 16px;margin:0 0 1em} +.eo-help dt{font-weight:600;white-space:nowrap}.eo-help dd{margin:0;opacity:.85} +.eo-note{position:absolute;top:max(14px,env(safe-area-inset-top));left:50%;transform:translateX(-50%);max-width:min(560px,90vw); + background:rgba(0,0,0,.7);border:1px solid rgba(255,255,255,.25);border-radius:8px;padding:10px 14px;font-size:14px;line-height:1.4;text-align:center} +.eo-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} +@media (prefers-reduced-motion: reduce){.eo-ui,.eo-black{transition:none}} +`; + + const el = (tag, cls, parent, html) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (html != null) e.innerHTML = html; + if (parent) parent.appendChild(e); + return e; + }; + const esc = (s) => + String(s == null ? '' : s).replace( + /[&<>"]/g, + (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] + ); + + // button and note words when DHS.essayTrack isn't inlined (it holds the full list, translatable per track) + const FALLBACK_UI = { + begin: 'Begin', + withSound: 'Begin with sound', + silently: 'Begin silently', + pause: 'Pause', + play: 'Play', + playAgain: 'Play again', + next: 'Next', + back: 'Back', + keys: 'Keys', + close: 'Close', + fullscreen: 'Full screen', + soundOn: 'Sound on', + soundOff: 'Sound off', + soundLoading: 'Preparing sound\u2026', + auto: 'Plays by itself', + waits: 'Waits for clicks', + part: 'part {n} of {total}', + pressKeys: 'Press ? for keys', + language: 'Language', + progress: 'Progress', + noGL: "This screen can't draw the moving pictures. The words and numbers still play.", + help: [ + ['Space', 'Pause or play'], + ['Click, \u2192', 'Next'], + ['Right-click, \u2190', 'Back'], + ['?', 'This card'], + ], + }; + + // A plain words layer for when DHS.essayText isn't inlined: each beat's text, no positions or fades. + function plainText(root, TL, essay) { + const box = el('div', '', root); + box.style.cssText = + 'position:absolute;left:8vw;right:8vw;bottom:18vh;font-size:clamp(18px,2.2vw,30px);line-height:1.4'; + let last = ''; + return { + render(s) { + const sc = essay.scenes[s.scene], + b = sc.beats && sc.beats[Math.max(0, s.beat)]; + const html = + b && !s.trans + ? (b.text || []).map((x) => '

' + esc(typeof x === 'string' ? x : x.text) + '

').join('') + : ''; + if (html !== last) box.innerHTML = last = html; + }, + boxes: () => [], + hideGlyphs() {}, + }; + } + + // series: one array of cell luminances (0..1) per frame at `fps`. A change is a swing of at least 0.1 from the last + // turning point with the darker side under 0.8; a flash is a pair of opposing changes (WCAG 2.3.1). + // Returns the most flashes in any one second in any cell, and the biggest frame-to-frame step. + function flashCount(series, fps = 60) { + let maxPerSecond = 0, + maxStep = 0; + const cells = series.length ? series[0].length : 0; + for (let c = 0; c < cells; c++) { + const changes = []; + let ext = series[0][c], + dir = 0; + for (let f = 1; f < series.length; f++) { + const v = series[f][c]; + maxStep = Math.max(maxStep, Math.abs(v - series[f - 1][c])); + if ((dir > 0 && v > ext) || (dir < 0 && v < ext)) + ext = v; // still moving the same way + else if (Math.abs(v - ext) >= 0.1 && Math.min(v, ext) < 0.8) { + changes.push(f); + dir = v > ext ? 1 : -1; + ext = v; + } + } + for (let a = 0; a < changes.length; a++) { + let b = a; + while (b + 1 < changes.length && changes[b + 1] - changes[a] < fps) b++; + maxPerSecond = Math.max(maxPerSecond, Math.floor((b - a + 1) / 2)); + } + } + return { maxPerSecond, maxStep }; + } + + function mount(source, opts = {}) { + const B = DHS.beats, + Tk = DHS.essayTrack; + const root = el('div', 'eo-root', opts.root || doc.body); + if (!doc.getElementById('eo-css')) el('style', '', doc.head, CSS).id = 'eo-css'; + const params = new URLSearchParams(G.location ? G.location.search : ''); + const manual = params.has('manual'); + const reducedMQ = G.matchMedia ? G.matchMedia('(prefers-reduced-motion: reduce)') : { matches: false }; + const reduced = () => reducedMQ.matches || params.get('reduced') === '1'; + + // ---- words: the language's track, resolved into plain scenes (sequences expanded, sources paged) + const tracks = opts.tracks || (Tk ? Tk.fromPage(doc) : {}); + const langs = Object.keys(tracks); + let lang = Tk ? Tk.pick(tracks, params.get('lang'), source.lang) : source.lang || 'en'; + const resolveLang = (l) => { + const R = Tk ? Tk.resolve(source, tracks[l] || {}) : { essay: source, ui: FALLBACK_UI, warnings: [] }; + R.warnings.forEach((w) => console.warn('essay:', w)); + return R; + }; + let R = resolveLang(lang), + essay = R.essay, + ui = R.ui; + root.lang = lang; + + // ---- picture + const canvas = el('canvas', 'eo-gl', root); + canvas.setAttribute('aria-hidden', 'true'); + const lensKnobs = DHS.lens ? DHS.lens.fromQuery(G.location ? G.location.search : '', source.lens || null) : null; + const host = + DHS.gl && DHS.gl.host && params.get('gl') !== '0' + ? DHS.gl.host(canvas, { essay, lens: lensKnobs, reduced }) + : null; + const transDur = (type) => + DHS.gl && DHS.gl.transitions && DHS.gl.transitions[type] ? DHS.gl.transitions[type].dur : 1; + + const textRoot = el('div', 'eo-textroot', root); + textRoot.style.cssText = 'position:absolute;inset:0;pointer-events:none'; + const live = el('div', 'eo-sr', root); // screen readers hear each beat's words once + live.setAttribute('aria-live', 'polite'); + const black = el('div', 'eo-black', root); + const note = el('div', 'eo-note', root); + note.setAttribute('role', 'status'); + note.hidden = true; + const nogl = () => { + root.classList.add('eo-nogl'); + canvas.style.display = 'none'; + note.hidden = false; + }; + + // ---- sound: the essay's drone bed (DHS.bed) unless the page passes its own hook + const sound = + opts.sound || (source.sound && DHS.bed && DHS.dsp ? DHS.bed.sound(source.sound.bed || source.sound) : null); + if (sound && sound.prepare && !manual) sound.prepare().then(() => setSoundLabel()); + + // ---- controls + const ui0 = el('div', 'eo-ui', root); + const bar = el('div', 'eo-bar', ui0); + bar.setAttribute('role', 'slider'); + bar.tabIndex = -1; + const row = el('div', 'eo-row', ui0); + const bBack = el('button', '', row, '←'); + const bNext = el('button', '', row, '→'); + const where = el('div', 'eo-where', row); + const bSound = sound ? el('button', '', row) : null; + const langSel = langs.length > 1 ? el('select', 'eo-lang', row) : null; + const bAuto = el('button', '', row); + const bHelp = el('button', '', row, '?'); + const bFull = el('button', '', row); + // the pause button stays on screen while the essay plays (controls fade; this doesn't) + const bPP = el('button', 'eo-pp', root); + const help = el('div', 'eo-help', root); + help.hidden = true; + const start = el('div', 'eo-start', root); + if (manual) { + start.hidden = true; + root.classList.add('eo-on', 'eo-idle'); // stills: no controls until the mouse moves + } + if (langSel) + langs.forEach((l) => { + const o = el('option', '', langSel); + o.value = l; + o.textContent = (tracks[l].name || l) + (tracks[l].draft ? ' (draft)' : ''); + }); + + // ---- state + const clock = B.clock(60); + const st = { + started: manual, + playing: !manual, + auto: source.autoplay !== false, + rate: 1, + stopAt: null, + target: null, + dirty: true, + audio: null, + soundOn: false, + nav: false, + }; + let TL, text, segs; + + const label = (b, txt, aria) => { + b.textContent = txt; + if (aria) b.setAttribute('aria-label', aria); + }; + const setAuto = (a) => { + st.auto = a; + label(bAuto, a ? ui.auto : ui.waits); + bAuto.setAttribute('aria-pressed', String(a)); + }; + const PP_PAUSE = + ''; + const PP_PLAY = + ''; + const setPlaying = (p) => { + st.playing = p; + const end = TL && clock.t >= TL.total; + bPP.innerHTML = p ? PP_PAUSE : PP_PLAY; + bPP.setAttribute('aria-label', p ? ui.pause : end ? ui.playAgain : ui.play); + bPP.title = bPP.getAttribute('aria-label') + ' (Space)'; + }; + const setSoundLabel = () => { + if (!bSound) return; + const busy = sound.status === 'rendering'; + label(bSound, busy ? ui.soundLoading : st.soundOn ? ui.soundOn : ui.soundOff); + bSound.setAttribute('aria-pressed', String(st.soundOn)); + }; + + // (re)build everything that holds words: timeline, words layer, progress bar, labels, start screen, help card + const build = () => { + TL = B.compile(essay, { transDur }); + textRoot.innerHTML = ''; + text = DHS.essayText + ? DHS.essayText.create(textRoot, TL, essay, { reduced, host }) + : plainText(textRoot, TL, essay); + bar.innerHTML = ''; + bar.setAttribute('aria-label', ui.progress); + segs = TL.chapters.map((c) => { + const sg = el('div', 'eo-seg', bar); + sg.style.flex = String(Math.max(0.001, c.end - c.start)); + sg.title = essay.scenes[c.scene].chapterName || c.name; + return { c, sg, fill: el('i', '', sg) }; + }); + label(bBack, '←', ui.back); + label(bNext, '→', ui.next); + label(bHelp, '?', ui.keys); + label(bFull, ui.fullscreen); + if (langSel) { + langSel.value = lang; + langSel.setAttribute('aria-label', ui.language); + } + setAuto(st.auto); + setPlaying(st.playing); + setSoundLabel(); + note.textContent = ui.noGL; + help.innerHTML = + ``; + help.querySelector('button').onclick = () => toggleHelp(false); + start.innerHTML = + `

${esc(essay.title || '')}

` + + (essay.subtitle ? `

${esc(essay.subtitle)}

` : '') + + `
${sound ? `` : ``}
` + + (langSel ? '
' : '') + + `${esc(ui.pressKeys)}`; + start.querySelectorAll('button').forEach((b) => (b.onclick = () => begin(b.dataset.s === '1'))); + if (langSel) { + const s2 = langSel.cloneNode(true); + s2.value = lang; + s2.onchange = () => setLang(s2.value); + start.querySelector('.eo-langrow').appendChild(s2); + } + lastKey = ''; + if (host && host.ok) host.setEssay(essay); + st.dirty = true; + }; + + const S = () => TL.at(clock.t, { reduced: reduced() }); + const fi = () => TL.flatIndex(clock.t); + + const jump = (t) => { + clock.set(t); + st.target = null; + st.rate = 1; + st.dirty = true; + }; + // next: finish the current beat; else play the next one in (its scene's transition first) + const next = () => { + const F = TL.flat, + k = fi(), + cur = F[k].B; + st.target = null; + st.rate = 1; + if (clock.t < cur.shown - 1e-3) jump(cur.shown); + else if (k + 1 < F.length) { + const n = F[k + 1]; + jump(n.beat === 0 ? TL.scenes[n.scene].start : n.B.start); + st.stopAt = st.auto ? null : n.B.shown; + } else jump(TL.total); + st.nav = true; + setPlaying(true); + }; + // back: run back at 2.4x to the previous beat, fully shown (jump if that would take more than 3 s) + const back = () => { + const F = TL.flat, + k = Math.max(0, fi() - 1); + const to = F[k].B.shown; + if (to >= clock.t) return jump(to); + st.nav = true; + if ((clock.t - to) / 2.4 > 3 || reduced()) jump(to); + else { + st.target = to; + st.rate = -2.4; + } + st.stopAt = st.auto ? null : to; + setPlaying(true); + }; + const togglePlay = () => { + if (clock.t >= TL.total) jump(0); + setPlaying(!st.playing); + wake(); + }; + const goBeat = (i, j, where2 = 'shown') => { + jump(TL.timeOf(i, j, where2)); + st.stopAt = null; + }; + const fromHash = () => { + const m = /^#(.+)-(\d+)$/.exec((G.location && G.location.hash) || ''); + if (!m) return false; + const i = TL.sceneIndex(decodeURIComponent(m[1])); + if (i < 0) return false; + goBeat(i, +m[2] - 1); + return true; + }; + // switch language at the same scene and beat (the timeline changes: holds follow the new words) + const setLang = (l) => { + if (!tracks[l] || l === lang) return; + const s = S(), + id = s.id, + beat = Math.max(0, s.beat); + lang = l; + R = resolveLang(l); + essay = R.essay; + ui = R.ui; + root.lang = l; + build(); + const i = TL.sceneIndex(id); + goBeat(i < 0 ? 0 : i, beat); + if (G.history && G.location && !manual) { + const u = new URL(G.location.href); + u.searchParams.set('lang', l); + G.history.replaceState(null, '', u.toString()); + } + draw(); + }; + if (langSel) langSel.onchange = () => setLang(langSel.value); + + // ---- sound + const ensureAudio = () => { + if (!sound || st.audio) return; + try { + const AC = G.AudioContext || G.webkitAudioContext; + st.audio = new AC({ sampleRate: 48000 }); + const pr = sound.start(st.audio); + setSoundLabel(); + if (pr && pr.then) pr.then(setSoundLabel); + } catch (err) { + console.warn('essay: no sound', err); + } + }; + const setSound = (on) => { + if (!sound) return; + st.soundOn = on; + if (on) ensureAudio(); + if (sound.setMuted) sound.setMuted(!on); + setSoundLabel(); + }; + + // ---- the frame + let lastKey = '', + lastLive = ''; + const draw = () => { + const s = S(); + if (host && host.ok) host.render(s); + text.render(s); + segs.forEach( + ({ c, fill }) => + (fill.style.width = (100 * B.clamp01((s.t - c.start) / Math.max(1e-6, c.end - c.start))).toFixed(2) + '%') + ); + bar.setAttribute('aria-valuenow', String(Math.round((100 * s.t) / TL.total))); + const key = TL.scenes[s.scene].id + '-' + (Math.max(0, s.beat) + 1); + if (key !== lastKey && st.started) { + lastKey = key; + const sc = TL.scenes[s.scene], + spec = essay.scenes[s.scene]; + where.textContent = + (spec.chapterName ? spec.chapterName + ' · ' : '') + + ui.part.replace('{n}', s.scene + 1).replace('{total}', TL.scenes.length); + if (G.history && G.location && !manual) { + const url = '#' + encodeURIComponent(sc.id) + '-' + (Math.max(0, s.beat) + 1); + if (G.location.hash !== url) G.history[st.nav ? 'pushState' : 'replaceState'](null, '', url); + } + st.nav = false; + const b = spec.beats && spec.beats[Math.max(0, s.beat)]; + // the sources list is read where it is (its links are real); the live region says the rest once + const said = b + ? (b.text || []) + .filter((x) => !x.items) + .map((x) => (typeof x === 'string' ? x : x.text)) + .join(' ') + : ''; + if (said && said !== lastLive) live.textContent = lastLive = said; + } + if (sound && st.audio && sound.update) sound.update(s.t, st.playing && st.soundOn); + }; + + let prev = 0; + const frame = (now) => { + G.requestAnimationFrame(frame); + const dt = prev ? (now - prev) / 1000 : 0; + prev = now; + if (st.started && st.playing) { + const before = clock.t; + clock.advance(dt, st.rate); + if (st.target != null && clock.t <= st.target) { + clock.set(st.target); + st.target = null; + st.rate = 1; + if (!st.auto) setPlaying(false); + } + if (st.stopAt != null && clock.t >= st.stopAt && st.rate > 0) { + clock.set(st.stopAt); + st.stopAt = null; + setPlaying(false); + } + // waiting for clicks: stop when the current beat is fully shown + if (!st.auto && st.rate > 0 && st.stopAt == null) { + const cur = TL.flat[fi()].B; + if (before < cur.shown && clock.t >= cur.shown) { + clock.set(cur.shown); + setPlaying(false); + } + } + if (clock.t >= TL.total) { + clock.set(TL.total); + setPlaying(false); + } + if (clock.t !== before) st.dirty = true; + } + if (st.dirty) { + st.dirty = false; + draw(); + } + }; + + // ---- resize (pixel density capped at 2, picture capped at 2560 x 1600 either way round) + const resize = () => { + const r = root.getBoundingClientRect(); + const big = Math.max(r.width, r.height), + small = Math.min(r.width, r.height); + const d = Math.min(2, G.devicePixelRatio || 1, 2560 / Math.max(1, big), 1600 / Math.max(1, small)); + if (host && host.ok) host.resize(Math.max(2, Math.round(r.width * d)), Math.max(2, Math.round(r.height * d))); + if (text.resize) text.resize(r.width, r.height); + st.dirty = true; + }; + G.addEventListener('resize', resize); + + // ---- input + let idleT = 0; + const wake = () => { + root.classList.remove('eo-idle'); + G.clearTimeout(idleT); + idleT = G.setTimeout(() => { + if (help.hidden && st.started) root.classList.add('eo-idle'); + }, 3000); + }; + // only a real move wakes the controls (browsers send a mousemove when the page changes under a still pointer) + let mx = null, + my = null; + root.addEventListener('mousemove', (e) => { + const moved = mx != null && Math.abs(e.clientX - mx) + Math.abs(e.clientY - my) > 2; + mx = e.clientX; + my = e.clientY; + if (moved) wake(); + }); + const inUI = (e) => e.target.closest && e.target.closest('.eo-ui,.eo-help,.eo-start,.eo-pp,a,select'); + root.addEventListener('click', (e) => { + if (!st.started || inUI(e) || e.pointerType === 'touch') return; + next(); + }); + root.addEventListener('contextmenu', (e) => { + if (!st.started || inUI(e)) return; + e.preventDefault(); + back(); + }); + let tx = null, + ty = 0; + root.addEventListener('touchstart', (e) => { + tx = e.touches[0].clientX; + ty = e.touches[0].clientY; + }); + root.addEventListener('touchend', (e) => { + if (tx == null || !st.started) return; + const t = e.changedTouches[0], + dx = t.clientX - tx, + dy = t.clientY - ty; + tx = null; + if (inUI(e)) return; + if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) dx < 0 ? next() : back(); + else wake(); // a tap shows the controls + }); + const toggleHelp = (on = help.hidden) => { + help.hidden = !on; + if (on) help.querySelector('button').focus(); + wake(); + }; + const fullscreen = () => { + if (doc.fullscreenElement) doc.exitFullscreen(); + else if (root.requestFullscreen) root.requestFullscreen().catch(() => {}); + }; + G.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey || !st.started) return; + const k = e.key, + tag = e.target.tagName; + if (!help.hidden && (k === 'Escape' || k === '?')) return toggleHelp(false); + if ((tag === 'BUTTON' || tag === 'A') && (k === ' ' || k === 'Enter')) return; + if (tag === 'SELECT') return; + const act = { + ' ': togglePlay, + k: togglePlay, + K: togglePlay, + ArrowRight: next, + PageDown: next, + Enter: next, + ArrowLeft: back, + PageUp: back, + Backspace: back, + a: () => setAuto(!st.auto), + A: () => setAuto(!st.auto), + m: () => setSound(!st.soundOn), + M: () => setSound(!st.soundOn), + '.': () => black.classList.toggle('on'), + f: fullscreen, + F: fullscreen, + '?': () => toggleHelp(), + h: () => toggleHelp(), + Home: () => goBeat(0, 0), + End: () => goBeat(TL.scenes.length - 1, 1e9), + }[k]; + if (act) { + e.preventDefault(); + act(); + wake(); + } + }); + bBack.onclick = () => back(); + bNext.onclick = () => next(); + bPP.onclick = togglePlay; + bAuto.onclick = () => setAuto(!st.auto); + bHelp.onclick = () => toggleHelp(); + bFull.onclick = fullscreen; + if (bSound) bSound.onclick = () => setSound(!st.soundOn); + bar.addEventListener('click', (e) => { + let t = 0; + for (const { c, sg } of segs) { + const sr = sg.getBoundingClientRect(); + if (e.clientX >= sr.left - 3 && e.clientX <= sr.right + 3) + t = c.start + B.clamp01((e.clientX - sr.left) / sr.width) * (c.end - c.start); + } + const k = TL.flatIndex(t); + st.nav = true; + goBeat(TL.flat[k].scene, TL.flat[k].beat, 'shown'); + }); + G.addEventListener('popstate', () => fromHash()); + G.addEventListener('hashchange', () => fromHash()); + + const begin = (withSound) => { + start.hidden = true; + st.started = true; + root.classList.add('eo-on'); + if (withSound) setSound(true); + if (!fromHash()) jump(0); + setPlaying(true); + fullscreen(); + wake(); + if (!note.hidden) G.setTimeout(() => (note.hidden = true), 8000); // said once; then out of the words' way + }; + + // ---- test hooks: repeatable stills of any beat or any point in a transition + const E = { + get TL() { + return TL; + }, + get essay() { + return essay; + }, + get lang() { + return lang; + }, + langs, + host, + sound, + // scene: index or id; beat: index (-1 = the start of its transition); t: seconds after the beat starts, + // or 'shown' (fully in) / 'end' (the last frame of its hold) + seek(scene, beat = 0, t = 'shown') { + const i = TL.sceneIndex(scene), + Sc = TL.scenes[i]; + if (beat < 0) jump(Sc.start); + else { + const b = Sc.beats[Math.min(beat, Sc.beats.length - 1)]; + jump(t === 'shown' ? b.shown : t === 'end' ? b.end - 1e-3 : b.start + t); + } + setPlaying(false); + draw(); + return E.state(); + }, + // the transition into scene `scene` at progress p (0..1) + trans(scene, p) { + const Sc = TL.scenes[TL.sceneIndex(scene)]; + jump(Sc.start + B.clamp01(p) * Sc.trans.dur * 0.99999); + setPlaying(false); + draw(); + return E.state(); + }, + at(t) { + jump(t); + setPlaying(false); + draw(); + return E.state(); + }, + // ms per frame for a scene (waiting for the GPU each frame), drawn n times at its last beat + perf(scene, n = 60) { + if (!host || !host.ok) return null; + E.seek(scene, 1e9, 'shown'); + const s = S(); + const t0 = G.performance.now(); + for (let f = 0; f < n; f++) { + host.render(Object.assign({}, s, { sceneT: s.sceneT + f / 60, t: s.t + f / 60 })); + host.finish(); + } + return (G.performance.now() - t0) / n; + }, + // the 3-flashes-a-second rule (WCAG 2.3.1) for the transition into `scene`: the picture is stepped at 60 fps + // from 0.5 s before to 0.5 s after; flashes counted per cell of a 16 x 9 grid (DHS.essay.flashCount) + flashCheck(scene, cols = 16, rows = 9) { + if (!host || !host.ok) return null; + const Sc = TL.scenes[TL.sceneIndex(scene)], + t0 = Math.max(0, Sc.start - 0.5), + t1 = Math.min(TL.total, Sc.body + 0.5), + n = Math.round((t1 - t0) * 60); + const series = []; + for (let f = 0; f <= n; f++) { + host.render(TL.at(t0 + f / 60, { reduced: reduced() })); + series.push(host.lumaGrid(cols, rows)); + } + const { maxPerSecond, maxStep } = flashCount(series); + draw(); + return { maxPerSecond, maxStep, frames: series.length, pass: maxPerSecond <= 3 }; + }, + state() { + const s = S(); + return { + t: s.t, + total: TL.total, + scene: s.scene, + id: s.id, + beat: s.beat, + trans: s.trans, + gl: !!(host && host.ok), + reduced: reduced(), + lang, + playing: st.playing, + sound: sound ? sound.status : null, + }; + }, + textBoxes: () => text.boxes(), + contrast: () => (text.contrast ? text.contrast() : []), + layoutCheck: () => (text.layoutCheck ? text.layoutCheck() : []), + hideGlyphs: (on) => text.hideGlyphs(on), + next, + back, + begin, + setAuto, + setLang, + setSound, + togglePlay, + }; + G.EOMD_ESSAY = E; + + build(); + if (!host || !host.ok) nogl(); + if (host) host.onfail = nogl; + resize(); + setPlaying(st.playing); + if (manual) draw(); + G.requestAnimationFrame(frame); + return E; + } + + // Loads the language tracks (inline JSON, or data-src when served over http), then mounts. + const start = async (essay, opts = {}) => { + const tracks = opts.tracks || (DHS.essayTrack ? await DHS.essayTrack.load(doc) : {}); + return mount(essay, Object.assign({}, opts, { tracks })); + }; + + DHS.essay = { mount, start, flashCount }; +})(globalThis); diff --git a/kit/essay/text.js b/kit/essay/text.js new file mode 100644 index 0000000..6ded9e0 --- /dev/null +++ b/kit/essay/text.js @@ -0,0 +1,476 @@ +/* EOMD kit: essay/text.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/text.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* ESSAY TEXT: the words over the picture, in HTML (sharp at any size, selectable by screen readers through the + player's live region, and still there without WebGL2). A beat's text is a list of blocks: + { pos, kind, text } + pos center, chapter, quote (these three share the middle), lower-third, top-left, top-right, bottom-left, + bottom-right. Several blocks of one beat at one position stack (a big number and its caption). + sources: a list of { title, url, note }; titles are working links (http/https), with their site shown + kind body, headline, chapter, quote, source, number, note, takeaway (the closing statement), sources + The text is shown exactly as written; only its timing comes from it. + + Timing (a pure function of t, so seeks and stills match playback): + - a beat's blocks at one position arrive word by word when the beat arrives (each word fades in over 0.6 s, + about 0.09 s apart, closer for long text so all are in by the end of the beat's dur; a number arrives whole); + - they stay until a later beat puts text at the same position (then they fade out over 0.5 s while the new + text fades in), or until the scene ends (they fade out in the first 40% of the next transition); + - prefers-reduced-motion: each group fades in whole over 0.3 s, nothing moves. + Behind each group is a soft dark patch (a dark rounded box with soft edges, no glow) so the words hold on any picture. + Data labels from the scene (DHS.gl.sceneLabels: values, categories, the placeholder note) are drawn here too. + + const X = DHS.essayText.create(root, timeline, essay, { reduced, host }); + X.render(state); X.resize(w, h); X.boxes(); X.hideGlyphs(on); + X.contrast() -> [{ key, text, kind, ratio, need, against, pass }] WCAG contrast of each visible group against + the brightest and darkest picture pixels under it, with the patch composited in + Restyle with CSS variables on the player root: --eo-ink, --eo-font, --eo-display, --eo-serif, --eo-patch. */ +(function (G) { + 'use strict'; + const DHS = (G.DHS = G.DHS || {}); + const doc = G.document; + + const SLOT = { center: 'middle', chapter: 'middle', quote: 'middle' }; + const PATCH = { + sources: 0.6, + takeaway: 0.45, + body: 0.55, + headline: 0.5, + chapter: 0.42, + quote: 0.5, + source: 0.55, + number: 0.45, + note: 0.55, + label: 0.68, + }; + const CSS = ` +.eo-text{position:absolute;inset:0;pointer-events:none;color:var(--eo-ink,#f3f0e8);--m:max(5vw,env(safe-area-inset-left));--mt:max(8vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(8vh,env(safe-area-inset-bottom)) + 44px)} +.eo-pos{position:absolute;display:grid} +.eo-pos>.eo-g{grid-area:1/1;position:relative;padding:.9em 1.3em} +.eo-g>.eo-patch{position:absolute;inset:0;z-index:-1;border-radius:1.4em;background:rgba(0,0,0,var(--a));box-shadow:0 0 2.6em 1.2em rgba(0,0,0,var(--a))} +.eo-pos{z-index:0;isolation:isolate} +.eo-p-middle{left:50%;top:50%;transform:translate(-50%,-50%);width:min(30em,84vw);text-align:center} +.eo-g.eo-gp-quote{text-align:left} +.eo-p-lower-third{left:var(--m);right:var(--m);bottom:var(--mb);max-width:40em} +.eo-p-top-left{left:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-top-right{right:var(--m);top:var(--mt);width:min(28em,52vw)} +.eo-p-bottom-left{left:var(--m);bottom:var(--mb);width:min(28em,52vw)} +.eo-p-bottom-right{right:var(--m);bottom:var(--mb);width:min(28em,52vw);text-align:right} +.eo-b{margin:0}.eo-b+.eo-b{margin-top:.5em} +.eo-k-body{font-size:var(--eo-body,clamp(18px,1.1vw + 1.1vmin,34px));line-height:1.42;font-weight:400} +.eo-k-headline{font-family:var(--eo-display,inherit);font-size:clamp(26px,2vw + 2vmin,60px);line-height:1.12;font-weight:600;letter-spacing:-.01em} +.eo-k-chapter{font-family:var(--eo-display,inherit);font-size:clamp(30px,2.6vw + 2.4vmin,76px);line-height:1.1;font-weight:500;letter-spacing:.01em} +.eo-k-quote{font-family:var(--eo-serif,Georgia,"Times New Roman",serif);font-style:italic;font-size:clamp(22px,1.5vw + 1.5vmin,44px);line-height:1.35} +.eo-k-source{font-size:clamp(14px,.6vw + .8vmin,20px);line-height:1.4;opacity:.92} +.eo-k-number{font-family:var(--eo-display,inherit);font-size:clamp(44px,5vw + 4vmin,150px);line-height:1;font-weight:600;font-variant-numeric:tabular-nums;letter-spacing:-.02em} +.eo-w{display:inline-block;will-change:opacity} +.eo-hide .eo-w,.eo-hide .eo-lb{color:transparent!important} +.eo-lb{position:absolute;left:0;top:0;white-space:nowrap;font-size:clamp(13px,.5vw + .9vmin,22px);font-variant-numeric:tabular-nums;padding:.25em .6em; + border-radius:.8em; + background:rgba(0,0,0,${PATCH.label});box-shadow:0 0 .9em .4em rgba(0,0,0,${PATCH.label})} +.eo-lb.eo-k-value{font-weight:600;font-size:clamp(15px,.7vw + 1vmin,26px)} +.eo-lb.eo-k-note{font-size:clamp(12px,.4vw + .8vmin,17px);opacity:.95} +.eo-text a{pointer-events:auto;color:inherit;text-decoration:underline;text-decoration-thickness:1px;text-underline-offset:.18em} +.eo-text a:focus-visible{outline:2px solid var(--eo-accent,#e9e4d8);outline-offset:3px;border-radius:2px} +.eo-p-sources{left:var(--m);top:var(--mt);bottom:var(--mb);width:min(44em,90vw);align-content:start} +.eo-src{margin:.4em 0 0;padding-left:1.3em;font-size:clamp(15px,.55vw + .9vmin,22px);line-height:1.38} +.eo-src li{margin:0 0 .75em} +.eo-src-title{font-weight:600} +.eo-src-site{font-size:.86em} +.eo-src-note{display:block;margin-top:.15em} +.eo-k-takeaway{font-family:var(--eo-display,inherit);font-size:clamp(26px,2.2vw + 2.2vmin,64px);line-height:1.2;font-weight:500} +/* landscape screens 600 px tall or more (laptops at arm's length, TVs; not phones held sideways): labels, notes, + source lines and the sources list get a floor tied to the screen's height, so they read at 1366x768 and 1920x1080 + (about 2.4% of the height for a label). Phone sizes don't change. */ +@media (orientation:landscape) and (min-height:600px){ + .eo-lb{font-size:max(clamp(16px,.5vw + .9vmin,22px),2.4vh)} + .eo-lb.eo-k-value{font-size:max(clamp(18px,.7vw + 1vmin,26px),2.8vh)} + .eo-lb.eo-k-note{font-size:max(clamp(14px,.4vw + .8vmin,17px),2vh)} + .eo-k-source{font-size:max(clamp(16px,.6vw + .8vmin,20px),2.1vh)} + .eo-src{font-size:max(clamp(17px,.55vw + .9vmin,22px),2.6vh)}} +/* very wide screens (phones held sideways, ultrawide monitors; aspect 1.9 and up): the data takes the right 55% + (DHS.gl.band), so corner text stacks in a left column */ +@media (orientation:landscape) and (min-aspect-ratio:19/10){ + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right,.eo-p-lower-third{left:var(--m);right:auto;width:min(28em,40vw);text-align:left} + .eo-pos>.eo-g{padding:.6em 1em}} +/* portrait phones and tablets: corner positions go full width (the data band sits between them) */ +@media (orientation:portrait){.eo-text{--m:max(6vw,env(safe-area-inset-left));--mt:max(6vh,calc(env(safe-area-inset-top) + 66px));--mb:calc(max(4vh,env(safe-area-inset-bottom)) + 92px)} + .eo-p-top-left,.eo-p-top-right,.eo-p-bottom-left,.eo-p-bottom-right{width:auto;left:var(--m);right:var(--m);text-align:left} + .eo-p-middle{width:88vw}.eo-pos>.eo-g{padding:.7em 1em}} +`; + + const el = (tag, cls, parent) => { + const e = doc.createElement(tag); + if (cls) e.className = cls; + if (parent) parent.appendChild(e); + return e; + }; + const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x); + const smooth = (x) => ((x = clamp01(x)), x * x * (3 - 2 * x)); + + function create(root, TL, essay, opts = {}) { + const reduced = opts.reduced || (() => false), + host = opts.host; + if (!doc.getElementById('eo-text-css')) { + const st = el('style', '', doc.head); + st.id = 'eo-text-css'; + st.textContent = CSS; + } + const layer = el('div', 'eo-text', root); + let W = 1, + H = 1; + + // build every scene's groups once + const scenes = essay.scenes.map((spec, i) => { + const S = TL.scenes[i], + box = el('div', '', layer); + box.style.display = 'none'; + const posEls = {}, + groups = []; + (spec.beats || []).forEach((b, j) => { + const byPos = {}; + (b.text || []).forEach((x) => { + const blk = typeof x === 'string' ? { text: x } : x; + const pos = blk.pos || 'lower-third'; + (byPos[pos] = byPos[pos] || []).push(blk); + }); + Object.keys(byPos).forEach((pos) => { + // center, chapter and quote share the middle of the screen: a later one there replaces an earlier one + const slot = SLOT[pos] || pos; + if (!posEls[slot]) posEls[slot] = el('div', 'eo-pos eo-p-' + slot, box); + const g = el('div', 'eo-g eo-gp-' + pos, posEls[slot]), + patch = el('div', 'eo-patch', g); + const kind0 = byPos[pos][0].kind || 'body'; + const alpha = Math.max(...byPos[pos].map((x) => PATCH[x.kind || 'body'] || 0.5)); + patch.style.setProperty('--a', String(alpha)); + const words = [], + blocks = []; + // exact text: words become spans, the whitespace between them is kept as it was + const addWords = (parent, str, kind) => { + const bw = []; + String(str == null ? '' : str) + .split(/(\s+)/) + .forEach((part) => { + if (!part) return; + if (/^\s+$/.test(part)) return parent.appendChild(doc.createTextNode(part)); + const w = el('span', 'eo-w', parent); + w.textContent = part; + words.push({ el: w, whole: kind === 'number', last: '' }); + bw.push(w); + }); + blocks.push({ kind, text: String(str), words: bw }); + }; + byPos[pos].forEach((blk) => { + const kind = blk.kind || 'body'; + if (blk.items) { + // a sources list: each title is a working link (http and https only), its site, and a short note + const ol = el('ol', 'eo-b eo-src', g); + blk.items.forEach((it) => { + const li = el('li', '', ol), + ok = /^https?:\/\//i.test(it.url || ''); + const t = el(ok ? 'a' : 'span', 'eo-src-title', li); + if (ok) { + t.href = it.url; + t.target = '_blank'; + t.rel = 'noopener noreferrer'; + } + addWords(t, it.title, 'source-title'); + if (ok) { + li.appendChild(doc.createTextNode(' ')); + addWords( + el('span', 'eo-src-site', li), + new URL(it.url).hostname.replace(/^www\./, ''), + 'source-site' + ); + } + if (it.note) addWords(el('span', 'eo-src-note', li), it.note, 'source-note'); + }); + return; + } + addWords(el('p', 'eo-b eo-k-' + kind, g), blk.text, kind); + }); + // the sources list is read by screen readers where it is (links); other words come from the live region + if (!byPos[pos].some((b) => b.items)) g.setAttribute('aria-hidden', 'true'); + groups.push({ + pos: slot, + beat: j, + g, + patch, + words, + blocks, + alpha, + kind: kind0, + text: byPos[pos].map((x) => x.text).join(' '), + start: S.beats[j].arrive, + reveal: Math.max(1.2, S.beats[j].dur), + out: null, + last: '', + }); + }); + }); + // when each group leaves: the next group at the same position, or the next scene's transition + const nextS = TL.scenes[i + 1]; + groups.forEach((gr, k) => { + const later = groups.slice(k + 1).find((x) => x.pos === gr.pos && x.beat > gr.beat); + if (later) gr.out = [later.start, later.start + 0.5]; + else if (nextS) + gr.out = + nextS.trans.dur > 0 + ? [nextS.start, nextS.start + 0.4 * nextS.trans.dur] + : [nextS.start - 1e-6, nextS.start]; + else gr.out = null; // the last scene's words stay to the end + }); + return { box, groups, labels: [], lbBox: el('div', '', box) }; + }); + + const setOp = (o, e, v) => { + const s = v.toFixed(3); + if (o.last !== s) { + e.style.opacity = s; + o.last = s; + } + }; + const groupOp = (gr, t) => { + const red = reduced(); + if (t < gr.start) return 0; + const inn = red ? clamp01((t - gr.start) / 0.3) : 1; + return gr.out ? inn * (1 - smooth((t - gr.out[0]) / Math.max(1e-6, gr.out[1] - gr.out[0]))) : inn; + }; + const drawScene = (i, t, s, labelFade, p) => { + const sc = scenes[i], + red = reduced(); + sc.box.style.display = ''; + sc.groups.forEach((gr) => { + const op = groupOp(gr, t); + setOp(gr, gr.g, op); + gr.g.style.visibility = op > 0 ? 'visible' : 'hidden'; + const n = gr.words.length, + // every word is in by the time the beat has arrived (a long sources list reveals faster) + stag = red ? 0 : Math.min(0.09, Math.max(0, gr.reveal - 0.6) / Math.max(1, n - 1)); + gr.words.forEach((w, k) => setOp(w, w.el, red ? 1 : clamp01((t - gr.start - (w.whole ? 0 : k * stag)) / 0.6))); + }); + // data labels + const spec = essay.scenes[i]; + const L = DHS.gl && DHS.gl.sceneLabels ? DHS.gl.sceneLabels(spec, p, W / H) : []; + while (sc.labels.length < L.length) + sc.labels.push({ el: el('div', 'eo-lb', sc.lbBox), last: '', txt: null, pos: '' }); + sc.labels.forEach((lb, k) => { + const d = L[k]; + if (!d) return (lb.el.style.display = 'none'); + lb.el.style.display = ''; + if (lb.txt !== d.text) lb.el.textContent = lb.txt = d.text; + lb.el.className = 'eo-lb eo-k-' + d.kind; + const x = (d.x / (W / H) + 0.5) * W, + y = (0.5 - d.y) * H, + ax = d.align === 'right' ? '-100%' : d.align === 'left' ? '0' : '-50%'; + const pos = `translate(${x.toFixed(1)}px,${y.toFixed(1)}px) translate(${ax},-50%)`; + if (lb.pos !== pos) lb.el.style.transform = lb.pos = pos; + lb.data = d; + setOp(lb, lb.el, d.alpha * labelFade); + }); + }; + let shown = new Set(); + const X = { + render(s) { + const now = new Set([s.scene]); + if (s.trans && s.trans.from >= 0) now.add(s.trans.from); + shown.forEach((i) => !now.has(i) && (scenes[i].box.style.display = 'none')); + shown = now; + if (s.trans && s.trans.from >= 0) { + const f = s.trans.from; + drawScene( + f, + s.t, + s, + 1 - smooth(s.trans.p / 0.4), + TL.scenes[f].beats.map(() => 1) + ); + } + drawScene(s.scene, s.t, s, s.trans ? smooth((s.trans.p - 0.6) / 0.4) : 1, s.p); + }, + resize(w, h) { + W = Math.max(1, w); + H = Math.max(1, h); + }, + hideGlyphs(on) { + layer.classList.toggle('eo-hide', !!on); + }, + // visible groups and labels with their screen rectangles (CSS pixels) + boxes() { + const out = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) { + const pr = gr.patch.getBoundingClientRect(); + // one entry per paragraph: a big number and its small caption need different ratios + gr.blocks.forEach((b, n) => { + if (!b.words.length) return; + const wr = b.words.map((w) => w.getBoundingClientRect()); + out.push({ + key: i + ':' + gr.beat + ':' + gr.pos + ':' + n, + text: b.text, + kind: b.kind, + rect: b.words[0].parentNode.getBoundingClientRect(), + patch: pr, + alpha: gr.alpha * +gr.last, + words: wr, + el: b.words[0], + }); + }); + } + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) { + const r = lb.el.getBoundingClientRect(); + out.push({ + key: i + ':label:' + k, + text: lb.txt, + kind: lb.data.kind, + rect: r, + patch: r, + alpha: PATCH.label * +lb.last, + words: [r], + el: lb.el, + }); + } + }); + }); + return out; + }, + // problems a viewer would see: words or labels on top of each other, cut off at the screen's edge, or text + // panels covering the scene's data marks (DHS.gl.sceneMarks) + layoutCheck() { + const rootR = layer.getBoundingClientRect(), + out = []; + const items = []; + shown.forEach((i) => { + scenes[i].groups.forEach((gr) => { + if (+gr.last > 0.5) + items.push({ + key: i + ':' + gr.beat + ':' + gr.pos, + text: gr.text, + r: gr.g.getBoundingClientRect(), + scene: i, + }); + }); + scenes[i].labels.forEach((lb, k) => { + if (lb.el.style.display !== 'none' && +lb.last > 0.5) + items.push({ key: i + ':label:' + k, text: lb.txt, r: lb.el.getBoundingClientRect(), label: true }); + }); + }); + // text panels over the scene's data marks (bars, dots, circles): none may be hidden + const W0 = rootR.width, + H0 = rootR.height, + asp = W0 / H0; + shown.forEach((i) => { + const marks = DHS.gl && DHS.gl.sceneMarks ? DHS.gl.sceneMarks(essay.scenes[i], asp) : []; + const px = (x) => rootR.left + (x / asp + 0.5) * W0, + py = (y) => rootR.top + (0.5 - y) * H0; + items + .filter((it) => !it.label && it.scene === i) + .forEach((it) => { + const r = { left: it.r.left + 6, right: it.r.right - 6, top: it.r.top + 6, bottom: it.r.bottom - 6 }; + const hit = marks.some((m) => { + if (m.cx != null) { + // circle against rectangle: the rectangle's nearest point to the centre + const cx = px(m.cx), + cy = py(m.cy), + rr = m.r * H0; + const nx = Math.max(r.left, Math.min(cx, r.right)), + ny = Math.max(r.top, Math.min(cy, r.bottom)); + return (nx - cx) ** 2 + (ny - cy) ** 2 < rr * rr; + } + return r.left < px(m.r) && px(m.l) < r.right && r.top < py(m.b) && py(m.t) < r.bottom; + }); + if (hit) out.push({ problem: 'covers data', a: it.text }); + }); + }); + // groups have padding round their words: shrink them a little so touching patches aren't counted + const pad = (r, p) => ({ left: r.left + p, right: r.right - p, top: r.top + p, bottom: r.bottom - p }); + items.forEach((a, n) => { + const r = a.r; + if ( + r.left < rootR.left - 1 || + r.top < rootR.top - 1 || + r.right > rootR.right + 1 || + r.bottom > rootR.bottom + 1 + ) + out.push({ problem: 'off screen', a: a.text }); + items.slice(n + 1).forEach((b) => { + const A = pad(a.r, a.label ? 2 : 10), + Bb = pad(b.r, b.label ? 2 : 10); + if (A.left < Bb.right && Bb.left < A.right && A.top < Bb.bottom && Bb.top < A.bottom) + out.push({ problem: 'overlap', a: a.text, b: b.text }); + }); + }); + return out; + }, + contrast() { + const px = host && host.ok ? host.pixels() : null; + const rootR = layer.getBoundingClientRect(); + const sx = px ? px.w / rootR.width : 1, + sy = px ? px.h / rootR.height : 1; + const lum = DHS.gl.relLum, + con = DHS.gl.contrast; + // with no picture (no WebGL2), the fallback background's lightest colour + const fallback = [0x1b, 0x1c, 0x22]; + return X.boxes().map((b) => { + const cs = G.getComputedStyle(b.el), + ink = cs.color.match(/[\d.]+/g).map(Number); + // the text's own opacity (fades, dimmed labels, a lighter source line), up to the layer + let op = 1; + for (let e = b.el; e && e !== layer; e = e.parentElement) op *= +G.getComputedStyle(e).opacity; + const size = parseFloat(cs.fontSize), + bold = +cs.fontWeight >= 600; + const need = size >= 24 || (bold && size >= 18.66) ? 3 : 4.5; + let worst = Infinity, + against = '', + lo = Infinity, + hi = -Infinity; + const samples = []; + b.words.forEach((r) => { + const step = Math.max(1, Math.floor(Math.min(r.width, r.height) / 6)); + for (let y = r.top; y <= r.bottom; y += step) + for (let x = r.left; x <= r.right; x += step) { + // inside the patch box the patch is solid (its soft edge lies outside, past the words) + const inside = x >= b.patch.left && x <= b.patch.right && y >= b.patch.top && y <= b.patch.bottom; + const a = inside ? b.alpha : 0; + let c = fallback; + if (px) { + const X0 = Math.min(px.w - 1, Math.max(0, Math.round((x - rootR.left) * sx))), + Y0 = Math.min(px.h - 1, Math.max(0, Math.round((y - rootR.top) * sy))); + const k = ((px.h - 1 - Y0) * px.w + X0) * 4; + c = [px.data[k], px.data[k + 1], px.data[k + 2]]; + } + const bg = c.map((v) => v * (1 - a)); + const l = lum(bg[0], bg[1], bg[2]); + lo = Math.min(lo, l); + hi = Math.max(hi, l); + samples.push([bg, l]); + } + }); + samples.forEach(([bg, l]) => { + // text drawn at opacity op over this pixel (CSS blends in sRGB) + const t = ink.slice(0, 3).map((v, i) => v * op + bg[i] * (1 - op)); + const r = con(lum(t[0], t[1], t[2]), l); + if (r < worst) { + worst = r; + against = l >= (lo + hi) / 2 ? 'brightest' : 'darkest'; + } + }); + return { + key: b.key, + text: b.text, + kind: b.kind, + ratio: worst, + need, + against, + opacity: +op.toFixed(3), + pass: worst >= need, + }; + }); + }, + }; + return X; + } + + DHS.essayText = { create, PATCH }; +})(globalThis); diff --git a/kit/essay/track.js b/kit/essay/track.js new file mode 100644 index 0000000..b47648e --- /dev/null +++ b/kit/essay/track.js @@ -0,0 +1,242 @@ +/* EOMD kit: essay/track.js. Copyright (C) 2026 Bryan Patrick Murphy. SPDX-License-Identifier: AGPL-3.0-only + Copied from engine/src/essay/track.js (https://github.com/BPMData/EOMD) by tools/build_kit.py: change the source in EOMD, not this copy. */ +/* TRACK: an essay's on-screen words as a separate track, one JSON per language, never baked into the picture. + The essay file holds the structure (scenes, scene templates, data rows, timing); a track holds the words, keyed + by scene id and beat number. Reading-time holds are computed from the active track's words, so each language + gets its own pacing. Copy is shown exactly as written; numbers come from the data, formatted for the language. + + A track: + { + "lang": "en", "draft": false, draft: a translation nobody has checked yet (shown in the console) + "title": "...", "subtitle": "...", + "ui": { "begin": "Begin", ... }, player buttons and notes (DHS.essayTrack.UI has every key) + "chapters": { "opening": "Opening" }, chapter names by chapter id + "fields": { "population": "Population" }, data field names, used as chart labels + "text": { + "opening": { "1": [{ "pos": "chapter", "kind": "chapter", "text": "..." }], "2": [ ... ] }, + "bars": { "1": [ ... ], "labels": ["A", "B"], "note": "Source: ..." }, + "country#1": { "1": [{ "pos": "top-left", "kind": "headline", "text": "{name}" }], "note": "..." }, + "sources": { "1": [{ "kind": "headline", "text": "Sources" }] } + }, + "sources": [{ "title": "...", "url": "https://...", "note": "..." }] + } + "country#1" is step 1 of the scene template "country": {field} in its text is filled from each data row. + + Scene entries in the essay that this expands: + { sequence: 'country', rows: [row, ...], scale: 'row' | 'all', transition } + one short run of scenes per row from essay.templates.country.steps: [{ scene, fields, data, beats, + transition }]. A step's chart values are row[field] for its fields (a missing field stays missing, never + zero); scale 'all' puts every row on one scale (comparable bars across countries). + { id: 'sources', type: 'sources', perPage: 3 } + the sources chapter: the track's sources, perPage to a beat, as a list with working links. + + DHS.essayTrack.resolve(essay, track) -> { essay (plain scenes with text), ui, warnings } + DHS.essayTrack.fromPage(document) -> { lang: track } from + + + + + + + + + + + + + + + + diff --git a/tools/CLAUDE.md b/tools/CLAUDE.md index 0fba943..10f69e7 100644 --- a/tools/CLAUDE.md +++ b/tools/CLAUDE.md @@ -20,6 +20,7 @@ Status, the regression history and known limits: `tools/STATUS.md`. | `calibrate.py`, `porter.py`, `midi.py`, `regress.py` | Music library tools (`audio/CLAUDE.md`) | | `hershey_words.py` | Makes the `living/words*.json` files for any word list (`VARIANT`) | | `build_kit.py` | Builds `kit/` (engine parts ProofEr copies in) from their engine sources, with headers, and rewrites `kit/KIT.json` (sha256 of every file; the version is set by hand, with a `kit/CHANGELOG.md` section). `MODE = 'check'` changes nothing and lists problems; CI runs it | +| `build_essay_demo.py` | The kit's demo motion essay: `engine/essay-demo/` with the kit copies inlined → `dist/essay-demo.html`, copied to `players/essay-demo.html`. Stops if the kit is stale (run `build_kit.py` first). Check it with `node engine/tools/essay-qa.js players/essay-demo.html ` | | `check_stage_reads.py` | The peeking audit: restricted reads before a new piece's toolbox gate, from the stage logs `proj/*/access.jsonl` (written by the hook `.claude/hooks/stage_log.py`). Warnings only; CI runs it | | `eval_new_piece.py` | The first-question eval: a one-sentence new-piece request on a copy of the repo (Sonnet, read-only, capped at $0.50), checking files opened, context and cost before the first question; PASS/FAIL. CI runs it (`.github/workflows/eval.yml`) when the context files change and an `ANTHROPIC_API_KEY` secret exists | @@ -31,7 +32,7 @@ Never render an MP4 by hand in a sandbox: use `html_to_mp4.py` (it drives `?manu ## Publishing a build `players/` holds published copies of `dist/jukebox.html`, `pltw-cse.html`, `cdrom-player.html`, `cdrom-ambient.html`, -`living-player.html`, `living-player-cs.html`, `living-player-ex.html`, `danbury-academies-clock.html` and `sanctioned-corporate-calm.html` (their build copies them there itself), `gen/dist/gen-player.html` and +`living-player.html`, `living-player-cs.html`, `living-player-ex.html`, `danbury-academies-clock.html`, `sanctioned-corporate-calm.html` and `essay-demo.html` (their build copies them there itself), `gen/dist/gen-player.html` and `proj/cse-loop/cse-loop.html` (built in place by `proj/cse-loop/build.py`, published as `players/cse-loop.html`). After rebuilding one, copy it into `players/` and commit, so the public copies don't go stale. Only publish a build that loads without script errors. Adding or renaming a player: update `index.html` (the Pages landing page; `.nojekyll` must stay, or Pages diff --git a/tools/build_essay_demo.py b/tools/build_essay_demo.py new file mode 100644 index 0000000..b8ca3f2 --- /dev/null +++ b/tools/build_essay_demo.py @@ -0,0 +1,82 @@ +# tools/build_essay_demo.py: BUILD THE DEMO ESSAY. Run in Thonny (the Run button; no command-line arguments). +# The demo shows what the kit's essay engine does, with placeholder words and made-up numbers (labelled so on +# screen). Its words are language tracks (engine/essay-demo/tracks/*.json), inlined as JSON. It inlines the KIT copies (kit/, what ProofEr gets) into engine/essay-demo/dev.html, so it is built the +# way a ProofEr essay would be: one offline HTML file, nothing loaded from the internet. +# engine/essay-demo/dev.html + essay.js + kit/*.js -> dist/essay-demo.html, copied to players/essay-demo.html +# Run tools/build_kit.py first after changing an engine source (this script stops if a kit copy is stale). +import os, re, json, shutil, sys + +# ===================== SETTINGS ===================== +PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # the repo root +DEV_PAGE = os.path.join(PROJECT_DIR, 'engine', 'essay-demo', 'dev.html') +OUT = os.path.join(PROJECT_DIR, 'dist', 'essay-demo.html') +PUBLISH = os.path.join(PROJECT_DIR, 'players', 'essay-demo.html') # None to skip publishing +TITLE = 'Placeholder Motion Essay (EOMD kit demo)' +# ==================================================== + +# a dev-page script path -> the kit file inlined in its place +KIT_FOR = { + '../src/essay/beats.js': 'essay/beats.js', + '../src/essay/track.js': 'essay/track.js', + '../src/audio/dsp.js': 'audio/dsp.js', + '../src/audio/bed.js': 'audio/bed.js', + '../src/fx/lens.js': 'fx/lens.js', + '../src/gl/gl.js': 'gl/gl.js', + '../src/gl/transitions.js': 'gl/transitions.js', + '../src/gl/scenes.js': 'gl/scenes.js', + '../src/gl/host.js': 'gl/host.js', + '../src/essay/text.js': 'essay/text.js', + '../src/essay/player.js': 'essay/player.js', +} + + +def main(): + sys.path.insert(0, os.path.join(PROJECT_DIR, 'tools')) + import build_kit + + problems = build_kit.check(log=lambda m: None) + if problems: + print('Stopped: the kit is not up to date. Run tools/build_kit.py first:') + for p in problems: + print(' ' + p) + return False + with open(DEV_PAGE, encoding='utf-8') as f: + html = f.read() + + def inline(m): + src = m.group(1) + if src in KIT_FOR: + path = os.path.join(PROJECT_DIR, 'kit', *KIT_FOR[src].split('/')) + else: + path = os.path.join(os.path.dirname(DEV_PAGE), src) + with open(path, encoding='utf-8') as f: + code = f.read() + return '' + + html = re.sub(r'', inline, html) + + # language tracks: the JSON goes inside its tag (a single file can't fetch files next to it) + def track(m): + with open(os.path.join(os.path.dirname(DEV_PAGE), m.group(2)), encoding='utf-8') as f: + data = json.load(f) + body = json.dumps(data, ensure_ascii=False, separators=(',', ':')).replace('{body}' + + html = re.sub(r'', track, html) + html = re.sub(r'.*?', '' + TITLE + '', html) + html = re.sub(r'\n', '', html, flags=re.S) + if re.search(r'(src|href)="(https?:)?//', html): + print('Stopped: the page would load something from the internet.') + return False + os.makedirs(os.path.dirname(OUT), exist_ok=True) + with open(OUT, 'w', encoding='utf-8', newline='\n') as f: + f.write(html) + print(f'Built {os.path.relpath(OUT, PROJECT_DIR)} ({len(html) // 1024} KB)') + if PUBLISH: + shutil.copyfile(OUT, PUBLISH) + print(f'Published {os.path.relpath(PUBLISH, PROJECT_DIR)}') + return True + + +if __name__ == '__main__': + main() diff --git a/tools/build_kit.py b/tools/build_kit.py index 0e04180..484d258 100644 --- a/tools/build_kit.py +++ b/tools/build_kit.py @@ -17,6 +17,17 @@ PARTS = { 'fx/lens.js': 'engine/src/fx/lens.js', 'audio/dsp.js': 'engine/src/audio/dsp.js', + 'audio/bed.js': 'engine/src/audio/bed.js', + 'essay/beats.js': 'engine/src/essay/beats.js', + 'essay/track.js': 'engine/src/essay/track.js', + 'essay/text.js': 'engine/src/essay/text.js', + 'essay/player.js': 'engine/src/essay/player.js', + 'gl/gl.js': 'engine/src/gl/gl.js', + 'gl/transitions.js': 'engine/src/gl/transitions.js', + 'gl/scenes.js': 'engine/src/gl/scenes.js', + 'gl/host.js': 'engine/src/gl/host.js', + 'tools/essay-qa.js': 'engine/tools/essay-qa.js', + 'tools/render-bed.js': 'engine/tools/render-bed.js', } # Hand-written kit files (listed and hashed in KIT.json, never generated) DOCS = ['README.md', 'CHANGELOG.md']