@biunow/agent-biutalk 0.0.0-stage → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/bin/server.js +355 -0
  2. package/engine/AGENTS.md +1414 -0
  3. package/engine/CLAUDE.md +1 -0
  4. package/engine/LICENSE +21 -0
  5. package/engine/README.md +216 -0
  6. package/engine/bin/explainroo.js +19 -0
  7. package/engine/dev/audio-lab.mjs +268 -0
  8. package/engine/docs/media/contact-sheet.jpg +0 -0
  9. package/engine/docs/media/dns-poster.jpg +0 -0
  10. package/engine/docs/media/intro-poster.jpg +0 -0
  11. package/engine/docs/media/logo-dark.png +0 -0
  12. package/engine/docs/media/logo-light.png +0 -0
  13. package/engine/docs/media/looks-dark.webp +0 -0
  14. package/engine/docs/media/looks-light.webp +0 -0
  15. package/engine/docs/media/product-demo.webp +0 -0
  16. package/engine/docs/media/rebase-poster.jpg +0 -0
  17. package/engine/docs/media/sizes-dark.webp +0 -0
  18. package/engine/docs/media/sizes-light.webp +0 -0
  19. package/engine/engine/audio/dsp.js +69 -0
  20. package/engine/engine/audio/instruments.js +147 -0
  21. package/engine/engine/audio/music.js +576 -0
  22. package/engine/engine/audio/pcm.js +93 -0
  23. package/engine/engine/audio/rng.js +40 -0
  24. package/engine/engine/audio/sfx.js +287 -0
  25. package/engine/engine/audio/soundtrack.js +201 -0
  26. package/engine/engine/audio/synth.js +721 -0
  27. package/engine/engine/audio/theory.js +105 -0
  28. package/engine/engine/audio/wav.js +47 -0
  29. package/engine/engine/captions.js +131 -0
  30. package/engine/engine/clips.js +107 -0
  31. package/engine/engine/code.js +179 -0
  32. package/engine/engine/director.js +475 -0
  33. package/engine/engine/frame.html +135 -0
  34. package/engine/engine/icons/LICENSE-lucide.txt +43 -0
  35. package/engine/engine/icons/lucide-tags.json +1 -0
  36. package/engine/engine/icons/lucide.json +1 -0
  37. package/engine/engine/layout.js +69 -0
  38. package/engine/engine/pathdata.js +234 -0
  39. package/engine/engine/pen.js +240 -0
  40. package/engine/engine/player.html +67 -0
  41. package/engine/engine/player.js +219 -0
  42. package/engine/engine/readability.js +9 -0
  43. package/engine/engine/runtime.js +690 -0
  44. package/engine/engine/stage.js +2247 -0
  45. package/engine/engine/studio.html +216 -0
  46. package/engine/engine/text.js +81 -0
  47. package/engine/engine/themes.js +360 -0
  48. package/engine/engine/transitions.js +161 -0
  49. package/engine/engine/ui.js +1042 -0
  50. package/engine/engine/upload.js +32 -0
  51. package/engine/engine/util.js +204 -0
  52. package/engine/examples/callbacks-to-async-await/code-versions.js +34 -0
  53. package/engine/examples/callbacks-to-async-await/scenes.js +106 -0
  54. package/engine/examples/callbacks-to-async-await/script.md +22 -0
  55. package/engine/examples/callbacks-to-async-await/video.json +16 -0
  56. package/engine/examples/circle-area/scenes.js +228 -0
  57. package/engine/examples/circle-area/script.md +37 -0
  58. package/engine/examples/circle-area/video.json +14 -0
  59. package/engine/examples/explainroo-intro/scenes.js +133 -0
  60. package/engine/examples/explainroo-intro/script.md +27 -0
  61. package/engine/examples/explainroo-intro/video.json +8 -0
  62. package/engine/examples/how-dns-works/scenes.js +130 -0
  63. package/engine/examples/how-dns-works/script.md +28 -0
  64. package/engine/examples/how-dns-works/video.json +8 -0
  65. package/engine/examples/leap-years/scenes.js +156 -0
  66. package/engine/examples/leap-years/script.md +25 -0
  67. package/engine/examples/leap-years/video.json +16 -0
  68. package/engine/examples/leap-years-ja/scenes.js +194 -0
  69. package/engine/examples/leap-years-ja/script.md +32 -0
  70. package/engine/examples/leap-years-ja/video.json +17 -0
  71. package/engine/examples/merge-vs-rebase/scenes.js +129 -0
  72. package/engine/examples/merge-vs-rebase/script.md +22 -0
  73. package/engine/examples/merge-vs-rebase/video.json +8 -0
  74. package/engine/examples/password-storage-zh/scenes.js +185 -0
  75. package/engine/examples/password-storage-zh/script.md +25 -0
  76. package/engine/examples/password-storage-zh/video.json +19 -0
  77. package/engine/examples/sqlite-demo/README.md +19 -0
  78. package/engine/examples/sqlite-demo/scenes.js +423 -0
  79. package/engine/examples/sqlite-demo/script.md +35 -0
  80. package/engine/examples/sqlite-demo/video.json +17 -0
  81. package/engine/examples/unspar-demo/assets/fonts/Figtree-400.woff2 +0 -0
  82. package/engine/examples/unspar-demo/assets/fonts/Figtree-500.woff2 +0 -0
  83. package/engine/examples/unspar-demo/assets/fonts/Figtree-600.woff2 +0 -0
  84. package/engine/examples/unspar-demo/assets/fonts/Figtree-700.woff2 +0 -0
  85. package/engine/examples/unspar-demo/assets/fonts/Figtree-OFL.txt +93 -0
  86. package/engine/examples/unspar-demo/assets/unspar-logo.svg +23 -0
  87. package/engine/examples/unspar-demo/scenes.js +367 -0
  88. package/engine/examples/unspar-demo/script.md +25 -0
  89. package/engine/examples/unspar-demo/video.json +21 -0
  90. package/engine/examples/why-is-the-sky-blue-es/scenes.js +160 -0
  91. package/engine/examples/why-is-the-sky-blue-es/script.md +22 -0
  92. package/engine/examples/why-is-the-sky-blue-es/video.json +15 -0
  93. package/engine/fonts/ArchitectsDaughter-400-latin-ext.woff2 +0 -0
  94. package/engine/fonts/ArchitectsDaughter-400-latin.woff2 +0 -0
  95. package/engine/fonts/CabinSketch-400-latin.woff2 +0 -0
  96. package/engine/fonts/CabinSketch-700-latin.woff2 +0 -0
  97. package/engine/fonts/InstrumentSerif-400-italic-latin-ext.woff2 +0 -0
  98. package/engine/fonts/InstrumentSerif-400-italic-latin.woff2 +0 -0
  99. package/engine/fonts/InstrumentSerif-400-normal-latin-ext.woff2 +0 -0
  100. package/engine/fonts/InstrumentSerif-400-normal-latin.woff2 +0 -0
  101. package/engine/fonts/Inter-400-latin-ext.woff2 +0 -0
  102. package/engine/fonts/Inter-400-latin.woff2 +0 -0
  103. package/engine/fonts/JetBrainsMono-400-latin-ext.woff2 +0 -0
  104. package/engine/fonts/JetBrainsMono-400-latin.woff2 +0 -0
  105. package/engine/fonts/Kalam-400-latin-ext.woff2 +0 -0
  106. package/engine/fonts/Kalam-400-latin.woff2 +0 -0
  107. package/engine/fonts/Kalam-700-latin-ext.woff2 +0 -0
  108. package/engine/fonts/Kalam-700-latin.woff2 +0 -0
  109. package/engine/fonts/NotoSansDevanagari-400.ttf +0 -0
  110. package/engine/fonts/NotoSansDevanagari-700.ttf +0 -0
  111. package/engine/fonts/PatrickHand-400-latin-ext.woff2 +0 -0
  112. package/engine/fonts/PatrickHand-400-latin.woff2 +0 -0
  113. package/engine/fonts/PlusJakartaSans-600-latin-ext.woff2 +0 -0
  114. package/engine/fonts/PlusJakartaSans-600-latin.woff2 +0 -0
  115. package/engine/fonts/SpaceGrotesk-500-latin-ext.woff2 +0 -0
  116. package/engine/fonts/SpaceGrotesk-500-latin.woff2 +0 -0
  117. package/engine/fonts/fonts.json +216 -0
  118. package/engine/fonts/licenses/ArchitectsDaughter-OFL.txt +93 -0
  119. package/engine/fonts/licenses/CabinSketch-OFL.txt +93 -0
  120. package/engine/fonts/licenses/InstrumentSerif-OFL.txt +93 -0
  121. package/engine/fonts/licenses/Inter-OFL.txt +93 -0
  122. package/engine/fonts/licenses/JetBrainsMono-OFL.txt +93 -0
  123. package/engine/fonts/licenses/Kalam-OFL.txt +93 -0
  124. package/engine/fonts/licenses/NotoSansDevanagari-OFL.txt +118 -0
  125. package/engine/fonts/licenses/PatrickHand-OFL.txt +93 -0
  126. package/engine/fonts/licenses/PlusJakartaSans-OFL.txt +93 -0
  127. package/engine/fonts/licenses/SpaceGrotesk-OFL.txt +93 -0
  128. package/engine/package-lock.json +1201 -0
  129. package/engine/package.json +67 -0
  130. package/engine/scripts/build-icons.mjs +74 -0
  131. package/engine/scripts/fetch-fonts.mjs +68 -0
  132. package/engine/skills/explainroo/SKILL.md +51 -0
  133. package/engine/src/align.js +357 -0
  134. package/engine/src/browser.js +121 -0
  135. package/engine/src/capture.js +315 -0
  136. package/engine/src/chapters.js +32 -0
  137. package/engine/src/cli.js +421 -0
  138. package/engine/src/clips.js +19 -0
  139. package/engine/src/elevenlabs.js +90 -0
  140. package/engine/src/env.js +16 -0
  141. package/engine/src/export.js +187 -0
  142. package/engine/src/ffmpeg.js +103 -0
  143. package/engine/src/fonts.js +86 -0
  144. package/engine/src/g2p.py +76 -0
  145. package/engine/src/images.js +151 -0
  146. package/engine/src/licenses/misaki-Apache-2.0.txt +201 -0
  147. package/engine/src/math.js +83 -0
  148. package/engine/src/models.js +161 -0
  149. package/engine/src/phonemes.js +162 -0
  150. package/engine/src/pipeline.js +63 -0
  151. package/engine/src/project.js +331 -0
  152. package/engine/src/qa.js +186 -0
  153. package/engine/src/recordings.js +89 -0
  154. package/engine/src/render.js +156 -0
  155. package/engine/src/script.js +266 -0
  156. package/engine/src/server.js +288 -0
  157. package/engine/src/subtitles.js +78 -0
  158. package/engine/src/timeline.js +55 -0
  159. package/engine/src/voice.js +240 -0
  160. package/engine/src/wav.js +98 -0
  161. package/engine/templates/starter/scenes.js +31 -0
  162. package/engine/templates/starter/script.md +14 -0
  163. package/engine/test/align.test.js +108 -0
  164. package/engine/test/brand.test.js +41 -0
  165. package/engine/test/browser.test.js +89 -0
  166. package/engine/test/camera-browser.test.js +225 -0
  167. package/engine/test/caption-phrases.test.js +35 -0
  168. package/engine/test/capture-browser.test.js +90 -0
  169. package/engine/test/capture-fixture.js +46 -0
  170. package/engine/test/capture.test.js +62 -0
  171. package/engine/test/chapters.test.js +41 -0
  172. package/engine/test/cjk-browser.test.js +101 -0
  173. package/engine/test/cjk.test.js +232 -0
  174. package/engine/test/cli-exit.test.js +25 -0
  175. package/engine/test/cli.test.js +116 -0
  176. package/engine/test/clips-browser.test.js +125 -0
  177. package/engine/test/clips.test.js +67 -0
  178. package/engine/test/code-morph-browser.test.js +99 -0
  179. package/engine/test/code-morph.test.js +110 -0
  180. package/engine/test/contrast-browser.test.js +63 -0
  181. package/engine/test/contrast.test.js +80 -0
  182. package/engine/test/director.test.js +316 -0
  183. package/engine/test/engine-pure.test.js +29 -0
  184. package/engine/test/export-browser.test.js +224 -0
  185. package/engine/test/export.test.js +96 -0
  186. package/engine/test/fixtures/capture.html +55 -0
  187. package/engine/test/formats-pace.test.js +104 -0
  188. package/engine/test/languages-browser.test.js +78 -0
  189. package/engine/test/languages.test.js +140 -0
  190. package/engine/test/looks-browser.test.js +109 -0
  191. package/engine/test/looks-preview.test.js +57 -0
  192. package/engine/test/looks.test.js +130 -0
  193. package/engine/test/math-browser.test.js +114 -0
  194. package/engine/test/math.test.js +54 -0
  195. package/engine/test/multi-size-browser.test.js +133 -0
  196. package/engine/test/multi-size.test.js +116 -0
  197. package/engine/test/phonemes.test.js +92 -0
  198. package/engine/test/readability-browser.test.js +36 -0
  199. package/engine/test/readability.test.js +20 -0
  200. package/engine/test/render-options.test.js +52 -0
  201. package/engine/test/script.test.js +67 -0
  202. package/engine/test/server.test.js +256 -0
  203. package/engine/test/stills-browser.test.js +70 -0
  204. package/engine/test/subtitles.test.js +83 -0
  205. package/engine/test/timeline.test.js +31 -0
  206. package/engine/test/transparent-browser.test.js +123 -0
  207. package/engine/test/ui-kit.test.js +96 -0
  208. package/engine/test/upload-browser.test.js +55 -0
  209. package/engine/test/voice-providers.test.js +338 -0
  210. package/lib/host.mjs +480 -0
  211. package/manifest.json +54 -0
  212. package/package.json +8 -4
  213. package/skills/biutalk/SKILL.md +21 -0
  214. package/studio/app.js +209 -0
  215. package/studio/assert-panel-permit.mjs +67 -0
  216. package/studio/composer.css +354 -0
  217. package/studio/composer.js +169 -0
  218. package/studio/index.html +82 -0
  219. package/studio/looks/blueprint.svg +21 -0
  220. package/studio/looks/chalk.svg +15 -0
  221. package/studio/looks/clean.svg +20 -0
  222. package/studio/looks/editorial.svg +18 -0
  223. package/studio/looks/midnight.svg +17 -0
  224. package/studio/looks/paper.svg +11 -0
  225. package/studio/select-menu.js +268 -0
  226. package/studio/styles.css +4 -0
  227. package/README.md +0 -3
