Skip to content

Explainer videos and product demos made by your AI agent. Free and open source: a local voice (Kokoro), word timing (Whisper) and a canvas renderer turn a script into a narrated MP4.

Animate code from one version to the next (#10)

Vincent Schmalbach736780df75ed
diff --git a/AGENTS.md b/AGENTS.md
index ffe80ac..05b75a1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -910,6 +910,24 @@ s.terminal(['$ npm install', 'added 42 packages in 3s'], { at: 1 });
`cps`, `lineDelay`, `highlight` (line numbers) and `highlightAt`. `check`
reports lines that are wider than the window.
+Use steps to show a change, a refactor or a fix:
+
+```js
+s.code([
+ { code: 'const total = items.length;', at: 0.5 },
+ { code: 'const total = items\n .filter((i) => i.active)\n .length;', at: 'filter', highlight: [2] },
+ { code: 'const activeCount = items\n .filter((i) => i.active)\n .length;', at: '#rename' },
+], { lang: 'js', title: 'stats.js' });
+```
+
+Parts that stay slide to their new place, removed parts fade out and new
+parts fade in. Each later step starts at its own `at`, and the change takes
+`morphDur` seconds (0.8, shortened by `pace`). The element's `at` defaults to
+the first step's. `reveal` applies to the first step only. A step's
+`highlight` replaces the earlier one. The window is as wide as the widest
+step, up to 86% of the frame, unless you set `w`, and its height follows the
+line count. `check` checks the lines of every step.
+
`s.terminal(lines, options)` shows a terminal. Lines that start with `$ ` are
typed as commands. Other lines are output. A line can also be `{ cmd, at }`
or `{ out, at, color }`. Options: `w`, `size`, `rows`, `title`, `prompt`,
diff --git a/engine/code.js b/engine/code.js
index 33f07c6..398f13d 100644
--- a/engine/code.js
+++ b/engine/code.js
@@ -1,6 +1,7 @@
// A small syntax highlighter for code on screen. It colors comments, strings,
// numbers, keywords and function calls for the common languages; anything it
// does not know stays plain.
+import { clamp, ease, lerp } from './util.js';
const KEYWORDS = {
js: 'async await break case catch class const continue default delete do else export extends false finally for from function if import in instanceof let new null of return static super switch this throw true try typeof undefined var void while yield',
@@ -110,3 +111,69 @@ export function highlightLine(line, lang) {
}
return out;
}
+
+export function codeTokens(lines, lang) {
+ const tokens = [];
+ lines.forEach((line, row) => {
+ let column = 0;
+ for (const tok of highlightLine(line, lang)) {
+ // The highlighter merges adjacent plain text and punctuation. Separate
+ // identifiers so a rename does not replace the rest of the line, and keep
+ // operators like => whole so the font draws them the same while moving.
+ const parts = ['plain', 'punct'].includes(tok.type)
+ ? tok.text.match(/\s+|[A-Za-z_$][\w$]*|===|!==|=>|==|!=|<=|>=|&&|\|\||\?\?|\.\.\.|->|::|[^\s]/g) || [] : [tok.text];
+ for (const text of parts) {
+ if (/\S/.test(text)) tokens.push({ text, type: tok.type, row, column });
+ column += text.length;
+ }
+ }
+ });
+ return tokens;
+}
+
+// Indices into the original sequences, with whitespace left out of the LCS.
+export function matchTokens(before, after) {
+ const a = before.map((t, i) => i).filter((i) => /\S/.test(before[i].text));
+ const b = after.map((t, i) => i).filter((i) => /\S/.test(after[i].text));
+ const same = (i, j) => before[a[i]].text === after[b[j]].text && before[a[i]].type === after[b[j]].type;
+ const cols = b.length + 1;
+ const lengths = new Uint32Array((a.length + 1) * cols);
+ for (let i = a.length - 1; i >= 0; i--) {
+ for (let j = b.length - 1; j >= 0; j--) {
+ lengths[i * cols + j] = same(i, j) ? 1 + lengths[(i + 1) * cols + j + 1]
+ : Math.max(lengths[(i + 1) * cols + j], lengths[i * cols + j + 1]);
+ }
+ }
+ const pairs = [];
+ let i = 0;
+ let j = 0;
+ while (i < a.length && j < b.length) {
+ if (same(i, j)) { pairs.push([a[i++], b[j++]]); }
+ else if (lengths[(i + 1) * cols + j] >= lengths[i * cols + j + 1]) i++;
+ else j++;
+ }
+ return pairs;
+}
+
+export function resolveCodeSteps(steps, o, time) {
+ if (!steps.length) throw new Error('code needs at least one step');
+ let highlight = o.highlight;
+ return steps.map((step, i) => {
+ if (!step || typeof step.code !== 'string') throw new Error(`code step ${i + 1} needs a code string`);
+ if (i && step.at === undefined) throw new Error(`code step ${i + 1} needs an at time`);
+ const at = time(step.at ?? o.at ?? 0);
+ if (!Number.isFinite(at)) throw new Error(`code step ${i + 1} needs a finite at time`);
+ if (step.highlight !== undefined) highlight = step.highlight;
+ return { at, lines: step.code.replace(/\t/g, ' ').split('\n'), highlight };
+ });
+}
+
+export function codeMorphState(steps, t, dur = 0.8, pace = 1) {
+ let to = 0;
+ for (let i = 1; i < steps.length; i++) if (t >= steps[i].at) to = i;
+ const from = Math.max(0, to - 1);
+ const raw = to ? (dur > 0 ? clamp((t - steps[to].at) / (dur / pace)) : 1) : 1;
+ const p = ease.inOut(raw);
+ return { from, to, p, removed: 1 - ease.inOut(clamp(raw * 2)), added: ease.inOut(clamp(raw * 2 - 1)),
+ lines: lerp(steps[from].lines.length, steps[to].lines.length, p) };
+}
diff --git a/engine/stage.js b/engine/stage.js
index 2fa9c07..c410a7e 100644
--- a/engine/stage.js
+++ b/engine/stage.js
@@ -7,7 +7,7 @@ import { colorOf, tintOf, fontString } from './themes.js';
import { scalePath, quadD, polyD, pathLength, pointAt } from './pathdata.js';
import { layoutText, lineStartX } from './text.js';
import { clipFrame, clipURL } from './clips.js';
-import { highlightLine } from './code.js';
+import { highlightLine, codeTokens, matchTokens, resolveCodeSteps, codeMorphState } from './code.js';
const DEFAULT_DUR = { draw: 0.9, write: 0.8, pop: 0.45, rise: 0.55, fade: 0.5, zoom: 0.6, drop: 0.55, grow: 1.0, none: 0.001, 'slide-left': 0.55, 'slide-right': 0.55, 'slide-up': 0.55, 'slide-down': 0.55 };
const ENTERS = ['draw', 'write', 'type', 'words', 'sync', 'pop', 'rise', 'fade', 'zoom', 'drop', 'grow', 'none', 'slide-left', 'slide-right', 'slide-up', 'slide-down'];
@@ -1291,7 +1291,11 @@ export class Stage {
const ctx = this.ctx;
const C = th.code;
const size = o.size ?? 32;
- const lines = String(src).replace(/\t/g, ' ').split('\n');
+ const steps = Array.isArray(src) ? resolveCodeSteps(src, o, (v) => this.time(v)) : null;
+ if (steps) o = { ...o, at: o.at ?? steps[0].at };
+ const morph = steps ? codeMorphState(steps, this.t, o.morphDur ?? 0.8, this.pace) : null;
+ const lines = steps ? steps[morph.to].lines : String(src).replace(/\t/g, ' ').split('\n');
+ const firstLines = steps ? steps[0].lines : lines;
const lh = size * 1.5;
const pad = size * 0.9;
const barH = o.title === false ? 0 : size * 1.6;
@@ -1300,20 +1304,25 @@ export class Stage {
ctx.font = font;
const charW = ctx.measureText('M').width;
ctx.restore();
- const numW = o.lineNumbers === false ? 0 : charW * (String(lines.length).length + 2);
- const w = o.w ?? Math.min(this._w(0.86), Math.max(...lines.map((l) => l.length)) * charW + numW + pad * 2);
- const h = o.h ?? lines.length * lh + pad * 1.6 + barH;
+ const maxLines = steps ? Math.max(...steps.map((step) => step.lines.length)) : lines.length;
+ const numW = o.lineNumbers === false ? 0 : charW * (String(maxLines).length + 2);
+ const allLines = steps ? steps.flatMap((step) => step.lines) : lines;
+ const naturalW = Math.max(...allLines.map((l) => l.length)) * charW + numW + pad * 2;
+ const w = o.w ?? Math.min(this._w(0.86), naturalW);
+ const h = o.h ?? (morph ? morph.lines : lines.length) * lh + pad * 1.6 + barH;
const x = o.x ?? this.cx;
const y = o.y ?? this.cy;
this._register(o.id, x, y, w, h);
const at = this.time(o.at ?? 0);
const reveal = o.reveal ?? 'type';
const cps = (o.cps ?? 40) * this.pace;
- const chars = lines.reduce((a, l) => a + l.length + 1, 0);
+ const chars = firstLines.reduce((a, l) => a + l.length + 1, 0);
const typeDur = chars / cps;
const lineDelay = (o.lineDelay ?? 0.3) / this.pace;
const startText = at + 0.35 / this.pace;
if (reveal === 'type') this._record('code', startText, typeDur, { sfx: o.sfx }, { label: 'typing', sustain: true });
+ if (steps) steps.slice(1).forEach((step, i) => this._record('code', step.at, (o.morphDur ?? 0.8) / this.pace,
+ { sfx: o.sfx === false || o.sfx === null ? false : undefined, sfxGain: 0.2 }, { sfx: 'whoosh', label: `morph${i + 2}` }));
const life = this._life({ ...o, sfx: null }, 'code', { dur: 0.5 });
if (!life) return geom(x, y, w, h);
this._push(x, y, life, o);
@@ -1335,8 +1344,20 @@ export class Stage {
ctx.fillText(String(o.title), 0, -h / 2 + barH / 2 + 4);
}
}
- if (o.highlight) {
- const hl = Array.isArray(o.highlight) ? o.highlight : [o.highlight];
+ if (steps && morph.to) {
+ const drawHighlight = (step, alpha) => {
+ const hl = Array.isArray(step.highlight) ? step.highlight : step.highlight ? [step.highlight] : [];
+ ctx.save();
+ ctx.globalAlpha *= alpha;
+ ctx.fillStyle = C.highlight;
+ for (const n of hl) ctx.fillRect(-w / 2 + 6, top + (n - 1) * lh - lh * 0.22, w - 12, lh);
+ ctx.restore();
+ };
+ drawHighlight(steps[morph.from], 1 - morph.p);
+ drawHighlight(steps[morph.to], morph.p);
+ } else if (steps ? steps[0].highlight : o.highlight) {
+ const highlight = steps ? steps[0].highlight : o.highlight;
+ const hl = Array.isArray(highlight) ? highlight : [highlight];
const ha = clamp((this.t - this.time(o.highlightAt ?? at + 0.4 / this.pace)) / (0.4 / this.pace));
if (ha > 0) {
ctx.save();
@@ -1350,38 +1371,75 @@ export class Stage {
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const room = w / 2 - pad * 0.5 - (left + numW);
- lines.forEach((line, i) => {
- if (ctx.measureText(line).width > room) this._overflow(`code line ${i + 1} ("${line.trim().slice(0, 40)}") is wider than its window; shorten it, lower size or raise w`);
- });
+ (steps || [{ lines }]).forEach((step, n) => step.lines.forEach((line, i) => {
+ if (ctx.measureText(line).width > room) this._overflow(`code ${steps ? `step ${n + 1} ` : ''}line ${i + 1} ("${line.trim().slice(0, 40)}") is wider than its window; shorten it, lower size or raise w`);
+ }));
ctx.save();
ctx.beginPath();
ctx.rect(-w / 2, -h / 2, w, h);
ctx.clip();
- let budget = reveal === 'type' ? Math.floor((this.t - startText) * cps) : Infinity;
- lines.forEach((line, i) => {
- if (reveal === 'lines' && this.t < startText + i * lineDelay) return;
- if (budget <= 0 && reveal === 'type') return;
- const ly = top + i * lh;
+ if (steps && morph.to && morph.p < 1) {
+ const position = (tok, step) => ({ x: left + numW + ctx.measureText(step.lines[tok.row].slice(0, tok.column)).width, y: top + tok.row * lh });
+ const drawToken = (tok, pos, alpha) => {
+ if (alpha <= 0) return;
+ ctx.save();
+ ctx.globalAlpha *= alpha;
+ ctx.fillStyle = C[tok.type] ?? C.fg;
+ ctx.fillText(tok.text, pos.x, pos.y);
+ ctx.restore();
+ };
+ const before = codeTokens(steps[morph.from].lines, o.lang ?? 'js');
+ const after = codeTokens(lines, o.lang ?? 'js');
+ const pairs = matchTokens(before, after);
+ const keptBefore = new Set(pairs.map(([a]) => a));
+ const keptAfter = new Set(pairs.map(([, b]) => b));
+ for (const [a, b] of pairs) {
+ const start = position(before[a], steps[morph.from]);
+ const end = position(after[b], steps[morph.to]);
+ drawToken(after[b], { x: lerp(start.x, end.x, morph.p), y: lerp(start.y, end.y, morph.p) }, 1);
+ }
+ before.forEach((tok, i) => { if (!keptBefore.has(i)) drawToken(tok, position(tok, steps[morph.from]), morph.removed); });
+ after.forEach((tok, i) => { if (!keptAfter.has(i)) drawToken(tok, position(tok, steps[morph.to]), morph.added); });
if (numW) {
ctx.fillStyle = C.lineNo;
ctx.textAlign = 'right';
- ctx.fillText(String(i + 1), left + numW - charW * 1.4, ly);
+ const oldCount = steps[morph.from].lines.length;
+ for (let i = 0; i < Math.max(oldCount, lines.length); i++) {
+ ctx.save();
+ ctx.globalAlpha *= i < Math.min(oldCount, lines.length) ? 1 : i < oldCount ? morph.removed : morph.added;
+ ctx.fillText(String(i + 1), left + numW - charW * 1.4, top + i * lh);
+ ctx.restore();
+ }
ctx.textAlign = 'left';
}
- let cx = left + numW;
- for (const tok of highlightLine(line, o.lang ?? 'js')) {
- let txt = tok.text;
- if (reveal === 'type') {
- if (budget <= 0) break;
- txt = txt.slice(0, budget);
- budget -= txt.length;
+ } else {
+ const activeReveal = morph?.to ? 'none' : reveal;
+ let budget = activeReveal === 'type' ? Math.floor((this.t - startText) * cps) : Infinity;
+ lines.forEach((line, i) => {
+ if (activeReveal === 'lines' && this.t < startText + i * lineDelay) return;
+ if (budget <= 0 && activeReveal === 'type') return;
+ const ly = top + i * lh;
+ if (numW) {
+ ctx.fillStyle = C.lineNo;
+ ctx.textAlign = 'right';
+ ctx.fillText(String(i + 1), left + numW - charW * 1.4, ly);
+ ctx.textAlign = 'left';
}
- ctx.fillStyle = C[tok.type] ?? C.fg;
- ctx.fillText(txt, cx, ly);
- cx += ctx.measureText(txt).width;
- }
- if (reveal === 'type') budget -= 1;
- });
+ let cx = left + numW;
+ for (const tok of highlightLine(line, o.lang ?? 'js')) {
+ let txt = tok.text;
+ if (activeReveal === 'type') {
+ if (budget <= 0) break;
+ txt = txt.slice(0, budget);
+ budget -= txt.length;
+ }
+ ctx.fillStyle = C[tok.type] ?? C.fg;
+ ctx.fillText(txt, cx, ly);
+ cx += ctx.measureText(txt).width;
+ }
+ if (activeReveal === 'type') budget -= 1;
+ });
+ }
ctx.restore();
this._logText({ text: 'code', x0: -w / 2, y0: -h / 2, x1: w / 2, y1: h / 2, size, fg: C.fg, bg: C.bg, block: true });
ctx.restore();
diff --git a/test/code-morph-browser.test.js b/test/code-morph-browser.test.js
new file mode 100644
index 0000000..ca0e132
--- /dev/null
+++ b/test/code-morph-browser.test.js
@@ -0,0 +1,99 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { findChrome } from '../src/browser.js';
+import { loadProject } from '../src/project.js';
+import { withEngine } from '../src/pipeline.js';
+
+let chrome;
+try { chrome = findChrome(); } catch {}
+
+test('code morphs draw deterministic tokens, highlights, geometry and sounds in the page', { skip: !chrome }, async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-code-morph-'));
+ try {
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'midnight', captions: false, music: false }));
+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo\n');
+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo(s) {} };');
+ const project = loadProject(dir);
+ const timeline = { pace: 1, duration: 6, frames: 180, fps: 30, width: 1920, height: 1080, transitionSeconds: 0,
+ scenes: [{ id: 'demo', index: 0, start: 0, dur: 6, words: [{ text: 'filter', start: 2, end: 2.5 }], marks: { rename: 4 }, voice: null, lead: 0, transition: 'none' }] };
+ await withEngine(project, timeline, {}, async page => {
+ const result = await page.evaluate(async () => {
+ const { boot } = await import('/engine/runtime.js');
+ const { engine } = await boot({ canvas: document.createElement('canvas') });
+ const steps = [
+ { code: 'const total = items.length;', at: 0.5 },
+ { code: 'const total = items\n .filter((i) => i.active)\n .length;', at: 'filter', highlight: [2] },
+ { code: 'const activeCount = items\n .filter((i) => i.active)\n .length;', at: '#rename', highlight: [] },
+ ];
+ let drawn = [];
+ let highlights = [];
+ let geometry;
+ const ctx = engine.ctx;
+ const fillText = ctx.fillText.bind(ctx);
+ const fillRect = ctx.fillRect.bind(ctx);
+ ctx.fillText = (text, x, y) => {
+ const pos = ctx.getTransform().transformPoint(new DOMPoint(x, y));
+ drawn.push({ text, x: pos.x, y: pos.y, alpha: ctx.globalAlpha });
+ fillText(text, x, y);
+ };
+ ctx.fillRect = (...args) => { highlights.push(ctx.globalAlpha); fillRect(...args); };
+ const draw = (t, src = steps, o = {}) => {
+ drawn = [];
+ highlights = [];
+ engine.scenesModule.demo = (s) => { geometry = s.code(src, { title: 'stats.js', size: 40, reveal: 'none', enter: 'none', ...o }); };
+ engine.drawScene(ctx, 0, t);
+ return { geometry, drawn, highlights, image: engine.canvas.toDataURL() };
+ };
+ const start = draw(1);
+ const mid = draw(2.4);
+ const end = draw(3);
+ const renameOut = draw(4.2);
+ const renameIn = draw(4.6);
+ const last = draw(5);
+ draw(0);
+ const repeated = draw(2.4);
+ const deterministic = repeated.image === mid.image;
+ const firstMatches = ['none', 'type', 'lines'].every((reveal) =>
+ draw(0.8, [steps[0]], { reveal }).image === draw(0.8, steps[0].code, { at: 0.5, reveal }).image);
+ const finalMatches = last.image === draw(5, steps[2].code, { at: 0.5, w: last.geometry.w }).image;
+ draw(0, steps, { reveal: 'type' });
+ const events = engine.collectEvents().events;
+ engine.sfxMode = 'minimal';
+ const minimal = engine.collectEvents().events.filter((e) => e.sfx);
+ engine.sfxMode = true;
+ draw(0, steps, { sfx: false });
+ const silent = engine.collectEvents().events.filter((e) => e.sfx);
+ draw(1, [steps[0], { ...steps[1], at: 20 }, { ...steps[2], at: 21 }], { w: 200 });
+ const issues = engine.check();
+ return { start: start.geometry, mid: mid.geometry, end: end.geometry, last: last.geometry,
+ lengthY: [start, mid, end].map((frame) => frame.drawn.find((d) => d.text === 'length')?.y),
+ renameOut: renameOut.drawn, renameIn: renameIn.drawn,
+ midHighlights: mid.highlights, lastHighlights: last.highlights,
+ firstMatches, finalMatches, deterministic, events, minimal, silent, issues };
+ });
+ assert.equal(result.deterministic, true);
+ assert.equal(result.firstMatches, true);
+ assert.equal(result.finalMatches, true);
+ assert.equal(result.start.w, result.end.w);
+ assert.equal(result.end.w, result.last.w);
+ assert.ok(Math.abs(result.mid.h - (result.start.h + result.end.h) / 2) < 1e-8);
+ assert.ok(Math.abs(result.lengthY[1] - (result.lengthY[0] + result.lengthY[2]) / 2) < 1e-8);
+ assert.ok(result.renameOut.some((d) => d.text === 'total' && Math.abs(d.alpha - 0.5) < 1e-8));
+ assert.equal(result.renameOut.some((d) => d.text === 'activeCount'), false);
+ assert.equal(result.renameIn.some((d) => d.text === 'total'), false);
+ assert.ok(result.renameIn.some((d) => d.text === 'activeCount' && Math.abs(d.alpha - 0.5) < 1e-8));
+ assert.ok(result.midHighlights.some((a) => Math.abs(a - 0.5) < 1e-8));
+ assert.ok(result.lastHighlights.every((a) => a === 0));
+ const sounds = result.events.filter((e) => e.sfx);
+ assert.deepEqual(sounds.map((e) => [e.sfx, e.at]), [['type', 0.85], ['whoosh', 2], ['whoosh', 4]]);
+ assert.ok(sounds.slice(1).every((e) => e.gain === 0.2));
+ assert.deepEqual(result.minimal, []);
+ assert.deepEqual(result.silent, []);
+ for (const n of [1, 2, 3]) assert.ok(result.issues.some((i) => i.message.includes(`code step ${n} line`)));
+ assert.ok(result.issues.some((i) => i.message.includes('20.00s but the scene ends')));
+ });
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+});
diff --git a/test/code-morph.test.js b/test/code-morph.test.js
new file mode 100644
index 0000000..906f5d3
--- /dev/null
+++ b/test/code-morph.test.js
@@ -0,0 +1,110 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { codeTokens, matchTokens, resolveCodeSteps, codeMorphState } from '../engine/code.js';
+import { Stage } from '../engine/stage.js';
+
+const tokens = (code) => codeTokens(code.split('\n'), 'js');
+const close = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} is not ${b}`);
+
+function matched(before, after) {
+ const a = tokens(before);
+ const b = tokens(after);
+ const pairs = matchTokens(a, b);
+ for (const [i, j] of pairs) {
+ assert.equal(a[i].text, b[j].text);
+ assert.equal(a[i].type, b[j].type);
+ }
+ return pairs.map(([i]) => a[i].text);
+}
+
+test('code tokens keep their positions and ignore whitespace', () => {
+ assert.deepEqual(tokens(' const total = items.length;').slice(0, 3), [
+ { text: 'const', type: 'keyword', row: 0, column: 2 },
+ { text: 'total', type: 'plain', row: 0, column: 8 },
+ { text: '=', type: 'punct', row: 0, column: 14 },
+ ]);
+ assert.equal(tokens('const x = "a b"; // a note').at(-1).text, '// a note');
+ assert.ok(tokens('const x = "a b";').some((t) => t.text === '"a b"'));
+});
+
+test('matching keeps existing tokens across insertions and deletions', () => {
+ const short = 'const total = items.length;';
+ const long = 'const total = items\n .filter((i) => i.active)\n .length;';
+ const expected = tokens(short).map((t) => t.text);
+ assert.deepEqual(matched(short, long), expected);
+ assert.deepEqual(matched(long, short), expected);
+});
+
+test('a rename removes and adds only the identifier', () => {
+ assert.deepEqual(matched('const total = items.length;', 'const activeCount = items.length;'),
+ ['const', '=', 'items', '.', 'length', ';']);
+});
+
+test('moved lines keep an ordered subsequence and move matching tokens to new rows', () => {
+ const a = tokens('first(alpha, beta, gamma);\nsecond(delta);');
+ const b = tokens('second(delta);\nfirst(alpha, beta, gamma);');
+ const pairs = matchTokens(a, b);
+ assert.ok(pairs.some(([i, j]) => a[i].row !== b[j].row && a[i].type === 'fn'));
+ assert.equal(pairs.length, 9);
+ pairs.slice(1).forEach(([i, j], n) => {
+ assert.ok(i > pairs[n][0]);
+ assert.ok(j > pairs[n][1]);
+ });
+});
+
+test('identical steps match every token, including repeated tokens', () => {
+ const a = tokens('const x = x + x;\nreturn x;');
+ assert.deepEqual(matchTokens(a, a), a.map((_, i) => [i, i]));
+ assert.deepEqual(matched('const x=1;', ' const x = 1;'), tokens('const x=1;').map((t) => t.text));
+ assert.deepEqual(matchTokens([], a), []);
+ assert.deepEqual(matchTokens(a, []), []);
+ assert.deepEqual(matchTokens([{ text: ' ', type: 'plain' }, { text: 'x', type: 'plain' }],
+ [{ text: 'x', type: 'plain' }, { text: '\n', type: 'plain' }]), [[1, 0]]);
+ assert.deepEqual(matchTokens([{ text: 'x', type: 'plain' }], [{ text: 'x', type: 'fn' }]), []);
+});
+
+test('matching handles forty lines of code', () => {
+ const code = Array.from({ length: 40 }, (_, i) => `const item${i} = items.filter((x) => x.id === ${i});`).join('\n');
+ assert.equal(matched(code, '// Added a comment\n' + code).length, tokens(code).length);
+});
+
+test('step times resolve seconds, words and markers with the stage time API', () => {
+ const engine = { theme: {}, config: {}, safeArea: { x: 0, y: 0, w: 1920, h: 1080 },
+ W: 1920, H: 1080, timeline: { pace: 1, scenes: [] } };
+ const scene = { id: 'demo', start: 0, words: [{ text: 'filter', start: 2, end: 2.5 }], marks: { rename: 4 } };
+ const s = new Stage(engine, null, scene, 0);
+ const steps = [{ code: 'x', at: 0.5 }, { code: 'y', at: 'filter', highlight: [2] }, { code: 'z', at: '#rename' }];
+ const resolved = resolveCodeSteps(steps, { highlight: [1] }, (v) => s.time(v));
+ assert.deepEqual(resolved.map((step) => step.at), [0.5, 2, 4]);
+ assert.deepEqual(resolved.map((step) => step.highlight), [[1], [2], [2]]);
+ assert.equal(resolveCodeSteps([{ code: '\tx' }], { at: '#rename' }, (v) => s.time(v))[0].at, 4);
+ assert.deepEqual(resolveCodeSteps([{ code: '\tx', highlight: [] }], {}, (v) => s.time(v))[0],
+ { at: 0, lines: [' x'], highlight: [] });
+ assert.throws(() => resolveCodeSteps([{ code: 'x', at: 'missing' }], {}, (v) => s.time(v)), /not in the narration/);
+ assert.throws(() => resolveCodeSteps([], {}, (v) => s.time(v)), /at least one step/);
+ assert.throws(() => resolveCodeSteps([{ at: 0 }], {}, (v) => s.time(v)), /needs a code string/);
+ assert.throws(() => resolveCodeSteps([{ code: 'x' }, { code: 'y' }], {}, (v) => s.time(v)), /step 2 needs an at time/);
+});
+
+test('morph height eases between line counts and follows pace and duration', () => {
+ const steps = resolveCodeSteps([{ code: 'a', at: 0.5 }, { code: 'a\nb\nc', at: 2 }, { code: 'd', at: 4 }], {}, (v) => v);
+ assert.equal(codeMorphState(steps, 1).lines, 1);
+ assert.equal(codeMorphState(steps, 2).lines, 1);
+ close(codeMorphState(steps, 2.2).lines, 1.125);
+ close(codeMorphState(steps, 2.4).lines, 2);
+ close(codeMorphState(steps, 2.6).lines, 2.875);
+ assert.equal(codeMorphState(steps, 3).lines, 3);
+ close(codeMorphState(steps, 4.4).lines, 2);
+ assert.equal(codeMorphState(steps, 5).lines, 1);
+ close(codeMorphState(steps, 2.2, 0.8, 2).lines, 2);
+ assert.equal(codeMorphState(steps, 2.4, 0.8, 2).lines, 3);
+ close(codeMorphState(steps, 2.2, 0.4).lines, 2);
+ assert.equal(codeMorphState(steps, 2, 0).lines, 3);
+ const middle = codeMorphState(steps, 2.4);
+ close(middle.removed, 0);
+ close(middle.added, 0);
+ close(codeMorphState(steps, 2.2).removed, 0.5);
+ close(codeMorphState(steps, 2.6).added, 0.5);
+ assert.deepEqual([middle.from, middle.to], [0, 1]);
+ assert.deepEqual(codeMorphState(steps, 2.2), codeMorphState(steps, 2.2));
+});