Skip to content

Code-first video & image, rendered natively on WebGPU.

feat(examples): 33 news explainer

okanaslc65dbc5c003a
diff --git a/README.md b/README.md
index 064d9429..db2a165f 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,11 @@ Every frame is rendered by framefields directly from TypeScript in [`examples/`]
<table>
<tr>
+ <td width="33.33%" align="center">
+ <a href="https://youtu.be/tR_j_twU4p4"><img src="assets/showcase/news-explainer.jpg" alt="News explainer film about the Palm Beach County jet crash" width="100%"></a>
+ <br><a href="https://youtu.be/tR_j_twU4p4"><b>News explainer</b></a>
+ <br><sub><a href="examples/33_news_explainer"><code>33_news_explainer</code></a></sub>
+ </td>
<td width="33.33%" align="center">
<a href="https://youtu.be/3lrQdiXjlnY"><img src="assets/showcase/relay.jpg" alt="Relay product film" width="100%"></a>
<br><a href="https://youtu.be/3lrQdiXjlnY"><b>Relay</b></a>
@@ -50,13 +55,13 @@ Every frame is rendered by framefields directly from TypeScript in [`examples/`]
<br><a href="https://youtu.be/xSowU7X48J8"><b>Shard storm</b></a>
<br><sub><a href="examples/31_shard_storm"><code>31_shard_storm</code></a></sub>
</td>
+ </tr>
+ <tr>
<td width="33.33%" align="center">
<a href="https://youtu.be/POC7rKnuoE4"><img src="assets/showcase/physics-dancer.jpg" alt="Physics dancer showcase film" width="100%"></a>
<br><a href="https://youtu.be/POC7rKnuoE4"><b>Physics dancer</b></a>
<br><sub><a href="examples/28_physics_dancer"><code>28_physics_dancer</code></a></sub>
</td>
- </tr>
- <tr>
<td width="33.33%" align="center">
<a href="https://youtu.be/k2lgbdL6_TA"><img src="assets/showcase/mac-keyboard.jpg" alt="Mac keyboard from 3D primitives" width="100%"></a>
<br><a href="https://youtu.be/k2lgbdL6_TA"><b>Mac Keyboard</b></a>
@@ -67,13 +72,13 @@ Every frame is rendered by framefields directly from TypeScript in [`examples/`]
<br><a href="https://youtu.be/FVXTqAozAv8"><b>Framefields launch</b></a>
<br><sub><a href="examples/22_framefields_launch"><code>22_framefields_launch</code></a></sub>
</td>
+ </tr>
+ <tr>
<td width="33.33%" align="center">
<a href="https://youtu.be/9BF1snfmg3o"><img src="assets/showcase/full-circle.jpg" alt="Full Circle film" width="100%"></a>
<br><a href="https://youtu.be/9BF1snfmg3o"><b>Full Circle</b></a>
<br><sub><a href="examples/21_full_circle"><code>21_full_circle</code></a></sub>
</td>
- </tr>
- <tr>
<td width="33.33%" align="center">
<a href="https://youtu.be/RQ3yi_lzPqI"><img src="assets/showcase/dancer.jpg" alt="Dancer showcase film" width="100%"></a>
<br><a href="https://youtu.be/RQ3yi_lzPqI"><b>Dancer showcase</b></a>
diff --git a/assets/showcase/news-explainer.jpg b/assets/showcase/news-explainer.jpg
new file mode 100644
index 00000000..97f220ed
Binary files /dev/null and b/assets/showcase/news-explainer.jpg differ
diff --git a/examples/33_news_explainer/.gitignore b/examples/33_news_explainer/.gitignore
new file mode 100644
index 00000000..ba84179a
--- /dev/null
+++ b/examples/33_news_explainer/.gitignore
@@ -0,0 +1,4 @@
+# Fonts fetched by `pnpm assets` (src/fonts.ts pins them); voice and music made by `pnpm audio`.
+assets/fonts/
+assets/takes/
+output/
diff --git a/examples/33_news_explainer/README.md b/examples/33_news_explainer/README.md
new file mode 100644
index 00000000..d83971b7
--- /dev/null
+++ b/examples/33_news_explainer/README.md
@@ -0,0 +1,47 @@
+# 33 — News Explainer
+
+A two-minute explainer, in the paper-collage style of video explainer journalism, about the
+Learjet 60 that came down in Palm Beach County, Florida, on November 1, 2026: what is known
+as of November 2. Paper on a desk, torn strips, tape, stamps, a hand that highlights and circles,
+a map of the flight, a cross-section of the storm, a chart of the fall, a street plan and a case
+file. Everything is shapes and type; there is no footage.
+
+Watch it: [youtu.be/tR_j_twU4p4](https://youtu.be/tR_j_twU4p4)
+
+The narration is Gemini 3.8 Flash TTS (voice Charon) and the bed is Lyria 3.5, both through the
+framefields AI gateway. Each line is generated on its own, checked against the script by Scribe
+(word for word, numbers spelled out on both sides by `spoken.ts`), trimmed to its speech and
+loudness-normalized; its word timings are kept in `assets/audio.json`. The timeline lays the lines
+out scene by scene from their measured lengths, and scenes cue pictures off the words heard
+(`wordIn(scene, "warned", "icing")`), so a retaken line re-times what follows it.
+
+```bash
+pnpm assets # fonts from google/fonts, pinned by commit and SHA-256
+pnpm audio cost # estimate (about $0.30)
+pnpm audio # voice and music; needs FRAMEFIELDS_API_KEY in the repo's .env
+pnpm render grid # output/grid.png
+pnpm render frames 800 1900
+pnpm render # output/explainer.mp4
+pnpm render:src # same, on the engine's source (no package builds)
+pnpm test
+```
+
+| Scene | Narration | On screen |
+| --- | --- | --- |
+| open | The crash; nine aboard | Dateline card, headline marked on "South Florida", nine figures, a Florida scrap |
+| title | What do we know? | WHAT WE KNOW on a torn yellow strip, an "as of" stamp |
+| route | The jet, the flight | Natural Earth / Census map, aircraft card, the great circle flown and the leg never flown, push in on Palm Beach County |
+| storm | Thunderstorm, warning, climb | Altitude cross-section, a storm grown puff by puff to 44,000 ft, the SIGMET ticked per hazard, the requested 37,000 ft |
+| dive | The fall | Altitude against time through the FAA's two altitudes and the reported rates, counter, panel figures, the 35 seconds of radio |
+| ground | Where it came down | Schematic plan of Military Trail, the mobile home park, the crater, the evacuation ring |
+| probe | The investigation | NTSB case notes, what comes next, "cause not yet determined" |
+| close | The open question | The question, sources and the date of the reporting |
+
+The dive's curve is illustrative and says so on screen: it passes through 35,250 and 8,750 ft
+about 76 seconds apart and reaches 10,000, 20,000 and then 30,000 ft per minute, as reported; the
+final seconds were not published. Sources: FAA, NTSB, AP, Reuters, CBS News, ABC News,
+FOX Weather and the Aviation Safety Network.
+
+Map data: [world-atlas](https://github.com/topojson/world-atlas) (Natural Earth 1:50m) and
+[us-atlas](https://github.com/topojson/us-atlas) (US Census 1:10m), both public domain, projected
+with d3-geo.
diff --git a/examples/33_news_explainer/assets/audio.json b/examples/33_news_explainer/assets/audio.json
new file mode 100644
index 00000000..3c21559c
--- /dev/null
+++ b/examples/33_news_explainer/assets/audio.json
@@ -0,0 +1,1578 @@
+{
+ "voice": {
+ "fell": {
+ "text": "On Sunday afternoon, a business jet fell out of the sky over South Florida.",
+ "input": {
+ "prompt": "On Sunday afternoon, a business jet fell out of the sky over South Florida.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "On Sunday afternoon, a business jet fell out of the sky over South Florida.",
+ "seconds": 5.02,
+ "words": [
+ {
+ "text": "On",
+ "start": 0.04,
+ "end": 0.14
+ },
+ {
+ "text": "Sunday",
+ "start": 0.26,
+ "end": 0.56
+ },
+ {
+ "text": "afternoon,",
+ "start": 0.64,
+ "end": 1.28
+ },
+ {
+ "text": "a",
+ "start": 1.58,
+ "end": 1.64
+ },
+ {
+ "text": "business",
+ "start": 1.7,
+ "end": 2.1
+ },
+ {
+ "text": "jet",
+ "start": 2.16,
+ "end": 2.48
+ },
+ {
+ "text": "fell",
+ "start": 2.56,
+ "end": 2.8
+ },
+ {
+ "text": "out",
+ "start": 2.88,
+ "end": 2.96
+ },
+ {
+ "text": "of",
+ "start": 3,
+ "end": 3.08
+ },
+ {
+ "text": "the",
+ "start": 3.12,
+ "end": 3.2
+ },
+ {
+ "text": "sky",
+ "start": 3.3,
+ "end": 3.76
+ },
+ {
+ "text": "over",
+ "start": 3.82,
+ "end": 4.019
+ },
+ {
+ "text": "South",
+ "start": 4.08,
+ "end": 4.28
+ },
+ {
+ "text": "Florida.",
+ "start": 4.36,
+ "end": 4.74
+ }
+ ]
+ },
+ "nine": {
+ "text": "All nine people on board were killed.",
+ "input": {
+ "prompt": "All nine people on board were killed.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "All nine people on board were killed.",
+ "seconds": 2.56,
+ "words": [
+ {
+ "text": "All",
+ "start": 0.08,
+ "end": 0.26
+ },
+ {
+ "text": "nine",
+ "start": 0.34,
+ "end": 0.6
+ },
+ {
+ "text": "people",
+ "start": 0.76,
+ "end": 1.06
+ },
+ {
+ "text": "on",
+ "start": 1.1,
+ "end": 1.22
+ },
+ {
+ "text": "board",
+ "start": 1.28,
+ "end": 1.66
+ },
+ {
+ "text": "were",
+ "start": 1.7,
+ "end": 1.84
+ },
+ {
+ "text": "killed.",
+ "start": 1.9,
+ "end": 2.26
+ }
+ ]
+ },
+ "know": {
+ "text": "So what do we actually know about what happened?",
+ "input": {
+ "prompt": "So what do we actually know about what happened?",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "So what do we actually know about what happened?",
+ "seconds": 2.9,
+ "words": [
+ {
+ "text": "So",
+ "start": 0.06,
+ "end": 0.22
+ },
+ {
+ "text": "what",
+ "start": 0.54,
+ "end": 0.66
+ },
+ {
+ "text": "do",
+ "start": 0.7,
+ "end": 0.78
+ },
+ {
+ "text": "we",
+ "start": 0.82,
+ "end": 0.94
+ },
+ {
+ "text": "actually",
+ "start": 1.04,
+ "end": 1.42
+ },
+ {
+ "text": "know",
+ "start": 1.48,
+ "end": 1.74
+ },
+ {
+ "text": "about",
+ "start": 1.84,
+ "end": 2.04
+ },
+ {
+ "text": "what",
+ "start": 2.06,
+ "end": 2.18
+ },
+ {
+ "text": "happened?",
+ "start": 2.24,
+ "end": 2.62
+ }
+ ]
+ },
+ "route": {
+ "text": "The plane, a Learjet 60 built in 2004, had taken off from Austin, Texas, that morning, bound for the Bahamas.",
+ "input": {
+ "prompt": "The plane, a Learjet 60 built in 2004, had taken off from Austin, Texas, that morning, bound for the Bahamas.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "The plane, a Learjet 60 built in 2004, had taken off from Austin, Texas that morning, bound for the Bahamas.",
+ "seconds": 7.68,
+ "words": [
+ {
+ "text": "The",
+ "start": 0.06,
+ "end": 0.14
+ },
+ {
+ "text": "plane,",
+ "start": 0.2,
+ "end": 0.6
+ },
+ {
+ "text": "a",
+ "start": 0.92,
+ "end": 0.96
+ },
+ {
+ "text": "Learjet",
+ "start": 1.02,
+ "end": 1.42
+ },
+ {
+ "text": "60",
+ "start": 1.66,
+ "end": 1.88
+ },
+ {
+ "text": "built",
+ "start": 1.94,
+ "end": 2.14
+ },
+ {
+ "text": "in",
+ "start": 2.18,
+ "end": 2.28
+ },
+ {
+ "text": "2004,",
+ "start": 2.46,
+ "end": 3.12
+ },
+ {
+ "text": "had",
+ "start": 3.72,
+ "end": 3.86
+ },
+ {
+ "text": "taken",
+ "start": 3.92,
+ "end": 4.16
+ },
+ {
+ "text": "off",
+ "start": 4.22,
+ "end": 4.34
+ },
+ {
+ "text": "from",
+ "start": 4.4,
+ "end": 4.6
+ },
+ {
+ "text": "Austin,",
+ "start": 4.68,
+ "end": 5
+ },
+ {
+ "text": "Texas",
+ "start": 5.12,
+ "end": 5.48
+ },
+ {
+ "text": "that",
+ "start": 5.54,
+ "end": 5.66
+ },
+ {
+ "text": "morning,",
+ "start": 5.7,
+ "end": 6
+ },
+ {
+ "text": "bound",
+ "start": 6.46,
+ "end": 6.64
+ },
+ {
+ "text": "for",
+ "start": 6.66,
+ "end": 6.74
+ },
+ {
+ "text": "the",
+ "start": 6.78,
+ "end": 6.84
+ },
+ {
+ "text": "Bahamas.",
+ "start": 6.88,
+ "end": 7.38
+ }
+ ]
+ },
+ "cruise": {
+ "text": "By early afternoon, it was cruising east over Florida at thirty-five thousand feet.",
+ "input": {
+ "prompt": "By early afternoon, it was cruising east over Florida at thirty-five thousand feet.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "By early afternoon, it was cruising east over Florida at 35,000 feet.",
+ "seconds": 5.12,
+ "words": [
+ {
+ "text": "By",
+ "start": 0.06,
+ "end": 0.2
+ },
+ {
+ "text": "early",
+ "start": 0.22,
+ "end": 0.48
+ },
+ {
+ "text": "afternoon,",
+ "start": 0.56,
+ "end": 1.1
+ },
+ {
+ "text": "it",
+ "start": 1.4,
+ "end": 1.48
+ },
+ {
+ "text": "was",
+ "start": 1.52,
+ "end": 1.66
+ },
+ {
+ "text": "cruising",
+ "start": 1.72,
+ "end": 2.14
+ },
+ {
+ "text": "east",
+ "start": 2.24,
+ "end": 2.5
+ },
+ {
+ "text": "over",
+ "start": 2.56,
+ "end": 2.76
+ },
+ {
+ "text": "Florida",
+ "start": 2.82,
+ "end": 3.18
+ },
+ {
+ "text": "at",
+ "start": 3.42,
+ "end": 3.58
+ },
+ {
+ "text": "35,000",
+ "start": 3.78,
+ "end": 4.52
+ },
+ {
+ "text": "feet.",
+ "start": 4.62,
+ "end": 4.82
+ }
+ ]
+ },
+ "storm": {
+ "text": "But a thunderstorm was building over Palm Beach County, with tops near forty-four thousand feet.",
+ "input": {
+ "prompt": "But a thunderstorm was building over Palm Beach County, with tops near forty-four thousand feet.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "But a thunderstorm was building over Palm Beach County with tops near 44,000 feet.",
+ "seconds": 5.9,
+ "words": [
+ {
+ "text": "But",
+ "start": 0.06,
+ "end": 0.26
+ },
+ {
+ "text": "a",
+ "start": 0.32,
+ "end": 0.42
+ },
+ {
+ "text": "thunderstorm",
+ "start": 0.48,
+ "end": 1.24
+ },
+ {
+ "text": "was",
+ "start": 1.28,
+ "end": 1.42
+ },
+ {
+ "text": "building",
+ "start": 1.48,
+ "end": 1.8
+ },
+ {
+ "text": "over",
+ "start": 1.86,
+ "end": 2.06
+ },
+ {
+ "text": "Palm",
+ "start": 2.1,
+ "end": 2.3
+ },
+ {
+ "text": "Beach",
+ "start": 2.36,
+ "end": 2.52
+ },
+ {
+ "text": "County",
+ "start": 2.6,
+ "end": 2.96
+ },
+ {
+ "text": "with",
+ "start": 3.26,
+ "end": 3.58
+ },
+ {
+ "text": "tops",
+ "start": 3.66,
+ "end": 3.96
+ },
+ {
+ "text": "near",
+ "start": 4.02,
+ "end": 4.2
+ },
+ {
+ "text": "44,000",
+ "start": 4.4,
+ "end": 5.32
+ },
+ {
+ "text": "feet.",
+ "start": 5.38,
+ "end": 5.62
+ }
+ ]
+ },
+ "warned": {
+ "text": "Forecasters had already warned of severe turbulence, icing, and hail.",
+ "input": {
+ "prompt": "Forecasters had already warned of severe turbulence, icing, and hail.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "Forecasters had already warned of severe turbulence, icing, and hail",
+ "seconds": 4.96,
+ "words": [
+ {
+ "text": "Forecasters",
+ "start": 0.06,
+ "end": 0.8
+ },
+ {
+ "text": "had",
+ "start": 0.84,
+ "end": 1.14
+ },
+ {
+ "text": "already",
+ "start": 1.22,
+ "end": 1.54
+ },
+ {
+ "text": "warned",
+ "start": 1.62,
+ "end": 1.92
+ },
+ {
+ "text": "of",
+ "start": 1.98,
+ "end": 2.08
+ },
+ {
+ "text": "severe",
+ "start": 2.14,
+ "end": 2.44
+ },
+ {
+ "text": "turbulence,",
+ "start": 2.5,
+ "end": 3.1
+ },
+ {
+ "text": "icing,",
+ "start": 3.54,
+ "end": 3.96
+ },
+ {
+ "text": "and",
+ "start": 4.12,
+ "end": 4.22
+ },
+ {
+ "text": "hail.",
+ "start": 4.36,
+ "end": 4.66
+ }
+ ]
+ },
+ "climb": {
+ "text": "The crew reported ice and turbulence, and asked to climb two thousand feet.",
+ "input": {
+ "prompt": "The crew reported ice and turbulence, and asked to climb two thousand feet.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "The crew reported ice and turbulence and asked to climb two thousand feet.",
+ "seconds": 4.98,
+ "words": [
+ {
+ "text": "The",
+ "start": 0.06,
+ "end": 0.12
+ },
+ {
+ "text": "crew",
+ "start": 0.18,
+ "end": 0.36
+ },
+ {
+ "text": "reported",
+ "start": 0.4,
+ "end": 0.94
+ },
+ {
+ "text": "ice",
+ "start": 1.06,
+ "end": 1.46
+ },
+ {
+ "text": "and",
+ "start": 1.52,
+ "end": 1.66
+ },
+ {
+ "text": "turbulence",
+ "start": 1.74,
+ "end": 2.46
+ },
+ {
+ "text": "and",
+ "start": 2.84,
+ "end": 2.9
+ },
+ {
+ "text": "asked",
+ "start": 2.96,
+ "end": 3.12
+ },
+ {
+ "text": "to",
+ "start": 3.16,
+ "end": 3.26
+ },
+ {
+ "text": "climb",
+ "start": 3.34,
+ "end": 3.7
+ },
+ {
+ "text": "two",
+ "start": 3.78,
+ "end": 3.92
+ },
+ {
+ "text": "thousand",
+ "start": 3.98,
+ "end": 4.3
+ },
+ {
+ "text": "feet.",
+ "start": 4.42,
+ "end": 4.66
+ }
+ ]
+ },
+ "fall": {
+ "text": "Then the jet started to fall.",
+ "input": {
+ "prompt": "Then the jet started to fall.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "Then the jet started to fall.",
+ "seconds": 2.24,
+ "words": [
+ {
+ "text": "Then",
+ "start": 0.06,
+ "end": 0.44
+ },
+ {
+ "text": "the",
+ "start": 0.5,
+ "end": 0.6
+ },
+ {
+ "text": "jet",
+ "start": 0.68,
+ "end": 0.92
+ },
+ {
+ "text": "started",
+ "start": 1.02,
+ "end": 1.34
+ },
+ {
+ "text": "to",
+ "start": 1.38,
+ "end": 1.52
+ },
+ {
+ "text": "fall.",
+ "start": 1.6,
+ "end": 2.02
+ }
+ ]
+ },
+ "minute": {
+ "text": "According to the FAA, it dropped from about thirty-five thousand feet to under nine thousand in just over a minute.",
+ "input": {
+ "prompt": "According to the FAA, it dropped from about thirty-five thousand feet to under nine thousand in just over a minute.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "According to the FAA, it dropped from about 35,000 feet to under 9,000 in just over a minute.",
+ "seconds": 7.22,
+ "words": [
+ {
+ "text": "According",
+ "start": 0.08,
+ "end": 0.42
+ },
+ {
+ "text": "to",
+ "start": 0.46,
+ "end": 0.54
+ },
+ {
+ "text": "the",
+ "start": 0.58,
+ "end": 0.66
+ },
+ {
+ "text": "FAA,",
+ "start": 0.78,
+ "end": 1.16
+ },
+ {
+ "text": "it",
+ "start": 1.64,
+ "end": 1.74
+ },
+ {
+ "text": "dropped",
+ "start": 1.8,
+ "end": 2.16
+ },
+ {
+ "text": "from",
+ "start": 2.22,
+ "end": 2.32
+ },
+ {
+ "text": "about",
+ "start": 2.4,
+ "end": 2.7
+ },
+ {
+ "text": "35,000",
+ "start": 2.88,
+ "end": 3.8
+ },
+ {
+ "text": "feet",
+ "start": 3.86,
+ "end": 4.08
+ },
+ {
+ "text": "to",
+ "start": 4.4,
+ "end": 4.5
+ },
+ {
+ "text": "under",
+ "start": 4.56,
+ "end": 4.8
+ },
+ {
+ "text": "9,000",
+ "start": 5.12,
+ "end": 5.72
+ },
+ {
+ "text": "in",
+ "start": 5.96,
+ "end": 6.08
+ },
+ {
+ "text": "just",
+ "start": 6.14,
+ "end": 6.32
+ },
+ {
+ "text": "over",
+ "start": 6.38,
+ "end": 6.52
+ },
+ {
+ "text": "a",
+ "start": 6.56,
+ "end": 6.62
+ },
+ {
+ "text": "minute.",
+ "start": 6.7,
+ "end": 6.96
+ }
+ ]
+ },
+ "rate": {
+ "text": "At its fastest, it was descending thirty thousand feet per minute.",
+ "input": {
+ "prompt": "At its fastest, it was descending thirty thousand feet per minute.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "At its fastest, it was descending thirty thousand feet per minute.",
+ "seconds": 4.62,
+ "words": [
+ {
+ "text": "At",
+ "start": 0.06,
+ "end": 0.12
+ },
+ {
+ "text": "its",
+ "start": 0.18,
+ "end": 0.36
+ },
+ {
+ "text": "fastest,",
+ "start": 0.44,
+ "end": 1.06
+ },
+ {
+ "text": "it",
+ "start": 1.42,
+ "end": 1.5
+ },
+ {
+ "text": "was",
+ "start": 1.54,
+ "end": 1.66
+ },
+ {
+ "text": "descending",
+ "start": 1.7,
+ "end": 2.2
+ },
+ {
+ "text": "thirty",
+ "start": 2.44,
+ "end": 2.72
+ },
+ {
+ "text": "thousand",
+ "start": 2.94,
+ "end": 3.38
+ },
+ {
+ "text": "feet",
+ "start": 3.52,
+ "end": 3.74
+ },
+ {
+ "text": "per",
+ "start": 3.8,
+ "end": 3.94
+ },
+ {
+ "text": "minute",
+ "start": 4,
+ "end": 4.28
+ }
+ ]
+ },
+ "speed": {
+ "text": "That's a vertical speed of about three hundred and forty miles an hour.",
+ "input": {
+ "prompt": "That's a vertical speed of about three hundred and forty miles an hour.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "That's a vertical speed of about three hundred and forty miles an hour.",
+ "seconds": 4.079,
+ "words": [
+ {
+ "text": "That's",
+ "start": 0.06,
+ "end": 0.24
+ },
+ {
+ "text": "a",
+ "start": 0.32,
+ "end": 0.38
+ },
+ {
+ "text": "vertical",
+ "start": 0.44,
+ "end": 0.84
+ },
+ {
+ "text": "speed",
+ "start": 0.94,
+ "end": 1.4
+ },
+ {
+ "text": "of",
+ "start": 1.48,
+ "end": 1.54
+ },
+ {
+ "text": "about",
+ "start": 1.6,
+ "end": 1.84
+ },
+ {
+ "text": "three",
+ "start": 1.92,
+ "end": 2.14
+ },
+ {
+ "text": "hundred",
+ "start": 2.18,
+ "end": 2.42
+ },
+ {
+ "text": "and",
+ "start": 2.46,
+ "end": 2.54
+ },
+ {
+ "text": "forty",
+ "start": 2.72,
+ "end": 2.96
+ },
+ {
+ "text": "miles",
+ "start": 3.06,
+ "end": 3.36
+ },
+ {
+ "text": "an",
+ "start": 3.4,
+ "end": 3.48
+ },
+ {
+ "text": "hour.",
+ "start": 3.56,
+ "end": 3.779
+ }
+ ]
+ },
+ "mayday": {
+ "text": "The crew declared an emergency. About thirty-five seconds later, the radio went quiet.",
+ "input": {
+ "prompt": "The crew declared an emergency. About thirty-five seconds later, the radio went quiet.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "The crew declared an emergency. About thirty-five seconds later, the radio went quiet.",
+ "seconds": 5.66,
+ "words": [
+ {
+ "text": "The",
+ "start": 0.06,
+ "end": 0.14
+ },
+ {
+ "text": "crew",
+ "start": 0.2,
+ "end": 0.44
+ },
+ {
+ "text": "declared",
+ "start": 0.48,
+ "end": 0.8
+ },
+ {
+ "text": "an",
+ "start": 0.84,
+ "end": 0.9
+ },
+ {
+ "text": "emergency.",
+ "start": 0.96,
+ "end": 1.5
+ },
+ {
+ "text": "About",
+ "start": 2.08,
+ "end": 2.46
+ },
+ {
+ "text": "thirty-five",
+ "start": 2.54,
+ "end": 3.08
+ },
+ {
+ "text": "seconds",
+ "start": 3.2,
+ "end": 3.54
+ },
+ {
+ "text": "later,",
+ "start": 3.58,
+ "end": 3.84
+ },
+ {
+ "text": "the",
+ "start": 4.1,
+ "end": 4.2
+ },
+ {
+ "text": "radio",
+ "start": 4.28,
+ "end": 4.7
+ },
+ {
+ "text": "went",
+ "start": 4.74,
+ "end": 4.9
+ },
+ {
+ "text": "quiet.",
+ "start": 5,
+ "end": 5.4
+ }
+ ]
+ },
+ "road": {
+ "text": "It came down beside a busy road in Palm Beach County, near a mobile home park.",
+ "input": {
+ "prompt": "It came down beside a busy road in Palm Beach County, near a mobile home park.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "It came down beside a busy road in Palm Beach County, near a mobile home park.",
+ "seconds": 4.88,
+ "words": [
+ {
+ "text": "It",
+ "start": 0.06,
+ "end": 0.18
+ },
+ {
+ "text": "came",
+ "start": 0.24,
+ "end": 0.46
+ },
+ {
+ "text": "down",
+ "start": 0.52,
+ "end": 0.78
+ },
+ {
+ "text": "beside",
+ "start": 0.82,
+ "end": 1.12
+ },
+ {
+ "text": "a",
+ "start": 1.16,
+ "end": 1.26
+ },
+ {
+ "text": "busy",
+ "start": 1.3,
+ "end": 1.6
+ },
+ {
+ "text": "road",
+ "start": 1.66,
+ "end": 1.98
+ },
+ {
+ "text": "in",
+ "start": 2.02,
+ "end": 2.14
+ },
+ {
+ "text": "Palm",
+ "start": 2.2,
+ "end": 2.38
+ },
+ {
+ "text": "Beach",
+ "start": 2.44,
+ "end": 2.62
+ },
+ {
+ "text": "County,",
+ "start": 2.74,
+ "end": 3.06
+ },
+ {
+ "text": "near",
+ "start": 3.46,
+ "end": 3.62
+ },
+ {
+ "text": "a",
+ "start": 3.68,
+ "end": 3.72
+ },
+ {
+ "text": "mobile",
+ "start": 3.76,
+ "end": 4
+ },
+ {
+ "text": "home",
+ "start": 4.06,
+ "end": 4.26
+ },
+ {
+ "text": "park.",
+ "start": 4.3,
+ "end": 4.58
+ }
+ ]
+ },
+ "crater": {
+ "text": "It left a crater by the road, and about six hundred nearby residents were evacuated.",
+ "input": {
+ "prompt": "It left a crater by the road, and about six hundred nearby residents were evacuated.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "It left a crater by the road and about six hundred nearby residents were evacuated.",
+ "seconds": 5.42,
+ "words": [
+ {
+ "text": "It",
+ "start": 0.06,
+ "end": 0.14
+ },
+ {
+ "text": "left",
+ "start": 0.18,
+ "end": 0.36
+ },
+ {
+ "text": "a",
+ "start": 0.4,
+ "end": 0.46
+ },
+ {
+ "text": "crater",
+ "start": 0.54,
+ "end": 1.02
+ },
+ {
+ "text": "by",
+ "start": 1.06,
+ "end": 1.18
+ },
+ {
+ "text": "the",
+ "start": 1.22,
+ "end": 1.3
+ },
+ {
+ "text": "road",
+ "start": 1.36,
+ "end": 1.66
+ },
+ {
+ "text": "and",
+ "start": 2.16,
+ "end": 2.22
+ },
+ {
+ "text": "about",
+ "start": 2.26,
+ "end": 2.52
+ },
+ {
+ "text": "six",
+ "start": 2.6,
+ "end": 2.82
+ },
+ {
+ "text": "hundred",
+ "start": 2.86,
+ "end": 3.2
+ },
+ {
+ "text": "nearby",
+ "start": 3.26,
+ "end": 3.64
+ },
+ {
+ "text": "residents",
+ "start": 3.7,
+ "end": 4.3
+ },
+ {
+ "text": "were",
+ "start": 4.34,
+ "end": 4.44
+ },
+ {
+ "text": "evacuated.",
+ "start": 4.48,
+ "end": 5.14
+ }
+ ]
+ },
+ "ground": {
+ "text": "No one on the ground was killed.",
+ "input": {
+ "prompt": "No one on the ground was killed.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "No one on the ground was killed.",
+ "seconds": 1.92,
+ "words": [
+ {
+ "text": "No",
+ "start": 0.06,
+ "end": 0.2
+ },
+ {
+ "text": "one",
+ "start": 0.24,
+ "end": 0.34
+ },
+ {
+ "text": "on",
+ "start": 0.4,
+ "end": 0.46
+ },
+ {
+ "text": "the",
+ "start": 0.5,
+ "end": 0.58
+ },
+ {
+ "text": "ground",
+ "start": 0.64,
+ "end": 1
+ },
+ {
+ "text": "was",
+ "start": 1.04,
+ "end": 1.18
+ },
+ {
+ "text": "killed.",
+ "start": 1.26,
+ "end": 1.62
+ }
+ ]
+ },
+ "ntsb": {
+ "text": "The National Transportation Safety Board is leading the investigation, and says the weather is a major focus.",
+ "input": {
+ "prompt": "The National Transportation Safety Board is leading the investigation, and says the weather is a major focus.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "The National Transportation Safety Board is leading the investigation and says the weather is a major focus.",
+ "seconds": 6.58,
+ "words": [
+ {
+ "text": "The",
+ "start": 0.06,
+ "end": 0.12
+ },
+ {
+ "text": "National",
+ "start": 0.18,
+ "end": 0.54
+ },
+ {
+ "text": "Transportation",
+ "start": 0.62,
+ "end": 1.32
+ },
+ {
+ "text": "Safety",
+ "start": 1.44,
+ "end": 1.72
+ },
+ {
+ "text": "Board",
+ "start": 1.82,
+ "end": 2.06
+ },
+ {
+ "text": "is",
+ "start": 2.12,
+ "end": 2.26
+ },
+ {
+ "text": "leading",
+ "start": 2.34,
+ "end": 2.58
+ },
+ {
+ "text": "the",
+ "start": 2.62,
+ "end": 2.7
+ },
+ {
+ "text": "investigation",
+ "start": 2.74,
+ "end": 3.48
+ },
+ {
+ "text": "and",
+ "start": 3.9,
+ "end": 4.06
+ },
+ {
+ "text": "says",
+ "start": 4.14,
+ "end": 4.34
+ },
+ {
+ "text": "the",
+ "start": 4.38,
+ "end": 4.52
+ },
+ {
+ "text": "weather",
+ "start": 4.58,
+ "end": 5.04
+ },
+ {
+ "text": "is",
+ "start": 5.12,
+ "end": 5.26
+ },
+ {
+ "text": "a",
+ "start": 5.32,
+ "end": 5.36
+ },
+ {
+ "text": "major",
+ "start": 5.52,
+ "end": 5.86
+ },
+ {
+ "text": "focus.",
+ "start": 5.92,
+ "end": 6.3
+ }
+ ]
+ },
+ "breakup": {
+ "text": "Investigators have also found signs that the plane may have begun to break apart in the air.",
+ "input": {
+ "prompt": "Investigators have also found signs that the plane may have begun to break apart in the air.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "Investigators have also found signs that the plane may have begun to break apart in the air.",
+ "seconds": 5.18,
+ "words": [
+ {
+ "text": "Investigators",
+ "start": 0.06,
+ "end": 0.8
+ },
+ {
+ "text": "have",
+ "start": 0.84,
+ "end": 0.96
+ },
+ {
+ "text": "also",
+ "start": 1.04,
+ "end": 1.36
+ },
+ {
+ "text": "found",
+ "start": 1.44,
+ "end": 1.68
+ },
+ {
+ "text": "signs",
+ "start": 1.74,
+ "end": 2.2
+ },
+ {
+ "text": "that",
+ "start": 2.24,
+ "end": 2.34
+ },
+ {
+ "text": "the",
+ "start": 2.38,
+ "end": 2.46
+ },
+ {
+ "text": "plane",
+ "start": 2.52,
+ "end": 2.78
+ },
+ {
+ "text": "may",
+ "start": 2.84,
+ "end": 2.96
+ },
+ {
+ "text": "have",
+ "start": 3,
+ "end": 3.1
+ },
+ {
+ "text": "begun",
+ "start": 3.14,
+ "end": 3.42
+ },
+ {
+ "text": "to",
+ "start": 3.48,
+ "end": 3.58
+ },
+ {
+ "text": "break",
+ "start": 3.62,
+ "end": 3.78
+ },
+ {
+ "text": "apart",
+ "start": 3.84,
+ "end": 4.42
+ },
+ {
+ "text": "in",
+ "start": 4.48,
+ "end": 4.54
+ },
+ {
+ "text": "the",
+ "start": 4.58,
+ "end": 4.68
+ },
+ {
+ "text": "air.",
+ "start": 4.78,
+ "end": 4.96
+ }
+ ]
+ },
+ "report": {
+ "text": "A preliminary report is expected within weeks. A final cause could take a year or more.",
+ "input": {
+ "prompt": "A preliminary report is expected within weeks. A final cause could take a year or more.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "A preliminary report is expected within weeks. A final cause could take a year or more.",
+ "seconds": 6.34,
+ "words": [
+ {
+ "text": "A",
+ "start": 0.06,
+ "end": 0.12
+ },
+ {
+ "text": "preliminary",
+ "start": 0.18,
+ "end": 0.76
+ },
+ {
+ "text": "report",
+ "start": 0.8,
+ "end": 1.32
+ },
+ {
+ "text": "is",
+ "start": 1.4,
+ "end": 1.46
+ },
+ {
+ "text": "expected",
+ "start": 1.52,
+ "end": 2.1
+ },
+ {
+ "text": "within",
+ "start": 2.16,
+ "end": 2.44
+ },
+ {
+ "text": "weeks.",
+ "start": 2.52,
+ "end": 2.84
+ },
+ {
+ "text": "A",
+ "start": 3.46,
+ "end": 3.52
+ },
+ {
+ "text": "final",
+ "start": 3.58,
+ "end": 3.88
+ },
+ {
+ "text": "cause",
+ "start": 3.96,
+ "end": 4.42
+ },
+ {
+ "text": "could",
+ "start": 4.48,
+ "end": 4.68
+ },
+ {
+ "text": "take",
+ "start": 4.76,
+ "end": 4.92
+ },
+ {
+ "text": "a",
+ "start": 5,
+ "end": 5.06
+ },
+ {
+ "text": "year",
+ "start": 5.16,
+ "end": 5.52
+ },
+ {
+ "text": "or",
+ "start": 5.58,
+ "end": 5.68
+ },
+ {
+ "text": "more.",
+ "start": 5.76,
+ "end": 6.04
+ }
+ ]
+ },
+ "question": {
+ "text": "For now, the question is how a jet cruising at thirty-five thousand feet could fall so far, so fast.",
+ "input": {
+ "prompt": "For now, the question is how a jet cruising at thirty-five thousand feet could fall so far, so fast.",
+ "voice": "Charon",
+ "style_instructions": "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent."
+ },
+ "heard": "For now, the question is how a jet cruising at 35,000 feet could fall so far so fast.",
+ "seconds": 7.06,
+ "words": [
+ {
+ "text": "For",
+ "start": 0.06,
+ "end": 0.18
+ },
+ {
+ "text": "now,",
+ "start": 0.24,
+ "end": 0.46
+ },
+ {
+ "text": "the",
+ "start": 0.54,
+ "end": 0.62
+ },
+ {
+ "text": "question",
+ "start": 0.7,
+ "end": 1.12
+ },
+ {
+ "text": "is",
+ "start": 1.2,
+ "end": 1.36
+ },
+ {
+ "text": "how",
+ "start": 1.74,
+ "end": 1.88
+ },
+ {
+ "text": "a",
+ "start": 1.94,
+ "end": 2.02
+ },
+ {
+ "text": "jet",
+ "start": 2.1,
+ "end": 2.32
+ },
+ {
+ "text": "cruising",
+ "start": 2.4,
+ "end": 2.74
+ },
+ {
+ "text": "at",
+ "start": 2.78,
+ "end": 2.92
+ },
+ {
+ "text": "35,000",
+ "start": 3.1,
+ "end": 3.94
+ },
+ {
+ "text": "feet",
+ "start": 4.02,
+ "end": 4.24
+ },
+ {
+ "text": "could",
+ "start": 4.7,
+ "end": 4.82
+ },
+ {
+ "text": "fall",
+ "start": 4.88,
+ "end": 5.02
+ },
+ {
+ "text": "so",
+ "start": 5.22,
+ "end": 5.42
+ },
+ {
+ "text": "far",
+ "start": 5.5,
+ "end": 6.04
+ },
+ {
+ "text": "so",
+ "start": 6.1,
+ "end": 6.26
+ },
+ {
+ "text": "fast.",
+ "start": 6.34,
+ "end": 6.76
+ }
+ ]
+ }
+ },
+ "music": {
+ "prompt": "A soft instrumental underscore for a two-minute news explainer video about a tragic plane crash. No vocals, no singing, no spoken words, no drums.\nReflective, respectful and quietly curious at 72 BPM in D minor: felt piano playing a sparse repeating motif, warm string pad, a soft low cello drone and a faint, slow plucked pulse. Gentle and understated throughout, always staying in the background under a narrator.\n[0:00-0:20] Felt piano motif alone over a soft pad, intimate.\n[0:20-0:45] The plucked pulse enters, light and steady, like a clock.\n[0:45-1:10] The low cello drone joins and the harmony darkens slightly, tense but restrained.\n[1:10-1:40] It opens up a little: warm strings carry the motif, hopeful but sober.\n[1:40-2:05] It thins back to the piano motif and settles on one long, quiet final chord.\n[2:05-2:10] Silence.",
+ "seconds": 125
+ }
+}
diff --git a/examples/33_news_explainer/framefields.json b/examples/33_news_explainer/framefields.json
new file mode 100644
index 00000000..f76e2d00
--- /dev/null
+++ b/examples/33_news_explainer/framefields.json
@@ -0,0 +1,3 @@
+{
+ "components": "src/components"
+}
diff --git a/examples/33_news_explainer/package.json b/examples/33_news_explainer/package.json
new file mode 100644
index 00000000..b0628933
--- /dev/null
+++ b/examples/33_news_explainer/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@framefields/example-33-news-explainer",
+ "version": "2.13.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "assets": "tsx src/fetch-fonts.ts",
+ "audio": "tsx src/generate-audio.ts",
+ "render": "tsx src/render.ts",
+ "render:src": "tsx --tsconfig tsconfig.dev.json --conditions=development src/render.ts",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit -p ."
+ },
+ "dependencies": {
+ "framefields": "workspace:*"
+ },
+ "devDependencies": {
+ "@framefields/tsconfig": "workspace:*",
+ "@types/d3-geo": "3.1.0",
+ "@types/geojson": "^7946.0.16",
+ "@types/node": "^24.1.0",
+ "@types/topojson-client": "3.1.5",
+ "@types/topojson-specification": "^1.0.5",
+ "d3-geo": "3.1.1",
+ "topojson-client": "3.1.0",
+ "tsx": "^4.20.3",
+ "typescript": "^5.8.3",
+ "us-atlas": "3.0.1",
+ "vitest": "^4.1.5",
+ "world-atlas": "2.0.2"
+ }
+}
diff --git a/examples/33_news_explainer/src/audio.ts b/examples/33_news_explainer/src/audio.ts
new file mode 100644
index 00000000..9f84d95b
--- /dev/null
+++ b/examples/33_news_explainer/src/audio.ts
@@ -0,0 +1,127 @@
+/**
+ * The film's generated sound, all through the framefields AI gateway: Gemini
+ * 3.8 Flash TTS reads the narration and Lyria 3.5 plays a soft bed under it.
+ * `pnpm audio` makes the files (media stays out of git) and records what it
+ * measured in assets/audio.json, which is committed so the film can be timed
+ * without them.
+ *
+ * The narration reports what officials and early coverage said on November
+ * 1–2, 2026 (FAA, NTSB, AP, Reuters, CBS News, FOX Weather); no cause had been
+ * determined, and the script says so.
+ */
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { ASSETS } from "./theme.js";
+
+export const VOICE_MODEL = "google/gemini-3.8-flash-tts";
+export const MUSIC_MODEL = "google/lyria-3.5";
+export const TRANSCRIBER = "elevenlabs/speech-to-text/scribe-v2";
+
+/** Gemini's informative male voice. */
+export const VOICE = "Charon";
+export const STYLE =
+ "A thoughtful American journalist narrating a calm news explainer video about a fatal plane crash. Clear, measured and quietly serious, curious rather than dramatic, never sensational. A steady conversational pace with no long pauses. Standard American English accent.";
+
+/** The narration, in the order it is heard. */
+export const LINES = {
+ fell: "On Sunday afternoon, a business jet fell out of the sky over South Florida.",
+ nine: "All nine people on board were killed.",
+ know: "So what do we actually know about what happened?",
+ route:
+ "The plane, a Learjet 60 built in 2004, had taken off from Austin, Texas, that morning, bound for the Bahamas.",
+ cruise:
+ "By early afternoon, it was cruising east over Florida at thirty-five thousand feet.",
+ storm:
+ "But a thunderstorm was building over Palm Beach County, with tops near forty-four thousand feet.",
+ warned:
+ "Forecasters had already warned of severe turbulence, icing, and hail.",
+ climb:
+ "The crew reported ice and turbulence, and asked to climb two thousand feet.",
+ fall: "Then the jet started to fall.",
+ minute:
+ "According to the FAA, it dropped from about thirty-five thousand feet to under nine thousand in just over a minute.",
+ rate: "At its fastest, it was descending thirty thousand feet per minute.",
+ speed:
+ "That's a vertical speed of about three hundred and forty miles an hour.",
+ mayday:
+ "The crew declared an emergency. About thirty-five seconds later, the radio went quiet.",
+ road: "It came down beside a busy road in Palm Beach County, near a mobile home park.",
+ crater:
+ "It left a crater by the road, and about six hundred nearby residents were evacuated.",
+ ground: "No one on the ground was killed.",
+ ntsb: "The National Transportation Safety Board is leading the investigation, and says the weather is a major focus.",
+ breakup:
+ "Investigators have also found signs that the plane may have begun to break apart in the air.",
+ report:
+ "A preliminary report is expected within weeks. A final cause could take a year or more.",
+ question:
+ "For now, the question is how a jet cruising at thirty-five thousand feet could fall so far, so fast.",
+} as const;
+
+export type LineId = keyof typeof LINES;
+export const LINE_IDS = Object.keys(LINES) as LineId[];
+
+/** What the voice model is asked for one line: its text and the shared delivery. */
+export const voiceInput = (id: LineId) => ({
+ prompt: LINES[id],
+ voice: VOICE,
+ style_instructions: STYLE,
+});
+
+/**
+ * A soft bed, instrumental throughout, longer than the film so it can be cut
+ * and faded on the last frame.
+ */
+export const MUSIC_SECONDS = 125;
+export const MUSIC_PROMPT = `A soft instrumental underscore for a two-minute news explainer video about a tragic plane crash. No vocals, no singing, no spoken words, no drums.
+Reflective, respectful and quietly curious at 72 BPM in D minor: felt piano playing a sparse repeating motif, warm string pad, a soft low cello drone and a faint, slow plucked pulse. Gentle and understated throughout, always staying in the background under a narrator.
+[0:00-0:20] Felt piano motif alone over a soft pad, intimate.
+[0:20-0:45] The plucked pulse enters, light and steady, like a clock.
+[0:45-1:10] The low cello drone joins and the harmony darkens slightly, tense but restrained.
+[1:10-1:40] It opens up a little: warm strings carry the motif, hopeful but sober.
+[1:40-2:05] It thins back to the piano motif and settles on one long, quiet final chord.
+[2:05-2:10] Silence.`;
+
+export interface SpokenWord {
+ text: string;
+ start: number;
+ end: number;
+}
+
+export interface AudioManifest {
+ voice: Record<
+ LineId,
+ {
+ text: string;
+ /** What the voice model was asked, so a changed line or delivery is read again. */
+ input: ReturnType<typeof voiceInput>;
+ /** What the transcriber heard, which must match `text` word for word. */
+ heard: string;
+ /** Trimmed to the speech: 60 ms before the first word, 300 ms after the last. */
+ seconds: number;
+ /** Each word heard, in seconds into the trimmed file, so a picture can land on a word. */
+ words: SpokenWord[];
+ }
+ >;
+ /** The prompt it was made from, and its length once cut. */
+ music: { prompt: string; seconds: number };
+}
+
+/** Where the first word starts in a trimmed line. */
+export const VOICE_LEAD = 0.06;
+
+export const MANIFEST = path.join(ASSETS, "audio.json");
+export const voicePath = (id: LineId) =>
+ path.join(ASSETS, "voice", `${id}.wav`);
+export const MUSIC_PATH = path.join(ASSETS, "music.wav");
+
+export function readManifest(): AudioManifest {
+ return JSON.parse(readFileSync(MANIFEST, "utf8")) as AudioManifest;
+}
+
+/** Generated files not on disk yet. */
+export function missingAudio(): string[] {
+ return [...LINE_IDS.map(voicePath), MUSIC_PATH]
+ .filter((file) => !existsSync(file))
+ .map((file) => path.relative(ASSETS, file));
+}
diff --git a/examples/33_news_explainer/src/components/annotate/index.ts b/examples/33_news_explainer/src/components/annotate/index.ts
new file mode 100644
index 00000000..739ae174
--- /dev/null
+++ b/examples/33_news_explainer/src/components/annotate/index.ts
@@ -0,0 +1,503 @@
+/**
+ * Annotate: marks that draw on to point at something. Underline a phrase,
+ * circle a number, strike a claim, box a region, draw an arrow; clean
+ * geometry or hand-drawn, with a boil that keeps hand-drawn marks alive.
+ *
+ * Coordinates are the parent's: the root sits at 0, 0, so targets resolve
+ * where they are drawn. Text targets give one mark per line.
+ */
+import { LayerAnimation, type LayoutNode } from "framefields";
+import {
+ type Animatable,
+ type ArrowCurve,
+ anchorPoint,
+ arrowPaths,
+ bindComponent,
+ boilKeys,
+ boundsOf,
+ boxPath,
+ defineComponent,
+ ellipsePath,
+ linePath,
+ type Rect,
+ resolveTarget,
+ scaleFrames,
+ squigglePath,
+ type Target,
+ targetSchema,
+ themeFrames,
+ toPathData,
+ type Vec2,
+ wobblePoints,
+ z,
+} from "framefields/components";
+
+export const MARKS = [
+ "underline",
+ "circle",
+ "box",
+ "highlight",
+ "strike",
+ "cross",
+ "bracket",
+ "arrow",
+ "squiggle",
+] as const;
+export type Mark = (typeof MARKS)[number];
+
+const TEXTURE = {
+ /** Even, confident line. */
+ ink: { width: 1, opacity: 1 },
+ /** Broad felt tip. */
+ marker: { width: 1.5, opacity: 0.94 },
+ /** Thin and light. */
+ pencil: { width: 0.55, opacity: 0.85 },
+} as const;
+
+export interface AnnotateCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** The mark is fully drawn. */
+ drawn: ReadonlyArray<{ frame: number }>;
+ /** The label starts to appear (empty without a label). */
+ labelIn: ReadonlyArray<{ frame: number }>;
+}
+
+/** One stroke of a mark: its path for a boil variant, and a length for pacing. */
+interface Stroke {
+ path(variant: number): string;
+ length: number;
+ kind: "line" | "fill" | "head";
+}
+
+export const annotate = /* @__PURE__ */ defineComponent({
+ name: "Annotate",
+ props: () => ({
+ /** What to mark. Rects (e.g. `TextReveal.rects("word")`) give one mark per rect for line marks. */
+ target: z.union([
+ z.array(
+ z.object({
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ }),
+ ),
+ targetSchema(),
+ ]),
+ mark: z.enum(MARKS).default("underline"),
+ /** Where an arrow starts (it points at `target`). */
+ from: targetSchema().optional(),
+ curve: z.enum(["straight", "arc", "swoop"]).default("arc"),
+ color: z.string().optional(),
+ /** Stroke width before the texture's factor. Default the theme's bold stroke. */
+ width: z.number().positive().optional(),
+ /** `wobble` 0–1 (how loose the hand is); `boil`: frames between re-poses, 0 = still. */
+ hand: z
+ .union([
+ z.literal(false),
+ z
+ .object({
+ wobble: z.number().min(0).max(1).default(0.6),
+ boil: z.number().int().min(0).default(4),
+ seed: z.number().int().optional(),
+ })
+ .strict(),
+ ])
+ .default({ wobble: 0.6, boil: 4 }),
+ texture: z.enum(["ink", "marker", "pencil"]).default("marker"),
+ /** Frames the mark takes to draw. Default the theme's base speed (× 1.5 for arrows). */
+ drawDuration: z.number().int().positive().optional(),
+ label: z
+ .union([
+ z.string(),
+ z
+ .object({
+ text: z.string(),
+ side: z
+ .enum(["auto", "top", "bottom", "left", "right"])
+ .default("auto"),
+ font: z.string().optional(),
+ size: z.number().positive().optional(),
+ })
+ .strict(),
+ ])
+ .optional(),
+ /** Space between the target and the mark. */
+ padding: z.number().min(0).default(8),
+ }),
+ defaults: { enter: false, exit: false, hold: 45 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const s = theme.scale;
+ const pad = props.padding * s;
+ const hand = props.hand === false ? null : props.hand;
+ const wobble = (hand?.wobble ?? 0) * 5 * s;
+ const seed = hand?.seed ?? ctx.seed;
+ const texture = TEXTURE[props.texture];
+ const strokeW = (props.width ?? theme.stroke.bold * s) * texture.width;
+ const color = props.color ?? theme.color.highlight;
+
+ // ── Geometry ─────────────────────────────────────────────────────
+ const resolve = (t: Target) => {
+ const r = resolveTarget(t, { measure: host.measure, fps });
+ if (r.kind !== "static")
+ throw new Error(
+ "Annotate: targets must be static (points, rects, nodes, text). Moving targets arrive with Callout.",
+ );
+ return r;
+ };
+ const isRects =
+ Array.isArray(props.target) && typeof props.target[0] === "object";
+ const resolved = isRects ? null : resolve(props.target as Target);
+ const rects: Rect[] = isRects
+ ? (props.target as Rect[])
+ : (resolved?.rects ?? []);
+ if (rects.length === 0)
+ throw new Error("Annotate: the target covers nothing.");
+ const isText =
+ isRects ||
+ (typeof props.target === "object" &&
+ props.target !== null &&
+ "text" in (props.target as object));
+ const b = boundsOf(rects);
+ const hw = { wobble, seed };
+
+ const strokes: Stroke[] = [];
+ /** Points outside the target the strokes reach (an arrow's tail). */
+ const reach: Vec2[] = [];
+ const lineAt = (y: (r: Rect) => number, extend: number) =>
+ rects.forEach((r) => {
+ const from: Vec2 = [r.x - extend, y(r)];
+ const to: Vec2 = [r.x + r.width + extend, y(r)];
+ strokes.push({
+ path: (v) => linePath(from, to, hw, v + strokes.length * 7),
+ length: to[0] - from[0],
+ kind: "line",
+ });
+ });
+ // Text rects are a line tall: the baseline sits near 80 % of it.
+ const under = (r: Rect) =>
+ isText ? r.y + r.height * 0.84 + pad * 0.4 : r.y + r.height + pad;
+
+ switch (props.mark) {
+ case "underline":
+ lineAt(under, pad * 0.25);
+ break;
+ case "strike":
+ lineAt((r) => r.y + r.height * (isText ? 0.54 : 0.5), pad * 0.4);
+ break;
+ case "squiggle":
+ rects.forEach((r, i) => {
+ const from: Vec2 = [r.x, under(r)];
+ const to: Vec2 = [r.x + r.width, under(r)];
+ strokes.push({
+ path: (v) =>
+ squigglePath(
+ from,
+ to,
+ { ...hw, amplitude: 4 * s + strokeW * 0.4 },
+ v + i * 7,
+ ),
+ length: r.width * 1.3,
+ kind: "line",
+ });
+ });
+ break;
+ case "highlight":
+ rects.forEach((r, i) => {
+ const y = r.y + r.height * (isText ? 0.56 : 0.5);
+ const from: Vec2 = [r.x - pad * 0.4, y];
+ const to: Vec2 = [r.x + r.width + pad * 0.4, y];
+ strokes.push({
+ path: (v) =>
+ linePath(from, to, { ...hw, wobble: wobble * 0.5 }, v + i * 7),
+ length: to[0] - from[0],
+ kind: "fill",
+ });
+ });
+ break;
+ case "circle":
+ strokes.push({
+ path: (v) => ellipsePath(b, { ...hw, padding: pad * 1.5 }, v),
+ length: Math.PI * (b.width + b.height + pad * 3),
+ kind: "line",
+ });
+ break;
+ case "box":
+ strokes.push({
+ path: (v) => boxPath(b, { ...hw, padding: pad }, v),
+ length: 2 * (b.width + b.height + pad * 4),
+ kind: "line",
+ });
+ break;
+ case "cross": {
+ const x0 = b.x - pad;
+ const y0 = b.y - pad;
+ const x1 = b.x + b.width + pad;
+ const y1 = b.y + b.height + pad;
+ const d = Math.hypot(x1 - x0, y1 - y0);
+ strokes.push(
+ {
+ path: (v) => linePath([x0, y0], [x1, y1], hw, v),
+ length: d,
+ kind: "line",
+ },
+ {
+ path: (v) => linePath([x1, y0], [x0, y1], hw, v + 11),
+ length: d,
+ kind: "line",
+ },
+ );
+ break;
+ }
+ case "bracket": {
+ const x = b.x - pad * 1.5;
+ const lip = Math.min(18 * s, b.height * 0.2);
+ const pts: Vec2[] = [
+ [x + lip, b.y - pad * 0.5],
+ [x, b.y - pad * 0.5],
+ [x, b.y + b.height + pad * 0.5],
+ [x + lip, b.y + b.height + pad * 0.5],
+ ];
+ strokes.push({
+ path: (v) => toPathData(wobblePoints(densify(pts, 6), hw, v)),
+ length: b.height + lip * 2 + pad,
+ kind: "line",
+ });
+ break;
+ }
+ case "arrow": {
+ if (!props.from)
+ throw new Error('Annotate: mark "arrow" needs `from`.');
+ const start = resolve(props.from);
+ const tail = anchorPoint(boundsOf(start.rects), start.anchor);
+ const tip = edgeToward(b, tail, pad);
+ reach.push(tail);
+ const headSize =
+ (14 * s + strokeW * 1.6) * (props.texture === "pencil" ? 0.8 : 1);
+ const geometry = (v: number) =>
+ arrowPaths(
+ tail,
+ tip,
+ { ...hw, curve: props.curve as ArrowCurve, headSize },
+ v,
+ );
+ const length = Math.hypot(tip[0] - tail[0], tip[1] - tail[1]);
+ strokes.push(
+ { path: (v) => geometry(v).shaft, length, kind: "line" },
+ { path: (v) => geometry(v).head, length: headSize * 2, kind: "head" },
+ );
+ break;
+ }
+ }
+
+ // ── Timing ───────────────────────────────────────────────────────
+ const drawFrames =
+ props.drawDuration ??
+ Math.round(
+ themeFrames(theme, "base", fps) * (props.mark === "arrow" ? 1.5 : 1.2),
+ );
+ const bodies = strokes.filter((st) => st.kind !== "head");
+ const total = bodies.reduce((a, st) => a + Math.max(1, st.length), 0);
+ let cursor = 0;
+ const windows: Array<{ start: number; end: number }> = [];
+ for (const st of strokes) {
+ const prev = windows[windows.length - 1];
+ if (st.kind === "head" && prev) {
+ // The head flicks on as the shaft reaches 92 %.
+ const start = Math.round(prev.start + (prev.end - prev.start) * 0.92);
+ windows.push({ start, end: start + Math.max(3, scaleFrames(5, fps)) });
+ continue;
+ }
+ const start = Math.round(cursor);
+ cursor += (drawFrames * Math.max(1, st.length)) / total;
+ windows.push({ start, end: Math.max(start + 2, Math.round(cursor)) });
+ }
+ const drawn = Math.max(...windows.map((w) => w.end));
+
+ // ── Nodes ────────────────────────────────────────────────────────
+ const lightBg = theme.mode === "light";
+ // The shapes' box must hold every stroke, or the renderer clips it.
+ const margin = pad * 4 + strokeW * 4;
+ const extentX = Math.max(b.x + b.width, ...reach.map((p) => p[0])) + margin;
+ const extentY =
+ Math.max(b.y + b.height, ...reach.map((p) => p[1])) + margin;
+ const boil =
+ hand && hand.boil > 0 && wobble > 0 ? scaleFrames(hand.boil, fps) : 0;
+ // Marks stay up: boil through the window, or a while past the hold.
+ const boilEnd =
+ (props as { duration?: number }).duration ??
+ drawn + Math.max(ctx.hold, fps * 6);
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const children: LayoutNode[] = [];
+ let maxX = extentX;
+ let maxY = extentY;
+
+ strokes.forEach((st, i) => {
+ const w = windows[i] as { start: number; end: number };
+ const fill = st.kind === "fill";
+ const rect = rects[i] ?? b;
+ const node = host.shape("path", {
+ id: ctx.partId(st.kind === "head" ? "head" : `stroke-${i}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: extentX,
+ height: extentY,
+ d: st.path(0),
+ fillType: "none",
+ strokeColor: color,
+ strokeWidth: fill ? rect.height * (isText ? 0.62 : 1) : strokeW,
+ strokeLineCap: fill ? "butt" : "round",
+ strokeLineJoin: "round",
+ trimEnd: 0,
+ opacity: fill ? (lightBg ? 0.9 : 0.38) : texture.opacity,
+ ...(fill && lightBg && { blendMode: "multiply" }),
+ });
+ const anim = LayerAnimation.create().keys("trimEnd", [
+ [w.start, 0],
+ [w.end, 1, st.kind === "head" ? "power2.out" : "power2.inOut"],
+ ]);
+ if (boil > 0)
+ anim.keys(
+ "d",
+ boilKeys(st.path, { start: 0, end: boilEnd, every: boil }),
+ );
+ node.animate(anim);
+ parts[st.kind === "head" ? "head" : `stroke-${i}`] = node;
+ children.push(node);
+ });
+
+ // ── Label ────────────────────────────────────────────────────────
+ let labelIn: number | null = null;
+ if (props.label !== undefined) {
+ const o =
+ typeof props.label === "string"
+ ? { text: props.label, side: "auto" as const }
+ : props.label;
+ const font =
+ ("font" in o && o.font) || theme.font.hand || theme.font.body;
+ const size = ("size" in o && o.size) || 34 * s;
+ const m = host.measure(o.text, { fontFamily: font, fontSize: size });
+ const gap = 10 * s + pad;
+ let x: number;
+ let y: number;
+ if (props.mark === "arrow" && props.from) {
+ const start = resolve(props.from);
+ const tail = anchorPoint(boundsOf(start.rects), start.anchor);
+ const tip = edgeToward(b, tail, pad);
+ const len = Math.hypot(tip[0] - tail[0], tip[1] - tail[1]) || 1;
+ const dx = (tip[0] - tail[0]) / len;
+ const dy = (tip[1] - tail[1]) / len;
+ const reach =
+ Math.abs(dx) * (m.width / 2) +
+ Math.abs(dy) * (m.height / 2) +
+ gap * 0.5;
+ x = tail[0] - dx * reach - m.width / 2;
+ y = tail[1] - dy * reach - m.height / 2;
+ } else {
+ const side =
+ o.side === "auto"
+ ? b.y - gap - m.height >= 0
+ ? "top"
+ : "bottom"
+ : o.side;
+ const top = props.mark === "circle" ? pad * 1.5 : pad;
+ x =
+ side === "left"
+ ? b.x - top - gap - m.width
+ : side === "right"
+ ? b.x + b.width + top + gap
+ : b.x + b.width - m.width;
+ y =
+ side === "top"
+ ? b.y - top - gap - m.height
+ : side === "bottom"
+ ? b.y + b.height + top + gap
+ : b.y + (b.height - m.height) / 2;
+ }
+ const label = host.text(o.text, {
+ id: ctx.partId("label"),
+ position: "absolute",
+ x,
+ y,
+ fontFamily: font,
+ fontSize: size,
+ fill: props.mark === "highlight" ? theme.color.ink : color,
+ });
+ labelIn = Math.max(0, drawn - scaleFrames(4, fps));
+ const intro = scaleFrames(10, fps);
+ label.animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [labelIn, 0],
+ [labelIn + intro, 1, "power2.out"],
+ ])
+ .keys("y", [
+ [labelIn, y + 8 * s],
+ [labelIn + intro, y, theme.motion.ease.enter],
+ ]),
+ );
+ parts.label = label;
+ children.push(label);
+ maxX = Math.max(maxX, x + m.width + 8);
+ maxY = Math.max(maxY, y + m.height + 8);
+ }
+
+ return {
+ children,
+ width: maxX,
+ height: maxY,
+ duration: Math.max(
+ drawn,
+ labelIn === null ? 0 : labelIn + scaleFrames(10, fps),
+ ),
+ openEnded: true,
+ origin: [0, 0],
+ cues: {
+ drawn: [{ frame: drawn }],
+ labelIn: labelIn === null ? [] : [{ frame: labelIn }],
+ } as AnnotateCues,
+ parts,
+ };
+ },
+});
+
+/** Where a mark around `rect` (+ gap) meets the line toward `from`. */
+function edgeToward(rect: Rect, from: Vec2, gap: number): Vec2 {
+ const cx = rect.x + rect.width / 2;
+ const cy = rect.y + rect.height / 2;
+ const dx = from[0] - cx;
+ const dy = from[1] - cy;
+ const hx = rect.width / 2 + gap;
+ const hy = rect.height / 2 + gap;
+ const t = Math.min(
+ dx === 0 ? Number.POSITIVE_INFINITY : hx / Math.abs(dx),
+ dy === 0 ? Number.POSITIVE_INFINITY : hy / Math.abs(dy),
+ );
+ return Number.isFinite(t) ? [cx + dx * t, cy + dy * t] : [cx, cy - hy];
+}
+
+/** Extra points along each segment, so a wobble bends lines instead of corners only. */
+function densify(points: readonly Vec2[], per: number): Vec2[] {
+ const out: Vec2[] = [];
+ points.forEach((p, i) => {
+ const next = points[i + 1];
+ if (!next) {
+ out.push(p);
+ return;
+ }
+ for (let k = 0; k < per; k++) {
+ const t = k / per;
+ out.push([p[0] + (next[0] - p[0]) * t, p[1] + (next[1] - p[1]) * t]);
+ }
+ });
+ return out;
+}
+
+/**
+ * Marks that draw on to point at something: underline, circle, box, highlight,
+ * strike, cross, bracket, arrow or squiggle, clean or hand-drawn with a boil,
+ * with an optional label.
+ */
+export const Annotate = /* @__PURE__ */ bindComponent(annotate);
diff --git a/examples/33_news_explainer/src/components/counter/index.ts b/examples/33_news_explainer/src/components/counter/index.ts
new file mode 100644
index 00000000..bfeff28d
--- /dev/null
+++ b/examples/33_news_explainer/src/components/counter/index.ts
@@ -0,0 +1,439 @@
+/**
+ * Counter: numbers that change in a way viewers trust. Every digit place is
+ * a clipped reel that spins like an odometer (`roll`) or steps (`count`);
+ * separators and affixes are laid out by the format, and the number slides
+ * to stay aligned as places appear.
+ */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+} from "framefields";
+import {
+ type Animatable,
+ bakeSamples,
+ bindComponent,
+ defineComponent,
+ type MeasureOptions,
+ themeFrames,
+ z,
+} from "framefields/components";
+import {
+ type CounterFormat,
+ milestones,
+ numberLayout,
+ placesOf,
+ reelPositions,
+ type ValueKey,
+ valueAt,
+} from "./plan.js";
+
+export type { CounterFormat } from "./plan.js";
+
+export interface CounterCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Every reel is at rest on the final value. */
+ settled: ReadonlyArray<{ frame: number }>;
+ /** Crossings of `milestoneEvery` (e.g. for tick sounds). */
+ milestones: ReadonlyArray<{ frame: number; value: number }>;
+}
+
+/** A slot in the number: a digit reel, a separator, or a character column. */
+interface Slot {
+ width: number;
+ /** Visible on each frame. */
+ visible: boolean[];
+ build(x: number): Animatable<LayoutNode>;
+}
+
+const MINUS = "−";
+/** Frames a slot takes to fade, and the number to slide, when places change. */
+const SETTLE = 6;
+
+export const counter = /* @__PURE__ */ defineComponent({
+ name: "Counter",
+ props: () => ({
+ from: z.number().default(0),
+ to: z.number().optional(),
+ /** Multi-step counts: `[frame, value, ease?]`, frames ascending. */
+ values: z
+ .array(
+ z.union([
+ z.tuple([z.number().int().min(0), z.number()]),
+ z.tuple([z.number().int().min(0), z.number(), z.string()]),
+ ]),
+ )
+ .min(1)
+ .optional(),
+ /** `",d"`, `"$,.2f"`, `".1%"`, Intl options, or `(n) => string`. */
+ format: z
+ .union([
+ z.string(),
+ z.custom<(value: number) => string>((v) => typeof v === "function"),
+ z.custom<Intl.NumberFormatOptions>(
+ (v) => typeof v === "object" && v !== null,
+ ),
+ ])
+ .default(",d"),
+ locale: z.string().default("en-US"),
+ prefix: z.string().default(""),
+ suffix: z.string().default(""),
+ /** Affix size relative to the digits (e.g. 0.6 for a small `%`). */
+ affixScale: z.number().min(0.2).max(1).default(1),
+ /** `roll`: odometer reels. `count`: digits step frame by frame. */
+ style: z.enum(["roll", "count"]).default("roll"),
+ /** Frames the count takes (`from` → `to`). Default: twice the theme's slow speed. */
+ countDuration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ /** Frames each higher place settles after the one below it (`roll`). */
+ digitStagger: z.number().min(0).default(2),
+ /** Vertical blur on fast reels (`roll`). */
+ motionBlur: z.boolean().default(true),
+ milestoneEvery: z.number().positive().optional(),
+ fontFamily: z.string().optional(),
+ fontSize: z.number().positive().optional(),
+ fontWeight: z.union([z.number(), z.string()]).optional(),
+ fill: z.string().optional(),
+ align: z.enum(["start", "center", "end"]).default("start"),
+ }),
+ defaults: { enter: false, exit: false, hold: 30 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const fs = props.fontSize ?? 120 * theme.scale;
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ const ease = props.ease ?? theme.motion.ease.move;
+ const roll = props.style === "roll";
+
+ if (props.values === undefined && props.to === undefined)
+ throw new Error("Counter: give `to` (or `values`).");
+ const keys: ValueKey[] = props.values
+ ? props.values.map((v) => [...v] as unknown as ValueKey)
+ : [
+ [0, props.from],
+ [
+ props.countDuration ?? themeFrames(theme, "slow", fps) * 2,
+ props.to as number,
+ ],
+ ];
+ keys.forEach((k, i) => {
+ const prev = keys[i - 1];
+ if (prev && k[0] <= prev[0])
+ throw new Error(
+ `Counter: \`values\` frames must ascend (${prev[0]} then ${k[0]}).`,
+ );
+ });
+
+ const text = (content: string, size: number, id: string, extra = {}) =>
+ host.text(content, {
+ id: ctx.partId(id),
+ position: "absolute",
+ fontFamily,
+ fontSize: size,
+ fill: props.fill ?? theme.color.ink,
+ ...(props.fontWeight !== undefined && { fontWeight: props.fontWeight }),
+ ...extra,
+ });
+ const measureWith = (s: string, size = fs) =>
+ host.measure(s, {
+ fontFamily,
+ fontSize: size,
+ fontWeight: props.fontWeight,
+ } satisfies MeasureOptions);
+ const lh = measureWith("0").lineHeight;
+
+ const layout = numberLayout(props.format as CounterFormat, props.locale);
+ const stagger = roll ? (props.digitStagger * fps) / 30 : 0;
+ const lastKey = (keys[keys.length - 1] as ValueKey)[0];
+ // Reels count in the last shown digit: 99.5 at two decimals is 9950.
+ const scale = layout ? layout.scale * 10 ** layout.decimals : 1;
+ const places = layout
+ ? Math.max(...keys.map((k) => placesOf(k[1] * scale, layout.decimals)))
+ : 1;
+ const settle = Math.round(lastKey + stagger * (places - 1));
+ const values = Array.from({ length: settle + 1 }, (_, f) =>
+ valueAt(keys, f, ease),
+ );
+ const scaled = values.map((v) => Math.round(v * scale));
+
+ // ── Slots, right to left ──────────────────────────────────────────
+ const slots: Slot[] = [];
+ if (layout) {
+ const cellW = Math.max(
+ ...[..."0123456789"].map((d) => measureWith(d).width),
+ );
+ const shows = (place: number) =>
+ scaled.map(
+ (n) =>
+ place <= layout.decimals ||
+ Math.floor(Math.abs(n) / 10 ** place) > 0,
+ );
+ for (let p = 0; p < places; p++) {
+ if (p === layout.decimals && layout.decimals > 0) {
+ const mark = layout.decimalMark;
+ slots.push({
+ width: measureWith(mark).width,
+ visible: scaled.map(() => true),
+ build: (x) => text(mark, fs, "decimal", { x, y: 0 }),
+ });
+ }
+ const q = p - layout.decimals;
+ if (layout.group && q > 0 && q % 3 === 0) {
+ const sep = layout.group;
+ slots.push({
+ width: measureWith(sep).width,
+ visible: shows(p),
+ build: (x) => text(sep, fs, `group-${q}`, { x, y: 0 }),
+ });
+ }
+ const place = p;
+ slots.push({
+ width: cellW,
+ visible: shows(place),
+ build: (x) =>
+ digitCell(
+ place,
+ x,
+ cellW,
+ roll
+ ? reelPositions(keys, place, {
+ scale,
+ stagger,
+ ease,
+ length: settle,
+ })
+ : scaled.map((n) => Math.floor(Math.abs(n) / 10 ** place) % 10),
+ ),
+ });
+ }
+ } else {
+ // A formatter function: one column per character from the right.
+ const format = props.format as (n: number) => string;
+ const strings = values.map((v) => format(v));
+ const columns = Math.max(...strings.map((s) => s.length));
+ for (let c = 0; c < columns; c++) {
+ const chars = strings.map((s) => s[s.length - 1 - c] ?? "");
+ const rows = [...new Set(chars)];
+ const width = Math.max(
+ 0,
+ ...rows.map((r) => (r ? measureWith(r).width : 0)),
+ );
+ const col = c;
+ slots.push({
+ width,
+ visible: chars.map((ch) => ch !== ""),
+ build: (x) => charCell(col, x, width, rows, chars),
+ });
+ }
+ }
+
+ function digitCell(
+ place: number,
+ x: number,
+ width: number,
+ positions: number[],
+ ): Animatable<LayoutNode> {
+ const lo = Math.floor(Math.min(...positions));
+ const hi = Math.ceil(Math.max(...positions));
+ const rows = roll
+ ? Array.from(
+ { length: hi - lo + 1 },
+ (_, k) => (((lo + k) % 10) + 10) % 10,
+ )
+ : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+ const base = roll ? lo : 0;
+ const ys = positions.map((pos) => -(pos - base) * lh);
+ const reel = text(rows.join("\n"), fs, `reel-${place}`, {
+ x: 0,
+ y: ys[0] ?? 0,
+ width,
+ align: "center",
+ ...(roll && props.motionBlur && { motionBlurShutter: 90 }),
+ });
+ reel.animate(
+ LayerAnimation.keys(
+ "y",
+ roll ? bakeSamples(ys, 0, { tolerance: 0.2 }) : stepKeys(ys),
+ ),
+ );
+ return host.box({
+ id: ctx.partId(`cell-${place}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width,
+ height: lh,
+ overflow: "hidden",
+ children: [reel],
+ });
+ }
+
+ function charCell(
+ column: number,
+ x: number,
+ width: number,
+ rows: string[],
+ chars: string[],
+ ): Animatable<LayoutNode> {
+ const ys = chars.map((ch) => -rows.indexOf(ch) * lh);
+ const reel = text(
+ rows.map((r) => r || " ").join("\n"),
+ fs,
+ `reel-${column}`,
+ {
+ x: 0,
+ y: ys[0] ?? 0,
+ width,
+ align: "center",
+ },
+ );
+ reel.animate(LayerAnimation.keys("y", stepKeys(ys)));
+ return host.box({
+ id: ctx.partId(`cell-${column}`),
+ position: "absolute",
+ x,
+ y: 0,
+ width,
+ height: lh,
+ overflow: "hidden",
+ children: [reel],
+ });
+ }
+
+ // ── Layout over time ──────────────────────────────────────────────
+ const affix = fs * props.affixScale;
+ const affixLh = measureWith("0", affix).lineHeight;
+ const affixY = (lh - affixLh) * 0.78;
+ const prefix = (layout?.prefix ?? "") + props.prefix;
+ const suffix = props.suffix + (layout?.suffix ?? "");
+ const prefixW = prefix ? measureWith(prefix, affix).width : 0;
+ const suffixW = suffix ? measureWith(suffix, affix).width : 0;
+ const negative = scaled.map((n) => n < 0);
+ const minusW = negative.some(Boolean) ? measureWith(MINUS).width : 0;
+
+ const digitsW = slots.reduce((a, s) => a + s.width, 0);
+ const W = prefixW + minusW + digitsW + suffixW;
+ const shown = scaled.map((_, f) =>
+ slots.reduce((a, s) => a + (s.visible[f] ? s.width : 0), 0),
+ );
+ const content = shown.map(
+ (w, f) => prefixW + (negative[f] ? minusW : 0) + w + suffixW,
+ );
+ const af = props.align === "center" ? 0.5 : props.align === "end" ? 1 : 0;
+ const left = content.map((c) => (W - c) * af);
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ let cursor = digitsW;
+ const cells = slots.map((s, i) => {
+ cursor -= s.width;
+ const node = s.build(cursor);
+ node.animate(LayerAnimation.keys("opacity", fadeKeys(s.visible)));
+ parts[`slot-${i}`] = node;
+ return node;
+ });
+ const digits = host.box({
+ id: ctx.partId("digits"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: digitsW,
+ height: lh,
+ children: cells,
+ });
+ const digitsX = shown.map(
+ (w, f) =>
+ (left[f] as number) +
+ prefixW +
+ (negative[f] ? minusW : 0) +
+ w -
+ digitsW,
+ );
+ digits.animate(LayerAnimation.keys("x", slideKeys(digitsX)));
+ parts.digits = digits;
+ const children: LayoutNode[] = [digits];
+
+ if (prefix) {
+ const node = text(prefix, affix, "prefix", { x: 0, y: affixY });
+ node.animate(LayerAnimation.keys("x", slideKeys(left)));
+ parts.prefix = node;
+ children.push(node);
+ }
+ if (minusW > 0) {
+ const node = text(MINUS, fs, "minus", { x: 0, y: 0 });
+ node.animate(
+ LayerAnimation.create()
+ .keys("x", slideKeys(left.map((l) => l + prefixW)))
+ .keys("opacity", fadeKeys(negative)),
+ );
+ parts.minus = node;
+ children.push(node);
+ }
+ if (suffix) {
+ const node = text(suffix, affix, "suffix", { x: 0, y: affixY });
+ node.animate(
+ LayerAnimation.keys("x", slideKeys(digitsX.map((x) => x + digitsW))),
+ );
+ parts.suffix = node;
+ children.push(node);
+ }
+
+ return {
+ children,
+ width: W,
+ height: lh,
+ duration: settle + 1,
+ openEnded: true,
+ cues: {
+ settled: [{ frame: settle }],
+ milestones:
+ props.milestoneEvery === undefined
+ ? []
+ : milestones(values, props.milestoneEvery),
+ } as CounterCues,
+ parts,
+ };
+ },
+});
+
+/** Hold keys at every change of a per-frame series. */
+function stepKeys(series: readonly number[]): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, series[0] ?? 0]];
+ for (let f = 1; f < series.length; f++)
+ if (series[f] !== series[f - 1])
+ keys.push([f, series[f] as number, "hold"]);
+ return keys;
+}
+
+/** A per-frame target that changes in steps, eased over {@link SETTLE} frames. */
+function slideKeys(series: readonly number[]): KeyframeTuple[] {
+ const keys: KeyframeTuple[] = [[0, series[0] ?? 0]];
+ for (let f = 1; f < series.length; f++) {
+ const prev = series[f - 1] as number;
+ const next = series[f] as number;
+ if (Math.abs(next - prev) < 0.01) continue;
+ const last = keys[keys.length - 1] as KeyframeTuple;
+ if (f - 1 > last[0]) keys.push([f - 1, prev]);
+ keys.push([f - 1 + SETTLE, next, "power2.out"]);
+ }
+ return dedupe(keys);
+}
+
+function fadeKeys(visible: readonly boolean[]): KeyframeTuple[] {
+ return slideKeys(visible.map((v) => (v ? 1 : 0)));
+}
+
+/** Keys must ascend: a later change replaces anything it overlaps. */
+function dedupe(keys: KeyframeTuple[]): KeyframeTuple[] {
+ const out: KeyframeTuple[] = [];
+ for (const k of keys) {
+ while (out.length > 0 && (out[out.length - 1] as KeyframeTuple)[0] >= k[0])
+ out.pop();
+ out.push(k);
+ }
+ return out;
+}
+
+/**
+ * A number that counts to its value on odometer reels (or stepping digits),
+ * with format-aware separators, affixes and multi-step values.
+ */
+export const Counter = /* @__PURE__ */ bindComponent(counter);
diff --git a/examples/33_news_explainer/src/components/counter/plan.ts b/examples/33_news_explainer/src/components/counter/plan.ts
new file mode 100644
index 00000000..d5e14e30
--- /dev/null
+++ b/examples/33_news_explainer/src/components/counter/plan.ts
@@ -0,0 +1,176 @@
+/**
+ * Counter planning, kept pure: how a format lays a number out (affixes,
+ * separators, fixed decimals), the value over time, and where each digit
+ * reel sits on every frame.
+ */
+import { evaluateEase } from "framefields/components";
+
+/** How a known format writes any value: digits are laid out from these. */
+export interface NumberLayout {
+ decimals: number;
+ /** Thousands separator, or null for none. */
+ group: string | null;
+ decimalMark: string;
+ prefix: string;
+ suffix: string;
+ /** 100 for percentages. */
+ scale: number;
+}
+
+export type CounterFormat =
+ | string
+ | Intl.NumberFormatOptions
+ | ((value: number) => string);
+
+/**
+ * A layout for a d3-style format string (`",d"`, `",.2f"`, `".1%"`,
+ * `"$,.0f"`) or Intl options. Functions return null: they are laid out per
+ * character instead.
+ */
+export function numberLayout(
+ format: CounterFormat,
+ locale = "en-US",
+): NumberLayout | null {
+ if (typeof format === "function") return null;
+ if (typeof format === "string") {
+ const m = format.match(/^(\$)?(,)?(?:\.(\d+))?([df%]?)$/);
+ if (!m) {
+ throw new Error(
+ `Counter: unsupported format "${format}". Use [$][,][.precision][d|f|%] (e.g. ",d", "$,.2f", ".1%"), Intl options, or a function.`,
+ );
+ }
+ const type = m[4] ?? "";
+ return {
+ decimals: type === "d" ? 0 : Number(m[3] ?? (type === "%" ? 0 : 0)),
+ group: m[2] ? "," : null,
+ decimalMark: ".",
+ prefix: m[1] ?? "",
+ suffix: type === "%" ? "%" : "",
+ scale: type === "%" ? 100 : 1,
+ };
+ }
+ const nf = new Intl.NumberFormat(locale, format);
+ const resolved = nf.resolvedOptions();
+ const parts = nf.formatToParts(1234567.891);
+ const first = parts.findIndex((p) => p.type === "integer");
+ const lastNumeric = parts.reduce(
+ (at, p, i) =>
+ ["integer", "group", "decimal", "fraction"].includes(p.type) ? i : at,
+ -1,
+ );
+ return {
+ decimals: resolved.maximumFractionDigits ?? 0,
+ group: parts.find((p) => p.type === "group")?.value ?? null,
+ decimalMark: parts.find((p) => p.type === "decimal")?.value ?? ".",
+ prefix: parts
+ .slice(0, first)
+ .map((p) => p.value)
+ .join(""),
+ suffix: parts
+ .slice(lastNumeric + 1)
+ .map((p) => p.value)
+ .join(""),
+ scale: format.style === "percent" ? 100 : 1,
+ };
+}
+
+/** `[frame, value, ease?]`: the value is reached at `frame`. */
+export type ValueKey = readonly [frame: number, value: number, ease?: string];
+
+/** The value at any frame of a piecewise trajectory. */
+export function valueAt(
+ keys: readonly ValueKey[],
+ frame: number,
+ fallbackEase: string,
+): number {
+ const first = keys[0];
+ if (!first) return 0;
+ if (frame <= first[0]) return first[1];
+ for (let i = 1; i < keys.length; i++) {
+ const a = keys[i - 1] as ValueKey;
+ const b = keys[i] as ValueKey;
+ if (frame <= b[0]) {
+ const t = (frame - a[0]) / Math.max(1, b[0] - a[0]);
+ return a[1] + (b[1] - a[1]) * evaluateEase(b[2] ?? fallbackEase, t);
+ }
+ }
+ return (keys[keys.length - 1] as ValueKey)[1];
+}
+
+/** Number of digit places a scaled integer shows (at least `decimals + 1`). */
+export function placesOf(n: number, decimals: number): number {
+ const abs = Math.abs(Math.round(n));
+ return Math.max(
+ decimals + 1,
+ abs === 0 ? 1 : Math.floor(Math.log10(abs)) + 1,
+ );
+}
+
+/** Most turns a reel makes in one move; the rest is a blur nobody can read. */
+export const MAX_TURNS = 3;
+
+/**
+ * Reel position (in digit steps) of place `p` on every frame `0..length`:
+ * each segment moves every place from its old digit to its new one, higher
+ * places later by `stagger × p` frames, spinning the way an odometer does
+ * (capped at {@link MAX_TURNS} turns). `pos mod 10` is the digit shown.
+ */
+export function reelPositions(
+ keys: readonly ValueKey[],
+ place: number,
+ o: { scale: number; stagger: number; ease: string; length: number },
+): number[] {
+ const unit = 10 ** place;
+ const digitsAt = (v: number) =>
+ Math.floor(Math.abs(Math.round(v * o.scale)) / unit);
+ const out = new Array<number>(o.length + 1);
+ let pos = digitsAt(keys[0]?.[1] ?? 0);
+ let free = Number.NEGATIVE_INFINITY;
+ const segments = keys.slice(1).map((b, i) => {
+ const a = keys[i] as ValueKey;
+ const delta = digitsAt(b[1]) - digitsAt(a[1]);
+ const turns = Math.abs(delta);
+ const distance =
+ Math.sign(delta) *
+ (turns <= MAX_TURNS * 10 ? turns : MAX_TURNS * 10 + (turns % 10));
+ // A place never starts a move before finishing its last one.
+ const start = Math.max(a[0] + o.stagger * place, free);
+ const seg = {
+ from: pos,
+ distance,
+ start,
+ end: start + (b[0] - a[0]),
+ ease: b[2] ?? o.ease,
+ };
+ pos += distance;
+ free = seg.end;
+ return seg;
+ });
+ for (let f = 0; f <= o.length; f++) {
+ let p = digitsAt(keys[0]?.[1] ?? 0);
+ for (const s of segments) {
+ if (f <= s.start) break;
+ const t = Math.min(1, (f - s.start) / Math.max(1, s.end - s.start));
+ p = s.from + s.distance * evaluateEase(s.ease, t);
+ }
+ out[f] = p;
+ }
+ return out;
+}
+
+/** Frames where `value` crosses a multiple of `every`, with that multiple. */
+export function milestones(
+ values: readonly number[],
+ every: number,
+): Array<{ frame: number; value: number }> {
+ const out: Array<{ frame: number; value: number }> = [];
+ for (let f = 1; f < values.length; f++) {
+ const a = Math.floor((values[f - 1] as number) / every);
+ const b = Math.floor((values[f] as number) / every);
+ if (a === b) continue;
+ const dir = Math.sign(b - a);
+ for (let k = a + (dir > 0 ? 1 : 0); dir > 0 ? k <= b : k > b; k += dir)
+ out.push({ frame: f, value: k * every });
+ }
+ return out;
+}
diff --git a/examples/33_news_explainer/src/components/text-reveal/index.ts b/examples/33_news_explainer/src/components/text-reveal/index.ts
new file mode 100644
index 00000000..ca08fc22
--- /dev/null
+++ b/examples/33_news_explainer/src/components/text-reveal/index.ts
@@ -0,0 +1,1089 @@
+/**
+ * TextReveal: headlines and body copy that animate in (and out) by
+ * character, word or line. One timing model, many looks. Glyph styles run on
+ * the GPU through baked per-unit schedules, so a paragraph stays one text
+ * node and its final frame is exactly the static text.
+ */
+import {
+ type KeyframeTuple,
+ LayerAnimation,
+ type LayoutNode,
+ type TextNode,
+} from "framefields";
+import {
+ type Animatable,
+ bakeSamples,
+ bindComponent,
+ constantExpression,
+ defineComponent,
+ evaluateEase,
+ findRange,
+ type GlyphAnimator,
+ type GlyphProps,
+ type GlyphUnit,
+ glyphAnimator,
+ lineShift,
+ type MeasureOptions,
+ type Metrics,
+ type Rect,
+ rangeRects,
+ rendererChars,
+ round as roundTo,
+ scaleFrames,
+ scheduleExpression,
+ stepExpression,
+ type Theme,
+ themeFrames,
+ typingFrames,
+ type UnitSchedule,
+ z,
+} from "framefields/components";
+import {
+ burstStarts,
+ indexedStarts,
+ scrambleSet,
+ unitStarts,
+ unitsOf,
+} from "./plan.js";
+
+export const REVEAL_STYLES = [
+ "rise",
+ "blur",
+ "mask",
+ "slam",
+ "scatter",
+ "scramble",
+ "type",
+ "stream",
+ "wipe",
+ "flip",
+] as const;
+export type RevealStyle = (typeof REVEAL_STYLES)[number];
+
+/** Styles that can also play out (`exitStyle`). */
+export const EXIT_STYLES = [
+ "rise",
+ "blur",
+ "mask",
+ "scatter",
+ "type",
+ "stream",
+ "wipe",
+ "flip",
+] as const;
+export type ExitStyle = (typeof EXIT_STYLES)[number];
+
+const ORDERS = ["forward", "reverse", "center", "edges", "random"] as const;
+
+interface StyleDefaults {
+ by: GlyphUnit;
+ /** Frames between units at 30 fps. */
+ stagger: number;
+ speed: keyof Theme["motion"]["speed"];
+ /** Multiplier on the speed token. */
+ length: number;
+ ease: string;
+}
+
+const STYLE: Record<RevealStyle, StyleDefaults> = {
+ rise: {
+ by: "word",
+ stagger: 3,
+ speed: "base",
+ length: 1.4,
+ ease: "expo.out",
+ },
+ blur: {
+ by: "char",
+ stagger: 1.2,
+ speed: "slow",
+ length: 1,
+ ease: "power3.out",
+ },
+ mask: {
+ by: "line",
+ stagger: 5,
+ speed: "base",
+ length: 1.5,
+ ease: "expo.out",
+ },
+ slam: { by: "word", stagger: 7, speed: "fast", length: 1, ease: "power3.in" },
+ scatter: {
+ by: "char",
+ stagger: 0.8,
+ speed: "slow",
+ length: 1.2,
+ ease: "expo.out",
+ },
+ scramble: {
+ by: "char",
+ stagger: 1.5,
+ speed: "base",
+ length: 1,
+ ease: "none",
+ },
+ type: { by: "char", stagger: 0, speed: "fast", length: 1, ease: "none" },
+ stream: {
+ by: "word",
+ stagger: 6,
+ speed: "slow",
+ length: 1,
+ ease: "power2.out",
+ },
+ wipe: {
+ by: "line",
+ stagger: 0,
+ speed: "slow",
+ length: 1.4,
+ ease: "power2.inOut",
+ },
+ flip: {
+ by: "char",
+ stagger: 1.5,
+ speed: "base",
+ length: 1.2,
+ ease: "back.out(1.4)",
+ },
+};
+
+/** What each glyph style pushes at full weight (font-size units, degrees). */
+function glyphFrom(style: RevealStyle, fs: number, exit: boolean): GlyphProps {
+ switch (style) {
+ case "rise":
+ return { y: (exit ? -0.32 : 0.42) * fs, opacity: 0 };
+ case "blur":
+ return { blur: 0.16 * fs, scale: 1.18, opacity: 0 };
+ case "flip":
+ return { rotationX: exit ? -90 : 90, opacity: 0 };
+ default:
+ return { opacity: 0 };
+ }
+}
+
+export interface TextRevealCues {
+ [name: string]: ReadonlyArray<{ frame: number }>;
+ /** Per unit: starts moving (`frame`) and comes to rest (`settled`). */
+ units: ReadonlyArray<{
+ frame: number;
+ settled: number;
+ index: number;
+ text: string;
+ }>;
+ /** The whole text is at rest. */
+ revealed: ReadonlyArray<{ frame: number }>;
+ /** The exit starts (empty without `exitStyle`). */
+ exitStart: ReadonlyArray<{ frame: number }>;
+ /** Each typed character (`type`) or arriving word (`stream`): for key sounds. */
+ keystrokes: ReadonlyArray<{ frame: number; index: number }>;
+}
+
+export interface TextRevealApi {
+ /**
+ * Rects (parent coordinates) that a match covers, one per line: hand
+ * them to `Annotate` or a camera. Without `match`, the whole text.
+ */
+ rects(match?: string | RegExp, nth?: number): Rect[];
+}
+
+type TextProps = Partial<
+ Pick<
+ TextNode,
+ | "fontFamily"
+ | "fontSize"
+ | "fontWeight"
+ | "fill"
+ | "align"
+ | "lineHeight"
+ | "letterSpacing"
+ | "direction"
+ | "width"
+ >
+>;
+
+const ALIGN = { start: "left", center: "center", end: "right" } as const;
+
+export const textReveal = /* @__PURE__ */ defineComponent({
+ name: "TextReveal",
+ props: () => ({
+ text: z.string().min(1),
+ style: z.enum(REVEAL_STYLES).default("rise"),
+ /** Unit of animation. Default per style. */
+ by: z.enum(["char", "word", "line"]).optional(),
+ /** Frames between units. Default per style. */
+ stagger: z.number().min(0).optional(),
+ order: z.enum(ORDERS).default("forward"),
+ /** Frames one unit's move takes. Default per style, from the theme. */
+ unitDuration: z.number().int().positive().optional(),
+ ease: z.string().optional(),
+ /** Play out after `hold`, unit by unit. */
+ exitStyle: z.union([z.enum(EXIT_STYLES), z.literal(false)]).default(false),
+ /** Typing speed for `type`, characters a second. */
+ cps: z.number().positive().default(24),
+ /** Caret for `type` and `stream`. */
+ caret: z.boolean().default(true),
+ /** Words or patterns drawn in the theme's accent. */
+ emphasis: z.array(z.union([z.string(), z.instanceof(RegExp)])).default([]),
+ accent: z.string().optional(),
+ fontFamily: z.string().optional(),
+ fontSize: z.number().positive().optional(),
+ fontWeight: z.union([z.number(), z.string()]).optional(),
+ fill: z.string().optional(),
+ align: z.enum(["start", "center", "end"]).default("start"),
+ lineHeight: z.number().positive().optional(),
+ letterSpacing: z.number().optional(),
+ direction: z.enum(["ltr", "rtl", "auto"]).optional(),
+ }),
+ defaults: { enter: false, exit: false, hold: 30 },
+ build(ctx, props) {
+ const { host, theme, fps } = ctx;
+ const text = props.text;
+ const fs = props.fontSize ?? 96 * theme.scale;
+ const fontFamily = props.fontFamily ?? theme.font.display;
+ const registered = host.fonts();
+ if (registered.length > 0 && !registered.includes(fontFamily)) {
+ throw new Error(
+ `TextReveal: font "${fontFamily}" is not registered. Registered: ${registered.join(", ")}.`,
+ );
+ }
+ const wrap = ctx.requested.width;
+ const textProps: TextProps = {
+ fontFamily,
+ fontSize: fs,
+ fill: props.fill ?? theme.color.ink,
+ align: props.align,
+ ...(props.fontWeight !== undefined && { fontWeight: props.fontWeight }),
+ ...(props.lineHeight !== undefined && { lineHeight: props.lineHeight }),
+ ...(props.letterSpacing !== undefined && {
+ letterSpacing: props.letterSpacing,
+ }),
+ ...(props.direction !== undefined && { direction: props.direction }),
+ ...(wrap !== undefined && { width: wrap }),
+ };
+ const measureOptions: MeasureOptions = {
+ fontFamily,
+ fontSize: fs,
+ fontWeight: props.fontWeight,
+ letterSpacing: props.letterSpacing,
+ lineHeight: props.lineHeight,
+ width: wrap,
+ align: ALIGN[props.align],
+ direction: props.direction,
+ };
+ const m = host.measure(text, measureOptions);
+ const W = wrap ?? m.width;
+ const H = m.height;
+
+ const style = STYLE[props.style];
+ const by: GlyphUnit = props.by ?? style.by;
+ // Stagger stays fractional: units may start between frames.
+ const perFps = (v: number) => (v * fps) / 30;
+ const stagger = perFps(props.stagger ?? style.stagger);
+ const duration =
+ props.unitDuration ??
+ Math.max(
+ 1,
+ Math.round(themeFrames(theme, style.speed, fps) * style.length),
+ );
+ const ease = props.ease ?? style.ease;
+
+ const parts: Record<string, Animatable<LayoutNode>> = {};
+ const children: LayoutNode[] = [];
+ const animators: GlyphAnimator[] = [];
+ const keystrokes: Array<{ frame: number; index: number }> = [];
+ let unitCues: TextRevealCues["units"] = [];
+ let revealed = 0;
+
+ // Emphasis is static colour, first in the stack so streaming ink mixes over it.
+ const emphasised = emphasisWeights(text, props.emphasis);
+ if (emphasised) {
+ animators.push(
+ glyphAnimator(
+ "emphasis",
+ constantExpression("char", rendererChars(text, emphasised)),
+ {
+ fillColor: props.accent ?? theme.color.accent,
+ },
+ ),
+ );
+ }
+
+ const units = unitsOf(text, by, m);
+ const schedule = (starts: number[], dur = duration, e = ease) => ({
+ starts: indexedStarts(text, by, units, starts),
+ duration: dur,
+ ease: e,
+ });
+ const cuesFor = (starts: number[], dur: number) =>
+ units.map((u, i) => ({
+ frame: Math.round(starts[i] ?? 0),
+ settled: Math.round((starts[i] ?? 0) + dur),
+ index: u.index,
+ text: u.text,
+ }));
+
+ const textNode = host.text(text, {
+ ...textProps,
+ id: ctx.partId("text"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ });
+ parts.text = textNode;
+ // What carries the glyphs: the text node, or a wrapper around it (null when lines are split).
+ let main: LayoutNode | null = textNode;
+ let lines: MaskLine[] = [];
+ let sweep: ReturnType<typeof wipeMatte> | null = null;
+
+ // ── Enter ────────────────────────────────────────────────────────
+ switch (props.style) {
+ case "rise":
+ case "blur":
+ case "flip": {
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ animators.push(
+ glyphAnimator(
+ "enter",
+ scheduleExpression(by, schedule(starts), "enter"),
+ glyphFrom(props.style, fs, false),
+ ),
+ );
+ unitCues = cuesFor(starts, duration);
+ break;
+ }
+ case "slam": {
+ // Each unit is its own node so it scales around its own centre;
+ // the paragraph takes over the frame the last one lands.
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ unitCues = cuesFor(starts, duration);
+ const { width: _w, align: _a, ...unitProps } = textProps;
+ const pieces = units.map((u, i) => {
+ const rect = rangeRects(m, u.start, u.end, measureOptions)[0];
+ const s = starts[i] ?? 0;
+ const accented =
+ emphasised?.slice(u.start, u.end).every((v) => v === 1) ?? false;
+ const piece = host.text(u.text, {
+ ...unitProps,
+ ...(accented && { fill: props.accent ?? theme.color.accent }),
+ id: ctx.partId(`unit-${i}`),
+ position: "absolute",
+ x: rect?.x ?? 0,
+ y: rect?.y ?? 0,
+ });
+ piece.animate(
+ LayerAnimation.create()
+ .keys("scale", [
+ [s, 2.4],
+ [s + duration, 1, ease],
+ ])
+ .keys("opacity", [
+ [s, 0],
+ [s + Math.max(1, Math.round(duration * 0.45)), 1],
+ ]),
+ );
+ return piece;
+ });
+ const landed = Math.max(0, ...unitCues.map((u) => u.settled));
+ // Words land from 2.4×: neither box may clip them on the way in.
+ const group = host.box({
+ id: ctx.partId("units"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "visible",
+ children: pieces,
+ });
+ group.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [landed, 0, "hold"],
+ ]),
+ );
+ textNode.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [landed, 1, "hold"],
+ ]),
+ );
+ // A short landing shake as each unit hits.
+ const shake = host.box({
+ id: ctx.partId("shake"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "visible",
+ children: [group, textNode],
+ });
+ shake.animate(...slamShake(unitCues, fs, ctx.rng("slam")));
+ parts.units = group;
+ parts.shake = shake;
+ main = shake;
+ break;
+ }
+ case "scatter": {
+ const starts = unitStarts(units.length, stagger, props.order, ctx.seed);
+ const sched = schedule(starts);
+ const per = (key: string) => {
+ const q = ctx.rng(key);
+ return rendererChars(
+ text,
+ Array.from({ length: text.length }, () => q.spread(1)),
+ );
+ };
+ const rx = per("scatter-x");
+ const ry = per("scatter-y");
+ const rr = per("scatter-r");
+ animators.push(
+ glyphAnimator("enter-x", scheduleExpression(by, sched, "enter", rx), {
+ x: 1.1 * fs,
+ }),
+ glyphAnimator("enter-y", scheduleExpression(by, sched, "enter", ry), {
+ y: 0.9 * fs,
+ }),
+ glyphAnimator("enter-r", scheduleExpression(by, sched, "enter", rr), {
+ rotation: 120,
+ }),
+ glyphAnimator("enter", scheduleExpression(by, sched, "enter"), {
+ opacity: 0,
+ blur: 0.06 * fs,
+ }),
+ );
+ unitCues = cuesFor(starts, duration);
+ break;
+ }
+ case "stream": {
+ const words = unitsOf(text, "word", m);
+ const step = scaleFrames(1, fps);
+ const starts = burstStarts(
+ words.length,
+ perFps(props.stagger ?? style.stagger),
+ step,
+ ctx.rng("stream"),
+ );
+ const fade = Math.max(2, themeFrames(theme, "fast", fps));
+ const ink = props.unitDuration ?? themeFrames(theme, "slow", fps);
+ animators.push(
+ glyphAnimator(
+ "enter",
+ scheduleExpression(
+ "word",
+ { starts, duration: fade, ease: "power2.out" },
+ "enter",
+ ),
+ { opacity: 0, y: 0.08 * fs },
+ ),
+ glyphAnimator(
+ "ink",
+ scheduleExpression(
+ "word",
+ { starts, duration: ink, ease: "sine.inOut" },
+ "enter",
+ ),
+ { fillColor: theme.color.muted },
+ ),
+ );
+ unitCues = words.map((w, i) => ({
+ frame: starts[i] ?? 0,
+ settled: (starts[i] ?? 0) + ink,
+ index: w.index,
+ text: w.text,
+ }));
+ words.forEach((w, i) => {
+ keystrokes.push({ frame: starts[i] ?? 0, index: w.index });
+ });
+ if (props.caret) {
+ const ends = words.map((w) => w.end);
+ const caret = buildCaret(ctx, m, measureOptions, fs, {
+ at: starts,
+ counts: ends,
+ until: (starts[starts.length - 1] ?? 0) + ink,
+ shape: "block",
+ });
+ children.push(caret);
+ parts.caret = caret;
+ }
+ break;
+ }
+ case "type": {
+ // Each glyph switches on at its keystroke inside the full layout,
+ // so centred or wrapped lines never reflow while typing.
+ const frames = typingFrames(text, props.cps, fps, ctx.rng("type"));
+ animators.push(
+ glyphAnimator(
+ "enter",
+ stepExpression("char", rendererChars(text, frames)),
+ { opacity: 0 },
+ ),
+ );
+ frames.forEach((f, i) => {
+ if (!/\s/.test(text[i] ?? ""))
+ keystrokes.push({ frame: f, index: i });
+ });
+ unitCues = keystrokes.map((k) => ({
+ frame: k.frame,
+ settled: k.frame,
+ index: k.index,
+ text: text[k.index] ?? "",
+ }));
+ revealed = (frames[frames.length - 1] ?? 0) + 1;
+ if (props.caret) {
+ const caret = buildCaret(ctx, m, measureOptions, fs, {
+ at: frames,
+ counts: frames.map((_, i) => i + 1),
+ until: revealed + ctx.hold,
+ shape: "bar",
+ });
+ children.push(caret);
+ parts.caret = caret;
+ }
+ break;
+ }
+ case "mask": {
+ lines = maskLines(ctx, text, m, measureOptions, textProps, fs);
+ const starts = unitStarts(lines.length, stagger, props.order, ctx.seed);
+ lines.forEach((line, i) => {
+ const s = starts[i] ?? 0;
+ line.text.animate(
+ LayerAnimation.keys("y", [
+ [s, line.restY + line.travel],
+ [s + duration, line.restY, ease],
+ ]),
+ );
+ children.push(line.clip);
+ parts[`line-${i}`] = line.clip;
+ });
+ unitCues = lines.map((l, i) => ({
+ frame: Math.round(starts[i] ?? 0),
+ settled: Math.round((starts[i] ?? 0) + duration),
+ index: i,
+ text: l.content,
+ }));
+ main = null;
+ break;
+ }
+ case "wipe": {
+ const w = wipeMatte(ctx, W, H, fs, "hidden");
+ sweep = w;
+ w.matte.animate(
+ LayerAnimation.keys("x", [
+ [0, w.hidden],
+ [duration, w.shown, ease],
+ ]),
+ );
+ host.matte(textNode, w.matte);
+ parts.matte = w.matte;
+ // The front trails a little blur over the glyphs it is uncovering.
+ const xs = rendererChars(text, glyphCenters(text, m, measureOptions));
+ const front = Array.from({ length: duration + 1 }, (_, f) =>
+ w.front(
+ w.hidden + (w.shown - w.hidden) * evaluateEase(ease, f / duration),
+ ),
+ );
+ animators.push(
+ glyphAnimator(
+ "wipe-blur",
+ `((X,T)=>{const f=clamp(frame,0,${duration});const k=floor(f);const front=T[k]+((T[k+1]??T[k])-T[k])*(f-k);return clamp(1-(front-(X[textIndex]??0))/${round(w.feather)},0,1);})(${list(xs)},${list(front)})`,
+ { blur: 0.12 * fs },
+ ),
+ );
+ unitCues = [{ frame: 0, settled: duration, index: 0, text }];
+ break;
+ }
+ case "scramble": {
+ const result = scramble(ctx, text, m, measureOptions, textProps, {
+ stagger,
+ cycle: duration,
+ order: props.order,
+ });
+ children.push(result.reels);
+ parts.reels = result.reels;
+ // The real text takes over the moment the last glyph locks.
+ textNode.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 0],
+ [result.done, 1, "hold"],
+ ]),
+ );
+ unitCues = result.cues;
+ break;
+ }
+ }
+
+ if (unitCues.length > 0 && props.style !== "type")
+ revealed = Math.max(...unitCues.map((u) => u.settled));
+ // The text is at rest only once the last landing shake dies out.
+ if (props.style === "slam") revealed += SHAKE.length - 1;
+
+ // ── Exit ─────────────────────────────────────────────────────────
+ let afterHold = 0;
+ const exitStart = revealed + ctx.hold;
+ if (props.exitStyle !== false) {
+ const out = props.exitStyle;
+ const outStyle = STYLE[out];
+ const outBy: GlyphUnit = props.by ?? outStyle.by;
+ const outUnits = unitsOf(text, outBy, m);
+ const outStagger = perFps((props.stagger ?? outStyle.stagger) * 0.5);
+ const outDur = Math.max(
+ 1,
+ Math.round(
+ themeFrames(theme, outStyle.speed, fps) * outStyle.length * 0.75,
+ ),
+ );
+ const outEase = theme.motion.ease.exit;
+ const starts = unitStarts(
+ outUnits.length,
+ outStagger,
+ props.order,
+ ctx.seed,
+ exitStart,
+ );
+ const sched: UnitSchedule = {
+ starts: indexedStarts(text, outBy, outUnits, starts),
+ duration: outDur,
+ ease: outEase,
+ };
+ afterHold = Math.round(Math.max(...starts) - exitStart + outDur);
+ switch (out) {
+ case "rise":
+ case "blur":
+ case "flip":
+ case "scatter":
+ case "stream":
+ animators.push(
+ glyphAnimator(
+ "exit",
+ scheduleExpression(outBy, sched, "exit"),
+ out === "scatter"
+ ? { y: -0.6 * fs, opacity: 0, blur: 0.06 * fs }
+ : glyphFrom(out, fs, true),
+ ),
+ );
+ break;
+ case "type": {
+ // Backspace, twice as fast as typing: the last glyph goes first.
+ const per = Math.max(1, Math.round(fps / (props.cps * 2)));
+ const gone = Array.from(
+ { length: text.length },
+ (_, c) => exitStart + per * (text.length - c),
+ );
+ animators.push(
+ glyphAnimator(
+ "exit",
+ `(1-${stepExpression("char", rendererChars(text, gone))})`,
+ { opacity: 0 },
+ ),
+ );
+ afterHold = per * text.length + 1;
+ break;
+ }
+ case "wipe": {
+ if (!sweep) {
+ sweep = wipeMatte(ctx, W, H, fs, "shown");
+ host.matte(textNode, sweep.matte);
+ parts.matte = sweep.matte;
+ }
+ sweep.matte.animate(
+ LayerAnimation.keys("x", [
+ [exitStart, sweep.shown],
+ [exitStart + outDur, sweep.gone, outEase],
+ ]),
+ );
+ afterHold = outDur;
+ break;
+ }
+ case "mask": {
+ if (lines.length === 0)
+ throw new Error(
+ 'TextReveal: exitStyle "mask" needs style "mask" (it splits the lines).',
+ );
+ const outStarts = unitStarts(
+ lines.length,
+ outStagger,
+ props.order,
+ ctx.seed,
+ exitStart,
+ );
+ lines.forEach((line, i) => {
+ const s = outStarts[i] ?? exitStart;
+ line.text.animate(
+ LayerAnimation.keys("y", [
+ [s, line.restY],
+ [s + outDur, line.restY - line.travel, outEase],
+ ]),
+ );
+ });
+ afterHold = Math.round(Math.max(...outStarts) - exitStart + outDur);
+ break;
+ }
+ }
+ }
+
+ if (animators.length > 0)
+ (textNode as unknown as { animators: GlyphAnimator[] }).animators =
+ animators;
+ if (main) children.unshift(main);
+
+ return {
+ children,
+ width: W,
+ height: H,
+ duration: Math.max(1, revealed),
+ openEnded: true,
+ afterHold,
+ cues: {
+ units: unitCues,
+ revealed: [{ frame: revealed }],
+ exitStart: props.exitStyle === false ? [] : [{ frame: exitStart }],
+ keystrokes,
+ } as TextRevealCues,
+ parts,
+ api: (placement): TextRevealApi => ({
+ rects(match, nth = 0) {
+ const range: [number, number] | null =
+ match === undefined
+ ? [0, text.length]
+ : findRange(text, match, nth);
+ if (!range)
+ throw new Error(
+ `TextReveal.rects: "${String(match)}" not found in "${text}".`,
+ );
+ return rangeRects(m, range[0], range[1], measureOptions).map((q) => ({
+ ...q,
+ x: q.x + placement.x,
+ y: q.y + placement.y,
+ }));
+ },
+ }),
+ };
+ },
+});
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+const round = (v: number) => roundTo(v, 4);
+const list = (values: readonly number[]) => `[${values.map(round).join(",")}]`;
+
+/** 1 for characters inside an emphasis match, else 0 (null when nothing matches). */
+function emphasisWeights(
+ text: string,
+ patterns: ReadonlyArray<string | RegExp>,
+): number[] | null {
+ if (patterns.length === 0) return null;
+ const w = new Array<number>(text.length).fill(0);
+ for (const p of patterns) {
+ for (let nth = 0; ; nth++) {
+ const range = findRange(text, p, nth);
+ if (!range || range[1] <= range[0]) break;
+ for (let i = range[0]; i < range[1]; i++) w[i] = 1;
+ }
+ }
+ return w.some((v) => v > 0) ? w : null;
+}
+
+/** Landing shake, per frame after a unit lands (× 0.045 em). */
+const SHAKE = [0, 1, -0.55, 0.3, -0.12, 0];
+
+function slamShake(
+ units: ReadonlyArray<{ settled: number }>,
+ fs: number,
+ r: { spread(n: number): number },
+): LayerAnimation[] {
+ const end = Math.max(0, ...units.map((u) => u.settled)) + 8;
+ const xs = new Array<number>(end + 1).fill(0);
+ const ys = new Array<number>(end + 1).fill(0);
+ const a = 0.045 * fs;
+ const profile = SHAKE;
+ for (const u of units) {
+ const dx = r.spread(1);
+ profile.forEach((p, k) => {
+ const f = u.settled + k;
+ if (f <= end) {
+ xs[f] = (xs[f] ?? 0) + a * p * dx;
+ ys[f] = (ys[f] ?? 0) + a * p * 0.6;
+ }
+ });
+ }
+ return [
+ // Tight tolerance: the text must come to rest exactly where it belongs.
+ LayerAnimation.keys("x", bakeSamples(xs, 0, { tolerance: 0.005 })),
+ LayerAnimation.keys("y", bakeSamples(ys, 0, { tolerance: 0.005 })),
+ ];
+}
+
+interface Ctx {
+ host: import("framefields/components").Host;
+ theme: Theme;
+ fps: number;
+ seed: number;
+ partId(part: string): string;
+ rng(key: string | number): import("framefields/components").Rng;
+}
+
+/** Where the caret sits after `count` characters: x, and the line's top. */
+function caretAt(
+ count: number,
+ m: Metrics,
+ options: MeasureOptions,
+): [number, number] {
+ let last: Metrics["glyphs"][number] | undefined;
+ for (const g of m.glyphs)
+ if (g.index < count && (!last || g.index > last.index)) last = g;
+ if (!last) return [lineShift(m, 0, options), 0];
+ const shift = lineShift(m, last.line, options);
+ return [
+ shift + last.x + last.width - (options.letterSpacing ?? 0),
+ last.line * m.lineHeight,
+ ];
+}
+
+function buildCaret(
+ ctx: Ctx,
+ m: Metrics,
+ options: MeasureOptions,
+ fs: number,
+ o: {
+ at: readonly number[];
+ counts: readonly number[];
+ until: number;
+ shape: "bar" | "block";
+ },
+): Animatable<LayoutNode> {
+ const w = o.shape === "bar" ? Math.max(2, 0.06 * fs) : 0.42 * fs;
+ const h = o.shape === "bar" ? 1.05 * fs : 0.42 * fs;
+ const dy =
+ o.shape === "bar" ? (m.lineHeight - h) / 2 : m.lineHeight * 0.52 - h / 2;
+ const gap = o.shape === "bar" ? 0.04 * fs : 0.18 * fs;
+ const [x0, y0] = caretAt(0, m, options);
+ const xs: KeyframeTuple[] = [[0, x0 + (o.shape === "bar" ? 0 : -w)]];
+ const ys: KeyframeTuple[] = [[0, y0 + dy]];
+ o.at.forEach((f, i) => {
+ const [x, y] = caretAt(o.counts[i] ?? 0, m, options);
+ xs.push([f, x + gap, "hold"]);
+ ys.push([f, y + dy, "hold"]);
+ });
+ const caret = ctx.host.box({
+ id: ctx.partId("caret"),
+ position: "absolute",
+ x: x0,
+ y: y0 + dy,
+ width: w,
+ height: h,
+ background: ctx.theme.color.accent,
+ borderRadius: o.shape === "bar" ? w / 2 : w * 0.18,
+ });
+ // Solid while text arrives, then a few blinks, then gone.
+ const last = o.at[o.at.length - 1] ?? 0;
+ const half = Math.max(1, Math.round(ctx.fps * 0.5));
+ const blink: KeyframeTuple[] = [[0, 1]];
+ let on = false;
+ for (let f = last + half; f < o.until; f += half, on = !on)
+ blink.push([f, on ? 1 : 0, "hold"]);
+ blink.push([Math.max(last + 1, o.until), 0, "hold"]);
+ caret.animate(
+ LayerAnimation.create().keys("x", xs).keys("y", ys).keys("opacity", blink),
+ );
+ return caret;
+}
+
+/** Centre x of every character (spaces included), wrapped and aligned. */
+function glyphCenters(
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+): number[] {
+ const xs = new Array<number>(text.length).fill(0);
+ for (const g of m.glyphs)
+ xs[g.index] = lineShift(m, g.line, options) + g.x + g.width / 2;
+ return xs;
+}
+
+/**
+ * A soft-edged matte for `wipe`: transparent → opaque → opaque → transparent,
+ * `feather` px ramps. `hidden` / `shown` / `gone` are its x for each phase.
+ */
+function wipeMatte(
+ ctx: Ctx,
+ W: number,
+ H: number,
+ fs: number,
+ initial: "hidden" | "shown",
+) {
+ const feather = Math.max(24, 0.9 * fs);
+ const pad = fs * 0.5;
+ const total = W + feather * 2;
+ const a = ((feather / total) * 100).toFixed(3);
+ const b = (((feather + W) / total) * 100).toFixed(3);
+ const hidden = -total;
+ const shown = -feather;
+ const matte = ctx.host.box({
+ id: ctx.partId("matte"),
+ position: "absolute",
+ x: initial === "hidden" ? hidden : shown,
+ y: -pad,
+ width: total,
+ height: H + pad * 2,
+ background: `linear-gradient(90deg, rgba(255,255,255,0) 0%, #ffffff ${a}%, #ffffff ${b}%, rgba(255,255,255,0) 100%)`,
+ });
+ return {
+ matte,
+ feather,
+ total,
+ hidden,
+ shown,
+ gone: W + feather,
+ /** Where visibility reaches zero, for a matte at `x`. */
+ front: (x: number) => x + total,
+ };
+}
+
+interface MaskLine {
+ clip: Animatable<LayoutNode>;
+ text: Animatable<TextNode>;
+ content: string;
+ restY: number;
+ travel: number;
+}
+
+/** One clipped text node per measured line, each at its wrapped position. */
+function maskLines(
+ ctx: Ctx,
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+ textProps: TextProps,
+ fs: number,
+): MaskLine[] {
+ const pad = Math.round(fs * 0.18);
+ const { width: _w, align: _a, ...lineProps } = textProps;
+ return unitsOf(text, "line", m).map((u, i) => {
+ const first = m.glyphs.find(
+ (g) => g.index >= u.start && !/\s/.test(g.char),
+ );
+ const x = lineShift(m, i, options) + (first?.x ?? 0);
+ const content = text.slice(u.start, u.end).trim();
+ const lineText = ctx.host.text(content, {
+ ...lineProps,
+ id: ctx.partId(`line-${i}-text`),
+ position: "absolute",
+ x,
+ y: pad,
+ });
+ const clip = ctx.host.box({
+ id: ctx.partId(`line-${i}`),
+ position: "absolute",
+ x: 0,
+ y: i * m.lineHeight - pad,
+ width: Math.max(m.width, options.width ?? 0) + fs,
+ height: m.lineHeight + pad * 2,
+ overflow: "hidden",
+ children: [lineText],
+ });
+ return {
+ clip,
+ text: lineText,
+ content,
+ restY: pad,
+ travel: m.lineHeight + pad,
+ };
+ });
+}
+
+/**
+ * Scramble: each character is a clipped vertical reel of seeded glyphs that
+ * steps every couple of frames and lands on the real glyph. Reels are as
+ * wide as the real glyph's advance, so the line never jitters.
+ */
+function scramble(
+ ctx: Ctx,
+ text: string,
+ m: Metrics,
+ options: MeasureOptions,
+ textProps: TextProps,
+ o: { stagger: number; cycle: number; order: (typeof ORDERS)[number] },
+) {
+ const units = unitsOf(text, "char", m);
+ const starts = unitStarts(units.length, o.stagger, o.order, ctx.seed);
+ const step = Math.max(1, scaleFrames(2, ctx.fps));
+ const { width: _w, align: _a, letterSpacing: _l, ...glyphProps } = textProps;
+ const reels: LayoutNode[] = [];
+ const cues: Array<{
+ frame: number;
+ settled: number;
+ index: number;
+ text: string;
+ }> = [];
+ let done = 0;
+ units.forEach((u, i) => {
+ const g = m.glyphs.find((q) => q.index === u.start);
+ if (!g) return;
+ const appear = Math.round((starts[i] ?? 0) * 0.5);
+ const lock = Math.round((starts[i] ?? 0) + o.cycle);
+ const r = ctx.rng(`scramble:${u.start}`);
+ const set = scrambleSet(u.text);
+ const count = Math.max(1, Math.floor((lock - appear) / step));
+ const glyphs = Array.from({ length: count }, () => r.pick([...set]));
+ glyphs.push(u.text);
+ const advance = g.width - (options.letterSpacing ?? 0);
+ const reel = ctx.host.text(glyphs.join("\n"), {
+ ...glyphProps,
+ id: ctx.partId(`reel-${u.start}`),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: advance,
+ align: "center",
+ });
+ const ys: KeyframeTuple[] = [[0, 0]];
+ for (let k = 1; k < count; k++)
+ ys.push([appear + k * step, -k * m.lineHeight, "hold"]);
+ ys.push([lock, -count * m.lineHeight, "hold"]);
+ reel.animate(
+ LayerAnimation.create()
+ .keys("y", ys)
+ .keys("opacity", [
+ [appear, 0],
+ [appear + 3, 1],
+ ]),
+ );
+ reels.push(
+ ctx.host.box({
+ id: ctx.partId(`cell-${u.start}`),
+ position: "absolute",
+ x: lineShift(m, g.line, options) + g.x,
+ y: g.line * m.lineHeight,
+ width: advance,
+ height: m.lineHeight,
+ overflow: "hidden",
+ children: [reel],
+ }),
+ );
+ cues.push({ frame: appear, settled: lock, index: u.index, text: u.text });
+ done = Math.max(done, lock);
+ });
+ const group = ctx.host.box({
+ id: ctx.partId("reels"),
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: m.width,
+ height: m.height,
+ children: reels,
+ });
+ group.animate(
+ LayerAnimation.keys("opacity", [
+ [0, 1],
+ [done, 0, "hold"],
+ ]),
+ );
+ return { reels: group, cues, done };
+}
+
+/**
+ * Headlines and body copy that animate in and out by character, word or line:
+ * rise, blur, mask, slam, scatter, scramble, type, stream, wipe and flip, each
+ * ending on exactly the static text.
+ */
+export const TextReveal = /* @__PURE__ */ bindComponent(textReveal);
diff --git a/examples/33_news_explainer/src/components/text-reveal/plan.ts b/examples/33_news_explainer/src/components/text-reveal/plan.ts
new file mode 100644
index 00000000..1d284129
--- /dev/null
+++ b/examples/33_news_explainer/src/components/text-reveal/plan.ts
@@ -0,0 +1,131 @@
+/**
+ * TextReveal timing, kept pure: which characters form each unit, when each
+ * unit starts, the streaming bursts (typing rhythm lives in `core/typing.ts`).
+ */
+import {
+ type GlyphUnit,
+ type Metrics,
+ type Rng,
+ rendererChars,
+ type StaggerOrder,
+ staggerRanks,
+ wordRanges,
+} from "framefields/components";
+
+export interface Unit {
+ index: number;
+ text: string;
+ /** Character range [start, end). */
+ start: number;
+ end: number;
+}
+
+const isSpace = (c: string) => /\s/.test(c);
+
+/** The units text animates by. Characters skip whitespace; lines follow measured wrapping. */
+export function unitsOf(text: string, by: GlyphUnit, metrics: Metrics): Unit[] {
+ if (by === "char") {
+ const out: Unit[] = [];
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i] as string;
+ if (!isSpace(c))
+ out.push({ index: out.length, text: c, start: i, end: i + 1 });
+ }
+ return out;
+ }
+ if (by === "word") {
+ return wordRanges(text).map((w) => ({
+ index: w.index,
+ text: w.text,
+ start: w.start,
+ end: w.end,
+ }));
+ }
+ const lines = new Map<number, { start: number; end: number }>();
+ for (const g of metrics.glyphs) {
+ const line = lines.get(g.line) ?? {
+ start: Number.POSITIVE_INFINITY,
+ end: 0,
+ };
+ line.start = Math.min(line.start, g.index);
+ line.end = Math.max(line.end, g.index + 1);
+ lines.set(g.line, line);
+ }
+ return [...lines.entries()]
+ .sort(([a], [b]) => a - b)
+ .map(([, r], index) => ({
+ index,
+ text: text.slice(r.start, r.end).trim(),
+ start: r.start,
+ end: r.end,
+ }));
+}
+
+/** Start frame per unit: rank in `order` × `stagger` (fractional frames allowed). */
+export function unitStarts(
+ count: number,
+ stagger: number,
+ order: StaggerOrder,
+ seed: number,
+ offset = 0,
+): number[] {
+ return staggerRanks(count, order, seed).map((r) => offset + r * stagger);
+}
+
+/**
+ * The schedule indexed the way the renderer indexes `by`: per character
+ * (spaces take the next unit's start, so they never lag) or per word / line.
+ */
+export function indexedStarts(
+ text: string,
+ by: GlyphUnit,
+ units: readonly Unit[],
+ starts: readonly number[],
+): number[] {
+ if (by !== "char") return [...starts];
+ // Built per string index, returned in the renderer's index order.
+ const out = new Array<number>(text.length).fill(0);
+ let next = starts[starts.length - 1] ?? 0;
+ for (let u = units.length - 1, i = text.length - 1; i >= 0; i--) {
+ const unit = units[u];
+ if (unit && unit.start === i) {
+ next = starts[u] ?? next;
+ u--;
+ }
+ out[i] = next;
+ }
+ return rendererChars(text, out);
+}
+
+/**
+ * Streaming: words arrive in seeded bursts of 1–3, one frame apart inside a
+ * burst, with an uneven pause between bursts (`gap` frames ± 50 %).
+ */
+export function burstStarts(
+ count: number,
+ gap: number,
+ step: number,
+ r: Rng,
+ start = 0,
+): number[] {
+ const out: number[] = [];
+ let t = start;
+ while (out.length < count) {
+ const size = r.int(1, 3);
+ for (let i = 0; i < size && out.length < count; i++) {
+ out.push(Math.round(t));
+ t += step;
+ }
+ t += gap * (0.5 + r.next());
+ }
+ return out;
+}
+
+/** Glyphs a scrambling character cycles through: same case or class, plus a few symbols. */
+export function scrambleSet(char: string): string {
+ const symbols = "#%&*+=/<>?$";
+ if (/[A-Z]/.test(char)) return `ABCDEFGHIJKLMNOPQRSTUVWXYZ${symbols}`;
+ if (/[a-z]/.test(char)) return `abcdefghijklmnopqrstuvwxyz${symbols}`;
+ if (/[0-9]/.test(char)) return `0123456789${symbols}`;
+ return `${symbols}ABCDEFGHJKMNPRSTUVWXYZ`;
+}
diff --git a/examples/33_news_explainer/src/fetch-fonts.ts b/examples/33_news_explainer/src/fetch-fonts.ts
new file mode 100644
index 00000000..a1be25f3
--- /dev/null
+++ b/examples/33_news_explainer/src/fetch-fonts.ts
@@ -0,0 +1,40 @@
+/**
+ * pnpm assets → assets/fonts/*.ttf
+ *
+ * Downloads the pinned faces listed in fonts.ts and checks each one's
+ * SHA-256. Idempotent: a file already on disk with the right hash is kept.
+ */
+import { createHash } from "node:crypto";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { FONT_FILES, fontPath, fontUrl } from "./fonts.js";
+
+type Family = keyof typeof FONT_FILES;
+
+const sha256 = (data: Uint8Array) =>
+ createHash("sha256").update(data).digest("hex");
+
+async function fetchFont(family: Family): Promise<void> {
+ const file = fontPath(family);
+ const { sha256: expected } = FONT_FILES[family];
+ const existing = await fs.readFile(file).catch(() => null);
+ if (existing && sha256(existing) === expected) {
+ console.log(`kept ${path.basename(file)}`);
+ return;
+ }
+ const url = fontUrl(family);
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
+ const data = new Uint8Array(await res.arrayBuffer());
+ const actual = sha256(data);
+ if (actual !== expected)
+ throw new Error(
+ `${url}: SHA-256 ${actual}, expected ${expected}. Not written.`,
+ );
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, data);
+ console.log(`wrote ${path.basename(file)} (${family})`);
+}
+
+await Promise.all((Object.keys(FONT_FILES) as Family[]).map(fetchFont));
+process.exit(0);
diff --git a/examples/33_news_explainer/src/film.test.ts b/examples/33_news_explainer/src/film.test.ts
new file mode 100644
index 00000000..c76e2adc
--- /dev/null
+++ b/examples/33_news_explainer/src/film.test.ts
@@ -0,0 +1,87 @@
+import { CompositorProgramSchema } from "framefields";
+import { describe, expect, it } from "vitest";
+import { LINE_IDS, LINES, readManifest } from "./audio.js";
+import { buildExplainer } from "./film.js";
+import { numberWords, spokenWords } from "./spoken.js";
+import { BREATH, SCENES } from "./timeline.js";
+
+describe("explainer", () => {
+ it("builds a valid, lint-clean program of 80 to 120 seconds", async () => {
+ const { film, timeline } = await buildExplainer();
+ const result = CompositorProgramSchema.safeParse(film.toSpec());
+ expect(
+ result.success,
+ JSON.stringify(result.error?.issues.slice(0, 3)),
+ ).toBe(true);
+ expect(film.lint().filter((d) => d.severity === "error")).toEqual([]);
+ const seconds = timeline.total / 30;
+ expect(seconds).toBeGreaterThanOrEqual(80);
+ expect(seconds).toBeLessThanOrEqual(120);
+ }, 60_000);
+
+ it("reads every line once, in order, one at a time", async () => {
+ const { timeline } = await buildExplainer();
+ expect(timeline.lines.map((l) => l.id)).toEqual(
+ SCENES.flatMap((s) => s.lines),
+ );
+ expect([...timeline.lines.map((l) => l.id)].sort()).toEqual(
+ [...LINE_IDS].sort(),
+ );
+ timeline.lines.forEach((line, i) => {
+ const next = timeline.lines[i + 1];
+ if (next)
+ expect(
+ next.start - line.end,
+ `${line.id} → ${next.id}`,
+ ).toBeGreaterThanOrEqual(BREATH);
+ });
+ }, 60_000);
+
+ it("finishes each scene's narration before the next scene arrives", async () => {
+ const { timeline } = await buildExplainer();
+ timeline.scenes.forEach((scene, i) => {
+ const next = timeline.scenes[i + 1];
+ const end = next ? next.start : timeline.total;
+ for (const [id, line] of Object.entries(scene.lines)) {
+ expect(scene.start + line.start, `${id} starts`).toBeGreaterThanOrEqual(
+ scene.start,
+ );
+ expect(
+ scene.start + line.end,
+ `${id} ends before ${next?.id ?? "the end"}`,
+ ).toBeLessThanOrEqual(end);
+ }
+ });
+ }, 60_000);
+
+ it("has a take of every line that was heard as written", () => {
+ const { voice } = readManifest();
+ for (const id of LINE_IDS) {
+ const take = voice[id];
+ expect(take.text, id).toBe(LINES[id]);
+ expect(spokenWords(take.heard), id).toBe(spokenWords(take.text));
+ expect(take.words.length, id).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe("spoken words", () => {
+ it("spells out numbers as they are said", () => {
+ expect(numberWords(2004)).toBe("two thousand four");
+ expect(numberWords(35000)).toBe("thirty five thousand");
+ expect(numberWords(340)).toBe("three hundred forty");
+ expect(numberWords(0)).toBe("zero");
+ });
+
+ it("compares a script with a transcript that writes numerals", () => {
+ expect(spokenWords("at thirty-five thousand feet.")).toBe(
+ spokenWords("at 35,000 feet"),
+ );
+ expect(spokenWords("three hundred and forty miles")).toBe(
+ spokenWords("340 miles"),
+ );
+ expect(spokenWords("a Learjet 60 built in 2004")).toBe(
+ "a learjet sixty built in two thousand four",
+ );
+ });
+});
diff --git a/examples/33_news_explainer/src/film.ts b/examples/33_news_explainer/src/film.ts
new file mode 100644
index 00000000..287a50a4
--- /dev/null
+++ b/examples/33_news_explainer/src/film.ts
@@ -0,0 +1,124 @@
+/**
+ * What we know about the Florida jet crash: a two-minute news explainer in
+ * the collage style of explainer journalism, about the Learjet 60 that came
+ * down in Palm Beach County on November 1, 2026.
+ *
+ * open the dateline, the headline, the nine aboard
+ * title WHAT WE KNOW
+ * route the jet, and the flight from Austin toward the Bahamas
+ * storm the thunderstorm, the warning, the climb the crew asked for
+ * dive the fall, on a chart of altitude against time
+ * ground where it came down, and the evacuation
+ * probe the investigation, and what comes next
+ * close the open question, and the sources
+ *
+ * Every scene is paper on a desk, built from shapes and type (no footage).
+ * Gemini 3.8 Flash TTS reads the narration and Lyria 3.5 plays under it
+ * (audio.ts); the timeline places every line on its scene, and scenes cue
+ * their pictures off the words heard in it.
+ */
+import {
+ Composition,
+ FilmGrain,
+ Layer,
+ LayerAnimation,
+ type LayoutNode,
+ Vignette,
+} from "framefields";
+import { MUSIC_PATH, readManifest, voicePath } from "./audio.js";
+import { registerFonts } from "./fonts.js";
+import { paperTexture } from "./paper.js";
+import { closeScene } from "./scenes/close.js";
+import { diveScene } from "./scenes/dive.js";
+import { groundScene } from "./scenes/ground.js";
+import { openScene } from "./scenes/open.js";
+import { probeScene } from "./scenes/probe.js";
+import { routeScene } from "./scenes/route.js";
+import { stormScene } from "./scenes/storm.js";
+import { titleScene } from "./scenes/title.js";
+import { FPS, H, PAPER, W } from "./theme.js";
+import {
+ ducking,
+ planTimeline,
+ type SceneId,
+ type SceneTiming,
+ type Timeline,
+} from "./timeline.js";
+
+const BUILDERS: Record<SceneId, (t: SceneTiming) => LayoutNode> = {
+ open: openScene,
+ title: titleScene,
+ route: routeScene,
+ storm: stormScene,
+ dive: diveScene,
+ ground: groundScene,
+ probe: probeScene,
+ close: closeScene,
+};
+
+export interface Film {
+ film: Composition;
+ timeline: Timeline;
+}
+
+export async function buildExplainer(): Promise<Film> {
+ const fonts = await registerFonts();
+ const { voice } = readManifest();
+ const timeline = planTimeline(voice);
+ const scenes = Layer.sequence(
+ timeline.scenes.map((t) => ({
+ scene: BUILDERS[t.id](t),
+ duration: t.duration,
+ transition: t.transition,
+ })),
+ { id: "scenes", width: W, height: H },
+ );
+ if (scenes.totalFrames !== timeline.total)
+ throw new Error(
+ `The sequence runs ${scenes.totalFrames} frames, the timeline ${timeline.total}.`,
+ );
+
+ const film = new Composition({
+ width: W,
+ height: H,
+ fps: FPS,
+ durationMs: (timeline.total / FPS) * 1000,
+ backgroundColor: PAPER,
+ fonts,
+ });
+ film.add([
+ scenes,
+ ...paperTexture(),
+ ...timeline.lines.map((line) =>
+ Layer.audio(voicePath(line.id), {
+ id: `voice-${line.id}`,
+ startFrame: line.start,
+ durationFrames: line.end - line.start + 2,
+ volume: 1,
+ }),
+ ),
+ Layer.audio(MUSIC_PATH, {
+ id: "music",
+ startFrame: 0,
+ durationFrames: timeline.total,
+ volume: 0,
+ }).animate(
+ LayerAnimation.keys("volume", ducking(timeline.lines, timeline.total)),
+ ),
+ ]);
+ film.apply(new Vignette({ strength: 22, radius: 1.1, softness: 0.7 }));
+ film.apply(
+ new FilmGrain({
+ strength: 7,
+ size: 1.4,
+ monochrome: true,
+ animated: true,
+ }),
+ );
+ return { film, timeline };
+}
+
+/** Builds the film; kept as the render script's entry point. */
+export async function buildFilm(): Promise<Composition> {
+ return (await buildExplainer()).film;
+}
diff --git a/examples/33_news_explainer/src/fonts.ts b/examples/33_news_explainer/src/fonts.ts
new file mode 100644
index 00000000..f322fb93
--- /dev/null
+++ b/examples/33_news_explainer/src/fonts.ts
@@ -0,0 +1,58 @@
+/**
+ * The four faces, from google/fonts pinned to one commit and checked by
+ * SHA-256 (Anton, Libre Franklin and JetBrains Mono are SIL OFL 1.1,
+ * Permanent Marker is Apache 2.0). Font files stay out of git; `pnpm assets`
+ * fetches them into assets/fonts/.
+ */
+import { existsSync } from "node:fs";
+import { FontManager } from "framefields";
+import { DISPLAY, FONTS, HAND, MONO, SANS } from "./theme.js";
+
+export const GOOGLE_FONTS_COMMIT = "2fe1e8c6b137fb13041a7cfca6fdcd8a910ea4dc";
+
+export const FONT_FILES = {
+ [DISPLAY]: {
+ file: "Anton.ttf",
+ source: "ofl/anton/Anton-Regular.ttf",
+ sha256: "a4ba3a92350ebb031da0cb47630ac49eb265082ca1bc0450442f4a83ab947cab",
+ },
+ [SANS]: {
+ file: "LibreFranklin.ttf",
+ source: "ofl/librefranklin/LibreFranklin%5Bwght%5D.ttf",
+ sha256: "2329f394b10ed1c71107df20fddc11e2bb1b68c1ecbb385f975b36fd64a971f8",
+ },
+ [MONO]: {
+ file: "JetBrainsMono.ttf",
+ source: "ofl/jetbrainsmono/JetBrainsMono%5Bwght%5D.ttf",
+ sha256: "48715a42ec242c21e9f02692891e147d022299a52e48d5e413e1a942193ffeda",
+ },
+ [HAND]: {
+ file: "PermanentMarker.ttf",
+ source: "apache/permanentmarker/PermanentMarker-Regular.ttf",
+ sha256: "28f82c8a7943cb8e9d599f8554da1d4fc75dbcf69b9885ad6c0611d20c6946c5",
+ },
+} as const;
+
+export const fontPath = (family: keyof typeof FONT_FILES) =>
+ `${FONTS}${FONT_FILES[family].file}`;
+
+export const fontUrl = (family: keyof typeof FONT_FILES) =>
+ `https://raw.githubusercontent.com/google/fonts/${GOOGLE_FONTS_COMMIT}/${FONT_FILES[family].source}`;
+
+const FAMILIES = Object.keys(FONT_FILES) as Array<keyof typeof FONT_FILES>;
+
+/** Fonts not on disk yet. */
+export const missingFonts = () =>
+ FAMILIES.filter((family) => !existsSync(fontPath(family)));
+
+/** Registers every face; returns their files for `Composition.fonts`. */
+export async function registerFonts(): Promise<string[]> {
+ const missing = missingFonts();
+ if (missing.length > 0)
+ throw new Error(
+ `Missing fonts (${missing.join(", ")}). Run \`pnpm assets\` first.`,
+ );
+ for (const family of FAMILIES)
+ await FontManager.register({ family, source: fontPath(family) });
+ return FAMILIES.map(fontPath);
+}
diff --git a/examples/33_news_explainer/src/generate-audio.ts b/examples/33_news_explainer/src/generate-audio.ts
new file mode 100644
index 00000000..3e4a80a1
--- /dev/null
+++ b/examples/33_news_explainer/src/generate-audio.ts
@@ -0,0 +1,321 @@
+/**
+ * pnpm audio → assets/voice/<line>.wav, assets/music.wav, and what was
+ * measured in assets/audio.json
+ * pnpm audio cost → print the estimate, no calls
+ *
+ * Gemini 3.8 Flash TTS reads each line of the narration and Lyria 3.5 plays
+ * the bed. Scribe v2 checks that every line was read as written and finds its
+ * first and last word, so each line is trimmed to its speech and the film can
+ * start it exactly where it belongs; it also checks the music has no voice in
+ * it. Idempotent: delete a file to make it again. Raw takes are kept in
+ * assets/takes/.
+ */
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync } from "node:fs";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { ai } from "framefields";
+import {
+ type AudioManifest,
+ LINE_IDS,
+ LINES,
+ type LineId,
+ MANIFEST,
+ MUSIC_MODEL,
+ MUSIC_PATH,
+ MUSIC_PROMPT,
+ MUSIC_SECONDS,
+ type SpokenWord,
+ TRANSCRIBER,
+ VOICE_LEAD,
+ VOICE_MODEL,
+ voiceInput,
+ voicePath,
+} from "./audio.js";
+import { spokenWords } from "./spoken.js";
+import { ASSETS } from "./theme.js";
+
+/**
+ * The gateway's rates (November 2026: fal's price plus 25 %): per minute
+ * transcribed, per 1000 characters read, and per music track.
+ */
+const PER_MINUTE = 0.0125;
+const PER_1000_CHARACTERS = 0.05625;
+const PER_TRACK = 0.125;
+const SAMPLE_RATE = 48000;
+const MAX_TAKES = 4;
+const TAKES = path.join(ASSETS, "takes");
+/** Kept after a line's last word, faded over its second half. */
+const VOICE_TAIL = 0.3;
+/** Longest silence allowed between two words of a sentence; punctuation may hold longer (`HOLD`). */
+const MAX_PAUSE = 0.5;
+const KEYTERMS = [
+ "Learjet",
+ "Eleuthera",
+ "Palm Beach",
+ "FAA",
+ "Military Trail",
+];
+
+/** A take's file, named by what was asked for, so a changed prompt is made afresh. */
+const takePath = (
+ kind: string,
+ input: Record<string, unknown>,
+ take: number,
+ ext = "wav",
+) =>
+ path.join(
+ TAKES,
+ `${kind}-${createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 8)}-${take}.${ext}`,
+ );
+
+let spent = 0;
+
+/** Runs `model` and saves the audio it returns to `dest`. */
+async function generate(
+ model: string,
+ input: Record<string, unknown>,
+ dest: string,
+): Promise<void> {
+ const { data } = await ai.subscribe<{ audio: { url: string } }>(model, {
+ input,
+ });
+ const res = await fetch(data.audio.url);
+ if (!res.ok) throw new Error(`GET ${data.audio.url} → ${res.status}`);
+ await fs.mkdir(path.dirname(dest), { recursive: true });
+ await fs.writeFile(dest, Buffer.from(await res.arrayBuffer()));
+}
+
+interface Word {
+ text: string;
+ start: number;
+ end: number;
+}
+
+async function transcribe(file: string): Promise<Word[]> {
+ const type = file.endsWith(".mp3") ? "audio/mpeg" : "audio/wav";
+ const audio = new Blob([await fs.readFile(file)], { type });
+ const { data } = await ai.subscribe<{
+ words: Array<Word & { type: string }>;
+ }>(TRANSCRIBER, {
+ input: {
+ audio_url: audio,
+ language_code: "eng",
+ keyterms: KEYTERMS,
+ tag_audio_events: false,
+ },
+ });
+ spent += (PER_MINUTE * duration(file)) / 60;
+ return data.words
+ .filter((w) => w.type === "word")
+ .map(({ text, start, end }) => ({ text: text.trim(), start, end }));
+}
+
+function duration(file: string): number {
+ const out = execFileSync("ffprobe", [
+ "-v",
+ "error",
+ "-show_entries",
+ "format=duration",
+ "-of",
+ "csv=p=0",
+ file,
+ ]);
+ return Number(out.toString().trim());
+}
+
+/** Cuts `from`–`to` seconds of `src` through `filters` into a 48 kHz WAV. */
+function cut(
+ src: string,
+ dest: string,
+ from: number,
+ to: number,
+ filters: string[],
+ channels: 1 | 2,
+) {
+ mkdirSync(path.dirname(dest), { recursive: true });
+ execFileSync("ffmpeg", [
+ "-v",
+ "error",
+ "-y",
+ "-ss",
+ from.toFixed(3),
+ "-to",
+ to.toFixed(3),
+ "-i",
+ src,
+ "-af",
+ filters.join(","),
+ "-ar",
+ `${SAMPLE_RATE}`,
+ "-ac",
+ `${channels}`,
+ dest,
+ ]);
+}
+
+/** Word times moved by `by` seconds, rounded to the millisecond. */
+const shift = (heard: Word[], by: number): SpokenWord[] =>
+ heard.map(({ text, start, end }) => ({
+ text,
+ start: Number((start + by).toFixed(3)),
+ end: Number((end + by).toFixed(3)),
+ }));
+
+/** How much longer than a gap between words a punctuation mark may hold. */
+const HOLD = (word: string) =>
+ /[.:;]$/.test(word) ? 2 : /,$/.test(word) ? 1.4 : 1;
+
+/** The longest gap between words, each measured against what its punctuation allows. */
+function longestPause(heard: Word[]): number {
+ let longest = 0;
+ for (let i = 1; i < heard.length; i++) {
+ const before = heard[i - 1];
+ const word = heard[i];
+ if (!before || !word) continue;
+ longest = Math.max(longest, (word.start - before.end) / HOLD(before.text));
+ }
+ return longest;
+}
+
+async function voiceLine(id: LineId): Promise<AudioManifest["voice"][LineId]> {
+ const text = LINES[id];
+ for (let take = 1; take <= MAX_TAKES; take++) {
+ const input = voiceInput(id);
+ const raw = takePath(`voice-${id}`, input, take);
+ if (!existsSync(raw)) {
+ await generate(VOICE_MODEL, input, raw);
+ spent += (PER_1000_CHARACTERS * text.length) / 1000;
+ }
+ const heard = await transcribe(raw);
+ const said = heard.map((w) => w.text).join(" ");
+ const first = heard[0];
+ const last = heard.at(-1);
+ // Same words, no question where the script states something, no long pauses.
+ const asks = said.includes("?") && !text.includes("?");
+ const pause = longestPause(heard);
+ if (
+ !first ||
+ !last ||
+ spokenWords(said) !== spokenWords(text) ||
+ asks ||
+ pause > MAX_PAUSE
+ ) {
+ console.log(
+ `voice ${id} take ${take} heard "${said}" (longest pause ${pause.toFixed(2)} s), retrying`,
+ );
+ continue;
+ }
+ const from = Math.max(0, first.start - VOICE_LEAD);
+ const to = Math.min(duration(raw), last.end + VOICE_TAIL);
+ const length = to - from;
+ cut(
+ raw,
+ voicePath(id),
+ from,
+ to,
+ [
+ "afade=t=in:d=0.01",
+ `afade=t=out:st=${(length - VOICE_TAIL / 2).toFixed(3)}:d=${(VOICE_TAIL / 2).toFixed(3)}`,
+ "loudnorm=I=-16:TP=-1.5:LRA=11",
+ ],
+ 1,
+ );
+ const seconds = duration(voicePath(id));
+ console.log(`voice ${id} ${seconds.toFixed(2)} s "${said}"`);
+ return { text, input, heard: said, seconds, words: shift(heard, -from) };
+ }
+ throw new Error(
+ `No take of "${text}" was read as written in ${MAX_TAKES} tries.`,
+ );
+}
+
+async function music(): Promise<AudioManifest["music"]> {
+ const input = { prompt: MUSIC_PROMPT };
+ for (let take = 1; take <= MAX_TAKES; take++) {
+ const raw = takePath("music", input, take, "mp3");
+ if (!existsSync(raw)) {
+ await generate(MUSIC_MODEL, input, raw);
+ spent += PER_TRACK;
+ }
+ const length = duration(raw);
+ const heard = await transcribe(raw);
+ if (heard.length > 0 || length < MUSIC_SECONDS) {
+ console.log(
+ `music take ${take}: ${length.toFixed(1)} s, heard "${heard.map((w) => w.text).join(" ")}", retrying`,
+ );
+ continue;
+ }
+ cut(
+ raw,
+ MUSIC_PATH,
+ 0,
+ MUSIC_SECONDS,
+ [
+ `afade=t=out:st=${(MUSIC_SECONDS - 3).toFixed(3)}:d=3`,
+ "loudnorm=I=-20:TP=-2:LRA=11",
+ ],
+ 2,
+ );
+ const seconds = duration(MUSIC_PATH);
+ console.log(`music ${seconds.toFixed(1)} s of ${length.toFixed(1)} s`);
+ return { prompt: MUSIC_PROMPT, seconds };
+ }
+ throw new Error(
+ `No instrumental music take of ${MUSIC_SECONDS} s or more in ${MAX_TAKES} tries.`,
+ );
+}
+
+async function readPartial(): Promise<Partial<AudioManifest>> {
+ if (!existsSync(MANIFEST)) return {};
+ return JSON.parse(
+ await fs.readFile(MANIFEST, "utf8"),
+ ) as Partial<AudioManifest>;
+}
+
+async function save(manifest: Partial<AudioManifest>): Promise<void> {
+ await fs.writeFile(MANIFEST, `${JSON.stringify(manifest, null, "\t")}\n`);
+}
+
+async function main(): Promise<void> {
+ process.loadEnvFile(new URL("../../../.env", import.meta.url).pathname);
+ if (!process.env.FRAMEFIELDS_API_KEY)
+ throw new Error("FRAMEFIELDS_API_KEY missing from the repo root .env");
+ const manifest = await readPartial();
+ const voice: Partial<AudioManifest["voice"]> = {};
+ for (const id of LINE_IDS) {
+ const kept = manifest.voice?.[id];
+ const same = JSON.stringify(kept?.input) === JSON.stringify(voiceInput(id));
+ if (kept && same && existsSync(voicePath(id))) {
+ // Lines made before word timings were kept: read them off the trimmed file.
+ voice[id] = kept.words
+ ? kept
+ : { ...kept, words: shift(await transcribe(voicePath(id)), 0) };
+ continue;
+ }
+ voice[id] = await voiceLine(id);
+ await save({ ...manifest, voice: voice as AudioManifest["voice"] });
+ }
+ manifest.voice = voice as AudioManifest["voice"];
+ if (manifest.music?.prompt !== MUSIC_PROMPT || !existsSync(MUSIC_PATH)) {
+ manifest.music = await music();
+ await save(manifest);
+ }
+ console.log(`spent ~$${spent.toFixed(3)}`);
+}
+
+if (process.argv[2] === "cost") {
+ const characters = Object.values(LINES).join("").length;
+ const speech = Object.values(LINES).join(" ").split(" ").length / 2.6;
+ const usd =
+ (PER_1000_CHARACTERS * characters) / 1000 +
+ PER_TRACK +
+ (PER_MINUTE * (speech + MUSIC_SECONDS)) / 60;
+ console.log(
+ `estimate $${usd.toFixed(2)} per pass (${characters} characters of narration, a ${MUSIC_SECONDS} s music track), up to ${MAX_TAKES}× with retries`,
+ );
+} else {
+ await main();
+}
+process.exit(0);
diff --git a/examples/33_news_explainer/src/geo.ts b/examples/33_news_explainer/src/geo.ts
new file mode 100644
index 00000000..5f33e37c
--- /dev/null
+++ b/examples/33_news_explainer/src/geo.ts
@@ -0,0 +1,200 @@
+/**
+ * The map: Natural Earth 1:50m countries (world-atlas) and US Census 1:10m
+ * states (us-atlas), both public domain, projected to Mercator over the
+ * Gulf and fitted to the map sheet. The flight is drawn as great circles:
+ * Austin to the crash site, and the leg to North Eleuthera it never flew.
+ */
+import { createRequire } from "node:module";
+import {
+ type GeoProjection,
+ geoInterpolate,
+ geoMercator,
+ geoPath,
+} from "d3-geo";
+import type { Vec2 } from "framefields/components";
+import type { Feature, FeatureCollection, Geometry } from "geojson";
+import { feature, mesh } from "topojson-client";
+import type { GeometryCollection, Topology } from "topojson-specification";
+
+const require = createRequire(import.meta.url);
+
+type Lonlat = [lon: number, lat: number];
+
+/** Where things are (lon, lat). */
+export const PLACES = {
+ /** Austin–Bergstrom International Airport. */
+ austin: [-97.6699, 30.1945],
+ /** North Eleuthera Airport, the Bahamas. */
+ eleuthera: [-76.6835, 25.4749],
+ /** Military Trail at 10th Avenue North, Palm Beach County. */
+ crash: [-80.1131, 26.6329],
+} satisfies Record<string, Lonlat>;
+
+/** Map labels, at hand-picked points (lon, lat). */
+export const LABELS = {
+ texas: [-98.7, 28.1],
+ florida: [-81.45, 28.9],
+ mexico: [-99.5, 24.6],
+ cuba: [-79.3, 22.25],
+ bahamas: [-75.7, 23.1],
+} satisfies Record<string, Lonlat>;
+
+/** The part of the world on the sheet. */
+const BOUNDS: [Lonlat, Lonlat] = [
+ [-100.5, 22.6],
+ [-74.2, 32.6],
+];
+
+/** US states drawn lighter: the two ends of the flight. */
+const HOME_STATES = new Set(["48", "12"]);
+/** Natural Earth's id for the United States, drawn from the Census states instead. */
+const USA = "840";
+
+type Objects<K extends string> = Topology<Record<K, GeometryCollection>>;
+
+export interface MapGeometry {
+ width: number;
+ height: number;
+ project(p: Lonlat): Vec2;
+ /** Countries other than the US. */
+ countries: string;
+ /** Every US state. */
+ states: string;
+ /** Texas and Florida. */
+ home: string;
+ /** Lines between states, and between countries. */
+ stateLines: string;
+ countryLines: string;
+ /** Every coast (and outer border), drawn in ink. */
+ coasts: string;
+ /** The flight as flown, and the leg it never flew, as projected points. */
+ flown: Vec2[];
+ unflown: Vec2[];
+}
+
+function greatCircle(from: Lonlat, to: Lonlat, steps: number): Lonlat[] {
+ const at = geoInterpolate(from, to);
+ return Array.from({ length: steps + 1 }, (_, i) => at(i / steps) as Lonlat);
+}
+
+/** The map fitted into a `width` × `height` sheet, `margin` px inside its edges. */
+export function mapGeometry(
+ width: number,
+ height: number,
+ margin = 0,
+): MapGeometry {
+ const world =
+ require("world-atlas/countries-50m.json") as Objects<"countries">;
+ const us = require("us-atlas/states-10m.json") as Objects<"states">;
+ const projection: GeoProjection = geoMercator()
+ .fitExtent(
+ [
+ [margin, margin],
+ [width - margin, height - margin],
+ ],
+ { type: "MultiPoint", coordinates: BOUNDS },
+ )
+ .clipExtent([
+ [-20, -20],
+ [width + 20, height + 20],
+ ]);
+ const path = geoPath(projection).digits(1);
+ const draw = (features: Array<Feature<Geometry>>) =>
+ features.map((f) => path(f) ?? "").join("");
+ const countries = feature(
+ world,
+ world.objects.countries,
+ ) as FeatureCollection<Geometry>;
+ const states = feature(us, us.objects.states) as FeatureCollection<Geometry>;
+ const project = (p: Lonlat): Vec2 => {
+ const xy = projection(p);
+ if (!xy) throw new Error(`Cannot project ${p.join(", ")}`);
+ return [xy[0], xy[1]];
+ };
+ return {
+ width,
+ height,
+ project,
+ countries: draw(countries.features.filter((f) => f.id !== USA)),
+ states: draw(states.features),
+ home: draw(states.features.filter((f) => HOME_STATES.has(String(f.id)))),
+ stateLines: path(mesh(us, us.objects.states, (a, b) => a !== b)) ?? "",
+ countryLines:
+ path(
+ mesh(
+ world,
+ world.objects.countries,
+ (a, b) => a !== b && a.id !== USA && b.id !== USA,
+ ),
+ ) ?? "",
+ coasts:
+ (path(mesh(us, us.objects.states, (a, b) => a === b)) ?? "") +
+ (path(
+ mesh(world, world.objects.countries, (a, b) => a === b && a.id !== USA),
+ ) ?? ""),
+ flown: greatCircle(PLACES.austin, PLACES.crash, 80).map(project),
+ unflown: greatCircle(PLACES.crash, PLACES.eleuthera, 24).map(project),
+ };
+}
+
+/** Census FIPS code of Florida. */
+export const FLORIDA = "12";
+
+/** One state on its own, fitted into `width` × `height`: its outline and a projection. */
+export function stateOutline(
+ fips: string,
+ width: number,
+ height: number,
+ margin = 0,
+): { d: string; project(p: Lonlat): Vec2 } {
+ const us = require("us-atlas/states-10m.json") as Objects<"states">;
+ const states = feature(us, us.objects.states) as FeatureCollection<Geometry>;
+ const state = states.features.find((f) => String(f.id) === fips);
+ if (!state) throw new Error(`No state with FIPS ${fips}`);
+ const projection = geoMercator().fitExtent(
+ [
+ [margin, margin],
+ [width - margin, height - margin],
+ ],
+ state,
+ );
+ return {
+ d: geoPath(projection).digits(1)(state) ?? "",
+ project(p) {
+ const xy = projection(p);
+ if (!xy) throw new Error(`Cannot project ${p.join(", ")}`);
+ return [xy[0], xy[1]];
+ },
+ };
+}
+
+/** A polyline's length, and the point and heading (degrees) at a share of it. */
+export function along(points: Vec2[]): {
+ length: number;
+ at(share: number): { point: Vec2; heading: number };
+} {
+ const lengths = [0];
+ for (let i = 1; i < points.length; i++) {
+ const a = points[i - 1] as Vec2;
+ const b = points[i] as Vec2;
+ lengths.push((lengths[i - 1] ?? 0) + Math.hypot(b[0] - a[0], b[1] - a[1]));
+ }
+ const length = lengths.at(-1) ?? 0;
+ return {
+ length,
+ at(share) {
+ const target = Math.min(1, Math.max(0, share)) * length;
+ let i = 1;
+ while (i < points.length - 1 && (lengths[i] ?? 0) < target) i++;
+ const a = points[i - 1] as Vec2;
+ const b = points[i] as Vec2;
+ const from = lengths[i - 1] ?? 0;
+ const span = (lengths[i] ?? from) - from || 1;
+ const t = (target - from) / span;
+ return {
+ point: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t],
+ heading: (Math.atan2(b[1] - a[1], b[0] - a[0]) * 180) / Math.PI,
+ };
+ },
+ };
+}
diff --git a/examples/33_news_explainer/src/jet.ts b/examples/33_news_explainer/src/jet.ts
new file mode 100644
index 00000000..eae83703
--- /dev/null
+++ b/examples/33_news_explainer/src/jet.ts
@@ -0,0 +1,184 @@
+/**
+ * The Learjet 60 as two silhouettes, drawn nose to the right on a grid 100
+ * units long: from above (swept wings, rear engines, T-tail) for the map, and
+ * from the side for the storm diagram. Proportions follow the type: a
+ * 58.7 ft fuselage, a 43.8 ft wingspan.
+ */
+import { Layer, type LayoutNode } from "framefields";
+import { toPathData, type Vec2 } from "framefields/components";
+
+/** Half the outline seen from above, nose to tail along the top (−y) side. */
+const TOP_HALF: Vec2[] = [
+ [50, 0],
+ [48.5, -2.2],
+ [45, -3.8],
+ [38, -4.6],
+ [9, -4.6],
+ [-4, -37],
+ [-10, -37.4],
+ [-11, -4.6],
+ [-25, -4.4],
+ [-25, -10.4],
+ [-41, -10.4],
+ [-41.5, -4.2],
+ [-43, -3.9],
+ [-47, -15.5],
+ [-52, -15.5],
+ [-50.5, -2.6],
+ [-51, 0],
+];
+
+const mirror = (points: Vec2[]): Vec2[] => [
+ ...points,
+ ...points
+ .slice(1, -1)
+ .reverse()
+ .map(([x, y]): Vec2 => [x, -y]),
+];
+
+/** The outline seen from the side: fuselage, cockpit, fin and stabilizer. */
+const SIDE: Vec2[] = [
+ [50, 0.6],
+ [48.8, -1.8],
+ [46, -3.6],
+ [41, -5.6],
+ [36.5, -7.4],
+ [30, -8.2],
+ [-26, -8.2],
+ [-36, -7.4],
+ [-44, -24],
+ [-41.5, -24.6],
+ [-58, -25.2],
+ [-58.2, -23.6],
+ [-50.5, -23.2],
+ [-53.5, -7],
+ [-55, -4.2],
+ [-48, -1.2],
+ [-30, 2.6],
+ [10, 3.8],
+ [36, 3.4],
+ [45, 2.6],
+];
+/** The engine nacelle on the near side, high on the rear fuselage. */
+const NACELLE: Vec2[] = [
+ [-20, -11.4],
+ [-36, -11.4],
+ [-38.5, -9.2],
+ [-36, -6.6],
+ [-20, -6.6],
+ [-18.6, -9],
+];
+/** The near wing, swept back and down from the lower fuselage. */
+const WING: Vec2[] = [
+ [14, 2.6],
+ [-12, 2.2],
+ [-20, 5.2],
+ [-6, 5.6],
+];
+
+const scaled = (points: Vec2[], s: number, dx: number, dy: number): Vec2[] =>
+ points.map(([x, y]): Vec2 => [x * s + dx, y * s + dy]);
+
+/** Path data for the jet from above, `length` px long, centred on its box. */
+export function topViewPath(length: number): string {
+ const s = length / 102;
+ return toPathData(
+ scaled(mirror(TOP_HALF), s, length / 2, length * 0.38),
+ true,
+ );
+}
+
+/** The box the top view sits in (it is as wide as it is long × 0.76). */
+export const topViewSize = (length: number) => ({
+ width: length,
+ height: length * 0.76,
+});
+
+export interface SideView {
+ body: string;
+ nacelle: string;
+ wing: string;
+ windows: Array<{ x: number; y: number; size: number }>;
+ width: number;
+ height: number;
+ /** How far below the box's top the fuselage's centreline runs. */
+ axisY: number;
+}
+
+/** The side view's parts, `length` px long. */
+export function sideView(length: number): SideView {
+ const s = length / 110;
+ const dx = 58.5 * s;
+ const dy = 26 * s;
+ const at = (p: Vec2[]) => toPathData(scaled(p, s, dx, dy), true);
+ return {
+ body: at(SIDE),
+ nacelle: at(NACELLE),
+ wing: at(WING),
+ windows: [24, 17, 10, 3, -4, -11].map((x) => ({
+ x: x * s + dx,
+ y: -3.6 * s + dy,
+ size: 2.6 * s,
+ })),
+ width: length,
+ height: 32 * s,
+ axisY: dy,
+ };
+}
+
+/** The jet from above as one layer, nose to the right, centred on `at`; it turns about its centre. */
+export function jetTop(o: {
+ id: string;
+ length: number;
+ color: string;
+ at: Vec2;
+}): ReturnType<typeof Layer.shape> {
+ const { width, height } = topViewSize(o.length);
+ return Layer.shape("path", {
+ id: o.id,
+ position: "absolute",
+ x: o.at[0] - width / 2,
+ y: o.at[1] - height / 2,
+ width,
+ height,
+ d: topViewPath(o.length),
+ fill: o.color,
+ });
+}
+
+/** The jet from the side: body, nacelle, wing and a row of windows. */
+export function jetSide(o: {
+ id: string;
+ length: number;
+ color: string;
+ window: string;
+}): LayoutNode[] {
+ const v = sideView(o.length);
+ const part = (name: string, d: string, fill: string) =>
+ Layer.shape("path", {
+ id: `${o.id}-${name}`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: v.width,
+ height: v.height,
+ d,
+ fill,
+ });
+ return [
+ part("wing", v.wing, o.color),
+ part("body", v.body, o.color),
+ part("nacelle", v.nacelle, o.color),
+ ...v.windows.map((w, i) =>
+ Layer.shape("ellipse", {
+ id: `${o.id}-window-${i}`,
+ position: "absolute",
+ x: w.x - w.size / 2,
+ y: w.y - w.size / 2,
+ width: w.size * 1.3,
+ height: w.size,
+ fill: o.window,
+ }),
+ ),
+ ];
+}
diff --git a/examples/33_news_explainer/src/paper.ts b/examples/33_news_explainer/src/paper.ts
new file mode 100644
index 00000000..603800ec
--- /dev/null
+++ b/examples/33_news_explainer/src/paper.ts
@@ -0,0 +1,352 @@
+/**
+ * The collage kit: the desk, sheets of paper laid on it with a soft shadow,
+ * strips torn from a roll, tape, rubber stamps and pins. Torn edges are
+ * seeded, so a strip tears the same way on every render.
+ */
+import {
+ Color,
+ Layer,
+ LayerAnimation,
+ LayerStyle,
+ type LayoutNode,
+} from "framefields";
+import { rng, toPathData, type Vec2 } from "framefields/components";
+import {
+ H,
+ INK,
+ MONO,
+ PAPER,
+ PAPER_DEEP,
+ RED,
+ SHADOW,
+ SHEET,
+ W,
+} from "./theme.js";
+
+type Node = ReturnType<typeof Layer.box>;
+
+/** A soft contact shadow under paper: short, warm and a little to the right. */
+export const paperShadow = (lift = 1) =>
+ new LayerStyle({
+ dropShadow: {
+ enabled: true,
+ color: SHADOW,
+ opacity: 0.22 + 0.06 * lift,
+ angle: 115,
+ distance: 5 * lift,
+ size: 14 * lift,
+ },
+ });
+
+/**
+ * Paper fibre as an SVG: fractal noise turned grey, for a soft-light pass
+ * over the whole frame (grey is neutral there, so only the grain shows).
+ */
+function fibreSvg(seed: number, frequency: number, octaves: number): string {
+ return `data:image/svg+xml;utf8,${encodeURIComponent(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><filter id="f" x="0" y="0" width="100%" height="100%"><feTurbulence type="fractalNoise" baseFrequency="${frequency}" numOctaves="${octaves}" seed="${seed}"/><feColorMatrix type="matrix" values="0.33 0.33 0.33 0 0 0.33 0.33 0.33 0 0 0.33 0.33 0.33 0 0 0 0 0 0 1"/></filter><rect width="${W}" height="${H}" filter="url(#f)"/></svg>`,
+ )}`;
+}
+
+/** The texture over everything: fine fibre, and a slow mottle of thicker paper. */
+export function paperTexture(): LayoutNode[] {
+ const full = {
+ position: "absolute" as const,
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ };
+ return [
+ Layer.svg(fibreSvg(11, 0.7, 3), {
+ id: "paper-fibre",
+ ...full,
+ fit: "fill",
+ blendMode: "soft-light",
+ opacity: 0.55,
+ }),
+ Layer.svg(fibreSvg(23, 0.006, 4), {
+ id: "paper-mottle",
+ ...full,
+ fit: "fill",
+ blendMode: "soft-light",
+ opacity: 0.4,
+ }),
+ ];
+}
+
+/** The desk: warm paper, a little darker toward the corners. */
+export function desk(id: string): LayoutNode {
+ return Layer.box({
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ background: `radial-gradient(ellipse at 50% 45%, ${PAPER} 0%, ${PAPER} 45%, ${PAPER_DEEP} 100%)`,
+ });
+}
+
+export interface SheetOptions {
+ id: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ rotation?: number;
+ color?: string;
+ children?: LayoutNode[];
+ lift?: number;
+ /** Clip children to the sheet. */
+ clip?: boolean;
+}
+
+/** A sheet of paper on the desk. */
+export function sheet(o: SheetOptions): Node {
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: o.width,
+ height: o.height,
+ rotation: o.rotation ?? 0,
+ background: o.color ?? SHEET,
+ ...(o.clip !== false && { overflow: "hidden" as const }),
+ children: o.children ?? [],
+ }).withEffect(paperShadow(o.lift));
+}
+
+/**
+ * The outline of a strip torn off a roll, `width` × `height`: the long edges
+ * waver a little, the short ends are ragged.
+ */
+export function tornPath(width: number, height: number, seed: number): string {
+ const r = rng(seed);
+ const tear = Math.min(14, height * 0.14);
+ const points: Vec2[] = [];
+ const edge = (from: Vec2, to: Vec2, steps: number, jag: number) => {
+ for (let i = 0; i < steps; i++) {
+ const t = i / steps;
+ const x = from[0] + (to[0] - from[0]) * t;
+ const y = from[1] + (to[1] - from[1]) * t;
+ const nx = to[1] - from[1];
+ const ny = from[0] - to[0];
+ const len = Math.hypot(nx, ny) || 1;
+ const d = r.spread(jag);
+ points.push([x + (nx / len) * d, y + (ny / len) * d]);
+ }
+ };
+ edge([tear, 0], [width - tear, 0], Math.round(width / 60), 1.6);
+ edge([width - tear, 0], [width - tear, height], Math.round(height / 7), tear);
+ edge([width - tear, height], [tear, height], Math.round(width / 60), 1.6);
+ edge([tear, height], [tear, 0], Math.round(height / 7), tear);
+ return toPathData(points, true);
+}
+
+/** A torn strip of colored paper (a label, a highlight band, a title). */
+export function strip(o: {
+ id: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ color: string;
+ seed: number;
+ rotation?: number;
+ children?: LayoutNode[];
+}): Node {
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ width: o.width,
+ height: o.height,
+ rotation: o.rotation ?? 0,
+ children: [
+ Layer.shape("path", {
+ id: `${o.id}-paper`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: o.width,
+ height: o.height,
+ d: tornPath(o.width, o.height, o.seed),
+ fill: o.color,
+ }).withEffect(paperShadow(0.7)),
+ ...(o.children ?? []),
+ ],
+ });
+}
+
+/** A piece of masking tape across a corner. */
+export function tape(o: {
+ id: string;
+ x: number;
+ y: number;
+ width?: number;
+ rotation: number;
+ seed: number;
+}) {
+ const width = o.width ?? 150;
+ const height = 40;
+ return Layer.shape("path", {
+ id: o.id,
+ position: "absolute",
+ x: o.x - width / 2,
+ y: o.y - height / 2,
+ width,
+ height,
+ rotation: o.rotation,
+ d: tornPath(width, height, o.seed),
+ fill: Color.alpha("#efe3c2", 0.82),
+ });
+}
+
+/** A rubber stamp: ink in a ruled box, slightly rotated, a little uneven. */
+export function stamp(o: {
+ id: string;
+ text: string;
+ x: number;
+ y: number;
+ rotation: number;
+ color?: string;
+ fontSize?: number;
+}): Node {
+ const color = o.color ?? RED;
+ const size = o.fontSize ?? 30;
+ const pad = size * 0.45;
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ rotation: o.rotation,
+ padding: pad,
+ borderColor: color,
+ borderWidth: Math.max(3, size * 0.12),
+ borderRadius: 6,
+ opacity: 0.88,
+ blendMode: "multiply",
+ children: [
+ Layer.text(o.text, {
+ id: `${o.id}-text`,
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: size,
+ letterSpacing: size * 0.08,
+ fill: color,
+ }),
+ ],
+ });
+}
+
+/** A stamp landing: pressed in from slightly larger, with a tiny settle. */
+export const stampIn = (at: number) =>
+ LayerAnimation.create()
+ .keys("opacity", [
+ [at, 0],
+ [at + 2, 0.88],
+ ])
+ .keys("scale", [
+ [at, 1.35],
+ [at + 5, 0.97, "power3.in"],
+ [at + 10, 1, "power2.out"],
+ ]);
+
+/** Paper laid down: dropped from a little above, landing with a small turn. */
+export const layDown = (
+ at: number,
+ o: { y: number; rotation?: number; from?: number; frames?: number },
+) => {
+ const frames = o.frames ?? 16;
+ const rotation = o.rotation ?? 0;
+ return LayerAnimation.create()
+ .keys("opacity", [
+ [at, 0],
+ [at + 4, 1],
+ ])
+ .keys("y", [
+ [at, o.y + (o.from ?? -40)],
+ [at + frames, o.y, "expo.out"],
+ ])
+ .keys("rotation", [
+ [at, rotation - 3],
+ [at + frames, rotation, "expo.out"],
+ ])
+ .keys("scale", [
+ [at, 1.06],
+ [at + frames, 1, "expo.out"],
+ ]);
+};
+
+/** A map pin: a dot with a white ring, the color of what it marks. */
+export function pin(o: {
+ id: string;
+ at: Vec2;
+ color?: string;
+ size?: number;
+}): Node {
+ const size = o.size ?? 22;
+ return Layer.box({
+ id: o.id,
+ position: "absolute",
+ x: o.at[0] - size / 2,
+ y: o.at[1] - size / 2,
+ width: size,
+ height: size,
+ children: [
+ Layer.shape("circle", {
+ id: `${o.id}-ring`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: size,
+ height: size,
+ fill: "#ffffff",
+ }),
+ Layer.shape("circle", {
+ id: `${o.id}-dot`,
+ position: "absolute",
+ x: size * 0.2,
+ y: size * 0.2,
+ width: size * 0.6,
+ height: size * 0.6,
+ fill: o.color ?? INK,
+ }),
+ ],
+ }).withEffect(paperShadow(0.5));
+}
+
+/** Pops in from nothing with a small overshoot. */
+export const popIn = (at: number, frames = 12) =>
+ LayerAnimation.create()
+ .keys("opacity", [
+ [at, 0],
+ [at + 3, 1],
+ ])
+ .keys("scale", [
+ [at, 0.2],
+ [at + frames, 1, "back.out(2.2)"],
+ ]);
+
+/** Fades and lifts in. */
+export const riseIn = (at: number, y: number, frames = 14, distance = 24) =>
+ LayerAnimation.create()
+ .keys("opacity", [
+ [at, 0],
+ [at + Math.round(frames * 0.6), 1, "power2.out"],
+ ])
+ .keys("y", [
+ [at, y + distance],
+ [at + frames, y, "expo.out"],
+ ]);
+
+/** A slow push that never stops, so a held frame still breathes. */
+export const drift = (frames: number, to = 1.045) =>
+ LayerAnimation.keys("scale", [
+ [0, 1],
+ [frames, to, "sine.inOut"],
+ ]);
diff --git a/examples/33_news_explainer/src/render.ts b/examples/33_news_explainer/src/render.ts
new file mode 100644
index 00000000..1aa891f9
--- /dev/null
+++ b/examples/33_news_explainer/src/render.ts
@@ -0,0 +1,65 @@
+/**
+ * pnpm render → output/explainer.mp4
+ * pnpm render frames 60 180 → output/frames/f0060.png …
+ * pnpm render grid → output/grid.png, a contact sheet of the film
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { HeadlessMediaRenderer } from "framefields";
+import { missingAudio } from "./audio.js";
+import { buildFilm } from "./film.js";
+import { FPS, OUTPUT } from "./theme.js";
+
+const [mode = "video", ...args] = process.argv.slice(2);
+const film = await buildFilm();
+const total = Math.round(((film.durationMs ?? 0) / 1000) * FPS);
+await fs.mkdir(path.join(OUTPUT, "frames"), { recursive: true });
+
+if (mode === "frames") {
+ const renderer = new HeadlessMediaRenderer();
+ for (const frame of args.map(Number)) {
+ const file = path.join(
+ OUTPUT,
+ "frames",
+ `f${String(frame).padStart(4, "0")}.png`,
+ );
+ await fs.writeFile(file, await film.renderFrame({ frame, renderer }));
+ console.log(file);
+ }
+} else if (mode === "grid") {
+ const frames =
+ args.length > 0
+ ? args.map(Number)
+ : Array.from({ length: 20 }, (_, i) =>
+ Math.round((i * (total - 1)) / 19),
+ );
+ const file = path.join(OUTPUT, "grid.png");
+ await fs.writeFile(
+ file,
+ await film.renderFrameGrid({
+ frames,
+ columns: 4,
+ cellWidth: 480,
+ showLabels: true,
+ }),
+ );
+ console.log(file);
+} else {
+ const missing = missingAudio();
+ if (missing.length > 0) {
+ console.error(
+ `Missing sounds (${missing.join(", ")}). Run \`pnpm assets\` and \`pnpm audio\` first.`,
+ );
+ process.exit(1);
+ }
+ const started = Date.now();
+ const result = await film.renderVideo({
+ outputPath: path.join(OUTPUT, "explainer.mp4"),
+ quality: "high",
+ });
+ await result.cleanup?.().catch(() => {});
+ console.log(
+ `${result.filePath} (${((Date.now() - started) / 1000).toFixed(1)} s)`,
+ );
+}
+process.exit(0);
diff --git a/examples/33_news_explainer/src/scenes/close.ts b/examples/33_news_explainer/src/scenes/close.ts
new file mode 100644
index 00000000..16040206
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/close.ts
@@ -0,0 +1,159 @@
+/**
+ * The close: the question left open, word by word as it is asked, "SO FAR,
+ * SO FAST" marked; then the sources the film reports from, how current it
+ * is, and the nine people on board.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { Annotate } from "../components/annotate/index.js";
+import { TextReveal } from "../components/text-reveal/index.js";
+import { riseIn, sheet, strip } from "../paper.js";
+import {
+ CARD,
+ DISPLAY,
+ INK,
+ INK_SOFT,
+ MONO,
+ RED,
+ SANS,
+ sec,
+ W,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const SOURCES =
+ "FAA · NTSB · AP · Reuters · CBS News · ABC News · FOX Weather · Aviation Safety Network";
+
+export function closeScene(t: SceneTiming): LayoutNode {
+ const question = lineIn(t, "question");
+ const askedAt = wordIn(t, "question", "how").start;
+ const farAt = wordIn(t, "question", "far").start;
+ const settle = question.end + sec(0.5);
+ const kicker = strip({
+ id: "close-kicker",
+ x: 200,
+ y: 150,
+ width: 420,
+ height: 74,
+ color: RED,
+ seed: 81,
+ rotation: -2,
+ children: [
+ Layer.text("THE OPEN QUESTION", {
+ id: "close-kicker-text",
+ position: "absolute",
+ x: 0,
+ y: 18,
+ width: 420,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 28,
+ letterSpacing: 3,
+ fill: CARD,
+ }),
+ ],
+ }).animate(
+ riseIn(wordIn(t, "question", "question").start - 4, 150, 12, 16),
+ LayerAnimation.keys("opacity", [
+ [settle, 1],
+ [settle + 12, 0, "power2.in"],
+ ]),
+ );
+ const headline = TextReveal({
+ ...kit,
+ id: "close-headline",
+ text: "HOW COULD IT FALL\nSO FAR, SO FAST?",
+ style: "rise",
+ by: "word",
+ stagger: 9,
+ fontFamily: DISPLAY,
+ fontSize: 172,
+ lineHeight: 1.02,
+ fill: INK,
+ position: "absolute",
+ x: 200,
+ y: 260,
+ at: askedAt,
+ });
+ const marked = Annotate({
+ ...kit,
+ id: "close-mark",
+ target: headline.rects("SO FAR, SO FAST?"),
+ mark: "highlight",
+ at: farAt - 2,
+ drawDuration: 18,
+ padding: 6,
+ seed: 7,
+ });
+ const lifted = LayerAnimation.keys("y", [
+ [settle, 0],
+ [settle + sec(0.8), -150, "power3.inOut"],
+ ]);
+ const statement = Layer.box({
+ id: "close-statement",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: 700,
+ children: [kicker, marked, headline],
+ }).animate(lifted);
+ const card = { x: 200, y: 700, width: 1520, height: 250 };
+ const sources = sheet({
+ id: "close-sources",
+ ...card,
+ rotation: 0.6,
+ color: CARD,
+ lift: 1.3,
+ children: [
+ Layer.text("SOURCES", {
+ id: "close-sources-title",
+ position: "absolute",
+ x: 48,
+ y: 36,
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 22,
+ letterSpacing: 4,
+ fill: INK_SOFT,
+ }),
+ Layer.text(SOURCES, {
+ id: "close-sources-list",
+ position: "absolute",
+ x: 48,
+ y: 74,
+ width: card.width - 96,
+ fontFamily: SANS,
+ fontWeight: 700,
+ fontSize: 32,
+ fill: INK,
+ }),
+ Layer.text(
+ "Reporting as of Nov. 2, 2026. The cause has not been determined; early details may change.",
+ {
+ id: "close-sources-asof",
+ position: "absolute",
+ x: 48,
+ y: 132,
+ width: card.width - 96,
+ fontFamily: SANS,
+ fontWeight: 500,
+ fontSize: 26,
+ fill: INK_SOFT,
+ },
+ ),
+ Layer.text("In memory of the nine people on board.", {
+ id: "close-memory",
+ position: "absolute",
+ x: 48,
+ y: 182,
+ fontFamily: SANS,
+ fontWeight: 700,
+ fontSize: 26,
+ fill: RED,
+ }),
+ ],
+ }).animate(riseIn(settle + sec(0.3), card.y, sec(0.9), 60));
+ return sceneRoot(t, { stage: [statement, sources], push: 1.03 });
+}
diff --git a/examples/33_news_explainer/src/scenes/dive.ts b/examples/33_news_explainer/src/scenes/dive.ts
new file mode 100644
index 00000000..15e9d6d5
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/dive.ts
@@ -0,0 +1,551 @@
+/**
+ * The fall, on a dark board: altitude against time. The cruise holds at
+ * 35,250 ft; on "dropped" the line plunges to 8,750 ft over just over a
+ * minute while a counter reads it off. The panel on the right takes one
+ * figure at a time: the 26,500 ft lost, the descent rate climbing to 30,000
+ * ft a minute (marked on the curve as each rate is reached), its speed in
+ * miles an hour, and the 35 seconds between the emergency call and the last
+ * transmission.
+ *
+ * The curve is illustrative: it passes through the FAA's two altitudes and
+ * reaches the rates reported from flight tracking (10,000, 20,000, then up to
+ * 30,000 ft/min), as altitude = 35,250 − 26,500 · (t / 76 s)^1.47.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { toPathData, type Vec2 } from "framefields/components";
+import { Annotate } from "../components/annotate/index.js";
+import { Counter } from "../components/counter/index.js";
+import { popIn, riseIn, sheet } from "../paper.js";
+import { DISPLAY, HAND, MONO, sec, W } from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const BOARD = "#202427";
+const CHALK = "#efe8da";
+const CHALK_SOFT = "#a9adae";
+const CHALK_FAINT = "#5b6266";
+const HOT = "#ff5b3d";
+const HIGHLIGHT = "#f7d94c";
+
+const SHEET_BOX = { x: 50, y: 36, width: W - 100, height: 1008 } as const;
+/** The plot, in sheet px: seconds since the dive began across, feet up. */
+const T0 = -15;
+const T1 = 95;
+const X0 = 210;
+const X1 = 1170;
+const BASE = 870;
+const PER_FT = 0.0175;
+const tx = (t: number) => X0 + ((t - T0) / (T1 - T0)) * (X1 - X0);
+const ay = (feet: number) => BASE - feet * PER_FT;
+
+const START_FT = 35250;
+const LOW_FT = 8750;
+/** "A little over a minute" from 35,250 to 8,750 ft. */
+const DIVE_S = 76;
+const POWER = 1.47;
+export const altitudeAt = (t: number) =>
+ START_FT - (START_FT - LOW_FT) * (Math.max(0, t) / DIVE_S) ** POWER;
+/** Feet per minute, at `t` seconds. */
+export const rateAt = (t: number) =>
+ (60 * POWER * (START_FT - LOW_FT) * (t / DIVE_S) ** (POWER - 1)) / DIVE_S;
+/** When the descent reaches `perMinute`. */
+export const timeAtRate = (perMinute: number) =>
+ DIVE_S *
+ ((perMinute * DIVE_S) / (60 * POWER * (START_FT - LOW_FT))) **
+ (1 / (POWER - 1));
+
+const PANEL_X = 1260;
+
+function plotLine(
+ id: string,
+ d: string,
+ color: string,
+ width: number,
+ extra: Record<string, unknown> = {},
+) {
+ return Layer.shape("path", {
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: SHEET_BOX.width,
+ height: SHEET_BOX.height,
+ d,
+ fillType: "none",
+ fill: "transparent",
+ strokeColor: color,
+ strokeWidth: width,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ ...extra,
+ });
+}
+
+const label = (
+ id: string,
+ text: string,
+ o: {
+ x: number;
+ y: number;
+ size?: number;
+ color?: string;
+ width?: number;
+ align?: "start" | "center" | "end";
+ font?: string;
+ weight?: number;
+ },
+) =>
+ Layer.text(text, {
+ id,
+ position: "absolute",
+ x: o.x,
+ y: o.y,
+ ...(o.width !== undefined && { width: o.width }),
+ align: o.align ?? "start",
+ fontFamily: o.font ?? MONO,
+ fontWeight: o.weight ?? 600,
+ fontSize: o.size ?? 20,
+ letterSpacing: (o.size ?? 20) * 0.06,
+ fill: o.color ?? CHALK_SOFT,
+ });
+
+function axes(): LayoutNode[] {
+ const grid = [10000, 20000, 30000, 40000]
+ .map((f) => `M${X0} ${ay(f)} L${X1} ${ay(f)}`)
+ .join(" ");
+ const minutes = [0, 30, 60, 90];
+ return [
+ plotLine("dive-grid", grid, CHALK_FAINT, 1.5, { strokeDashArray: "4 10" }),
+ plotLine(
+ "dive-axes",
+ `M${X0} ${ay(42000)} L${X0} ${BASE} L${X1} ${BASE}`,
+ CHALK_SOFT,
+ 3,
+ ),
+ ...[0, 10000, 20000, 30000, 40000].map((f) =>
+ label(`dive-y-${f}`, f === 0 ? "0 FT" : `${f / 1000},000`, {
+ x: 0,
+ y: ay(f) - 12,
+ width: X0 - 18,
+ align: "end",
+ }),
+ ),
+ ...minutes.map((s) =>
+ label(
+ `dive-x-${s}`,
+ `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`,
+ {
+ x: tx(s) - 40,
+ y: BASE + 14,
+ width: 80,
+ align: "center",
+ },
+ ),
+ ),
+ label("dive-x-title", "TIME SINCE THE DIVE BEGAN (MIN:SEC)", {
+ x: X0,
+ y: BASE + 50,
+ size: 17,
+ color: CHALK_FAINT,
+ }),
+ label("dive-y-title", "ALTITUDE (FT)", {
+ x: X0 - 4,
+ y: ay(42000) - 44,
+ size: 18,
+ }),
+ ];
+}
+
+/** A point on the curve with a value beside it. */
+function marker(
+ id: string,
+ at: Vec2,
+ text: string,
+ appear: number,
+ side: "right" | "above-right" | "above-left" = "right",
+): LayoutNode[] {
+ const left = side === "above-left";
+ const x = left ? at[0] - 262 : at[0] + 22;
+ const y = side === "right" ? at[1] - 13 : at[1] - 50;
+ return [
+ Layer.shape("circle", {
+ id: `${id}-dot`,
+ position: "absolute",
+ x: at[0] - 10,
+ y: at[1] - 10,
+ width: 20,
+ height: 20,
+ fill: CHALK,
+ strokeColor: HOT,
+ strokeWidth: 5,
+ }).animate(popIn(appear, 10)),
+ label(`${id}-label`, text, {
+ x,
+ y,
+ width: 240,
+ align: left ? "end" : "start",
+ size: 21,
+ weight: 800,
+ color: CHALK,
+ }).animate(riseIn(appear + 3, y, 10, 8)),
+ ];
+}
+
+/**
+ * One figure in the panel: a big number and a note under it, risen in on
+ * `appear` (the note on `noteAt`), dimmed on `dim` when the next arrives.
+ */
+function panelFigure(
+ id: string,
+ figure: string,
+ note: string,
+ o: {
+ y: number;
+ size: number;
+ color: string;
+ appear: number;
+ noteAt?: number;
+ dim: number;
+ },
+): LayoutNode[] {
+ const noteY = o.y + o.size * 1.34;
+ return [
+ label(id, figure, {
+ x: PANEL_X,
+ y: o.y,
+ font: DISPLAY,
+ size: o.size,
+ weight: 400,
+ color: o.color,
+ }).animate(riseIn(o.appear, o.y, 14, 16), dimAt(o.dim)),
+ label(`${id}-note`, note, {
+ x: PANEL_X + 4,
+ y: noteY,
+ size: 24,
+ color: CHALK,
+ }).animate(riseIn(o.noteAt ?? o.appear + 4, noteY, 14, 12), dimAt(o.dim)),
+ ];
+}
+
+/** Dims a panel figure once the next one arrives, so the eye goes to the new one. */
+const dimAt = (at: number) =>
+ LayerAnimation.keys("opacity", [
+ [at, 1],
+ [at + 10, 0.4, "power2.inOut"],
+ ]);
+
+export function diveScene(t: SceneTiming): LayoutNode {
+ const fall = lineIn(t, "fall");
+ const mayday = lineIn(t, "mayday");
+ const dropFrom = wordIn(t, "minute", "dropped").start;
+ const dropTo = Math.max(dropFrom + sec(3), wordIn(t, "minute", "minute").end);
+ const speedAt = wordIn(t, "speed", "vertical").start;
+
+ // The cruise, then the dive drawn in time with "dropped … just over a minute".
+ const cruise = plotLine(
+ "dive-cruise",
+ `M${tx(T0)} ${ay(START_FT)} L${tx(0)} ${ay(START_FT)}`,
+ CHALK,
+ 5,
+ { trimEnd: 0 },
+ ).animate(
+ LayerAnimation.keys("trimEnd", [
+ [0, 0],
+ [fall.start + 12, 1, "power2.inOut"],
+ ]),
+ );
+ const samples = 64;
+ const divePoints: Vec2[] = Array.from({ length: samples + 1 }, (_, i) => {
+ const s = (i / samples) * DIVE_S;
+ return [tx(s), ay(altitudeAt(s))];
+ });
+ const progressKeys: Array<[number, number]> = [];
+ const dotX: Array<[number, number]> = [];
+ const dotY: Array<[number, number]> = [];
+ const counterKeys: Array<[number, number]> = [];
+ const frames = Array.from(
+ { length: Math.floor((dropTo - dropFrom) / 2) },
+ (_, i) => dropFrom + i * 2,
+ );
+ for (const f of [...frames, dropTo]) {
+ const share = (f - dropFrom) / (dropTo - dropFrom);
+ const s = share * DIVE_S;
+ progressKeys.push([f, share]);
+ dotX.push([f, tx(s)]);
+ dotY.push([f, ay(altitudeAt(s))]);
+ counterKeys.push([f - dropFrom, Math.round(altitudeAt(s))]);
+ }
+ // The plunge is close to straight in x, so trim (arc length) and time agree
+ // only roughly; trim follows the arc share of each sample instead.
+ const arc = arcShares(divePoints);
+ const dive = plotLine("dive-plunge", toPathData(divePoints), HOT, 6, {
+ trimEnd: 0,
+ }).animate(
+ LayerAnimation.keys(
+ "trimEnd",
+ progressKeys.map(([f, share]) => [f, arc(share)] as [number, number]),
+ ),
+ );
+ const tip = Layer.shape("circle", {
+ id: "dive-tip",
+ position: "absolute",
+ x: tx(0) - 11,
+ y: ay(START_FT) - 11,
+ width: 22,
+ height: 22,
+ fill: HOT,
+ }).animate(
+ LayerAnimation.create()
+ .keys(
+ "x",
+ dotX.map(([f, x]) => [f, x - 11] as [number, number]),
+ )
+ .keys(
+ "y",
+ dotY.map(([f, y]) => [f, y - 11] as [number, number]),
+ )
+ .keys("opacity", [
+ [fall.start, 0],
+ [fall.start + 4, 1],
+ ]),
+ );
+ const unknown = plotLine(
+ "dive-unknown",
+ `M${tx(DIVE_S)} ${ay(LOW_FT)} L${tx(DIVE_S + 17)} ${ay(0)}`,
+ HOT,
+ 4,
+ { strokeDashArray: "8 10", trimEnd: 0 },
+ ).animate(
+ LayerAnimation.keys("trimEnd", [
+ [mayday.start, 0],
+ [mayday.start + 20, 1, "power2.out"],
+ ]),
+ );
+
+ const markers = [
+ ...marker(
+ "dive-start",
+ [tx(0), ay(START_FT)],
+ "35,250 FT",
+ fall.start + 8,
+ "above-left",
+ ),
+ ...marker("dive-low", [tx(DIVE_S), ay(LOW_FT)], "8,750 FT", dropTo),
+ ];
+ const rates = [10000, 20000, 30000].map((perMinute, i) => {
+ const s = timeAtRate(perMinute);
+ return marker(
+ `dive-rate-${i}`,
+ [tx(s), ay(altitudeAt(s))],
+ `${perMinute / 1000},000 FT/MIN`,
+ wordIn(t, "rate", "fastest").start + i * 9,
+ "above-right",
+ );
+ });
+ const fastest = timeAtRate(30000);
+ const fastestRing = Annotate({
+ ...kit,
+ id: "dive-fastest",
+ target: {
+ x: tx(fastest) - 16,
+ y: ay(altitudeAt(fastest)) - 16,
+ width: 32,
+ height: 32,
+ },
+ mark: "circle",
+ color: HIGHLIGHT,
+ texture: "marker",
+ width: 4,
+ at: wordIn(t, "rate", "thirty").start,
+ drawDuration: 12,
+ padding: 8,
+ seed: 21,
+ });
+ const since = plotLine(
+ "dive-span",
+ `M${tx(0)} ${BASE - 34} L${tx(DIVE_S)} ${BASE - 34}`,
+ HIGHLIGHT,
+ 3,
+ { trimEnd: 0 },
+ ).animate(
+ LayerAnimation.keys("trimEnd", [
+ [dropFrom, 0],
+ [dropTo, 1, "none"],
+ ]),
+ );
+ const spanLabel = label("dive-span-label", "just over a minute", {
+ x: tx(DIVE_S / 2) - 200,
+ y: BASE - 82,
+ width: 400,
+ align: "center",
+ font: HAND,
+ size: 30,
+ weight: 400,
+ color: HIGHLIGHT,
+ }).animate(riseIn(dropTo - 4, BASE - 82, 10, 8));
+
+ // The panel: one figure at a time. The counter reads the cruise from
+ // "Then the jet started to fall", and runs with the line from "dropped".
+ const counterAt = fall.start + 6;
+ const holdFor = dropFrom - counterAt;
+ const altitude = [
+ label("dive-alt-label", "ALTITUDE", { x: PANEL_X, y: 96, size: 22 }),
+ Counter({
+ ...kit,
+ id: "dive-counter",
+ from: START_FT,
+ values: [
+ [0, START_FT],
+ ...counterKeys.map(([f, v]) => [f + holdFor, v] as [number, number]),
+ ],
+ style: "count",
+ format: ",d",
+ suffix: " FT",
+ fontFamily: DISPLAY,
+ fontSize: 120,
+ fill: CHALK,
+ position: "absolute",
+ x: PANEL_X,
+ y: 130,
+ at: counterAt,
+ hold: t.duration,
+ }),
+ ];
+ const rateAt = wordIn(t, "rate", "thirty").start;
+ const mphAt = wordIn(t, "speed", "three").start;
+ const lost = panelFigure("dive-lost", "−26,500 FT", "IN JUST OVER A MINUTE", {
+ y: 290,
+ size: 96,
+ color: HOT,
+ appear: dropTo + 6,
+ dim: rateAt,
+ });
+ const rateFigure = panelFigure(
+ "dive-rate",
+ "30,000 FT/MIN",
+ "AT ITS FASTEST",
+ {
+ y: 480,
+ size: 84,
+ color: CHALK,
+ appear: rateAt,
+ dim: mphAt,
+ },
+ );
+ const mph = panelFigure("dive-mph", "≈ 340 MPH", "VERTICAL SPEED", {
+ y: 650,
+ size: 84,
+ color: HIGHLIGHT,
+ appear: mphAt,
+ noteAt: speedAt,
+ dim: wordIn(t, "mayday", "emergency").start,
+ });
+
+ const radio = radioStrip(t);
+ const board = sheet({
+ id: "dive-board",
+ ...SHEET_BOX,
+ rotation: -0.4,
+ color: BOARD,
+ lift: 2,
+ children: [
+ ...axes(),
+ since,
+ spanLabel,
+ cruise,
+ dive,
+ unknown,
+ ...markers,
+ ...rates.flat(),
+ fastestRing,
+ tip,
+ ...altitude,
+ ...lost,
+ ...rateFigure,
+ ...mph,
+ ...radio,
+ label(
+ "dive-source",
+ "ILLUSTRATIVE PROFILE THROUGH FAA ALTITUDES AND REPORTED DESCENT RATES · FINAL SECONDS NOT PUBLISHED",
+ { x: X0, y: SHEET_BOX.height - 52, size: 15, color: CHALK_FAINT },
+ ),
+ ],
+ });
+ return sceneRoot(t, { stage: [board], push: 1.025 });
+}
+
+/** The radio, under the panel: the emergency call, 35 seconds, the last transmission. */
+function radioStrip(t: SceneTiming): LayoutNode[] {
+ const y = 860;
+ const left = PANEL_X;
+ const right = PANEL_X + 470;
+ const called = wordIn(t, "mayday", "emergency").start;
+ const quiet = wordIn(t, "mayday", "quiet").start;
+ const counting = wordIn(t, "mayday", "later").start - 12;
+ const tick = (id: string, x: number, at: number) =>
+ Layer.shape("rect", {
+ id,
+ position: "absolute",
+ x: x - 2,
+ y: y - 16,
+ width: 4,
+ height: 32,
+ fill: CHALK,
+ }).animate(popIn(at, 8));
+ return [
+ tick("radio-start", left, called),
+ label("radio-called", "MAYDAY", {
+ x: left - 6,
+ y: y - 52,
+ size: 22,
+ weight: 800,
+ color: HOT,
+ }).animate(riseIn(called + 2, y - 52, 10, 8)),
+ plotLine("radio-bar", `M${left} ${y} L${right} ${y}`, CHALK, 4, {
+ strokeDashArray: "2 9",
+ trimEnd: 0,
+ }).animate(
+ LayerAnimation.keys("trimEnd", [
+ [counting, 0],
+ [quiet, 1, "none"],
+ ]),
+ ),
+ label("radio-span", "≈ 35 SECONDS", {
+ x: left,
+ y: y + 26,
+ width: right - left,
+ align: "center",
+ size: 22,
+ weight: 800,
+ color: CHALK,
+ }).animate(riseIn(counting + 6, y + 26, 10, 8)),
+ tick("radio-end", right, quiet),
+ label("radio-last", "LAST CALL", {
+ x: right - 200,
+ y: y - 52,
+ width: 206,
+ align: "end",
+ size: 22,
+ weight: 800,
+ color: CHALK,
+ }).animate(riseIn(quiet + 2, y - 52, 10, 8)),
+ ];
+}
+
+/** Maps a share of the samples to the share of the polyline's length drawn by then. */
+function arcShares(points: Vec2[]): (share: number) => number {
+ const lengths = [0];
+ for (let i = 1; i < points.length; i++) {
+ const a = points[i - 1] as Vec2;
+ const b = points[i] as Vec2;
+ lengths.push((lengths[i - 1] ?? 0) + Math.hypot(b[0] - a[0], b[1] - a[1]));
+ }
+ const total = lengths.at(-1) ?? 1;
+ return (share) => {
+ const f = Math.min(1, Math.max(0, share)) * (points.length - 1);
+ const i = Math.floor(f);
+ const a = lengths[i] ?? total;
+ const b = lengths[Math.min(points.length - 1, i + 1)] ?? total;
+ return (a + (b - a) * (f - i)) / total;
+ };
+}
diff --git a/examples/33_news_explainer/src/scenes/ground.ts b/examples/33_news_explainer/src/scenes/ground.ts
new file mode 100644
index 00000000..0317ea6e
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/ground.ts
@@ -0,0 +1,424 @@
+/**
+ * Where it came down, as a schematic street plan (not to scale): Military
+ * Trail marked as "a busy road" is said, the mobile home park boxed on
+ * "mobile", the crater beside the road, then the evacuation ring opening on
+ * "six hundred", and a stamp for the people on the ground.
+ */
+import { Color, Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { rng, toPathData, type Vec2 } from "framefields/components";
+import { Annotate } from "../components/annotate/index.js";
+import { popIn, riseIn, sheet, stamp, stampIn, strip } from "../paper.js";
+import {
+ CARD,
+ HAND,
+ INK,
+ INK_SOFT,
+ MONO,
+ RED,
+ SANS,
+ SHEET,
+ YELLOW,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const PLAN = { x: 70, y: 50, width: 1780, height: 980 } as const;
+const BLOCK = "#e9e3d5";
+const STREET = "#d2c9b7";
+const PARK = "#dde3c9";
+const HOME = "#f6f2e6";
+
+/** Military Trail runs north–south, 10th Avenue North east–west. */
+const TRAIL = { x: 800, width: 90 } as const;
+const AVENUE = { y: 430, height: 70 } as const;
+const MINOR = 44;
+const PARK_BOX = { x: 960, y: 560, width: 560, height: 330 } as const;
+const SITE: Vec2 = [925, 640];
+
+const rect = (
+ id: string,
+ r: { x: number; y: number; width: number; height: number },
+ fill: string,
+ extra: Record<string, unknown> = {},
+) => Layer.shape("rect", { id, position: "absolute", ...r, fill, ...extra });
+
+function streets(): LayoutNode[] {
+ const minorX = [280, 1640];
+ const minorY = [170, 940];
+ return [
+ rect(
+ "plan-blocks",
+ { x: 0, y: 0, width: PLAN.width, height: PLAN.height },
+ BLOCK,
+ ),
+ ...minorX.map((x, i) =>
+ rect(
+ `plan-street-x-${i}`,
+ { x, y: 0, width: MINOR, height: PLAN.height },
+ STREET,
+ { opacity: 0.7 },
+ ),
+ ),
+ ...minorY.map((y, i) =>
+ rect(
+ `plan-street-y-${i}`,
+ { x: 0, y, width: PLAN.width, height: MINOR },
+ STREET,
+ { opacity: 0.7 },
+ ),
+ ),
+ rect(
+ "plan-avenue",
+ { x: 0, y: AVENUE.y, width: PLAN.width, height: AVENUE.height },
+ STREET,
+ ),
+ rect(
+ "plan-trail",
+ { x: TRAIL.x, y: 0, width: TRAIL.width, height: PLAN.height },
+ STREET,
+ ),
+ Layer.shape("path", {
+ id: "plan-trail-centre",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PLAN.width,
+ height: PLAN.height,
+ d: `M${TRAIL.x + TRAIL.width / 2} 0 L${TRAIL.x + TRAIL.width / 2} ${PLAN.height} M0 ${AVENUE.y + AVENUE.height / 2} L${PLAN.width} ${AVENUE.y + AVENUE.height / 2}`,
+ fillType: "none",
+ fill: "transparent",
+ strokeColor: Color.alpha("#ffffff", 0.9),
+ strokeWidth: 3,
+ strokeDashArray: "18 14",
+ }),
+ Layer.text("MILITARY TRAIL", {
+ id: "plan-trail-name",
+ position: "absolute",
+ x: TRAIL.x + TRAIL.width / 2 - 180,
+ y: 230,
+ width: 360,
+ align: "center",
+ rotation: -90,
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 26,
+ letterSpacing: 6,
+ fill: INK_SOFT,
+ }),
+ Layer.text("10TH AVE. N.", {
+ id: "plan-avenue-name",
+ position: "absolute",
+ x: 1180,
+ y: AVENUE.y + 20,
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 24,
+ letterSpacing: 5,
+ fill: INK_SOFT,
+ }),
+ ];
+}
+
+function park(): LayoutNode[] {
+ const homes: LayoutNode[] = [];
+ for (let row = 0; row < 5; row++)
+ for (let col = 0; col < 9; col++)
+ homes.push(
+ rect(
+ `plan-home-${row}-${col}`,
+ {
+ x: PARK_BOX.x + 40 + col * 56,
+ y: PARK_BOX.y + 34 + row * 56,
+ width: 30,
+ height: 40,
+ },
+ HOME,
+ { borderRadius: 3 },
+ ),
+ );
+ return [
+ rect("plan-park", PARK_BOX, PARK, { borderRadius: 8 }),
+ ...homes,
+ Layer.text("MOBILE HOME PARK", {
+ id: "plan-park-name",
+ position: "absolute",
+ x: PARK_BOX.x,
+ y: PARK_BOX.y + PARK_BOX.height + 14,
+ width: PARK_BOX.width,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 22,
+ letterSpacing: 4,
+ fill: INK_SOFT,
+ }),
+ ];
+}
+
+/** The blocks around it, filled with house footprints (seeded, some lots empty). */
+function neighbourhood(): LayoutNode {
+ const blocks = [
+ { x: 20, y: 20, width: 240, height: 130 },
+ { x: 344, y: 20, width: 436, height: 130 },
+ { x: 910, y: 20, width: 710, height: 130 },
+ { x: 20, y: 234, width: 240, height: 176 },
+ { x: 344, y: 234, width: 436, height: 176 },
+ { x: 910, y: 234, width: 710, height: 176 },
+ { x: 20, y: 520, width: 240, height: 400 },
+ { x: 344, y: 520, width: 436, height: 400 },
+ ];
+ const r = rng(12);
+ const lots: string[] = [];
+ for (const b of blocks)
+ for (let y = b.y + 14; y + 26 <= b.y + b.height - 10; y += 46)
+ for (let x = b.x + 14; x + 34 <= b.x + b.width - 10; x += 52)
+ if (r.next() > 0.22) {
+ const w = r.range(26, 36);
+ const h = r.range(20, 28);
+ lots.push(
+ `M${x.toFixed(1)} ${y.toFixed(1)} h${w.toFixed(1)} v${h.toFixed(1)} h${(-w).toFixed(1)} Z`,
+ );
+ }
+ return Layer.shape("path", {
+ id: "plan-houses",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PLAN.width,
+ height: PLAN.height,
+ d: lots.join(" "),
+ fill: "#ddd4c2",
+ opacity: 0.8,
+ });
+}
+
+/** North, top right. */
+function north(): LayoutNode[] {
+ const x = PLAN.width - 90;
+ const y = 40;
+ return [
+ Layer.shape("path", {
+ id: "plan-north-arrow",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PLAN.width,
+ height: PLAN.height,
+ d: `M${x} ${y} L${x + 16} ${y + 44} L${x} ${y + 34} L${x - 16} ${y + 44} Z`,
+ fill: INK,
+ }),
+ Layer.text("N", {
+ id: "plan-north",
+ position: "absolute",
+ x: x - 20,
+ y: y + 50,
+ width: 40,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 24,
+ fill: INK,
+ }),
+ ];
+}
+
+/** A ragged scorch with a darker core, `radius` px across at most. */
+function craterPath(radius: number, seed: number): string {
+ const r = rng(seed);
+ const points: Vec2[] = Array.from({ length: 22 }, (_, i) => {
+ const a = (i / 22) * Math.PI * 2;
+ const d = radius * r.range(0.72, 1);
+ return [radius + Math.cos(a) * d, radius + Math.sin(a) * d * 0.86];
+ });
+ return toPathData(points, true);
+}
+
+export function groundScene(t: SceneTiming): LayoutNode {
+ const road = wordIn(t, "road", "road").start;
+ const mobile = wordIn(t, "road", "mobile").start;
+ const crater = wordIn(t, "crater", "crater").start;
+ const six = wordIn(t, "crater", "six").start;
+ const ground = lineIn(t, "ground");
+
+ const roadMark = Annotate({
+ ...kit,
+ id: "plan-road-mark",
+ target: { x: TRAIL.x, y: 40, width: TRAIL.width, height: PLAN.height - 80 },
+ mark: "highlight",
+ at: road - 10,
+ drawDuration: 16,
+ padding: 0,
+ seed: 31,
+ });
+ const parkMark = Annotate({
+ ...kit,
+ id: "plan-park-mark",
+ target: PARK_BOX,
+ mark: "box",
+ color: INK,
+ texture: "marker",
+ width: 4,
+ at: mobile,
+ drawDuration: 16,
+ padding: 14,
+ seed: 32,
+ });
+ const scorch = Layer.box({
+ id: "plan-crater",
+ position: "absolute",
+ x: SITE[0] - 60,
+ y: SITE[1] - 52,
+ width: 120,
+ height: 104,
+ children: [
+ Layer.shape("path", {
+ id: "plan-crater-scorch",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: 120,
+ height: 104,
+ d: craterPath(60, 5),
+ fill: "#4a3d33",
+ }),
+ Layer.shape("path", {
+ id: "plan-crater-core",
+ position: "absolute",
+ x: 24,
+ y: 20,
+ width: 72,
+ height: 62,
+ d: craterPath(36, 8),
+ fill: "#231c17",
+ }),
+ ],
+ }).animate(popIn(crater - 4, 12));
+ const craterNote = Annotate({
+ ...kit,
+ id: "plan-crater-note",
+ target: { x: SITE[0] - 50, y: SITE[1] - 40, width: 100, height: 80 },
+ from: { x: 560, y: 760, width: 1, height: 1 },
+ mark: "arrow",
+ curve: "arc",
+ color: RED,
+ texture: "marker",
+ width: 5,
+ at: crater + 6,
+ drawDuration: 14,
+ padding: 10,
+ label: { text: "crater by the road", side: "left", size: 38 },
+ seed: 33,
+ });
+ const ringR = 360;
+ const ring = Layer.shape("circle", {
+ id: "plan-evacuation",
+ position: "absolute",
+ x: SITE[0] - ringR,
+ y: SITE[1] - ringR,
+ width: ringR * 2,
+ height: ringR * 2,
+ fill: Color.alpha(RED, 0.07),
+ strokeColor: RED,
+ strokeWidth: 4,
+ strokeDashArray: "16 12",
+ }).animate(
+ LayerAnimation.create()
+ .keys("scale", [
+ [six - 4, 0.1],
+ [six + 26, 1, "expo.out"],
+ ])
+ .keys("opacity", [
+ [six - 4, 0],
+ [six + 2, 1],
+ ]),
+ );
+ const evacuated = strip({
+ id: "plan-evacuated",
+ x: 1240,
+ y: 150,
+ width: 470,
+ height: 120,
+ color: YELLOW,
+ seed: 52,
+ rotation: 2.5,
+ children: [
+ Layer.text("≈ 600 RESIDENTS\nEVACUATED", {
+ id: "plan-evacuated-text",
+ position: "absolute",
+ x: 0,
+ y: 14,
+ width: 470,
+ align: "center",
+ fontFamily: SANS,
+ fontWeight: 900,
+ fontSize: 38,
+ lineHeight: 1.1,
+ fill: INK,
+ }),
+ ],
+ }).animate(popIn(six + 10, 12));
+ const safe = stamp({
+ id: "plan-ground-stamp",
+ text: "NO DEATHS ON THE GROUND",
+ x: 180,
+ y: 110,
+ rotation: -5,
+ color: INK,
+ fontSize: 34,
+ }).animate(stampIn(ground.start + 4));
+ const plan = sheet({
+ id: "plan",
+ ...PLAN,
+ rotation: 0.4,
+ color: SHEET,
+ lift: 1.2,
+ children: [
+ ...streets(),
+ neighbourhood(),
+ ...park(),
+ ...north(),
+ roadMark,
+ ring,
+ parkMark,
+ scorch,
+ craterNote,
+ Layer.text("SCHEMATIC · NOT TO SCALE · POSITIONS APPROXIMATE", {
+ id: "plan-note",
+ position: "absolute",
+ x: PLAN.width - 720,
+ y: PLAN.height - 46,
+ width: 690,
+ align: "end",
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 17,
+ letterSpacing: 1.5,
+ fill: INK_SOFT,
+ }),
+ ],
+ });
+ const place = strip({
+ id: "plan-place",
+ x: 120,
+ y: 880,
+ width: 640,
+ height: 84,
+ color: CARD,
+ seed: 64,
+ rotation: -1.5,
+ children: [
+ Layer.text("Cresthaven, Palm Beach County", {
+ id: "plan-place-text",
+ position: "absolute",
+ x: 0,
+ y: 20,
+ width: 640,
+ align: "center",
+ fontFamily: HAND,
+ fontSize: 36,
+ fill: INK,
+ }),
+ ],
+ }).animate(riseIn(Math.max(0, lineIn(t, "road").start - 6), 880, 14, 20));
+ return sceneRoot(t, { stage: [plan, evacuated, safe, place], push: 1.04 });
+}
diff --git a/examples/33_news_explainer/src/scenes/open.ts b/examples/33_news_explainer/src/scenes/open.ts
new file mode 100644
index 00000000..b8bf627f
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/open.ts
@@ -0,0 +1,239 @@
+/**
+ * The cold open. A dateline card lands on the desk; the headline rises word
+ * by word as it is read, "SOUTH FLORIDA" is marked as it is said, and a scrap
+ * of map pins Palm Beach County. On "nine", nine figures, one by one.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { Annotate } from "../components/annotate/index.js";
+import { TextReveal } from "../components/text-reveal/index.js";
+import { FLORIDA, PLACES, stateOutline } from "../geo.js";
+import { layDown, pin, popIn, riseIn, sheet, strip, tape } from "../paper.js";
+import {
+ CARD,
+ DISPLAY,
+ HAND,
+ INK,
+ INK_SOFT,
+ LAND_HOME,
+ MONO,
+ RED,
+ SEA,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const CARD_BOX = { x: 150, y: 140, width: 1020, height: 760 } as const;
+const SCRAP = { x: 1250, y: 150, width: 500, height: 640 } as const;
+
+/** One of the nine aboard: a head and shoulders. */
+function figure(id: string, x: number, y: number) {
+ return Layer.box({
+ id,
+ position: "absolute",
+ x,
+ y,
+ width: 44,
+ height: 64,
+ children: [
+ Layer.shape("circle", {
+ id: `${id}-head`,
+ position: "absolute",
+ x: 10,
+ y: 0,
+ width: 24,
+ height: 24,
+ fill: INK,
+ }),
+ Layer.shape("rect", {
+ id: `${id}-body`,
+ position: "absolute",
+ x: 0,
+ y: 28,
+ width: 44,
+ height: 36,
+ radiusTL: 22,
+ radiusTR: 22,
+ radiusBL: 4,
+ radiusBR: 4,
+ fill: INK,
+ }),
+ ],
+ });
+}
+
+export function openScene(t: SceneTiming): LayoutNode {
+ const fell = lineIn(t, "fell");
+ const nine = wordIn(t, "nine", "nine");
+
+ const dateline = Layer.text("SUNDAY, NOV. 1, 2026 · 12:50 P.M. EST", {
+ id: "open-dateline",
+ position: "absolute",
+ x: 64,
+ y: 58,
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 26,
+ letterSpacing: 2,
+ fill: INK_SOFT,
+ }).animate(riseIn(fell.start - 6, 58, 12, 12));
+ const rule = Layer.shape("rect", {
+ id: "open-rule",
+ position: "absolute",
+ x: 64,
+ y: 108,
+ width: 892,
+ height: 4,
+ fill: INK,
+ anchorX: 0,
+ }).animate(
+ LayerAnimation.keys("scaleX", [
+ [fell.start - 4, 0],
+ [fell.start + 14, 1, "expo.out"],
+ ]),
+ );
+ const headline = TextReveal({
+ ...kit,
+ id: "open-headline",
+ text: "BUSINESS JET\nCRASHES IN\nSOUTH FLORIDA",
+ style: "rise",
+ by: "word",
+ stagger: 7,
+ fontFamily: DISPLAY,
+ fontSize: 128,
+ lineHeight: 1.02,
+ fill: INK,
+ position: "absolute",
+ x: 64,
+ y: 150,
+ at: wordIn(t, "fell", "business").start,
+ });
+ const marked = Annotate({
+ ...kit,
+ id: "open-mark",
+ target: headline.rects("SOUTH FLORIDA"),
+ mark: "highlight",
+ at: wordIn(t, "fell", "south").start,
+ drawDuration: 14,
+ padding: 6,
+ seed: 3,
+ });
+ const figures = Array.from({ length: 9 }, (_, i) =>
+ figure(`open-figure-${i}`, 64 + i * 66, 590).animate(
+ popIn(nine.start + i * 3, 10),
+ ),
+ );
+ const aboard = Layer.text("9 ON BOARD · NO SURVIVORS", {
+ id: "open-aboard",
+ position: "absolute",
+ x: 64,
+ y: 682,
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 28,
+ letterSpacing: 1.5,
+ fill: RED,
+ }).animate(riseIn(nine.start + 30, 682, 14, 10));
+
+ const card = sheet({
+ id: "open-card",
+ ...CARD_BOX,
+ rotation: -1.8,
+ color: CARD,
+ lift: 1.4,
+ children: [dateline, rule, marked, headline, ...figures, aboard],
+ }).animate(
+ layDown(Math.max(0, fell.start - 24), { y: CARD_BOX.y, rotation: -1.8 }),
+ );
+
+ const florida = stateOutline(FLORIDA, SCRAP.width, SCRAP.height, 50);
+ const site = florida.project(PLACES.crash);
+ const scrapIn = wordIn(t, "fell", "florida").start - 4;
+ const pulse = Layer.shape("circle", {
+ id: "open-pulse",
+ position: "absolute",
+ x: site[0] - 40,
+ y: site[1] - 40,
+ width: 80,
+ height: 80,
+ fill: "transparent",
+ strokeColor: RED,
+ strokeWidth: 4,
+ }).animate(
+ LayerAnimation.create()
+ .keys("scale", [
+ [scrapIn + 14, 0.2],
+ [scrapIn + 44, 1.4, "power2.out"],
+ ])
+ .keys("opacity", [
+ [scrapIn + 14, 1],
+ [scrapIn + 44, 0, "power2.in"],
+ ]),
+ );
+ const scrap = sheet({
+ id: "open-scrap",
+ ...SCRAP,
+ rotation: 3.5,
+ color: SEA,
+ children: [
+ Layer.shape("path", {
+ id: "open-florida",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: SCRAP.width,
+ height: SCRAP.height,
+ d: florida.d,
+ fill: LAND_HOME,
+ strokeColor: INK,
+ strokeWidth: 2.5,
+ strokeLineJoin: "round",
+ }),
+ pulse,
+ pin({ id: "open-site", at: site, color: RED, size: 26 }).animate(
+ popIn(scrapIn + 12),
+ ),
+ strip({
+ id: "open-county",
+ x: site[0] - 300,
+ y: site[1] + 46,
+ width: 270,
+ height: 58,
+ color: CARD,
+ seed: 13,
+ rotation: -4,
+ children: [
+ Layer.text("PALM BEACH COUNTY", {
+ id: "open-county-text",
+ position: "absolute",
+ x: 0,
+ y: 14,
+ width: 270,
+ align: "center",
+ fontFamily: HAND,
+ fontSize: 26,
+ fill: INK,
+ }),
+ ],
+ }).animate(popIn(scrapIn + 20, 10)),
+ ],
+ }).animate(layDown(scrapIn, { y: SCRAP.y, rotation: 3.5, from: -60 }));
+
+ return sceneRoot(t, {
+ stage: [
+ card,
+ scrap,
+ tape({
+ id: "open-tape",
+ x: SCRAP.x + SCRAP.width / 2,
+ y: SCRAP.y + 6,
+ rotation: -4,
+ seed: 9,
+ }).animate(
+ LayerAnimation.keys("opacity", [
+ [scrapIn + 8, 0],
+ [scrapIn + 12, 1],
+ ]),
+ ),
+ ],
+ });
+}
diff --git a/examples/33_news_explainer/src/scenes/probe.ts b/examples/33_news_explainer/src/scenes/probe.ts
new file mode 100644
index 00000000..7f93134d
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/probe.ts
@@ -0,0 +1,288 @@
+/**
+ * The investigation, as a case folder: who leads it, the weather marked as a
+ * major focus, the signs of a break-up circled, then what comes next on a
+ * short timeline (a preliminary report within weeks, a cause in a year or
+ * more), and a stamp: no cause yet.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { Annotate } from "../components/annotate/index.js";
+import {
+ layDown,
+ popIn,
+ riseIn,
+ sheet,
+ stamp,
+ stampIn,
+ tape,
+} from "../paper.js";
+import {
+ CARD,
+ DISPLAY,
+ INK,
+ INK_FAINT,
+ INK_SOFT,
+ MONO,
+ RED,
+ SANS,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const FOLDER = { x: 230, y: 120, width: 1460, height: 880 } as const;
+const MANILA = "#d9c08e";
+const NOTES = { x: 70, y: 70, width: 1320, height: 760 } as const;
+const ROW_X = 70;
+
+function note(
+ id: string,
+ text: string,
+ y: number,
+ at: number,
+ o: { size?: number; color?: string; font?: string; weight?: number } = {},
+) {
+ return Layer.text(text, {
+ id,
+ position: "absolute",
+ x: ROW_X,
+ y,
+ fontFamily: o.font ?? MONO,
+ fontWeight: o.weight ?? 700,
+ fontSize: o.size ?? 36,
+ fill: o.color ?? INK,
+ }).animate(riseIn(at, y, 12, 10));
+}
+
+function milestone(
+ id: string,
+ x: number,
+ y: number,
+ title: string,
+ when: string,
+ at: number,
+): LayoutNode[] {
+ return [
+ Layer.shape("circle", {
+ id: `${id}-dot`,
+ position: "absolute",
+ x: x - 14,
+ y: y - 14,
+ width: 28,
+ height: 28,
+ fill: INK,
+ }).animate(popIn(at, 10)),
+ Layer.text(title, {
+ id: `${id}-title`,
+ position: "absolute",
+ x: x - 230,
+ y: y + 30,
+ width: 460,
+ align: "center",
+ fontFamily: SANS,
+ fontWeight: 800,
+ fontSize: 32,
+ fill: INK,
+ }).animate(riseIn(at + 3, y + 30, 12, 10)),
+ Layer.text(when, {
+ id: `${id}-when`,
+ position: "absolute",
+ x: x - 230,
+ y: y + 76,
+ width: 460,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 26,
+ letterSpacing: 1.5,
+ fill: RED,
+ }).animate(riseIn(at + 6, y + 76, 12, 10)),
+ ];
+}
+
+export function probeScene(t: SceneTiming): LayoutNode {
+ const ntsb = lineIn(t, "ntsb");
+ const report = lineIn(t, "report");
+ const leadAt = wordIn(t, "ntsb", "national").start;
+ const weatherAt = wordIn(t, "ntsb", "weather").start;
+ const focusAt = wordIn(t, "ntsb", "focus").start;
+ const signsAt = wordIn(t, "breakup", "signs").start;
+ const apartAt = wordIn(t, "breakup", "apart").start;
+ const prelimAt = wordIn(t, "report", "preliminary").start;
+ const finalAt = wordIn(t, "report", "final").start;
+
+ const lead = note("probe-lead", "LEAD: NTSB · SUPPORT: FAA", 150, leadAt);
+ const weather = note(
+ "probe-weather",
+ "WEATHER IS A MAJOR FOCUS",
+ 240,
+ weatherAt,
+ );
+ const breakup = note(
+ "probe-breakup",
+ "SIGNS OF A POSSIBLE IN-FLIGHT BREAKUP",
+ 330,
+ signsAt,
+ );
+ const marks = [
+ Annotate({
+ ...kit,
+ id: "probe-weather-mark",
+ target: { text: weather, match: "MAJOR FOCUS" },
+ mark: "highlight",
+ at: focusAt - 4,
+ drawDuration: 12,
+ padding: 4,
+ seed: 41,
+ }),
+ Annotate({
+ ...kit,
+ id: "probe-breakup-mark",
+ target: { text: breakup, match: "IN-FLIGHT BREAKUP" },
+ mark: "circle",
+ color: RED,
+ texture: "marker",
+ width: 4,
+ at: apartAt - 4,
+ drawDuration: 16,
+ padding: 10,
+ seed: 42,
+ }),
+ ];
+ const lineY = 560;
+ const fromX = 330;
+ const toX = 990;
+ const next = [
+ note("probe-next", "WHAT COMES NEXT", 450, report.start - 8, {
+ size: 24,
+ color: INK_SOFT,
+ }),
+ Layer.shape("path", {
+ id: "probe-timeline",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: NOTES.width,
+ height: NOTES.height,
+ d: `M${fromX} ${lineY} L${toX} ${lineY}`,
+ fillType: "none",
+ fill: "transparent",
+ strokeColor: INK,
+ strokeWidth: 4,
+ strokeDashArray: "4 10",
+ strokeLineCap: "round",
+ trimEnd: 0,
+ }).animate(
+ LayerAnimation.keys("trimEnd", [
+ [prelimAt + 8, 0],
+ [finalAt, 1, "power2.inOut"],
+ ]),
+ ),
+ ...milestone(
+ "probe-prelim",
+ fromX,
+ lineY,
+ "PRELIMINARY REPORT",
+ "WITHIN WEEKS",
+ prelimAt,
+ ),
+ ...milestone(
+ "probe-final",
+ toX,
+ lineY,
+ "FINAL CAUSE",
+ "A YEAR OR MORE",
+ finalAt,
+ ),
+ ];
+ const notes = sheet({
+ id: "probe-notes",
+ ...NOTES,
+ rotation: 0.8,
+ color: CARD,
+ lift: 1.1,
+ children: [
+ Layer.text("CASE NOTES", {
+ id: "probe-heading",
+ position: "absolute",
+ x: ROW_X,
+ y: 40,
+ fontFamily: DISPLAY,
+ fontSize: 64,
+ fill: INK,
+ }),
+ Layer.text("LEARJET 60 · PALM BEACH COUNTY, FLA. · NOV. 1, 2026", {
+ id: "probe-subject",
+ position: "absolute",
+ x: ROW_X + 330,
+ y: 66,
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 22,
+ letterSpacing: 1,
+ fill: INK_FAINT,
+ }),
+ ...marks,
+ lead,
+ weather,
+ breakup,
+ ...next,
+ ],
+ }).animate(
+ layDown(Math.max(0, ntsb.start - 18), { y: NOTES.y, rotation: 0.8 }),
+ );
+ const folder = Layer.box({
+ id: "probe-folder",
+ position: "absolute",
+ ...FOLDER,
+ children: [
+ Layer.shape("rect", {
+ id: "probe-folder-tab",
+ position: "absolute",
+ x: 40,
+ y: -56,
+ width: 460,
+ height: 80,
+ radiusTL: 14,
+ radiusTR: 14,
+ fill: MANILA,
+ }),
+ Layer.text("NTSB INVESTIGATION", {
+ id: "probe-folder-label",
+ position: "absolute",
+ x: 70,
+ y: -40,
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 26,
+ letterSpacing: 3,
+ fill: INK_SOFT,
+ }),
+ sheet({
+ id: "probe-folder-body",
+ x: 0,
+ y: 0,
+ width: FOLDER.width,
+ height: FOLDER.height,
+ color: MANILA,
+ lift: 1.4,
+ clip: false,
+ }),
+ notes,
+ tape({
+ id: "probe-tape",
+ x: NOTES.x + NOTES.width - 40,
+ y: NOTES.y + 4,
+ rotation: 32,
+ seed: 19,
+ }),
+ ],
+ });
+ const undetermined = stamp({
+ id: "probe-stamp",
+ text: "CAUSE NOT YET DETERMINED",
+ x: 1120,
+ y: 900,
+ rotation: -5,
+ fontSize: 38,
+ }).animate(stampIn(report.end - 8));
+ return sceneRoot(t, { stage: [folder, undetermined], push: 1.035 });
+}
diff --git a/examples/33_news_explainer/src/scenes/route.ts b/examples/33_news_explainer/src/scenes/route.ts
new file mode 100644
index 00000000..c924aa6b
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/route.ts
@@ -0,0 +1,440 @@
+/**
+ * The flight. A map sheet of the Gulf; an index card for the aircraft while
+ * it is named; Austin pinned as it is said, the planned route to North
+ * Eleuthera dashed in on "Bahamas". Then the jet flies it, the line drawn
+ * behind it, and the map pushes in on Palm Beach County as it reaches
+ * Florida, where it is tagged at its cruising height.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { toPathData, type Vec2 } from "framefields/components";
+import { Annotate } from "../components/annotate/index.js";
+import { along, LABELS, mapGeometry, PLACES } from "../geo.js";
+import { jetSide, jetTop, topViewSize } from "../jet.js";
+import { layDown, pin, popIn, riseIn, sheet, strip, tape } from "../paper.js";
+import {
+ BORDER,
+ CARD,
+ DISPLAY,
+ INK,
+ INK_FAINT,
+ INK_SOFT,
+ LAND,
+ LAND_HOME,
+ MONO,
+ RED,
+ SANS,
+ SEA,
+ SHEET,
+ sec,
+ YELLOW,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const MAP = { x: 70, y: 50, width: 1780, height: 980 } as const;
+const MAP_ROTATION = -0.6;
+/** How far the map pushes in on Palm Beach County. */
+const ZOOM = 1.9;
+/** Share of the flown leg the jet covers: it stops just short of the site. */
+const REACH = 0.975;
+/** The jet on the map, nose to tail, px. */
+const JET_LENGTH = 60;
+/** Frames between the keys that carry the jet along its path. */
+const STEP = 2;
+
+/** The eased share of a move at frame `f` of `from`–`to`: smooth start, steady cruise, gentle stop. */
+function cruiseShare(f: number, from: number, to: number): number {
+ const t = Math.min(1, Math.max(0, (f - from) / (to - from)));
+ return t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2;
+}
+
+function mapLayer(
+ id: string,
+ d: string,
+ style: {
+ fill?: string;
+ stroke?: string;
+ width?: number;
+ dash?: string;
+ /** Drawn on from nothing. */
+ drawOn?: boolean;
+ },
+): ReturnType<typeof Layer.shape> {
+ return Layer.shape("path", {
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: MAP.width,
+ height: MAP.height,
+ d,
+ fill: style.fill ?? "transparent",
+ ...(style.fill === undefined && { fillType: "none" as const }),
+ ...(style.stroke && {
+ strokeColor: style.stroke,
+ strokeWidth: style.width ?? 1.5,
+ strokeLineJoin: "round" as const,
+ strokeLineCap: "round" as const,
+ }),
+ ...(style.dash && { strokeDashArray: style.dash }),
+ ...(style.drawOn && { trimEnd: 0 }),
+ });
+}
+
+function placeLabel(
+ id: string,
+ text: string,
+ at: Vec2,
+ o: { size: number; font?: string; color?: string; spacing?: number },
+): ReturnType<typeof Layer.text> {
+ return Layer.text(text, {
+ id,
+ position: "absolute",
+ x: at[0] - 300,
+ y: at[1] - o.size * 0.6,
+ width: 600,
+ align: "center",
+ fontFamily: o.font ?? SANS,
+ fontWeight: 700,
+ fontSize: o.size,
+ letterSpacing: o.spacing ?? o.size * 0.18,
+ fill: o.color ?? INK_FAINT,
+ });
+}
+
+/** A pinned place with its name and what it was to the flight, centred above or below the pin (shifted `dx`). */
+function placeTag(
+ id: string,
+ at: Vec2,
+ name: string,
+ role: string,
+ side: "above" | "below",
+ appear: number,
+ dx = 0,
+): LayoutNode[] {
+ const x = at[0] - 200 + dx;
+ const y = side === "above" ? at[1] - 104 : at[1] + 26;
+ const text = (part: string, content: string, dy: number, style: object) =>
+ Layer.text(content, {
+ id: `${id}-${part}`,
+ position: "absolute",
+ x,
+ y: y + dy,
+ width: 400,
+ align: "center",
+ ...style,
+ }).animate(riseIn(appear + 4 + dy / 10, y + dy, 12, 10));
+ return [
+ text("name", name, 0, {
+ fontFamily: SANS,
+ fontWeight: 800,
+ fontSize: 30,
+ fill: INK,
+ }),
+ text("role", role, 38, {
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 20,
+ letterSpacing: 2,
+ fill: INK_SOFT,
+ }),
+ ];
+}
+
+/** The aircraft's index card, laid on the map while the jet is named. */
+function aircraftCard(t: SceneTiming): LayoutNode {
+ const named = wordIn(t, "route", "learjet").start - 8;
+ const leaves = wordIn(t, "route", "austin").start + 4;
+ const box = { x: 150, y: 640, width: 600, height: 330 };
+ const plane = Layer.box({
+ id: "card-plane",
+ position: "absolute",
+ x: 370,
+ y: 60,
+ width: 200,
+ height: 60,
+ children: jetSide({
+ id: "card-jet",
+ length: 200,
+ color: INK,
+ window: CARD,
+ }),
+ }).animate(riseIn(named + 10, 60, 16, 14));
+ const type = Layer.text("LEARJET 60", {
+ id: "card-type",
+ position: "absolute",
+ x: 40,
+ y: 36,
+ fontFamily: DISPLAY,
+ fontSize: 76,
+ fill: INK,
+ });
+ const specs = Layer.text(
+ "TWIN-ENGINE BUSINESS JET\nBUILT IN 2004\nREGISTRATION N722BD",
+ {
+ id: "card-specs",
+ position: "absolute",
+ x: 42,
+ y: 158,
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 26,
+ lineHeight: 1.6,
+ letterSpacing: 1,
+ fill: INK_SOFT,
+ },
+ );
+ const built = Annotate({
+ ...kit,
+ id: "card-built",
+ target: { text: specs, match: "2004" },
+ mark: "highlight",
+ at: wordIn(t, "route", "2004").start - 2,
+ drawDuration: 10,
+ padding: 4,
+ seed: 5,
+ });
+ return Layer.box({
+ id: "card",
+ position: "absolute",
+ ...box,
+ children: [
+ sheet({
+ id: "card-sheet",
+ x: 0,
+ y: 0,
+ width: box.width,
+ height: box.height,
+ color: CARD,
+ lift: 1.6,
+ children: [
+ Layer.shape("rect", {
+ id: "card-rule",
+ position: "absolute",
+ x: 0,
+ y: 132,
+ width: box.width,
+ height: 2,
+ fill: RED,
+ opacity: 0.6,
+ }),
+ built,
+ type,
+ specs,
+ plane,
+ ],
+ }),
+ tape({ id: "card-tape", x: box.width / 2, y: 0, rotation: 3, seed: 17 }),
+ ],
+ }).animate(
+ layDown(named, { y: box.y, rotation: -3, from: -50 }),
+ LayerAnimation.create()
+ .keys("y", [
+ [leaves, box.y],
+ [leaves + 16, box.y + 520, "power3.in"],
+ ])
+ .keys("rotation", [
+ [leaves, -3],
+ [leaves + 16, -9, "power2.in"],
+ ]),
+ );
+}
+
+export function routeScene(t: SceneTiming): LayoutNode {
+ const geo = mapGeometry(MAP.width, MAP.height, 40);
+ const p = (k: keyof typeof PLACES) => geo.project(PLACES[k]);
+ const austin = p("austin");
+ const eleuthera = p("eleuthera");
+ const site = p("crash");
+ const cruise = lineIn(t, "cruise");
+ const departs = wordIn(t, "route", "austin").start;
+ const bound = wordIn(t, "route", "bahamas").start;
+
+ // The flight: off on "By", along the great circle until the line is read.
+ const flyFrom = cruise.start;
+ const flyTo = cruise.end - sec(0.4);
+ const flown = along(geo.flown);
+ const jetBox = topViewSize(JET_LENGTH);
+ const jetKeys = {
+ x: [] as Array<[number, number]>,
+ y: [] as Array<[number, number]>,
+ rotation: [] as Array<[number, number]>,
+ trim: [] as Array<[number, number]>,
+ };
+ for (let f = flyFrom; f <= flyTo + STEP; f += STEP) {
+ const share = cruiseShare(f, flyFrom, flyTo) * REACH;
+ const { point, heading } = flown.at(share);
+ jetKeys.x.push([f, point[0] - jetBox.width / 2]);
+ jetKeys.y.push([f, point[1] - jetBox.height / 2]);
+ jetKeys.rotation.push([f, heading]);
+ jetKeys.trim.push([f, share]);
+ }
+ const flownLine = mapLayer("route-flown", toPathData(geo.flown), {
+ stroke: RED,
+ width: 5,
+ drawOn: true,
+ }).animate(LayerAnimation.keys("trimEnd", [[0, 0], ...jetKeys.trim]));
+ const planned = mapLayer(
+ "route-planned",
+ toPathData([...geo.flown, ...geo.unflown.slice(1)]),
+ { stroke: INK_SOFT, width: 3, dash: "10 9", drawOn: true },
+ ).animate(
+ LayerAnimation.keys("trimEnd", [
+ [bound - 6, 0],
+ [bound + 30, 1, "power2.inOut"],
+ ]),
+ );
+ const jet = jetTop({
+ id: "route-jet",
+ length: JET_LENGTH,
+ color: INK,
+ at: austin,
+ }).animate(
+ LayerAnimation.create()
+ .keys("x", jetKeys.x)
+ .keys("y", jetKeys.y)
+ .keys("rotation", jetKeys.rotation)
+ .keys("opacity", [
+ [flyFrom - 4, 0],
+ [flyFrom + 2, 1],
+ ]),
+ );
+
+ // Pushes in on the site as Florida is said: the site ends at the sheet's centre.
+ const zoomAt = wordIn(t, "cruise", "florida").start - 6;
+ const cx = MAP.width / 2;
+ const cy = MAP.height / 2;
+ // Between the site and the Bahamas, so the leg it never flew stays in view.
+ const target: Vec2 = [site[0] + 60, site[1] + 20];
+ const camera = LayerAnimation.create()
+ .keys("scale", [
+ [zoomAt, 1],
+ [zoomAt + sec(1.6), ZOOM, "power3.inOut"],
+ ])
+ .keys("x", [
+ [zoomAt, 0],
+ [zoomAt + sec(1.6), -ZOOM * (target[0] - cx), "power3.inOut"],
+ ])
+ .keys("y", [
+ [zoomAt, 0],
+ [zoomAt + sec(1.6), -ZOOM * (target[1] - cy), "power3.inOut"],
+ ]);
+
+ const tagAt = wordIn(t, "cruise", "feet").start - 10;
+ const tag = strip({
+ id: "route-altitude",
+ x: site[0] - 250,
+ y: site[1] + 34,
+ width: 270,
+ height: 58,
+ color: YELLOW,
+ seed: 61,
+ rotation: -3,
+ children: [
+ Layer.text("35,000 FT · EAST", {
+ id: "route-altitude-text",
+ position: "absolute",
+ x: 0,
+ y: 15,
+ width: 270,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 21,
+ fill: INK,
+ }),
+ ],
+ }).animate(popIn(tagAt, 10));
+
+ const labels = [
+ placeLabel("label-texas", "TEXAS", geo.project(LABELS.texas), {
+ size: 44,
+ font: DISPLAY,
+ }),
+ placeLabel("label-florida", "FLORIDA", geo.project(LABELS.florida), {
+ size: 30,
+ font: DISPLAY,
+ }),
+ placeLabel("label-mexico", "MEXICO", geo.project(LABELS.mexico), {
+ size: 22,
+ }),
+ placeLabel("label-cuba", "CUBA", geo.project(LABELS.cuba), { size: 22 }),
+ placeLabel("label-bahamas", "THE BAHAMAS", geo.project(LABELS.bahamas), {
+ size: 18,
+ }),
+ ];
+
+ const content = Layer.box({
+ id: "route-camera",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: MAP.width,
+ height: MAP.height,
+ children: [
+ mapLayer("map-countries", geo.countries, { fill: LAND }),
+ mapLayer("map-states", geo.states, { fill: LAND }),
+ mapLayer("map-home", geo.home, { fill: LAND_HOME }),
+ mapLayer("map-state-lines", geo.stateLines, {
+ stroke: BORDER,
+ width: 1.4,
+ }),
+ mapLayer("map-country-lines", geo.countryLines, {
+ stroke: BORDER,
+ width: 1.6,
+ }),
+ mapLayer("map-coasts", geo.coasts, { stroke: INK_SOFT, width: 1.6 }),
+ ...labels,
+ planned,
+ flownLine,
+ pin({ id: "pin-austin", at: austin }).animate(popIn(departs - 2)),
+ pin({ id: "pin-eleuthera", at: eleuthera, color: SHEET }).animate(
+ popIn(bound + 24),
+ ),
+ ...placeTag(
+ "tag-austin",
+ austin,
+ "AUSTIN, TEXAS",
+ "DEPARTED",
+ "above",
+ departs,
+ ),
+ ...placeTag(
+ "tag-eleuthera",
+ eleuthera,
+ "NORTH ELEUTHERA",
+ "DESTINATION",
+ "below",
+ bound + 24,
+ -90,
+ ),
+ jet,
+ tag,
+ ],
+ }).animate(camera);
+
+ const map = sheet({
+ id: "route-map",
+ ...MAP,
+ rotation: MAP_ROTATION,
+ color: SEA,
+ lift: 1.2,
+ children: [
+ content,
+ Layer.text("APPROXIMATE ROUTE", {
+ id: "route-note",
+ position: "absolute",
+ x: MAP.width - 330,
+ y: MAP.height - 52,
+ width: 300,
+ align: "end",
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 18,
+ letterSpacing: 2,
+ fill: INK_SOFT,
+ }),
+ ],
+ });
+ return sceneRoot(t, { stage: [map, aircraftCard(t)], push: 1.02 });
+}
diff --git a/examples/33_news_explainer/src/scenes/shell.ts b/examples/33_news_explainer/src/scenes/shell.ts
new file mode 100644
index 00000000..bed6bb37
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/shell.ts
@@ -0,0 +1,79 @@
+/**
+ * What every scene shares: the desk it is laid on, a stage that drifts in
+ * slowly for the scene's whole length, and the tokens the registry
+ * components (Annotate, Counter, TextReveal) draw with.
+ */
+import { Layer, type LayoutNode } from "framefields";
+import type { ThemeInput } from "framefields/components";
+import { desk, drift } from "../paper.js";
+import {
+ DISPLAY,
+ FPS,
+ H,
+ HAND,
+ INK,
+ INK_SOFT,
+ MONO,
+ PAPER,
+ RED,
+ SANS,
+ SHADOW,
+ SHEET,
+ W,
+ YELLOW,
+} from "../theme.js";
+import type { SceneTiming } from "../timeline.js";
+
+export const FILM_THEME: ThemeInput = {
+ mode: "light",
+ color: {
+ bg: PAPER,
+ surface: SHEET,
+ ink: INK,
+ muted: INK_SOFT,
+ accent: RED,
+ highlight: YELLOW,
+ shadow: SHADOW,
+ },
+ font: { display: DISPLAY, body: SANS, mono: MONO, hand: HAND },
+};
+
+/** Props every component in the film takes. */
+export const kit = { theme: FILM_THEME, fps: FPS } as const;
+
+/**
+ * A scene: the desk, then a stage pushing in by `push` over the scene's
+ * length, then anything that must stay put above the drift.
+ */
+export function sceneRoot(
+ t: SceneTiming,
+ o: {
+ stage: LayoutNode[];
+ fixed?: LayoutNode[];
+ push?: number;
+ background?: LayoutNode;
+ },
+): LayoutNode {
+ return Layer.box({
+ id: t.id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ overflow: "hidden",
+ children: [
+ o.background ?? desk(`${t.id}-desk`),
+ Layer.box({
+ id: `${t.id}-stage`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: W,
+ height: H,
+ children: o.stage,
+ }).animate(drift(t.duration, o.push ?? 1.04)),
+ ...(o.fixed ?? []),
+ ],
+ });
+}
diff --git a/examples/33_news_explainer/src/scenes/storm.ts b/examples/33_news_explainer/src/scenes/storm.ts
new file mode 100644
index 00000000..14910e18
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/storm.ts
@@ -0,0 +1,507 @@
+/**
+ * The weather, as a cross-section on graph paper: altitude up the side, the
+ * jet cruising at 35,000 ft, and a thunderstorm over Palm Beach County that
+ * grows puff by puff to an anvil near 44,000 ft as it is described. The
+ * forecasters' warning is pinned item by item as it is read; then the crew's
+ * report, and the 2,000 ft climb they asked for.
+ */
+import { Color, Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { rng, type Vec2 } from "framefields/components";
+import { Annotate } from "../components/annotate/index.js";
+import { jetSide, sideView } from "../jet.js";
+import { layDown, popIn, riseIn, sheet, strip, tape } from "../paper.js";
+import {
+ CARD,
+ DISPLAY,
+ INK,
+ INK_FAINT,
+ INK_SOFT,
+ MONO,
+ RED,
+ SHEET,
+ STORM,
+ STORM_LIGHT,
+ sec,
+} from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const PAPER_BOX = { x: 70, y: 50, width: 1780, height: 980 } as const;
+const GRID = 40;
+const GRID_INK = "#c7d4da";
+/** Where the ground is, and how many px a thousand feet climbs. */
+const GROUND = 840;
+const PER_KFT = 14;
+const AXIS_X = 190;
+const RIGHT = PAPER_BOX.width - 60;
+const alt = (feet: number) => GROUND - (feet / 1000) * PER_KFT;
+
+const JET_LENGTH = 200;
+const JET_X = 360;
+
+function gridPath(): string {
+ const lines: string[] = [];
+ for (let x = GRID; x < PAPER_BOX.width; x += GRID)
+ lines.push(`M${x} 0 L${x} ${PAPER_BOX.height}`);
+ for (let y = GRID; y < PAPER_BOX.height; y += GRID)
+ lines.push(`M0 ${y} L${PAPER_BOX.width} ${y}`);
+ return lines.join(" ");
+}
+
+const line = (
+ id: string,
+ d: string,
+ color: string,
+ width: number,
+ extra: Record<string, unknown> = {},
+) =>
+ Layer.shape("path", {
+ id,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: PAPER_BOX.width,
+ height: PAPER_BOX.height,
+ d,
+ fillType: "none",
+ fill: "transparent",
+ strokeColor: color,
+ strokeWidth: width,
+ strokeLineCap: "round",
+ ...extra,
+ });
+
+function axis(): LayoutNode[] {
+ const ticks = [0, 10, 20, 30, 40, 50];
+ return [
+ line("storm-axis", `M${AXIS_X} ${alt(52000)} L${AXIS_X} ${GROUND}`, INK, 3),
+ ...ticks.flatMap((k) => [
+ line(
+ `storm-tick-${k}`,
+ `M${AXIS_X - 12} ${alt(k * 1000)} L${AXIS_X} ${alt(k * 1000)}`,
+ INK,
+ 3,
+ ),
+ Layer.text(k === 0 ? "GROUND" : `${k},000 FT`, {
+ id: `storm-tick-label-${k}`,
+ position: "absolute",
+ x: 0,
+ y: alt(k * 1000) - 12,
+ width: AXIS_X - 22,
+ align: "end",
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 19,
+ fill: INK_SOFT,
+ }),
+ ]),
+ ];
+}
+
+interface Puff {
+ x: number;
+ y: number;
+ r: number;
+ /** 0 at the base, 1 at the top: the order it grows in. */
+ h: number;
+ lit: boolean;
+}
+
+/** The thunderstorm as puffs: a base, a tower and an anvil spread at the top. */
+function stormPuffs(): Puff[] {
+ const r = rng(44);
+ const puffs: Puff[] = [];
+ const cx = 1230;
+ const base = alt(5000);
+ const top = alt(44000);
+ // The base: a broad, low row.
+ for (let x = cx - 330; x <= cx + 330; x += 70)
+ puffs.push({
+ x: x + r.spread(14),
+ y: base - r.range(0, 30),
+ r: r.range(70, 92),
+ h: 0,
+ lit: false,
+ });
+ // The tower: narrowing columns rising to the anvil.
+ for (let y = base - 80; y > top + 110; y -= 62) {
+ const h = (base - y) / (base - top);
+ const half = 250 - 110 * h;
+ for (let x = cx - half; x <= cx + half; x += 95)
+ puffs.push({
+ x: x + r.spread(26),
+ y: y + r.spread(18),
+ r: r.range(78, 112) * (1 - 0.25 * h),
+ h,
+ lit: x < cx - half * 0.2,
+ });
+ }
+ // The anvil: wide and flat, leaning downwind.
+ for (let x = cx - 420; x <= cx + 470; x += 64)
+ puffs.push({
+ x: x + r.spread(10),
+ y: top + 58 + Math.abs(x - cx) * 0.06 + r.spread(10),
+ r: r.range(42, 60),
+ h: 1,
+ lit: x < cx,
+ });
+ return puffs;
+}
+
+function storm(grow: number, tops: number): LayoutNode[] {
+ const puffs = stormPuffs();
+ const span = tops - grow;
+ const at = (p: Puff) => Math.round(grow + p.h * span);
+ const shadow = puffs.map((p, i) =>
+ Layer.shape("circle", {
+ id: `storm-puff-${i}`,
+ position: "absolute",
+ x: p.x - p.r,
+ y: p.y - p.r,
+ width: p.r * 2,
+ height: p.r * 2,
+ fill: STORM,
+ }).animate(popIn(at(p), 14)),
+ );
+ const light = puffs
+ .filter((p) => p.lit)
+ .map((p, i) =>
+ Layer.shape("circle", {
+ id: `storm-lit-${i}`,
+ position: "absolute",
+ x: p.x - p.r * 0.75 - p.r * 0.18,
+ y: p.y - p.r * 0.75 - p.r * 0.22,
+ width: p.r * 1.5,
+ height: p.r * 1.5,
+ fill: STORM_LIGHT,
+ opacity: 0.85,
+ }).animate(popIn(at(p) + 4, 14)),
+ );
+ const rain: string[] = [];
+ const r = rng(7);
+ for (let x = 940; x < 1540; x += 26) {
+ const y0 = alt(4200) + r.range(0, 30);
+ rain.push(`M${x} ${y0} L${x - 22} ${GROUND - 6}`);
+ }
+ const rainAt = grow + 18;
+ return [
+ line("storm-rain", rain.join(" "), STORM_LIGHT, 3, { opacity: 0 }).animate(
+ LayerAnimation.keys("opacity", [
+ [rainAt, 0],
+ [rainAt + 12, 0.8],
+ ]),
+ ),
+ ...shadow,
+ ...light,
+ ];
+}
+
+/** A horizontal reference line across the plot with its name at the left end, above or below it. */
+function level(
+ id: string,
+ feet: number,
+ text: string,
+ color: string,
+ appear: number,
+ side: "above" | "below" = "above",
+): LayoutNode[] {
+ const y = alt(feet);
+ const labelY = side === "above" ? y - 34 : y + 20;
+ return [
+ line(id, `M${AXIS_X} ${y} L${RIGHT} ${y}`, color, 2.5, {
+ strokeDashArray: "12 10",
+ trimEnd: 0,
+ }).animate(
+ LayerAnimation.keys("trimEnd", [
+ [appear, 0],
+ [appear + 24, 1, "power2.inOut"],
+ ]),
+ ),
+ Layer.text(text, {
+ id: `${id}-label`,
+ position: "absolute",
+ x: AXIS_X + 16,
+ y: labelY,
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 20,
+ letterSpacing: 1.5,
+ fill: color,
+ }).animate(riseIn(appear + 6, labelY, 12, 8)),
+ ];
+}
+
+/** The forecasters' warning, one hazard per word. */
+function warning(t: SceneTiming): LayoutNode {
+ const warned = lineIn(t, "warned");
+ const box = { x: 230, y: 470, width: 560, height: 270 };
+ const items: Array<[string, string]> = [
+ ["SEVERE TURBULENCE", "turbulence"],
+ ["ICING", "icing"],
+ ["HAIL", "hail"],
+ ];
+ const rows = items.flatMap(([label, word], i) => {
+ const at = wordIn(t, "warned", word).start - 3;
+ const y = 112 + i * 48;
+ return [
+ Layer.shape("rect", {
+ id: `warning-box-${i}`,
+ position: "absolute",
+ x: 36,
+ y: y + 4,
+ width: 24,
+ height: 24,
+ fill: "transparent",
+ strokeColor: INK,
+ strokeWidth: 3,
+ }),
+ Layer.shape("path", {
+ id: `warning-check-${i}`,
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: box.width,
+ height: box.height,
+ d: `M40 ${y + 16} L49 ${y + 26} L66 ${y - 2}`,
+ fillType: "none",
+ fill: "transparent",
+ strokeColor: RED,
+ strokeWidth: 5,
+ strokeLineCap: "round",
+ strokeLineJoin: "round",
+ trimEnd: 0,
+ }).animate(
+ LayerAnimation.keys("trimEnd", [
+ [at, 0],
+ [at + 8, 1, "power2.out"],
+ ]),
+ ),
+ Layer.text(label, {
+ id: `warning-item-${i}`,
+ position: "absolute",
+ x: 84,
+ y,
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 28,
+ fill: INK,
+ }).animate(riseIn(at, y, 10, 8)),
+ ];
+ });
+ return Layer.box({
+ id: "warning",
+ position: "absolute",
+ ...box,
+ children: [
+ sheet({
+ id: "warning-sheet",
+ x: 0,
+ y: 0,
+ width: box.width,
+ height: box.height,
+ color: CARD,
+ lift: 1.5,
+ children: [
+ Layer.shape("rect", {
+ id: "warning-band",
+ position: "absolute",
+ x: 0,
+ y: 0,
+ width: box.width,
+ height: 86,
+ fill: RED,
+ }),
+ Layer.text("WEATHER WARNING", {
+ id: "warning-title",
+ position: "absolute",
+ x: 32,
+ y: 14,
+ fontFamily: DISPLAY,
+ fontSize: 48,
+ letterSpacing: 1,
+ fill: SHEET,
+ }),
+ Layer.text("SIGMET IN EFFECT", {
+ id: "warning-kind",
+ position: "absolute",
+ x: 340,
+ y: 34,
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 18,
+ letterSpacing: 2,
+ fill: SHEET,
+ }),
+ ...rows,
+ ],
+ }),
+ tape({
+ id: "warning-tape",
+ x: 60,
+ y: 6,
+ rotation: -24,
+ seed: 23,
+ width: 120,
+ }),
+ ],
+ }).animate(
+ layDown(warned.start - 8, { y: box.y, rotation: -2.5, from: -60 }),
+ );
+}
+
+export function stormScene(t: SceneTiming): LayoutNode {
+ const grow = wordIn(t, "storm", "thunderstorm").start;
+ const tops = wordIn(t, "storm", "tops").start + 6;
+ const reported = wordIn(t, "climb", "reported").start;
+ const asked = wordIn(t, "climb", "climb").start - 4;
+ const view = sideView(JET_LENGTH);
+ const jet = Layer.box({
+ id: "storm-plane",
+ position: "absolute",
+ x: JET_X,
+ y: alt(35000) - view.axisY,
+ width: view.width,
+ height: view.height,
+ children: jetSide({
+ id: "storm-jet",
+ length: JET_LENGTH,
+ color: INK,
+ window: SHEET,
+ }),
+ }).animate(
+ LayerAnimation.create()
+ .keys("x", [
+ [0, -260],
+ [sec(1.4), JET_X - 40, "expo.out"],
+ [t.duration, JET_X + 110, "none"],
+ ])
+ .wiggle("y", { frequency: 0.6, amplitude: 3, seed: 5 }),
+ );
+ const nose: Vec2 = [JET_X + JET_LENGTH + 40, alt(35000) - 8];
+ const climbTo: Vec2 = [JET_X + JET_LENGTH + 250, alt(37000) - 4];
+ const climbArrow = Annotate({
+ ...kit,
+ id: "storm-climb",
+ target: { x: climbTo[0], y: climbTo[1] - 6, width: 12, height: 12 },
+ from: { x: nose[0], y: nose[1], width: 1, height: 1 },
+ mark: "arrow",
+ curve: "arc",
+ color: RED,
+ texture: "ink",
+ width: 4,
+ at: asked,
+ drawDuration: 14,
+ padding: 0,
+ seed: 8,
+ });
+ const report = strip({
+ id: "storm-report",
+ x: JET_X - 40,
+ y: alt(35000) - 170,
+ width: 330,
+ height: 64,
+ color: SHEET,
+ seed: 91,
+ rotation: -2,
+ children: [
+ Layer.text("CREW: ICE, TURBULENCE", {
+ id: "storm-report-text",
+ position: "absolute",
+ x: 0,
+ y: 18,
+ width: 330,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 800,
+ fontSize: 22,
+ fill: INK,
+ }),
+ ],
+ }).animate(popIn(reported, 10));
+ const topsNote = Annotate({
+ ...kit,
+ id: "storm-tops-note",
+ target: { x: 1180, y: alt(44000) - 6, width: 60, height: 20 },
+ from: { x: 900, y: alt(50500), width: 1, height: 1 },
+ mark: "arrow",
+ curve: "swoop",
+ color: INK,
+ texture: "marker",
+ width: 4,
+ at: tops + 6,
+ drawDuration: 14,
+ padding: 4,
+ label: { text: "storm tops ≈ 44,000 ft", size: 34 },
+ seed: 12,
+ });
+ const ground = [
+ Layer.shape("rect", {
+ id: "storm-ground",
+ position: "absolute",
+ x: AXIS_X,
+ y: GROUND,
+ width: RIGHT - AXIS_X,
+ height: 46,
+ fill: "#cdbf9c",
+ }),
+ Layer.text("PALM BEACH COUNTY", {
+ id: "storm-ground-label",
+ position: "absolute",
+ x: 1000,
+ y: GROUND + 58,
+ width: 460,
+ align: "center",
+ fontFamily: MONO,
+ fontWeight: 700,
+ fontSize: 22,
+ letterSpacing: 3,
+ fill: INK_SOFT,
+ }),
+ ];
+ const paper = sheet({
+ id: "storm-paper",
+ ...PAPER_BOX,
+ rotation: 0.5,
+ color: "#f7f4ec",
+ lift: 1.2,
+ children: [
+ line("storm-grid", gridPath(), GRID_INK, 1.2, { opacity: 0.8 }),
+ ...axis(),
+ ...ground,
+ ...storm(grow, tops),
+ ...level(
+ "storm-cruise",
+ 35000,
+ "CRUISING · 35,000 FT",
+ INK,
+ sec(0.6),
+ "below",
+ ),
+ ...level("storm-tops", 44000, "", Color.alpha(INK_FAINT, 0.9), tops),
+ ...level(
+ "storm-climb-level",
+ 37000,
+ "REQUESTED · 37,000 FT",
+ RED,
+ asked + 6,
+ ),
+ jet,
+ report,
+ climbArrow,
+ topsNote,
+ Layer.text("Not to scale horizontally", {
+ id: "storm-note",
+ position: "absolute",
+ x: PAPER_BOX.width - 420,
+ y: PAPER_BOX.height - 48,
+ width: 380,
+ align: "end",
+ fontFamily: MONO,
+ fontWeight: 600,
+ fontSize: 17,
+ fill: INK_SOFT,
+ }),
+ ],
+ });
+ return sceneRoot(t, { stage: [paper, warning(t)], push: 1.03 });
+}
diff --git a/examples/33_news_explainer/src/scenes/title.ts b/examples/33_news_explainer/src/scenes/title.ts
new file mode 100644
index 00000000..c0652c0c
--- /dev/null
+++ b/examples/33_news_explainer/src/scenes/title.ts
@@ -0,0 +1,90 @@
+/**
+ * The title: a yellow strip torn off the roll, "WHAT WE KNOW" slammed onto
+ * it as the question is asked, what it is about on a white strip below, and
+ * a stamp dating what the film can know.
+ */
+import { Layer, LayerAnimation, type LayoutNode } from "framefields";
+import { TextReveal } from "../components/text-reveal/index.js";
+import { stamp, stampIn, strip } from "../paper.js";
+import { DISPLAY, INK, SANS, SHEET, W, YELLOW } from "../theme.js";
+import { lineIn, type SceneTiming, wordIn } from "../timeline.js";
+import { kit, sceneRoot } from "./shell.js";
+
+const BAND = { x: -60, y: 330, width: W + 120, height: 300 } as const;
+
+export function titleScene(t: SceneTiming): LayoutNode {
+ const know = lineIn(t, "know");
+ const title = TextReveal({
+ ...kit,
+ id: "title-text",
+ text: "WHAT WE KNOW",
+ style: "slam",
+ by: "word",
+ stagger: 5,
+ fontFamily: DISPLAY,
+ fontSize: 236,
+ fill: INK,
+ align: "center",
+ position: "absolute",
+ x: 60,
+ y: 14,
+ width: W,
+ at: wordIn(t, "know", "what").start,
+ });
+ const band = strip({
+ id: "title-band",
+ ...BAND,
+ color: YELLOW,
+ seed: 41,
+ rotation: -2,
+ children: [title],
+ }).animate(
+ LayerAnimation.create().keys("x", [
+ [0, BAND.x - W],
+ [know.start - 2, BAND.x, "expo.out"],
+ ]),
+ );
+ const subtitle = strip({
+ id: "title-sub",
+ x: 520,
+ y: 660,
+ width: 880,
+ height: 96,
+ color: SHEET,
+ seed: 77,
+ rotation: 1.2,
+ children: [
+ Layer.text("about the jet crash in Palm Beach County, Florida", {
+ id: "title-sub-text",
+ position: "absolute",
+ x: 0,
+ y: 26,
+ width: 880,
+ align: "center",
+ fontFamily: SANS,
+ fontWeight: 600,
+ fontSize: 36,
+ fill: INK,
+ }),
+ ],
+ }).animate(
+ LayerAnimation.create()
+ .keys("opacity", [
+ [wordIn(t, "know", "happened").start - 6, 0],
+ [wordIn(t, "know", "happened").start, 1],
+ ])
+ .keys("y", [
+ [wordIn(t, "know", "happened").start - 6, 700],
+ [wordIn(t, "know", "happened").start + 10, 660, "expo.out"],
+ ]),
+ );
+ const asOf = stamp({
+ id: "title-stamp",
+ text: "AS OF NOV. 2, 2026",
+ x: 1360,
+ y: 210,
+ rotation: 6,
+ fontSize: 30,
+ }).animate(stampIn(know.end - 4));
+ return sceneRoot(t, { stage: [band, subtitle, asOf], push: 1.03 });
+}
diff --git a/examples/33_news_explainer/src/spoken.ts b/examples/33_news_explainer/src/spoken.ts
new file mode 100644
index 00000000..920b6572
--- /dev/null
+++ b/examples/33_news_explainer/src/spoken.ts
@@ -0,0 +1,78 @@
+/**
+ * Text as it is spoken, for comparing a script with a transcript: the
+ * transcriber writes "35,000" where the script says "thirty-five thousand",
+ * and the script writes "2004" where the voice says "two thousand four".
+ */
+
+const ONES = [
+ "zero",
+ "one",
+ "two",
+ "three",
+ "four",
+ "five",
+ "six",
+ "seven",
+ "eight",
+ "nine",
+ "ten",
+ "eleven",
+ "twelve",
+ "thirteen",
+ "fourteen",
+ "fifteen",
+ "sixteen",
+ "seventeen",
+ "eighteen",
+ "nineteen",
+];
+const TENS = [
+ "",
+ "",
+ "twenty",
+ "thirty",
+ "forty",
+ "fifty",
+ "sixty",
+ "seventy",
+ "eighty",
+ "ninety",
+];
+
+function underThousand(n: number): string[] {
+ const words: string[] = [];
+ const hundreds = Math.floor(n / 100);
+ const rest = n % 100;
+ if (hundreds > 0) words.push(ONES[hundreds] ?? "", "hundred");
+ if (rest >= 20) {
+ words.push(TENS[Math.floor(rest / 10)] ?? "");
+ if (rest % 10 > 0) words.push(ONES[rest % 10] ?? "");
+ } else if (rest > 0 || words.length === 0) words.push(ONES[rest] ?? "");
+ return words;
+}
+
+/** A whole number below a million, in words ("2004" → "two thousand four"). */
+export function numberWords(n: number): string {
+ if (!Number.isInteger(n) || n < 0 || n >= 1_000_000)
+ throw new Error(`numberWords: ${n} is out of range`);
+ const thousands = Math.floor(n / 1000);
+ const rest = n % 1000;
+ const words = thousands > 0 ? [...underThousand(thousands), "thousand"] : [];
+ if (rest > 0 || thousands === 0) words.push(...underThousand(rest));
+ return words.join(" ");
+}
+
+/**
+ * Lowercase words with numbers spelled out, punctuation and hyphens gone, and
+ * no "and" (said inside numbers, "three hundred and forty", or not).
+ */
+export function spokenWords(s: string): string {
+ return s
+ .toLowerCase()
+ .replace(/(\d),(\d{3})/g, "$1$2")
+ .replace(/\d+/g, (digits) => ` ${numberWords(Number(digits))} `)
+ .replace(/[^a-z' ]/g, " ")
+ .split(/\s+/)
+ .filter((w) => w && w !== "and")
+ .join(" ");
+}
diff --git a/examples/33_news_explainer/src/theme.ts b/examples/33_news_explainer/src/theme.ts
new file mode 100644
index 00000000..7a27becf
--- /dev/null
+++ b/examples/33_news_explainer/src/theme.ts
@@ -0,0 +1,47 @@
+/**
+ * Tokens for the explainer: paper, ink, one highlighter and one warning red,
+ * four faces, an 8 px grid and one clock. Everything on screen reads from here.
+ */
+
+export const W = 1920;
+export const H = 1080;
+export const FPS = 30;
+export const OUTPUT = new URL("../output/", import.meta.url).pathname;
+export const ASSETS = new URL("../assets/", import.meta.url).pathname;
+export const FONTS = `${ASSETS}fonts/`;
+
+/** Seconds → frames. */
+export const sec = (s: number) => Math.round(s * FPS);
+/** The spacing grid. */
+export const space = (n: number) => n * 8;
+
+/** The desk every scene is pinned to, and the sheets laid on it. */
+export const PAPER = "#efe8da";
+export const PAPER_DEEP = "#e2d8c4";
+export const SHEET = "#f8f4ec";
+export const CARD = "#fbf8f2";
+/** Type and line work. */
+export const INK = "#171614";
+export const INK_SOFT = "#4b4740";
+export const INK_FAINT = "#8a8478";
+/** The highlighter, and the one color that means danger. */
+export const YELLOW = "#f7d94c";
+export const RED = "#d23f2a";
+/** The map: water, land, borders. */
+export const SEA = "#c4d5d3";
+export const LAND = "#ebe3d1";
+export const LAND_HOME = "#f6efdf";
+export const BORDER = "#b9ae98";
+/** The storm. */
+export const STORM = "#4a5560";
+export const STORM_LIGHT = "#7d8994";
+export const SHADOW = "#2b2418";
+
+/** Headlines: tall condensed caps. */
+export const DISPLAY = "Anton";
+/** Body copy and labels. */
+export const SANS = "Libre Franklin";
+/** Data, stamps, times. */
+export const MONO = "JetBrains Mono";
+/** The hand that writes notes in the margins. */
+export const HAND = "Permanent Marker";
diff --git a/examples/33_news_explainer/src/timeline.ts b/examples/33_news_explainer/src/timeline.ts
new file mode 100644
index 00000000..c4e9d986
--- /dev/null
+++ b/examples/33_news_explainer/src/timeline.ts
@@ -0,0 +1,240 @@
+/**
+ * The film's clock: eight scenes, each owning the lines read over it. Lines
+ * follow each other with a breath between them (longer where a picture has
+ * to land first), so every start comes from the measured voice lengths in
+ * assets/audio.json. Scene starts mirror `Layer.sequence`: each overlaps the
+ * one before by its transition.
+ */
+import { Transition, type TransitionSpec } from "framefields";
+import type { AudioManifest, LineId } from "./audio.js";
+import { FPS, sec } from "./theme.js";
+
+export type SceneId =
+ | "open"
+ | "title"
+ | "route"
+ | "storm"
+ | "dive"
+ | "ground"
+ | "probe"
+ | "close";
+
+interface ScenePlan {
+ id: SceneId;
+ lines: LineId[];
+ /** How the scene arrives from the one before. */
+ transition: TransitionSpec;
+ /** Frames from the scene's start to its first line. */
+ lead: number;
+ /** Frames from its last line's end to its own end (the next transition included). */
+ tail: number;
+ /** Extra frames of silence before a line, where a picture lands first. */
+ pause?: Partial<Record<LineId, number>>;
+}
+
+/** The breath between two lines of one scene, after the take's own 0.3 s tail. */
+export const BREATH = sec(0.15);
+
+export const SCENES: ScenePlan[] = [
+ {
+ id: "open",
+ lines: ["fell", "nine"],
+ transition: Transition.cut(),
+ lead: sec(1.0),
+ tail: sec(0.9),
+ pause: { nine: sec(0.4) },
+ },
+ {
+ id: "title",
+ lines: ["know"],
+ transition: Transition.slide("left", sec(0.6)),
+ lead: sec(0.6),
+ tail: sec(1.1),
+ },
+ {
+ id: "route",
+ lines: ["route", "cruise"],
+ transition: Transition.push("up", sec(0.7)),
+ lead: sec(0.8),
+ tail: sec(1.0),
+ pause: { cruise: sec(0.3) },
+ },
+ {
+ id: "storm",
+ lines: ["storm", "warned", "climb"],
+ transition: Transition.whip("left", sec(0.5)),
+ lead: sec(0.7),
+ tail: sec(1.0),
+ pause: { warned: sec(0.2), climb: sec(0.3) },
+ },
+ {
+ id: "dive",
+ lines: ["fall", "minute", "rate", "speed", "mayday"],
+ transition: Transition.cut(),
+ lead: sec(0.3),
+ tail: sec(1.3),
+ pause: { minute: sec(0.4), speed: sec(0.2), mayday: sec(0.4) },
+ },
+ {
+ id: "ground",
+ lines: ["road", "crater", "ground"],
+ transition: Transition.fadeThrough(sec(0.8)),
+ lead: sec(0.8),
+ tail: sec(1.0),
+ pause: { ground: sec(0.3) },
+ },
+ {
+ id: "probe",
+ lines: ["ntsb", "breakup", "report"],
+ transition: Transition.slide("up", sec(0.6)),
+ lead: sec(0.7),
+ tail: sec(1.0),
+ pause: { report: sec(0.3) },
+ },
+ {
+ id: "close",
+ lines: ["question"],
+ transition: Transition.wipe("right", sec(0.6)),
+ lead: sec(0.7),
+ tail: sec(4.0),
+ },
+];
+
+export interface LineCue {
+ id: LineId;
+ /** Composition frames. */
+ start: number;
+ end: number;
+}
+
+/** A line in scene-local frames, with each word heard in it. */
+export interface LocalLine {
+ start: number;
+ end: number;
+ words: Array<{ text: string; start: number; end: number }>;
+}
+
+export interface SceneTiming {
+ id: SceneId;
+ start: number;
+ duration: number;
+ transition: TransitionSpec;
+ /** The scene's lines, in scene-local frames. */
+ lines: Record<string, LocalLine>;
+}
+
+export interface Timeline {
+ scenes: SceneTiming[];
+ /** Every line, in composition frames, in the order heard. */
+ lines: LineCue[];
+ total: number;
+}
+
+const frames = (seconds: number) => Math.ceil(seconds * FPS);
+
+export function planTimeline(voice: AudioManifest["voice"]): Timeline {
+ const scenes: SceneTiming[] = [];
+ const lines: LineCue[] = [];
+ let end = 0;
+ for (const plan of SCENES) {
+ const start = Math.max(0, end - plan.transition.frames);
+ const local: SceneTiming["lines"] = {};
+ let cursor = plan.lead;
+ plan.lines.forEach((id, i) => {
+ if (i > 0) cursor += BREATH;
+ cursor += plan.pause?.[id] ?? 0;
+ const length = frames(voice[id].seconds);
+ const at = cursor;
+ local[id] = {
+ start: at,
+ end: at + length,
+ words: voice[id].words.map((w) => ({
+ text: w.text,
+ start: at + Math.round(w.start * FPS),
+ end: at + Math.round(w.end * FPS),
+ })),
+ };
+ lines.push({ id, start: start + cursor, end: start + cursor + length });
+ cursor += length;
+ });
+ const duration = cursor + plan.tail;
+ scenes.push({
+ id: plan.id,
+ start,
+ duration,
+ transition: plan.transition,
+ lines: local,
+ });
+ end = start + duration;
+ }
+ return { scenes, lines, total: end };
+}
+
+/** One scene's timing, or a throw naming the scene. */
+export function sceneTiming(t: Timeline, id: SceneId): SceneTiming {
+ const scene = t.scenes.find((s) => s.id === id);
+ if (!scene) throw new Error(`No scene "${id}" in the timeline.`);
+ return scene;
+}
+
+/** Where a scene's line starts and ends, scene-local. */
+export function lineIn(scene: SceneTiming, id: LineId): LocalLine {
+ const line = scene.lines[id];
+ if (!line)
+ throw new Error(`Line "${id}" is not read in scene "${scene.id}".`);
+ return line;
+}
+
+const bare = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
+
+/**
+ * The scene-local frame `word` is said in line `id` (its `nth` occurrence),
+ * so a picture lands on the word rather than somewhere in its sentence.
+ */
+export function wordIn(
+ scene: SceneTiming,
+ id: LineId,
+ word: string,
+ nth = 0,
+): { start: number; end: number } {
+ const matches = lineIn(scene, id).words.filter(
+ (w) => bare(w.text) === bare(word),
+ );
+ const hit = matches[nth];
+ if (!hit)
+ throw new Error(`"${word}" is not heard in line "${id}" (${scene.id}).`);
+ return hit;
+}
+
+/** Music level between lines, and under them. */
+const BED = 0.42;
+const DUCKED = 0.16;
+/** Lines closer than this keep the music down between them. */
+const BRIDGE = sec(1.2);
+
+/** The music's volume: down under every line, up between scenes, out by the end. */
+export function ducking(
+ lines: LineCue[],
+ total: number,
+): Array<[number, number, string?]> {
+ const keys: Array<[number, number, string?]> = [
+ [0, 0],
+ [sec(0.8), BED, "power2.out"],
+ ];
+ let i = 0;
+ while (i < lines.length) {
+ const start = lines[i]?.start ?? 0;
+ let end = lines[i]?.end ?? 0;
+ while (i + 1 < lines.length && (lines[i + 1]?.start ?? 0) - end < BRIDGE)
+ end = lines[++i]?.end ?? end;
+ keys.push(
+ [Math.max(sec(0.8), start - 8), BED, "hold"],
+ [start, DUCKED, "power2.out"],
+ [end, DUCKED, "hold"],
+ [end + sec(0.5), BED, "power2.inOut"],
+ );
+ i++;
+ }
+ keys.push([total - sec(3), BED, "hold"], [total, 0, "power2.in"]);
+ return keys;
+}
diff --git a/examples/33_news_explainer/tsconfig.dev.json b/examples/33_news_explainer/tsconfig.dev.json
new file mode 100644
index 00000000..c5e4355b
--- /dev/null
+++ b/examples/33_news_explainer/tsconfig.dev.json
@@ -0,0 +1,9 @@
+{
+ "extends": "./tsconfig.json",
+ "include": [
+ "src/**/*",
+ "../../nodes/**/*",
+ "../../packages/**/*",
+ "../../node_modules/@framefields/**/*"
+ ]
+}
diff --git a/examples/33_news_explainer/tsconfig.json b/examples/33_news_explainer/tsconfig.json
new file mode 100644
index 00000000..999801f9
--- /dev/null
+++ b/examples/33_news_explainer/tsconfig.json
@@ -0,0 +1,10 @@
+{
+ "extends": "@framefields/tsconfig/base.json",
+ "compilerOptions": {
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "target": "ES2022",
+ "noEmit": true
+ },
+ "include": ["src/**/*"]
+}
diff --git a/examples/33_news_explainer/vitest.config.ts b/examples/33_news_explainer/vitest.config.ts
new file mode 100644
index 00000000..be6fcdda
--- /dev/null
+++ b/examples/33_news_explainer/vitest.config.ts
@@ -0,0 +1,6 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: { include: ["src/**/*.test.ts"], pool: "forks" },
+ resolve: { conditions: ["development"] },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c42ed31b..58702133 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -523,6 +523,52 @@ importers:
specifier: ^4.1.11
+ examples/33_news_explainer:
+ dependencies:
+ framefields:
+ specifier: workspace:*
+ version: link:../../packages/framefields
+ devDependencies:
+ '@framefields/tsconfig':
+ specifier: workspace:*
+ version: link:../../packages/tsconfig
+ '@types/d3-geo':
+ specifier: 3.1.0
+ version: 3.1.0
+ '@types/geojson':
+ specifier: ^7946.0.16
+ version: 7946.0.16
+ '@types/node':
+ specifier: ^24.1.0
+ version: 24.10.14
+ '@types/topojson-client':
+ specifier: 3.1.5
+ version: 3.1.5
+ '@types/topojson-specification':
+ specifier: ^1.0.5
+ version: 1.0.5
+ d3-geo:
+ specifier: 3.1.1
+ version: 3.1.1
+ topojson-client:
+ specifier: 3.1.0
+ version: 3.1.0
+ tsx:
+ specifier: ^4.20.3
+ version: 4.21.0
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+ us-atlas:
+ specifier: 3.0.1
+ version: 3.0.1
+ vitest:
+ specifier: ^4.1.11
+ world-atlas:
+ specifier: 2.0.2
+ version: 2.0.2
+
nodes/node-apply-lut:
dependencies:
'@framefields/core':
@@ -5244,6 +5290,9 @@ packages:
resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==}
+
resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}
@@ -5274,6 +5323,9 @@ packages:
resolution: {integrity: sha512-qNYerFky3muCmZPq+R+B3cUDRA5OONw/oh6aGGFxx2LOBz6yu8eamKusrhkHnC6rc2fm76+G9z9QoWSB2SaQaw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==}
+
resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==}
@@ -5286,6 +5338,12 @@ packages:
resolution: {integrity: sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-C79rySTyPxnQNNguTZNI1Ct4D7IXgvyAs3p9HPecnl6mNrJ5+UhvGNYcZfpROYV2lMHI48kJPxwR+F9C6c7nmw==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-C7KvcQh+C2nr6Y2Ub4YfgvWvWCgP2nOQMtfhlnwsRL4pYmmwzBS7HclGiS87eQfDOU/DLQpX6GEscviaz4yLIQ==}
+
'@vitest/[email protected]':
resolution: {integrity: sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==}
peerDependencies:
@@ -5501,6 +5559,10 @@ packages:
resolution: {integrity: sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==}
engines: {node: '>=12'}
@@ -6607,6 +6669,10 @@ packages:
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
engines: {node: '>=8.0'}
+ resolution: {integrity: sha512-605uxS6bcYxGXw9qi62XyrV6Q3xwbndjachmNxu8HWTtVPxZfEJN9fd/SZS1Q54Sn2y0TMyMxFj/cJINqGHrKw==}
+ hasBin: true
+
resolution: {integrity: sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==}
engines: {node: '>=16'}
@@ -6738,6 +6804,9 @@ packages:
resolution: {integrity: sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==}
+ resolution: {integrity: sha512-wEIZCq0ImPvGblTd8gZMqNNCPkQshugMUG/8nkSWXb02+XqNFREg9atHOKP9w6prLZTpqcLhSvdBW81MkV3/0Q==}
+
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -6928,6 +6997,9 @@ packages:
engines: {node: '>=8'}
hasBin: true
+ resolution: {integrity: sha512-IXfV0qwlKXpckz1FhwXVwKRjiIhOnWttOskm5CtxMsjgE/MXAYRHWJqgXOpM8IkcPBoXnyTU5lFHcYa5ChG0LQ==}
+
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
@@ -8356,6 +8428,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/geojson': 7946.0.16
+
'@types/[email protected]': {}
@@ -8384,6 +8460,8 @@ snapshots:
dependencies:
'@types/node': 24.10.14
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -8397,6 +8475,15 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/geojson': 7946.0.16
+ '@types/topojson-specification': 1.0.5
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/geojson': 7946.0.16
+
dependencies:
'@bcoe/v8-coverage': 1.0.2
@@ -8594,8 +8681,7 @@ snapshots:
- optional: true
@@ -8621,6 +8707,10 @@ snapshots:
+ dependencies:
+ d3-array: 3.2.4
+
dependencies:
d3-color: 3.1.0
@@ -9888,6 +9978,10 @@ snapshots:
dependencies:
is-number: 7.0.0
+ dependencies:
+ commander: 2.20.3
+
dependencies:
tldts: 7.0.29
@@ -10043,6 +10137,8 @@ snapshots:
graceful-fs: 4.2.11
node-int64: 0.4.0
+
@@ -10279,6 +10375,8 @@ snapshots:
siginfo: 2.0.0
stackback: 0.0.2
+
optional: true