@@ -0,0 +1,98 @@
1
+ // Minimal WAV reading and writing for mono/stereo PCM16 and float32 files.
2
+ import fs from 'node:fs';
3
+
4
+ export function readWav(file) {
5
+ const buf = fs.readFileSync(file);
6
+ if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') {
7
+ throw new Error(`${file} is not a WAV file`);
8
+ }
9
+ let off = 12;
10
+ let fmt = null;
11
+ while (off + 8 <= buf.length) {
12
+ const id = buf.toString('ascii', off, off + 4);
13
+ const size = buf.readUInt32LE(off + 4);
14
+ const body = off + 8;
15
+ if (id === 'fmt ') {
16
+ fmt = {
17
+ format: buf.readUInt16LE(body),
18
+ channels: buf.readUInt16LE(body + 2),
19
+ sampleRate: buf.readUInt32LE(body + 4),
20
+ bits: buf.readUInt16LE(body + 14),
21
+ };
22
+ } else if (id === 'data') {
23
+ if (!fmt) throw new Error(`${file}: data chunk before fmt chunk`);
24
+ const bytes = fmt.bits / 8;
25
+ const frames = Math.floor(size / (bytes * fmt.channels));
26
+ const out = new Float32Array(frames);
27
+ for (let i = 0; i < frames; i++) {
28
+ let sum = 0;
29
+ for (let c = 0; c < fmt.channels; c++) {
30
+ const p = body + (i * fmt.channels + c) * bytes;
31
+ if (fmt.format === 3 && fmt.bits === 32) sum += buf.readFloatLE(p);
32
+ else if (fmt.bits === 16) sum += buf.readInt16LE(p) / 32768;
33
+ else if (fmt.bits === 24) sum += buf.readIntLE(p, 3) / 8388608;
34
+ else if (fmt.bits === 32) sum += buf.readInt32LE(p) / 2147483648;
35
+ else throw new Error(`${file}: unsupported ${fmt.bits}-bit WAV`);
36
+ }
37
+ out[i] = sum / fmt.channels;
38
+ }
39
+ return { sampleRate: fmt.sampleRate, samples: out };
40
+ }
41
+ off = body + size + (size % 2);
42
+ }
43
+ throw new Error(`${file}: no audio data`);
44
+ }
45
+
46
+ export function writeWav(file, samples, sampleRate) {
47
+ const data = Buffer.alloc(samples.length * 2);
48
+ for (let i = 0; i < samples.length; i++) {
49
+ const v = Math.max(-1, Math.min(1, samples[i]));
50
+ data.writeInt16LE(Math.round(v < 0 ? v * 32768 : v * 32767), i * 2);
51
+ }
52
+ const head = Buffer.alloc(44);
53
+ head.write('RIFF', 0, 'ascii');
54
+ head.writeUInt32LE(36 + data.length, 4);
55
+ head.write('WAVE', 8, 'ascii');
56
+ head.write('fmt ', 12, 'ascii');
57
+ head.writeUInt32LE(16, 16);
58
+ head.writeUInt16LE(1, 20);
59
+ head.writeUInt16LE(1, 22);
60
+ head.writeUInt32LE(sampleRate, 24);
61
+ head.writeUInt32LE(sampleRate * 2, 28);
62
+ head.writeUInt16LE(2, 32);
63
+ head.writeUInt16LE(16, 34);
64
+ head.write('data', 36, 'ascii');
65
+ head.writeUInt32LE(data.length, 40);
66
+ fs.writeFileSync(file, Buffer.concat([head, data]));
67
+ }
68
+
69
+ export function resample(samples, from, to) {
70
+ if (from === to) return samples;
71
+ const ratio = from / to;
72
+ const out = new Float32Array(Math.floor(samples.length / ratio));
73
+ for (let i = 0; i < out.length; i++) {
74
+ const x = i * ratio;
75
+ const i0 = Math.floor(x);
76
+ const f = x - i0;
77
+ out[i] = samples[i0] * (1 - f) + (samples[i0 + 1] ?? 0) * f;
78
+ }
79
+ return out;
80
+ }
81
+
82
+ // Trims leading and trailing near-silence, keeping a short natural margin.
83
+ export function trimSilence(samples, sampleRate, { threshold = 0.004, keep = 0.04 } = {}) {
84
+ const win = Math.round(sampleRate * 0.01);
85
+ const loud = (i) => {
86
+ let peak = 0;
87
+ for (let k = i; k < Math.min(samples.length, i + win); k++) peak = Math.max(peak, Math.abs(samples[k]));
88
+ return peak > threshold;
89
+ };
90
+ let a = 0;
91
+ while (a < samples.length && !loud(a)) a += win;
92
+ let b = samples.length - win;
93
+ while (b > a && !loud(b)) b -= win;
94
+ const pad = Math.round(sampleRate * keep);
95
+ const start = Math.max(0, a - pad);
96
+ const end = Math.min(samples.length, b + win + pad);
97
+ return samples.subarray(start, Math.max(start, end));
98
+ }
@@ -0,0 +1,31 @@
1
+ // One function per scene in script.md. Each function draws one frame of its
2
+ // scene, and s.t is the time in seconds since the scene started. Give elements
3
+ // an `at` time (seconds, a spoken word or "#marker") and the look animates
4
+ // them in. The full scene API is in AGENTS.md in the explainroo folder.
5
+
6
+ export default {
7
+ hook(s) {
8
+ s.title('{{title}}', { y: s.safe.y + s.safe.h * 0.38 });
9
+ s.icon('mouse-pointer-click', { y: s.safe.y + s.safe.h * 0.7, size: 130, at: '#click', color: 'accent' });
10
+ },
11
+
12
+ steps(s) {
13
+ // s.safe is the part of the frame that is free for content. Wide videos
14
+ // show the steps side by side, tall ones stack them.
15
+ const tall = s.H > s.W;
16
+ s.text('Three steps', { font: 'display', size: 76, y: s.safe.y + 50, at: 0 });
17
+ const spots = tall
18
+ ? s.col(3, { y: s.safe.y + s.safe.h * 0.6, height: s.safe.h * 0.66 }).map((y) => ({ x: s.cx, y }))
19
+ : s.row(3, { width: Math.min(1180, s.safe.w - 260) }).map((x) => ({ x, y: s.cy }));
20
+ s.box('Find the server', { id: 'find', ...spots[0], icon: 'search', color: 'blue', at: '#one' });
21
+ s.box('Ask for the page', { id: 'ask', ...spots[1], icon: 'send', color: 'green', at: '#two' });
22
+ s.box('Draw it', { id: 'draw', ...spots[2], icon: 'paintbrush', color: 'purple', at: '#three' });
23
+ s.arrow('find', 'ask', { at: s.cue('Then') - 0.4 });
24
+ s.arrow('ask', 'draw', { at: s.cue('Finally') - 0.4 });
25
+ },
26
+
27
+ outro(s) {
28
+ s.number(3, { suffix: ' steps', y: s.safe.y + s.safe.h * 0.42, at: 0.2 });
29
+ s.subtitle('in less time than a blink', { at: '#fast', y: s.safe.y + s.safe.h * 0.62 });
30
+ },
31
+ };
@@ -0,0 +1,14 @@
1
+ # {{title}}
2
+
3
+ > One "##" block per scene. The id after "##" must match a function in scenes.js.
4
+ > Write narration the way you would say it. [#name] marks a moment you can
5
+ > animate on, [pause 0.5] adds silence, {API|A P I} shows "API" but says "A P I".
6
+
7
+ ## hook
8
+ Most people never think about what happens [#click] after they click a link.
9
+
10
+ ## steps
11
+ It takes three steps. First, [#one] your browser finds the server. Then [#two] it asks for the page. Finally, [#three] it draws what comes back.
12
+
13
+ ## outro {hold=1.5}
14
+ Three steps, [#fast] in less time than a blink.
@@ -0,0 +1,108 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { alignWords } from '../src/align.js';
4
+
5
+ const heard = (list) => list.map(([text, start, end]) => ({ text, start, end }));
6
+
7
+ test('aligns exact words', () => {
8
+ const r = alignWords([{ spoken: 'Hello' }, { spoken: 'world.' }], heard([['Hello', 0, 0.4], ['world.', 0.5, 0.9]]), 1);
9
+ assert.equal(r.matchRate, 1);
10
+ assert.deepEqual(r.words.map((w) => [w.start, w.end]), [[0, 0.4], [0.5, 0.9]]);
11
+ });
12
+
13
+ test('number words match digits', () => {
14
+ const r = alignWords([{ spoken: 'about' }, { spoken: 'twenty' }, { spoken: 'milliseconds.' }], heard([['about', 0, 0.3], ['20', 0.3, 0.6], ['milliseconds.', 0.6, 1.2]]), 1.3);
15
+ assert.equal(r.matchRate, 1);
16
+ });
17
+
18
+ test('a spelled-out group matches one heard word', () => {
19
+ const r = alignWords([{ spoken: 'The' }, { spoken: 'D N S' }, { spoken: 'lookup' }], heard([['The', 0, 0.2], ['DNS', 0.2, 0.7], ['lookup', 0.8, 1.2]]), 1.3);
20
+ assert.equal(r.words[1].matched, true);
21
+ assert.deepEqual([r.words[1].start, r.words[1].end], [0.2, 0.7]);
22
+ });
23
+
24
+ test('missing words are interpolated between neighbours', () => {
25
+ const r = alignWords([{ spoken: 'one' }, { spoken: 'xyzzy' }, { spoken: 'three' }], heard([['one', 0, 0.4], ['three', 1.0, 1.4]]), 1.5);
26
+ assert.equal(r.words[1].matched, false);
27
+ assert.ok(r.words[1].start >= 0.4 && r.words[1].end <= 1.0);
28
+ });
29
+
30
+ test('times stay monotonic', () => {
31
+ const r = alignWords([{ spoken: 'a' }, { spoken: 'b' }, { spoken: 'c' }], heard([['c', 0.1, 0.2]]), 1);
32
+ for (let i = 1; i < r.words.length; i++) assert.ok(r.words[i].start >= r.words[i - 1].start);
33
+ });
34
+
35
+ test('dotted names match their spoken form', () => {
36
+ const r = alignWords([{ spoken: 'runs' }, { spoken: 'dot' }, { spoken: 'com.' }], heard([['runs.com.', 0, 1]]), 1);
37
+ assert.equal(r.matchRate, 1);
38
+ const ip = alignWords([{ spoken: 'one dot one dot one dot one' }], heard([['1.1.1.1', 0, 1.4]]), 1.5);
39
+ assert.equal(ip.matchRate, 1);
40
+ });
41
+
42
+ test('split number tokens with leading dots still match', () => {
43
+ const r = alignWords([{ spoken: 'one dot one dot one dot one' }], heard([['1', 0, 0.3], ['.1', 0.3, 0.6], ['.1', 0.6, 0.9], ['.1', 0.9, 1.2]]), 1.3);
44
+ assert.equal(r.matchRate, 1);
45
+ });
46
+
47
+ test('spoken amounts match digits, dollars and percent', () => {
48
+ const r = alignWords(
49
+ [{ spoken: 'one thousand and fifty dollars.' }, { spoken: 'at' }, { spoken: 'five percent' }, { spoken: 'one thousand one hundred and two dollars fifty' }],
50
+ heard([['$1,050.', 0, 1], ['at', 1, 1.2], ['5%', 1.2, 1.6], ['$1,102.50', 1.6, 3]]),
51
+ 3,
52
+ );
53
+ assert.equal(r.matchRate, 1);
54
+ assert.ok(r.words.every((w) => w.matched));
55
+ });
56
+
57
+ test('digits in the script match digits Whisper wrote', () => {
58
+ const r = alignWords([{ spoken: 'After' }, { spoken: '10' }, { spoken: 'years' }], heard([['After', 0, 0.3], ['10', 0.3, 0.6], ['years', 0.6, 1]]), 1);
59
+ assert.equal(r.matchRate, 1);
60
+ });
61
+
62
+ test('number pieces from Whisper are joined', () => {
63
+ const r = alignWords([{ spoken: 'one thousand dollars' }, { spoken: 'five percent' }], heard([['$1', 0, 0.4], [',000', 0.4, 0.8], ['5', 0.8, 1], ['%', 1, 1.2]]), 1.2);
64
+ assert.equal(r.matchRate, 1);
65
+ });
66
+
67
+ test('a word counts as heard when Whisper writes its shown form', () => {
68
+ const one = alignWords([{ spoken: 'The' }, { spoken: 'sequel', display: 'SQL' }, { spoken: 'query.' }], heard([['The', 0, 0.2], ['SQL', 0.2, 0.7], ['query.', 0.7, 1.1]]), 1.2);
69
+ assert.equal(one.matchRate, 1);
70
+ assert.ok(one.words[1].matched);
71
+ const two = alignWords([{ spoken: 'The' }, { spoken: 'a sink', display: 'async' }, { spoken: 'keyword.' }], heard([['The', 0, 0.2], ['async', 0.2, 0.7], ['keyword.', 0.7, 1.1]]), 1.2);
72
+ assert.equal(two.matchRate, 1);
73
+ assert.equal(two.words[1].start, 0.2);
74
+ // The spoken form still matches as before.
75
+ const spoken = alignWords([{ spoken: 'a sink', display: 'async' }], heard([['a', 0, 0.2], ['sink', 0.2, 0.5]]), 0.6);
76
+ assert.equal(spoken.matchRate, 1);
77
+ // A different word is still not confirmed.
78
+ const wrong = alignWords([{ spoken: 'sequel', display: 'SQL' }], heard([['table', 0, 0.5]]), 0.6);
79
+ assert.ok(!wrong.words[0].matched);
80
+ });
81
+
82
+ test('four-digit numbers are read like years, the way the voice reads them', async () => {
83
+ const { yearWords, expand } = await import('../src/align.js');
84
+ assert.deepEqual(yearWords(1582), ['fifteen', 'eighty', 'two']);
85
+ assert.deepEqual(yearWords(1900), ['nineteen', 'hundred']);
86
+ assert.deepEqual(yearWords(1905), ['nineteen', 'oh', 'five']);
87
+ assert.deepEqual(yearWords(2015), ['twenty', 'fifteen']);
88
+ assert.equal(yearWords(2000), null);
89
+ assert.equal(yearWords(2005), null);
90
+ assert.equal(yearWords(1066), null);
91
+ // A comma makes it an ordinary number again: one thousand five hundred eighty two.
92
+ assert.equal(expand('1,582').length, 6);
93
+ const year = alignWords([{ spoken: 'In' }, { spoken: 'fifteen eighty two', display: '1582' }, { spoken: 'it' }, { spoken: 'changed.' }], heard([['In', 0, 0.2], ['1582', 0.2, 0.9], ['it', 0.9, 1], ['changed.', 1, 1.4]]), 1.5);
94
+ assert.equal(year.matchRate, 1);
95
+ const plain = alignWords([{ spoken: '1900' }, { spoken: 'was' }, { spoken: 'not.' }], heard([['1900', 0, 0.6], ['was', 0.6, 0.8], ['not.', 0.8, 1]]), 1.1);
96
+ assert.equal(plain.matchRate, 1);
97
+ const hundred = alignWords([{ spoken: 'nineteen hundred,', display: '1900,' }], heard([['1900,', 0, 0.6]]), 0.7);
98
+ assert.equal(hundred.matchRate, 1);
99
+ const cardinal = alignWords([{ spoken: 'two thousand', display: '2000' }], heard([['2000', 0, 0.6]]), 0.7);
100
+ assert.equal(cardinal.matchRate, 1);
101
+ });
102
+
103
+ test('ordinals match the words the voice says', () => {
104
+ const r = alignWords([{ spoken: 'February' }, { spoken: 'twenty ninth', display: '29' }], heard([['February', 0, 0.5], ['29th', 0.5, 1]]), 1.1);
105
+ assert.equal(r.matchRate, 1);
106
+ const first = alignWords([{ spoken: 'the' }, { spoken: '1st' }], heard([['the', 0, 0.2], ['first', 0.2, 0.5]]), 0.6);
107
+ assert.equal(first.matchRate, 1);
108
+ });
@@ -0,0 +1,41 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { normalizeConfig, loadProject, ProjectError } from '../src/project.js';
7
+
8
+ test('brand settings for the UI kit are checked', () => {
9
+ const cfg = normalizeConfig({ brand: { accent: '#245cff', background: '#f8f6f1', font: 'Figtree', headline: 'Instrument Serif', logo: 'assets/logo.svg' } });
10
+ assert.equal(cfg.brand.accent, '#245cff');
11
+ assert.equal(normalizeConfig({}).brand, null);
12
+ assert.throws(() => normalizeConfig({ brand: { color: '#245cff' } }), /unknown setting\(s\): color/);
13
+ assert.throws(() => normalizeConfig({ brand: { accent: 'blue' } }), /brand.accent must be a color/);
14
+ assert.throws(() => normalizeConfig({ brand: { logo: '../logo.svg' } }), /assets\/ folder/);
15
+ assert.throws(() => normalizeConfig({ brand: [] }), ProjectError);
16
+ assert.deepEqual(normalizeConfig({ brand: { colors: { text: '#141413', line: '#e8e6dc' } } }).brand.colors, { text: '#141413', line: '#e8e6dc' });
17
+ assert.throws(() => normalizeConfig({ brand: { colors: { ink2: '#000000' } } }), /unknown color "ink2"/);
18
+ assert.throws(() => normalizeConfig({ brand: { colors: { text: 'black' } } }), /brand.colors.text must be a color/);
19
+ });
20
+
21
+ test('a video can bring its own fonts', () => {
22
+ const ok = normalizeConfig({ fonts: [{ family: 'Figtree', src: 'assets/fonts/Figtree-600.woff2', weight: 600 }, { family: 'Inter', src: 'assets/fonts/Inter.woff2', weight: '100 900', style: 'italic' }] });
23
+ assert.equal(ok.fonts.length, 2);
24
+ assert.throws(() => normalizeConfig({ fonts: {} }), /fonts must be a list/);
25
+ assert.throws(() => normalizeConfig({ fonts: [{ family: 'X', src: 'fonts/x.woff2' }] }), /assets\/ folder/);
26
+ assert.throws(() => normalizeConfig({ fonts: [{ family: 'X', src: 'assets/x.png' }] }), /assets\/ folder/);
27
+ assert.throws(() => normalizeConfig({ fonts: [{ family: 'X', src: 'assets/../x.woff2' }] }), ProjectError);
28
+ assert.throws(() => normalizeConfig({ fonts: [{ family: 'X', src: 'assets/x.woff2', weight: 'bold' }] }), /weight/);
29
+ assert.throws(() => normalizeConfig({ fonts: [{ family: 'X', src: 'assets/x.woff2', style: 'oblique' }] }), /style/);
30
+ });
31
+
32
+ test('listed font and logo files must exist', () => {
33
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-brand-'));
34
+ fs.writeFileSync(path.join(dir, 'script.md'), '# T\n\n## a\nHello.\n');
35
+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { a() {} };');
36
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ brand: { logo: 'assets/logo.svg' } }));
37
+ assert.throws(() => loadProject(dir), /assets\/logo.svg is listed in video.json but the file is missing/);
38
+ fs.mkdirSync(path.join(dir, 'assets'));
39
+ fs.writeFileSync(path.join(dir, 'assets', 'logo.svg'), '<svg/>');
40
+ assert.equal(loadProject(dir).config.brand.logo, 'assets/logo.svg');
41
+ });
@@ -0,0 +1,89 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import http from 'node:http';
7
+ import { findChrome } from '../src/browser.js';
8
+
9
+ test('finds the headless shell that Playwright installs on Windows', () => {
10
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-pw-'));
11
+ const exe = path.join(base, 'chromium_headless_shell-1300', 'chrome-headless-shell-win64', 'chrome-headless-shell.exe');
12
+ fs.mkdirSync(path.dirname(exe), { recursive: true });
13
+ fs.writeFileSync(exe, '');
14
+ const saved = { pw: process.env.PLAYWRIGHT_BROWSERS_PATH, ex: process.env.EXPLAINROO_CHROME, cp: process.env.CHROME_PATH };
15
+ try {
16
+ process.env.PLAYWRIGHT_BROWSERS_PATH = base;
17
+ delete process.env.EXPLAINROO_CHROME;
18
+ delete process.env.CHROME_PATH;
19
+ assert.equal(findChrome(), exe);
20
+ } finally {
21
+ for (const [k, v] of [['PLAYWRIGHT_BROWSERS_PATH', saved.pw], ['EXPLAINROO_CHROME', saved.ex], ['CHROME_PATH', saved.cp]]) {
22
+ if (v === undefined) delete process.env[k];
23
+ else process.env[k] = v;
24
+ }
25
+ fs.rmSync(base, { recursive: true, force: true });
26
+ }
27
+ });
28
+
29
+ let chrome;
30
+ try { chrome = findChrome(); } catch {}
31
+
32
+ test('a page load that hangs is tried once more with a fresh page', { skip: !chrome }, async () => {
33
+ const { launch, openEngine } = await import('../src/browser.js');
34
+ let requests = 0;
35
+ const hung = [];
36
+ const server = http.createServer((req, res) => {
37
+ if (!req.url.startsWith('/frame.html')) return res.writeHead(404).end();
38
+ // The first load never answers, like a stalled page on a busy machine.
39
+ if (++requests === 1) return hung.push(res);
40
+ res.writeHead(200, { 'content-type': 'text/html' }).end('<script>window.explainrooReady = Promise.resolve();</script>');
41
+ });
42
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
43
+ const browser = await launch();
44
+ try {
45
+ // Long enough for the second page to load on a busy CI machine.
46
+ const page = await openEngine(browser, `http://127.0.0.1:${server.address().port}`, { timeout: 5000 });
47
+ assert.equal(requests, 2);
48
+ assert.equal(browser.contexts().flatMap((c) => c.pages()).length, 1);
49
+ assert.equal(await page.evaluate(() => typeof window.explainrooReady), 'object');
50
+ requests = 0;
51
+ server.removeAllListeners('request');
52
+ server.on('request', (req, res) => hung.push(res));
53
+ await assert.rejects(openEngine(browser, `http://127.0.0.1:${server.address().port}`, { timeout: 500 }), { name: 'TimeoutError' });
54
+ } finally {
55
+ await browser.close();
56
+ for (const res of hung) res.destroy();
57
+ server.closeAllConnections();
58
+ await new Promise((resolve) => server.close(resolve));
59
+ }
60
+ });
61
+
62
+ test('a page that loads without its scripts is tried once more', { skip: !chrome }, async () => {
63
+ const { launch, openEngine } = await import('../src/browser.js');
64
+ let pages = 0;
65
+ const server = http.createServer((req, res) => {
66
+ if (req.url.startsWith('/missing.js')) return res.writeHead(404).end();
67
+ if (!req.url.startsWith('/frame.html')) return res.writeHead(404).end();
68
+ // The first page's module script cannot load, so the engine never starts.
69
+ const script = ++pages === 1 ? "import '/missing.js'; window.explainrooReady = Promise.resolve();" : 'window.explainrooReady = Promise.resolve();';
70
+ res.writeHead(200, { 'content-type': 'text/html' }).end(`<script type="module">${script}</script>`);
71
+ });
72
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
73
+ const browser = await launch();
74
+ try {
75
+ const page = await openEngine(browser, `http://127.0.0.1:${server.address().port}`, { timeout: 5000 });
76
+ assert.equal(pages, 2);
77
+ assert.equal(browser.contexts().flatMap((c) => c.pages()).length, 1);
78
+ assert.equal(await page.evaluate(() => typeof window.explainrooReady), 'object');
79
+ // When it never starts, the error says so.
80
+ pages = 0;
81
+ server.removeAllListeners('request');
82
+ server.on('request', (req, res) => res.writeHead(200, { 'content-type': 'text/html' }).end('<p>no engine</p>'));
83
+ await assert.rejects(openEngine(browser, `http://127.0.0.1:${server.address().port}`, { timeout: 5000 }), /scripts did not/);
84
+ } finally {
85
+ await browser.close();
86
+ server.closeAllConnections();
87
+ await new Promise((resolve) => server.close(resolve));
88
+ }
89
+ });
@@ -0,0 +1,225 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { findChrome } from '../src/browser.js';
7
+ import { loadProject } from '../src/project.js';
8
+ import { buildTimeline } from '../src/timeline.js';
9
+ import { withEngine } from '../src/pipeline.js';
10
+
11
+ let chrome;
12
+ try { chrome = findChrome(); } catch {}
13
+
14
+ test('the camera measures what scenes draw where and as big as it is drawn', { skip: !chrome }, async () => {
15
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-camera-'));
16
+ try {
17
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'clean', captions: false, watermark: false, music: false, sfx: false }));
18
+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=8}\n');
19
+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo(s) {} };');
20
+ const project = loadProject(dir);
21
+ await withEngine(project, buildTimeline(project, {}), {}, async (page) => {
22
+ const r = await page.evaluate(async () => {
23
+ const { Engine, fetchState } = await import('/engine/runtime.js');
24
+ const state = await fetchState();
25
+ const plan = (demo) => {
26
+ const engine = new Engine({ canvas: document.createElement('canvas'), state, scenes: { demo }, icons: { dot: ['M0 0L24 24'] }, images: new Map() });
27
+ engine.planCameras();
28
+ return engine.cameraPlans.get(0)?.elements ?? [];
29
+ };
30
+ const out = {};
31
+ // Random positions: planned where they are drawn, one call each.
32
+ let calls = 0;
33
+ const drawn = [];
34
+ const scene = (s) => {
35
+ for (let i = 0; i < 3; i++) s.draw({ at: 0 }, (ctx) => { calls++; const x = 200 + Math.random() * 1400; drawn.push(x); ctx.fillRect(x, 400, 100, 100); });
36
+ };
37
+ out.random = { planned: plan(scene).filter((e) => e.kind === 'custom').map((e) => e.box.x - 50), calls };
38
+ const engine = new Engine({ canvas: document.createElement('canvas'), state, scenes: { demo: scene }, icons: {}, images: new Map() });
39
+ drawn.length = 0;
40
+ engine.renderFrame(4);
41
+ out.random.drawn = [...drawn];
42
+ // A drawing on its way out is measured at its full size.
43
+ out.leaving = plan((s) => s.draw({ at: 0, out: 7.9, exit: 'pop' }, (ctx) => ctx.fillRect(700, 400, 400, 200))).find((e) => e.kind === 'custom')?.box;
44
+ // Stroke widths count, through the transform.
45
+ out.stroked = plan((s) => s.draw({ x: 960, y: 540, at: 0 }, (ctx) => { ctx.lineWidth = 300; ctx.strokeRect(-50, -150, 100, 300); })).find((e) => e.kind === 'custom')?.box;
46
+ // A sharp miter corner reaches past half the line width.
47
+ out.miter = plan((s) => s.draw({ at: 0 }, (ctx) => {
48
+ ctx.lineWidth = 50;
49
+ ctx.beginPath(); ctx.moveTo(900, 650); ctx.lineTo(960, 400); ctx.lineTo(1020, 650); ctx.closePath(); ctx.stroke();
50
+ })).find((e) => e.kind === 'custom')?.box;
51
+ // Sharp corners under a squeezed transform, after a rectangle, and
52
+ // on curves without a moveTo reach as far as Chrome draws them.
53
+ const ink = (paint) => {
54
+ const c = document.createElement('canvas');
55
+ c.width = 1920; c.height = 1080;
56
+ const g = c.getContext('2d');
57
+ g.strokeStyle = '#f00';
58
+ paint(g);
59
+ const d = g.getImageData(0, 0, 1920, 1080).data;
60
+ const b = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
61
+ for (let i = 3; i < d.length; i += 4) if (d[i] > 128) {
62
+ const x = ((i - 3) / 4) % 1920;
63
+ const y = Math.floor((i - 3) / 4 / 1920);
64
+ b.x0 = Math.min(b.x0, x); b.y0 = Math.min(b.y0, y); b.x1 = Math.max(b.x1, x + 1); b.y1 = Math.max(b.y1, y + 1);
65
+ }
66
+ return b;
67
+ };
68
+ const strokes = {
69
+ squeezed: (ctx) => { ctx.scale(0.5, 1); ctx.lineWidth = 50; ctx.beginPath(); ctx.moveTo(1880, 650); ctx.lineTo(1920, 400); ctx.lineTo(1960, 650); ctx.closePath(); ctx.stroke(); },
70
+ stretched: (ctx) => { ctx.scale(1, 0.5); ctx.lineWidth = 40; ctx.lineCap = 'square'; ctx.beginPath(); ctx.moveTo(800, 1000); ctx.lineTo(1100, 1200); ctx.stroke(); },
71
+ afterRect: (ctx) => { ctx.lineWidth = 50; ctx.beginPath(); ctx.rect(930, 650, 60, 50); ctx.lineTo(960, 400); ctx.lineTo(990, 650); ctx.stroke(); },
72
+ curve: (ctx) => { ctx.lineWidth = 40; ctx.lineCap = 'square'; ctx.beginPath(); ctx.quadraticCurveTo(700, 300, 900, 600); ctx.stroke(); },
73
+ backwards: (ctx) => { ctx.lineWidth = 100; ctx.strokeRect(900, 500, -100, -100); ctx.strokeRect(1300, 500, -100, 100); },
74
+ arcTo: (ctx) => { ctx.lineWidth = 40; ctx.beginPath(); ctx.moveTo(800, 700); ctx.arcTo(960, 300, 1000, 700, 10); ctx.lineTo(1300, 300); ctx.stroke(); },
75
+ };
76
+ out.strokes = Object.fromEntries(Object.entries(strokes).map(([k, paint]) => {
77
+ const box = plan((s) => s.draw({ at: 0 }, paint)).find((e) => e.kind === 'custom')?.box;
78
+ return [k, { box: { x0: box.x - box.w / 2, y0: box.y - box.h / 2, x1: box.x + box.w / 2, y1: box.y + box.h / 2 }, ink: ink(paint) }];
79
+ }));
80
+ // A group on its way out is measured where it rests.
81
+ out.groupLeaving = plan((s) => s.group({ x: 960, y: 540, at: 0, out: 7.55, exit: 'pop' }, () => {
82
+ s.draw({ at: 0 }, (ctx) => ctx.fillRect(-550, -100, 1100, 200));
83
+ })).find((e) => e.kind === 'custom')?.box;
84
+ // A drawing's random numbers do not depend on which drawings are on screen.
85
+ const xs = [];
86
+ const two = (s) => {
87
+ s.draw({ at: 0, out: 2 }, (ctx) => { const x = 200 + Math.random() * 1400; xs.push(['early', s.t, x]); ctx.fillRect(x, 400, 100, 100); });
88
+ s.draw({ at: 0 }, (ctx) => { const x = 200 + Math.random() * 1400; xs.push(['always', s.t, x]); ctx.fillRect(x, 600, 100, 100); });
89
+ };
90
+ out.hidden = { planned: plan(two).filter((e) => e.kind === 'custom').map((e) => e.box.x - 50) };
91
+ const twice = new Engine({ canvas: document.createElement('canvas'), state, scenes: { demo: two }, icons: {}, images: new Map() });
92
+ xs.length = 0;
93
+ twice.renderFrame(1);
94
+ out.hidden.drawn = xs.map((v) => v[2]);
95
+ // An icon's label grows with the icon.
96
+ out.label = plan((s) => s.icon('dot', { x: 960, y: 400, size: 120, label: 'A label much wider than its icon', labelSize: 48, scale: 2, at: 0, enter: 'none' })).find((e) => e.kind === 'icon')?.box;
97
+ // A highlight in each code step is where that step's line is.
98
+ out.focus = plan((s) => s.code([
99
+ { code: Array.from({ length: 12 }, (_, i) => `const line${i} = ${i};`).join('\n'), at: 0, highlight: [1] },
100
+ { code: 'done();', at: 4, highlight: [1] },
101
+ ], { reveal: 'none', size: 32 })).filter((e) => e.kind === 'focus').map((e) => e.box.y);
102
+ return out;
103
+ });
104
+ assert.equal(r.random.calls, 3);
105
+ r.random.planned.forEach((x, i) => assert.ok(Math.abs(x - r.random.drawn[i]) < 1e-6, JSON.stringify(r.random)));
106
+ assert.deepEqual([r.leaving.w, r.leaving.h].map(Math.round), [400, 200]);
107
+ assert.deepEqual([r.stroked.x, r.stroked.y, r.stroked.w, r.stroked.h].map(Math.round), [960, 540, 400, 600]);
108
+ assert.ok(r.label.w > 1300, `label width ${r.label.w}`);
109
+ // The tip at (960, 400) turns by about 27 degrees: its miter reaches about 107 pixels higher.
110
+ assert.ok(r.miter.y - r.miter.h / 2 < 300, JSON.stringify(r.miter));
111
+ assert.deepEqual(r.hidden.planned.map(Math.round), r.hidden.drawn.map(Math.round));
112
+ for (const [k, { box, ink }] of Object.entries(r.strokes)) {
113
+ assert.ok(box.x0 <= ink.x0 + 0.5 && box.y0 <= ink.y0 + 0.5 && box.x1 >= ink.x1 - 0.5 && box.y1 >= ink.y1 - 0.5, `${k}: ${JSON.stringify({ box, ink })}`);
114
+ }
115
+ assert.equal(Math.round(r.groupLeaving.w), 1100);
116
+ // The 12-line window starts much higher than the one-line window.
117
+ assert.ok(r.focus[0] < r.focus[1] - 200, JSON.stringify(r.focus));
118
+ });
119
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
120
+ });
121
+
122
+ test('large type tracking stays with its own text', { skip: !chrome }, async () => {
123
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-tracking-'));
124
+ try {
125
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'clean', captions: false, watermark: false, music: false, sfx: false }));
126
+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=8}\n');
127
+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo(s) {} };');
128
+ const project = loadProject(dir);
129
+ await withEngine(project, buildTimeline(project, {}), {}, async (page) => {
130
+ const [alone, after] = await page.evaluate(async () => {
131
+ const { Engine, fetchState } = await import('/engine/runtime.js');
132
+ const state = await fetchState();
133
+ const box = (withTitle) => {
134
+ let b;
135
+ const engine = new Engine({ canvas: document.createElement('canvas'), state, scenes: { demo(s) {
136
+ // A hidden title is still laid out; its tracking must not reach the box.
137
+ if (withTitle) s.title('A big hidden title', { at: 6 });
138
+ b = s.box('Some words that wrap in a narrow box', { x: 960, y: 700, w: 420, size: 40, at: 0, enter: 'none' });
139
+ } }, icons: {}, images: new Map() });
140
+ engine.renderFrame(1);
141
+ return b.h;
142
+ };
143
+ return [box(false), box(true)];
144
+ });
145
+ assert.equal(after, alone);
146
+ });
147
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
148
+ });
149
+
150
+ test('the camera measures the labels of arrows and charts', { skip: !chrome }, async () => {
151
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-labels-'));
152
+ try {
153
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'clean', captions: false, watermark: false, music: false, sfx: false }));
154
+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=8}\n');
155
+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo(s) {} };');
156
+ const project = loadProject(dir);
157
+ await withEngine(project, buildTimeline(project, {}), {}, async (page) => {
158
+ const r = await page.evaluate(async () => {
159
+ const { Engine, fetchState } = await import('/engine/runtime.js');
160
+ const state = await fetchState();
161
+ const engine = (demo, canvas = document.createElement('canvas')) => new Engine({ canvas, state, scenes: { demo }, icons: { dot: ['M0 0L24 24'] }, images: new Map() });
162
+ const elements = (demo) => {
163
+ const e = engine(demo);
164
+ e.planCameras();
165
+ return e.cameraPlans.get(0)?.elements ?? [];
166
+ };
167
+ // Where a scene paints anything, compared with an empty scene.
168
+ const pixels = (demo) => {
169
+ const c = document.createElement('canvas');
170
+ c.width = 1920;
171
+ c.height = 1080;
172
+ engine(demo, c).renderFrame(5);
173
+ return c.getContext('2d').getImageData(0, 0, 1920, 1080).data;
174
+ };
175
+ const empty = pixels(() => {});
176
+ const ink = (demo) => {
177
+ const d = pixels(demo);
178
+ const b = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
179
+ for (let i = 0; i < d.length; i += 4) {
180
+ if (Math.abs(d[i] - empty[i]) + Math.abs(d[i + 1] - empty[i + 1]) + Math.abs(d[i + 2] - empty[i + 2]) < 60) continue;
181
+ const x = (i / 4) % 1920;
182
+ const y = Math.floor(i / 4 / 1920);
183
+ b.x0 = Math.min(b.x0, x); b.y0 = Math.min(b.y0, y); b.x1 = Math.max(b.x1, x + 1); b.y1 = Math.max(b.y1, y + 1);
184
+ }
185
+ return b;
186
+ };
187
+ const edges = (box) => box && { x0: box.x - box.w / 2, y0: box.y - box.h / 2, x1: box.x + box.w / 2, y1: box.y + box.h / 2 };
188
+ const scenes = {
189
+ // Only the label shows: the line is drawn in a transparent color.
190
+ arrow: (s) => s.arrow([500, 600], [1400, 450], { color: 'rgba(0,0,0,0)', labelColor: '#d00', label: 'asks for the page', labelSize: 48, at: 0 }),
191
+ curved: (s) => s.arrow([600, 500], [1300, 500], { bend: 0.8, color: 'rgba(0,0,0,0)', labelColor: '#d00', label: 'ask the name server', at: 0 }),
192
+ line: (s) => s.lineChart([3, 5, 4, 8, 13], { labels: ['Monday', 'Tue', 'Wed', 'Thu', 'Friday'], labelSize: 40, at: 0, dur: 1 }),
193
+ bars: (s) => s.bars([{ label: 'A very long label', value: 19 }, { label: 'B', value: 31 }], { suffix: ' thousand', at: 0 }),
194
+ pie: (s) => s.pie([{ label: 'Images', value: 55 }, { label: 'Other', value: 45 }], { at: 0 }),
195
+ };
196
+ const out = {};
197
+ for (const [name, demo] of Object.entries(scenes)) {
198
+ const els = elements(demo);
199
+ out[name] = { kinds: els.map((e) => e.kind), box: edges((els.find((e) => e.kind === 'label') ?? els.find((e) => e.kind === 'chart'))?.box), ink: ink(demo) };
200
+ }
201
+ // A label the frame never shows is left out.
202
+ out.offFrame = elements((s) => s.arrow([820, 540], [1120, 540], { at: 0, label: 'request', labelOffset: 640 })).map((e) => e.kind);
203
+ out.bare = elements((s) => {
204
+ s.icon('dot', { x: 300, y: 300, at: 0 });
205
+ s.icon('dot', { x: 700, y: 300, label: 'A label', at: 0 });
206
+ s.box('', { x: 300, y: 700, w: 200, h: 100, at: 0 });
207
+ s.box('Words', { x: 700, y: 700, at: 0 });
208
+ }).map((e) => e.bare);
209
+ return out;
210
+ });
211
+ const { bare, offFrame } = r;
212
+ delete r.bare;
213
+ delete r.offFrame;
214
+ for (const [name, { box, ink }] of Object.entries(r)) {
215
+ assert.ok(box, `${name}: ${JSON.stringify(r[name].kinds)}`);
216
+ assert.ok(box.x0 <= ink.x0 + 1 && box.y0 <= ink.y0 + 1 && box.x1 >= ink.x1 - 1 && box.y1 >= ink.y1 - 1, `${name}: ${JSON.stringify({ box, ink })}`);
217
+ }
218
+ // An arrow's label is its own element; the line stays an arrow.
219
+ assert.deepEqual(r.arrow.kinds, ['arrow', 'label']);
220
+ // Icons and boxes without words are marked, so the camera does not move in on them.
221
+ assert.deepEqual(bare, [true, undefined, true, undefined]);
222
+ assert.deepEqual(offFrame, ['arrow']);
223
+ });
224
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
225
+ });
@@ -0,0 +1,35 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { buildPhrases, balancePhrases } from '../engine/captions.js';
4
+
5
+ const words = (text, step = 0.3) => text.split(' ').map((t, i) => ({ text: t, start: i * step, end: i * step + 0.2 }));
6
+ const texts = (phrases) => phrases.map((p) => p.words.map((w) => w.text).join(' '));
7
+
8
+ test('a sentence that just overflows splits into balanced phrases, not a lonely last word', () => {
9
+ const phrases = buildPhrases({ scenes: [{ start: 0, words: words('La respuesta está en la luz del Sol y en el aire.') }] }, 46);
10
+ assert.equal(phrases.length, 2);
11
+ assert.ok(texts(phrases).every((t) => t.split(' ').length >= 3), texts(phrases).join(' | '));
12
+ });
13
+
14
+ test('phrases prefer a break after a comma and never exceed the limit', () => {
15
+ const out = balancePhrases(words('When the user arrives, its callback starts fetching the orders.'), 46);
16
+ assert.deepEqual(out.map((p) => p.map((w) => w.text).join(' ')), ['When the user arrives,', 'its callback starts fetching the orders.']);
17
+ const long = balancePhrases(words('Every phrase here stays within twenty eight characters on a phone screen.'), 28);
18
+ assert.ok(long.every((p) => p.map((w) => w.text).join(' ').length <= 28));
19
+ });
20
+
21
+ test('short sentences stay whole, sentences and long pauses start new phrases', () => {
22
+ const sc = { start: 1, words: [...words('One short line.'), { text: 'Next', start: 2, end: 2.2 }, { text: 'idea.', start: 2.3, end: 2.5 }] };
23
+ assert.deepEqual(texts(buildPhrases({ scenes: [sc] }, 46)), ['One short line.', 'Next idea.']);
24
+ const paused = { start: 0, words: [{ text: 'before', start: 0, end: 0.3 }, { text: 'after', start: 1.2, end: 1.5 }] };
25
+ assert.deepEqual(texts(buildPhrases({ scenes: [paused] }, 46)), ['before', 'after']);
26
+ });
27
+
28
+ test('a single word longer than the limit is its own phrase', () => {
29
+ assert.equal(balancePhrases(words('a supercalifragilisticexpialidocious word'), 10).length, 3);
30
+ });
31
+
32
+ test('a comma does not leave a lonely word behind', () => {
33
+ const out = balancePhrases(words('Yes, the browser asks a resolver for the address first.'), 46);
34
+ assert.ok(out.every((p) => p.length >= 3), out.map((p) => p.map((w) => w.text).join(' ')).join(' | '));
35
+ });