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.
JavaScript ai-agentsanimationcanvasclaude-codecodexexplainer-videoffmpegjavascriptkokoroproduct-demotext-to-speechvideo-generationwhisper
Let a project bring its own look (#5)
Vincent Schmalbachc1f72301daba
diff --git a/AGENTS.md b/AGENTS.mdindex 60bdabb..bc5ece7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -472,7 +472,7 @@ videos/<name>/| Setting | Default | What it does ||---|---|---|| `title` | from the script | shown in the preview |-| `theme` | `paper` | `paper`, `clean`, `chalk`, `blueprint`, `midnight` |+| `theme` | `paper` | a built-in look, or a relative path to a `.json` look file (see Custom looks) || `size` | `16:9` | a platform (`youtube`, `shorts`, `tiktok`, `reels`, `vertical`, `instagram`, `linkedin`, `square`), `16:9`, `9:16`, `1:1`, `4:5` or `WIDTHxHEIGHT` || `fps` | 30 | 24, 25, 30, 50 or 60 || `voice` | `af_heart` | see `explainroo voices` |@@ -501,6 +501,51 @@ The looks:| `blueprint` | white drawings on blueprint blue | wipe | tech || `midnight` | dark background with glowing colors | zoom | tech |+### Custom looks++A look file gives a project its own colors, fonts and texture without+changing explainroo. Set `"theme": "../brand/acme-look.json"` in `video.json`.+The path is relative to the video folder, so a file outside it can give+several videos the same look.++```json+{+ "extends": "clean",+ "name": "acme",+ "bg": "#fbfaf7",+ "ink": "#1d1b16",+ "accent": "orange",+ "colors": { "orange": "#e8590c" },+ "background": "dots",+ "transition": "fade",+ "music": "calm"+}+```++`extends` names the built-in look to start from. Every other key is+optional and changes only what it lists: `name`, `dark`, `bg`, `ink`, `muted`,+`surface`, `accent`, `colors`, `fonts`, `background`, `stroke`, `radius`,+`transition`, `music`, `code`, `terminal` and `caption`. In the nested ones,+like `colors` or `caption`, list only the values you change. `name` defaults+to the file name and cannot be a built-in name. Set `"dark": true` when you+give a light look a dark `bg`, so fills and shadows suit it.++Use colors like `"#e8590c"`. `caption.bg` and `code.highlight` also accept+`rgba(...)`. `accent` names one of the ten colors: red, orange, yellow,+green, teal, blue, purple, pink, gray or ink.++`fonts` sets the `display`, `body`, `hand` and `mono` roles. Each takes a+`family` and a numeric `weight`, for example+`"body": { "family": "Inter", "weight": 500 }`. Families must be built in+or listed in `video.json` under `fonts`. The look file does not load fonts.++`background` picks a texture: `paper` (paper grain), `dots` (a dot grid),+`chalk` (board smudges), `grid` (drafting lines), `glow` (two glows) or+`plain` (one flat color). Each uses your `bg`. Leave it out to keep the base+texture. `transition` and `music` set the look's defaults. Settings in+`video.json` still win. `preview` picks up look edits, and `check` warns+when `ink` or `muted` has too little contrast against `bg`.+## Commands| Command | What it does |diff --git a/engine/runtime.js b/engine/runtime.jsindex 22df162..7dae296 100644--- a/engine/runtime.js+++ b/engine/runtime.js@@ -13,8 +13,6 @@ import { playbackTextIssue } from './readability.js';Stage.UI = UI;-const AUTO_TRANSITION = { paper: 'brush', clean: 'slide', chalk: 'brush', blueprint: 'wipe', midnight: 'zoom' };-export async function fetchState() {const res = await fetch('/__state.json', { cache: 'no-store' });if (!res.ok) throw new Error(`could not load project state: ${res.status} ${await res.text()}`);@@ -76,7 +74,7 @@ export class Engine {this.appArea = areas.app;this.fps = config.fps;this.scale = scale;- this.theme = getTheme(config.theme);+ this.theme = getTheme(config.theme, config.look);this.pen = new Pen({ rough, theme: this.theme });this.icons = icons;this.iconCache = new Map();@@ -124,7 +122,7 @@ export class Engine {}transitionFor(sc) {- const name = sc.transition === 'auto' ? AUTO_TRANSITION[this.theme.name] : sc.transition;+ const name = sc.transition === 'auto' ? this.theme.transition : sc.transition;return name || 'fade';}@@ -289,6 +287,11 @@ export class Engine {check(step = 0.25, viewWidth = null) {const issues = [];const add = (level, scene, t, message) => issues.push({ level, scene, t: t === null ? null : Math.round(t * 100) / 100, message });+ if (this.config.look) {+ for (const [key, min] of [['ink', 4.5], ['muted', 3]]) {+ if (contrast(this.theme[key], this.theme.bg) < min) add('warn', null, null, `${this.config.theme}: ${key} has low contrast against bg; use colors with a contrast of at least ${min}`);+ }+ }for (const id of this.extraScenes) add('warn', id, null, `scenes.js has a function "${id}" but script.md has no scene with that id, so it is never shown`);const scratch = document.createElement('canvas');scratch.width = this.canvas.width;@@ -396,7 +399,7 @@ export class Engine {// Boots the engine for render, check or studio pages.export async function boot({ canvas, scale = 1, version = '' }) {const state = await fetchState();- const theme = getTheme(state.config.theme);+ const theme = getTheme(state.config.theme, state.config.look);const [icons, images, scenesMod, audio, iconTags] = await Promise.all([fetch('/engine/icons/lucide.json').then((r) => r.json()).then((j) => {// Old Lucide names keep working.diff --git a/engine/themes.js b/engine/themes.jsindex d7822ac..a98aca8 100644--- a/engine/themes.js+++ b/engine/themes.js@@ -1,9 +1,11 @@// The five looks. A theme decides colors, fonts, how strokes are drawn, how// elements enter, the default transition, the sound palette and the music.-import { mulberry32, mixColor, withAlpha } from './util.js';+import { mulberry32, mixColor, withAlpha, parseColor, rgba, clamp } from './util.js';const PAPER = {name: 'paper',+ background: 'paper',+ music: 'warm',dark: false,bg: '#f7f3ea',ink: '#26221d',@@ -34,6 +36,8 @@ const PAPER = {const CLEAN = {name: 'clean',+ background: 'dots',+ music: 'upbeat',dark: false,bg: '#f4f6fb',ink: '#111827',@@ -64,6 +68,8 @@ const CLEAN = {const CHALK = {name: 'chalk',+ background: 'chalk',+ music: 'calm',dark: true,bg: '#233d31',ink: '#f2f0e6',@@ -94,6 +100,8 @@ const CHALK = {const BLUEPRINT = {name: 'blueprint',+ background: 'grid',+ music: 'tech',dark: true,bg: '#12508f',ink: '#f1f7ff',@@ -124,6 +132,8 @@ const BLUEPRINT = {const MIDNIGHT = {name: 'midnight',+ background: 'glow',+ music: 'tech',dark: true,bg: '#0b1020',ink: '#e8eef8',@@ -154,10 +164,14 @@ const MIDNIGHT = {export const THEMES = { paper: PAPER, clean: CLEAN, chalk: CHALK, blueprint: BLUEPRINT, midnight: MIDNIGHT };-export function getTheme(name) {- const t = THEMES[name];+export function getTheme(name, look = null) {+ const t = THEMES[look ? look.extends : name];if (!t) throw new Error(`unknown theme "${name}". Themes: ${Object.keys(THEMES).join(', ')}`);- return t;+ if (!look) return t;+ const { extends: base, ...overrides } = look;+ const merge = (a, b) => Object.fromEntries(Object.entries({ ...a, ...b }).map(([k, v]) =>+ [k, v && typeof v === 'object' && !Array.isArray(v) ? merge(a?.[k], v) : v]));+ return merge(t, overrides);}// Resolves a color name ("blue", "accent", "ink", "muted") or passes a CSS color through.@@ -195,6 +209,15 @@ export function makeBackground(theme, W, H, seed = 1) {c.height = H;const g = c.getContext('2d');const rand = mulberry32(seed * 7919 + theme.name.length);+ const base = Object.values(THEMES).find((t) => t.background === theme.background);+ const bg = parseColor(theme.bg);+ const original = parseColor(base?.bg || theme.bg);+ // Shift the original tones with the background, keeping built-in pixels unchanged.+ const tone = (color) => {+ if (theme.bg === base?.bg) return color;+ const p = parseColor(color);+ return rgba({ r: clamp(p.r + bg.r - original.r, 0, 255), g: clamp(p.g + bg.g - original.g, 0, 255), b: clamp(p.b + bg.b - original.b, 0, 255), a: p.a });+ };const noise = (count, alphaMax, color, sizeMax = 1.6) => {for (let i = 0; i < count; i++) {g.fillStyle = withAlpha(color, rand() * alphaMax);@@ -202,15 +225,15 @@ export function makeBackground(theme, W, H, seed = 1) {g.fillRect(rand() * W, rand() * H, s, s);}};- switch (theme.name) {+ switch (theme.background) {case 'paper': {g.fillStyle = theme.bg;g.fillRect(0, 0, W, H);- noise(Math.round(W * H * 0.05), 0.07, '#6b5a3d');- noise(Math.round(W * H * 0.02), 0.08, '#ffffff', 2);+ noise(Math.round(W * H * 0.05), 0.07, tone('#6b5a3d'));+ noise(Math.round(W * H * 0.02), 0.08, tone('#ffffff'), 2);g.lineWidth = 0.7;for (let i = 0; i < 90; i++) {- g.strokeStyle = withAlpha('#8a7654', 0.05 + rand() * 0.05);+ g.strokeStyle = withAlpha(tone('#8a7654'), 0.05 + rand() * 0.05);const x = rand() * W;const y = rand() * H;const a = rand() * Math.PI;@@ -221,27 +244,27 @@ export function makeBackground(theme, W, H, seed = 1) {g.stroke();}const v = g.createRadialGradient(W / 2, H / 2, Math.min(W, H) * 0.35, W / 2, H / 2, Math.max(W, H) * 0.75);- v.addColorStop(0, 'rgba(120,96,60,0)');- v.addColorStop(1, 'rgba(120,96,60,0.10)');+ v.addColorStop(0, tone('rgba(120,96,60,0)'));+ v.addColorStop(1, tone('rgba(120,96,60,0.10)'));g.fillStyle = v;g.fillRect(0, 0, W, H);break;}- case 'clean': {+ case 'dots': {const gr = g.createLinearGradient(0, 0, W, H);- gr.addColorStop(0, '#f7f8fc');- gr.addColorStop(1, '#eef1f8');+ gr.addColorStop(0, tone('#f7f8fc'));+ gr.addColorStop(1, tone('#eef1f8'));g.fillStyle = gr;g.fillRect(0, 0, W, H);- g.fillStyle = 'rgba(17,24,39,0.045)';+ g.fillStyle = tone('rgba(17,24,39,0.045)');const step = 48;for (let y = step / 2; y < H; y += step) for (let x = step / 2; x < W; x += step) g.fillRect(x - 1.2, y - 1.2, 2.4, 2.4);break;}case 'chalk': {const gr = g.createRadialGradient(W * 0.45, H * 0.4, 0, W / 2, H / 2, Math.max(W, H) * 0.8);- gr.addColorStop(0, '#2a4a3b');- gr.addColorStop(1, '#1b3127');+ gr.addColorStop(0, tone('#2a4a3b'));+ gr.addColorStop(1, tone('#1b3127'));g.fillStyle = gr;g.fillRect(0, 0, W, H);for (let i = 0; i < 26; i++) {@@ -249,40 +272,40 @@ export function makeBackground(theme, W, H, seed = 1) {const y = rand() * H;const r = 80 + rand() * 320;const s = g.createRadialGradient(x, y, 0, x, y, r);- s.addColorStop(0, 'rgba(235,240,230,0.035)');- s.addColorStop(1, 'rgba(235,240,230,0)');+ s.addColorStop(0, tone('rgba(235,240,230,0.035)'));+ s.addColorStop(1, tone('rgba(235,240,230,0)'));g.fillStyle = s;g.fillRect(x - r, y - r, r * 2, r * 2);}- noise(Math.round(W * H * 0.03), 0.06, '#e8efe6');+ noise(Math.round(W * H * 0.03), 0.06, tone('#e8efe6'));break;}- case 'blueprint': {+ case 'grid': {const gr = g.createLinearGradient(0, 0, 0, H);- gr.addColorStop(0, '#14589d');- gr.addColorStop(1, '#0f4680');+ gr.addColorStop(0, tone('#14589d'));+ gr.addColorStop(1, tone('#0f4680'));g.fillStyle = gr;g.fillRect(0, 0, W, H);const minor = Math.round(Math.min(W, H) / 34);g.lineWidth = 1;for (let x = 0; x <= W; x += minor) {- g.strokeStyle = x % (minor * 5) === 0 ? 'rgba(190,225,255,0.20)' : 'rgba(190,225,255,0.08)';+ g.strokeStyle = tone(x % (minor * 5) === 0 ? 'rgba(190,225,255,0.20)' : 'rgba(190,225,255,0.08)');g.beginPath();g.moveTo(x + 0.5, 0);g.lineTo(x + 0.5, H);g.stroke();}for (let y = 0; y <= H; y += minor) {- g.strokeStyle = y % (minor * 5) === 0 ? 'rgba(190,225,255,0.20)' : 'rgba(190,225,255,0.08)';+ g.strokeStyle = tone(y % (minor * 5) === 0 ? 'rgba(190,225,255,0.20)' : 'rgba(190,225,255,0.08)');g.beginPath();g.moveTo(0, y + 0.5);g.lineTo(W, y + 0.5);g.stroke();}- noise(Math.round(W * H * 0.01), 0.05, '#ffffff');+ noise(Math.round(W * H * 0.01), 0.05, tone('#ffffff'));break;}- case 'midnight': {+ case 'glow': {g.fillStyle = theme.bg;g.fillRect(0, 0, W, H);const glow = (x, y, r, color) => {@@ -292,9 +315,9 @@ export function makeBackground(theme, W, H, seed = 1) {g.fillStyle = s;g.fillRect(0, 0, W, H);};- glow(W * 0.12, H * 0.08, Math.max(W, H) * 0.6, 'rgba(34,211,238,0.10)');- glow(W * 0.92, H * 0.95, Math.max(W, H) * 0.55, 'rgba(167,139,250,0.10)');- noise(Math.round(W * H * 0.01), 0.05, '#ffffff');+ glow(W * 0.12, H * 0.08, Math.max(W, H) * 0.6, tone('rgba(34,211,238,0.10)'));+ glow(W * 0.92, H * 0.95, Math.max(W, H) * 0.55, tone('rgba(167,139,250,0.10)'));+ noise(Math.round(W * H * 0.01), 0.05, tone('#ffffff'));break;}default:diff --git a/src/cli.js b/src/cli.jsindex 5fd2817..0701192 100644--- a/src/cli.js+++ b/src/cli.js@@ -179,7 +179,7 @@ export async function main(argv) {blueprint: 'white technical drafting on blueprint blue with a grid; wipe transitions; tech music',midnight: 'dark developer look with glowing accents; zoom transitions; tech music',};- print(THEMES.map((t) => `${t.padEnd(10)} ${desc[t]}`).join('\n') + `\n\nmusic styles: ${MUSIC_STYLES.join(', ')}`, { themes: desc, music: MUSIC_STYLES });+ print(THEMES.map((t) => `${t.padEnd(10)} ${desc[t]}`).join('\n') + `\n\nCustom looks: set theme in video.json to a relative .json file that extends a built-in look.\nmusic styles: ${MUSIC_STYLES.join(', ')}`, { themes: desc, music: MUSIC_STYLES });return 0;}case 'formats': {@@ -254,7 +254,15 @@ async function preview(dir, flags, log) {const server = await startServer({ projectDir: project.dir, getState: () => (lastError ? { ...state, error: lastError } : state), port: num(flags.port, 'port') ?? 4400 });log(`preview: ${server.url} (Ctrl+C to stop)`);const watched = ['video.json', 'script.md'];- const stamp = () => watched.map((f) => { try { return fs.statSync(path.join(project.dir, f)).mtimeMs; } catch { return 0; } }).join(':');+ const stamp = () => {+ const files = watched.map((f) => path.join(project.dir, f));+ // Read the current path too, so creating a missing look file clears its error.+ try {+ const { theme } = JSON.parse(fs.readFileSync(files[0], 'utf8'));+ if (typeof theme === 'string' && theme.endsWith('.json')) files.push(path.resolve(project.dir, theme));+ } catch {}+ return files.map((f) => { try { const st = fs.statSync(f); return `${f}:${st.mtimeMs}:${st.size}`; } catch { return `${f}:missing`; } }).join('|');+ };let last = stamp();let busy = false;const timer = setInterval(async () => {@@ -264,7 +272,7 @@ async function preview(dir, flags, log) {try {if (now !== last) {last = now;- log('script or settings changed, updating narration');+ log('script, settings or look changed, updating project');project = loadProject(project.dir);({ timeline } = await prepare(project, { log }));lastError = null;diff --git a/src/pipeline.js b/src/pipeline.jsindex 962fcd2..7a8d44f 100644--- a/src/pipeline.js+++ b/src/pipeline.js@@ -30,6 +30,7 @@ export function makeState(project, timeline) {const assets = listAssets(project.dir);const stamp = [fileStamp(project.paths.scenes),+ ...(project.paths.look ? [fileStamp(project.paths.look)] : []),...assets.map((a) => a + '@' + fileStamp(path.join(project.dir, a))),...fs.readdirSync(project.dir).filter((f) => f.endsWith('.js') || f.endsWith('.mjs')).map((f) => f + '@' + fileStamp(path.join(project.dir, f))),].join('|');diff --git a/src/project.js b/src/project.jsindex af91b37..c25b5e8 100644--- a/src/project.js+++ b/src/project.js@@ -7,11 +7,13 @@ import fs from 'node:fs';import path from 'node:path';import { parseScript } from './script.js';import { VOICES } from './models.js';+import { THEMES as LOOKS } from '../engine/themes.js';+import { parseColor } from '../engine/util.js';-export const THEMES = ['paper', 'clean', 'chalk', 'blueprint', 'midnight'];+export const THEMES = Object.keys(LOOKS);export const MUSIC_STYLES = ['warm', 'upbeat', 'calm', 'tech', 'playful'];export const TRANSITIONS = ['auto', 'fade', 'slide', 'wipe', 'zoom', 'brush', 'cut'];-export const THEME_MUSIC = { paper: 'warm', clean: 'upbeat', chalk: 'calm', blueprint: 'tech', midnight: 'tech' };+export const THEME_MUSIC = Object.fromEntries(THEMES.map((name) => [name, LOOKS[name].music]));const ASPECTS = { '16:9': [1920, 1080], '9:16': [1080, 1920], '1:1': [1080, 1080], '4:5': [1080, 1350] };// Named formats for the usual places a video goes. Vertical apps draw their@@ -68,6 +70,81 @@ function fail(msg) {throw new ProjectError(msg);}+const LOOK_KEYS = ['extends', 'name', 'dark', 'bg', 'ink', 'muted', 'surface', 'accent', 'colors', 'fonts', 'background', 'stroke', 'radius', 'transition', 'music', 'code', 'terminal', 'caption'];+const TEXTURES = ['paper', 'dots', 'chalk', 'grid', 'glow', 'plain'];+const BUILTIN_FONTS = [...new Set(JSON.parse(fs.readFileSync(new URL('../fonts/fonts.json', import.meta.url), 'utf8')).map((f) => f.family))];++function lookPath(theme) {+ return typeof theme === 'string' && theme.endsWith('.json') && !path.isAbsolute(theme) && !path.win32.isAbsolute(theme);+}++export function loadLook(dir, file, fonts = []) {+ const bad = (key, message) => fail(`${file}: ${key} ${message}`);+ let raw;+ try {+ raw = JSON.parse(fs.readFileSync(path.resolve(dir, file), 'utf8'));+ } catch (e) {+ if (e.code === 'ENOENT') bad('theme', 'file is missing. Check the path in video.json.');+ bad('theme', `file could not be read as JSON: ${e.message}`);+ }+ const object = (value, key, keys) => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) bad(key, 'must be an object');+ for (const k of Object.keys(value)) if (!keys.includes(k)) bad(`${key}.${k}`, `is unknown. Known: ${keys.join(', ')}`);+ };+ const oneOf = (value, key, values) => {+ if (!values.includes(value)) bad(key, `must be one of ${values.join(', ')}`);+ };+ const number = (value, key, min, max) => {+ if (!(typeof value === 'number' && Number.isFinite(value) && value >= min && value <= max)) bad(key, `must be a number between ${min} and ${max}`);+ };+ const color = (value, key, alpha = false) => {+ const p = typeof value === 'string' && /^rgba\(\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*\d+(?:\.\d+)?\s*,\s*(?:\d+(?:\.\d+)?|\.\d+)\s*\)$/.test(value) ? parseColor(value) : null;+ if (!(typeof value === 'string' && HEX.test(value)) && !(alpha && p && [p.r, p.g, p.b].every((v) => v <= 255) && p.a <= 1)) {+ bad(key, `must be a color like "#2563eb"${alpha ? ' or "rgba(17,24,39,0.82)"' : ''}`);+ }+ };+ object(raw, 'look', LOOK_KEYS);+ oneOf(raw.extends, 'extends', THEMES);+ const name = raw.name === undefined ? path.basename(file, '.json') : raw.name;+ if (!(typeof name === 'string' && name.trim()) || THEMES.includes(name)) bad('name', 'must be a non-empty name that is not a built-in look');+ if (raw.dark !== undefined && typeof raw.dark !== 'boolean') bad('dark', 'must be true or false');+ for (const k of ['bg', 'ink', 'muted', 'surface']) if (raw[k] !== undefined) color(raw[k], k);+ if (raw.accent !== undefined) oneOf(raw.accent, 'accent', Object.keys(LOOKS.paper.colors));+ if (raw.background !== undefined) oneOf(raw.background, 'background', TEXTURES);+ if (raw.transition !== undefined) oneOf(raw.transition, 'transition', TRANSITIONS.filter((v) => v !== 'auto'));+ if (raw.music !== undefined) oneOf(raw.music, 'music', MUSIC_STYLES);+ if (raw.radius !== undefined) number(raw.radius, 'radius', 0, 200);+ for (const group of ['colors', 'code', 'terminal', 'caption']) {+ if (raw[group] === undefined) continue;+ const base = LOOKS[raw.extends][group];+ object(raw[group], group, Object.keys(base));+ for (const [k, v] of Object.entries(raw[group])) color(v, `${group}.${k}`, String(base[k]).startsWith('rgba('));+ }+ if (raw.fonts !== undefined) {+ object(raw.fonts, 'fonts', Object.keys(LOOKS.paper.fonts));+ for (const [role, f] of Object.entries(raw.fonts)) {+ const key = `fonts.${role}`;+ object(f, key, ['family', 'weight']);+ if (f.family !== undefined && ![...BUILTIN_FONTS, ...fonts.map((v) => v.family)].includes(f.family)) bad(`${key}.family`, `must be listed in video.json fonts or be built in. Built-in families: ${BUILTIN_FONTS.join(', ')}`);+ if (f.weight !== undefined) {+ number(f.weight, `${key}.weight`, 1, 1000);+ if (!Number.isInteger(f.weight)) bad(`${key}.weight`, 'must be a whole number');+ }+ }+ }+ if (raw.stroke !== undefined) {+ const ranges = { width: [0, 20], roughness: [0, 5], bowing: [0, 5], hachureGap: [1, 100], fillWeight: [0, 20], glow: [0, 100] };+ object(raw.stroke, 'stroke', ['rough', ...Object.keys(ranges), 'fillStyle', 'texture']);+ for (const [k, v] of Object.entries(raw.stroke)) {+ if (ranges[k]) number(v, `stroke.${k}`, ...ranges[k]);+ else if (k === 'rough' && typeof v !== 'boolean') bad('stroke.rough', 'must be true or false');+ else if (k === 'fillStyle') oneOf(v, 'stroke.fillStyle', ['solid', 'hachure', 'cross-hatch', 'zigzag', 'dots']);+ else if (k === 'texture') oneOf(v, 'stroke.texture', ['chalk']);+ }+ }+ return { ...raw, name };+}+export function resolveSize(size) {if (FORMATS[size]) return { width: FORMATS[size].size[0], height: FORMATS[size].size[1], safe: FORMATS[size].safe || null };if (ASPECTS[size]) return { width: ASPECTS[size][0], height: ASPECTS[size][1] };@@ -79,11 +156,11 @@ export function resolveSize(size) {return { width, height };}-export function normalizeConfig(raw) {+export function normalizeConfig(raw, dir = '.') {const cfg = { ...DEFAULTS, ...raw };const unknown = Object.keys(raw).filter((k) => !(k in DEFAULTS) && !k.startsWith('_'));if (unknown.length) fail(`video.json has unknown setting(s): ${unknown.join(', ')}. Known: ${Object.keys(DEFAULTS).join(', ')}`);- if (!THEMES.includes(cfg.theme)) fail(`theme must be one of ${THEMES.join(', ')}, not "${cfg.theme}"`);+ if (!THEMES.includes(cfg.theme) && !lookPath(cfg.theme)) fail(`theme must be one of ${THEMES.join(', ')} or a relative path to a .json look file, not "${cfg.theme}"`);if (!VOICES[cfg.voice]) fail(`voice "${cfg.voice}" does not exist. Run "explainroo voices" for the list.`);if (!(cfg.speed >= 0.6 && cfg.speed <= 1.6)) fail('speed must be between 0.6 and 1.6');if (!(cfg.pace >= 0.7 && cfg.pace <= 1.6)) fail('pace must be between 0.7 and 1.6 (1 is normal, 1.3 is 30% faster)');@@ -144,8 +221,9 @@ export function normalizeConfig(raw) {if (f.style !== undefined && !['normal', 'italic'].includes(f.style)) fail(`${where}.style must be "normal" or "italic"`);});+ if (lookPath(cfg.theme)) cfg.look = loadLook(dir, cfg.theme, cfg.fonts);let music = cfg.music;- if (music === true) music = { style: THEME_MUSIC[cfg.theme] };+ if (music === true) music = { style: cfg.look ? (cfg.look.music ?? THEME_MUSIC[cfg.look.extends]) : THEME_MUSIC[cfg.theme] };else if (typeof music === 'string') music = { style: music };if (music) {// A faster pace plays the music a little faster too.@@ -179,7 +257,7 @@ export function loadProject(arg) {} catch (e) {fail(`video.json is not valid JSON: ${e.message}`);}- const config = normalizeConfig(raw);+ const config = normalizeConfig(raw, dir);for (const f of [...config.fonts.map((x) => x.src), ...(config.brand?.logo ? [config.brand.logo] : [])]) {if (!fs.existsSync(path.join(dir, f))) fail(`${f} is listed in video.json but the file is missing`);}@@ -191,7 +269,7 @@ export function loadProject(arg) {if (!fs.existsSync(scenesPath)) fail(`${scenesPath} is missing`);const build = path.join(dir, 'build');const out = path.join(dir, 'out');- return { dir, config, script, paths: { build, out, voice: path.join(build, 'voice'), scenes: scenesPath, script: scriptPath } };+ return { dir, config, script, paths: { build, out, voice: path.join(build, 'voice'), scenes: scenesPath, script: scriptPath, look: config.look ? path.resolve(dir, config.theme) : null } };}export function listAssets(dir) {diff --git a/test/looks-browser.test.js b/test/looks-browser.test.jsnew file mode 100644index 0000000..38facee--- /dev/null+++ b/test/looks-browser.test.js@@ -0,0 +1,109 @@+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';+import { buildTimeline } from '../src/timeline.js';++let chrome;+try { chrome = findChrome(); } catch {}++function fixture(t, look) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-look-browser-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: 'look.json', captions: false, sfx: false, fonts: [{ family: 'Figtree', src: 'assets/font.woff2', weight: 700 }] }));+ fs.writeFileSync(path.join(dir, 'look.json'), JSON.stringify(look));+ fs.mkdirSync(path.join(dir, 'assets'));+ fs.copyFileSync(new URL('../examples/unspar-demo/assets/fonts/Figtree-700.woff2', import.meta.url), path.join(dir, 'assets/font.woff2'));+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=2}\n\n## end {min=2}');+ fs.writeFileSync(path.join(dir, 'scenes.js'), `export default {+ demo(s) { s.text('Custom look', { y: 400, at: 0, size: 80 }); s.box('Example', { y: 650, at: 1 }); },+ end(s) { s.circle({ x: 960, y: 540, r: 100, at: 0 }); }+ };`);+ const project = loadProject(dir);+ return { dir, project, timeline: buildTimeline(project, {}) };+}++test('the page builds the custom look, loads its font and uses its transition without serving its JSON', { skip: !chrome }, async t => {+ const { project, timeline } = fixture(t, { extends: 'clean', dark: true, bg: '#152337', ink: '#ffffff', muted: '#c9d1cb', background: 'glow', transition: 'fade', music: 'calm', fonts: { body: { family: 'Figtree', weight: 700 } } });+ await withEngine(project, timeline, {}, async page => {+ const result = await page.evaluate(async () => {+ const { fetchState, Engine } = await import('/engine/runtime.js');+ const { getTheme } = await import('/engine/themes.js');+ const state = await fetchState();+ const theme = getTheme(state.config.theme, state.config.look);+ window.explainroo.frames([45, 61]);+ return {+ theme, music: state.config.music.style,+ transition: Engine.prototype.transitionFor.call({ theme }, state.timeline.scenes[1]),+ explicit: Engine.prototype.transitionFor.call({ theme }, { transition: 'cut' }),+ font: document.fonts.check('700 40px Figtree'),+ fetched: performance.getEntriesByType('resource').some(r => r.name.endsWith('/project/look.json')),+ status: (await fetch('/project/look.json')).status,+ issues: window.explainroo.check(),+ };+ });+ assert.equal(result.theme.background, 'glow');+ assert.equal(result.theme.bg, '#152337');+ assert.equal(result.theme.fonts.body.family, 'Figtree');+ assert.equal(result.font, true);+ assert.equal(result.transition, 'fade');+ assert.equal(result.explicit, 'cut');+ assert.equal(result.music, 'calm');+ assert.equal(result.fetched, false);+ assert.equal(result.status, 404);+ assert.deepEqual(result.issues, []);+ });+});++test('check warns about the custom look palette at the ink and muted thresholds', { skip: !chrome }, async t => {+ const { project, timeline } = fixture(t, { extends: 'clean', bg: '#ffffff', ink: '#888888', muted: '#bbbbbb' });+ await withEngine(project, timeline, {}, async page => {+ const result = await page.evaluate(async () => {+ const { Engine, fetchState } = await import('/engine/runtime.js');+ const state = await fetchState();+ const paletteWarnings = (config) => {+ const engine = new Engine({ canvas: document.createElement('canvas'), state: { ...state, config }, scenes: { demo(s) { s.circle({ at: 0 }); }, end(s) { s.circle({ at: 0 }); } }, icons: {}, images: new Map() });+ return engine.check().filter(i => i.message.startsWith('look.json:'));+ };+ return {+ low: paletteWarnings(state.config),+ good: paletteWarnings({ ...state.config, look: { ...state.config.look, ink: '#000000', muted: '#888888' } }),+ builtin: paletteWarnings({ ...state.config, theme: 'paper', look: null }),+ };+ });+ assert.equal(result.low.length, 2);+ assert.deepEqual(result.low.map(i => i.level), ['warn', 'warn']);+ assert.match(result.low[0].message, /ink.*at least 4.5/);+ assert.match(result.low[1].message, /muted.*at least 3/);+ assert.equal(result.low[0].scene, null);+ assert.deepEqual(result.good, []);+ assert.deepEqual(result.builtin, []);+ });+});++test('all six textures follow bg and render deterministically regardless of the base look', { skip: !chrome }, async t => {+ const { project, timeline } = fixture(t, { extends: 'clean' });+ await withEngine(project, timeline, {}, async page => {+ const results = await page.evaluate(async () => {+ const { getTheme, makeBackground } = await import('/engine/themes.js');+ return ['paper', 'dots', 'chalk', 'grid', 'glow', 'plain'].map(background => {+ const draw = (base, bg) => makeBackground(getTheme('', { extends: base, name: 'custom', background, bg }), 160, 90, 4);+ const a = draw('clean', '#9b5c32');+ const b = draw('paper', '#9b5c32');+ const c = draw('clean', '#28517a');+ const d = draw('clean', '#9b5c32');+ return { background, same: a.toDataURL() === b.toDataURL(), deterministic: a.toDataURL() === d.toDataURL(), changed: a.toDataURL() !== c.toDataURL(), pixel: [...a.getContext('2d').getImageData(80, 45, 1, 1).data] };+ });+ });+ for (const r of results) {+ assert.equal(r.same, true, r.background);+ assert.equal(r.deterministic, true, r.background);+ assert.equal(r.changed, true, r.background);+ }+ assert.deepEqual(results.at(-1).pixel, [155, 92, 50, 255]);+ });+});diff --git a/test/looks-preview.test.js b/test/looks-preview.test.jsnew file mode 100644index 0000000..e686135--- /dev/null+++ b/test/looks-preview.test.js@@ -0,0 +1,57 @@+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 { spawn } from 'node:child_process';+import { once } from 'node:events';+import { setTimeout } from 'node:timers/promises';+import { fileURLToPath } from 'node:url';++test('preview reloads an outside look and recovers after invalid or missing look files', { timeout: 15000 }, async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-look-preview-'));+ const dir = path.join(root, 'video');+ fs.mkdirSync(dir);+ const settings = path.join(dir, 'video.json');+ const look = path.join(root, 'brand.json');+ fs.writeFileSync(settings, JSON.stringify({ theme: '../brand.json' }));+ fs.writeFileSync(look, JSON.stringify({ extends: 'clean' }));+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=1}');+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo() {} };');+ const bin = fileURLToPath(new URL('../bin/explainroo.js', import.meta.url));+ const child = spawn(process.execPath, [bin, 'preview', dir, '--port', '0'], { stdio: ['ignore', 'ignore', 'pipe'] });+ const exited = once(child, 'exit');+ let logs = '';+ child.stderr.on('data', chunk => { logs += chunk; });+ const until = async fn => {+ for (let i = 0; i < 80; i++) {+ const value = await fn();+ if (value) return value;+ await setTimeout(100);+ }+ assert.fail(`preview did not update: ${logs}`);+ };+ try {+ const url = await until(() => /preview: (http:\/\/127\.0\.0\.1:\d+)/.exec(logs)?.[1]);+ const state = async () => (await fetch(url + '/__state.json')).json();+ const first = await state();+ fs.writeFileSync(look, JSON.stringify({ extends: 'clean', bg: '#ffffff' }));+ const changed = await until(async () => {+ const s = await state();+ return s.config.look.bg === '#ffffff' && s;+ });+ assert.notEqual(changed.version, first.version);+ fs.writeFileSync(look, JSON.stringify({ extends: 'clean', dark: 'yes' }));+ await until(async () => (await state()).error?.includes('dark'));+ fs.writeFileSync(look, JSON.stringify({ extends: 'clean', bg: '#eeeeee' }));+ await until(async () => { const s = await state(); return !s.error && s.config.look.bg === '#eeeeee'; });+ fs.writeFileSync(settings, JSON.stringify({ theme: '../missing.json' }));+ await until(async () => (await state()).error?.includes('missing.json'));+ fs.writeFileSync(path.join(root, 'missing.json'), JSON.stringify({ extends: 'paper' }));+ await until(async () => { const s = await state(); return !s.error && s.config.look.extends === 'paper'; });+ } finally {+ child.kill('SIGTERM');+ await exited;+ fs.rmSync(root, { recursive: true, force: true });+ }+});diff --git a/test/looks.test.js b/test/looks.test.jsnew file mode 100644index 0000000..5e92847--- /dev/null+++ b/test/looks.test.js@@ -0,0 +1,130 @@+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 { loadLook, loadProject, normalizeConfig, ProjectError, THEMES } from '../src/project.js';+import { getTheme } from '../engine/themes.js';+import { makeState } from '../src/pipeline.js';++function fixture(t) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-look-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ const dir = path.join(root, 'video');+ fs.mkdirSync(dir);+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme: '../brand.json' }));+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo\nHello.');+ fs.writeFileSync(path.join(dir, 'scenes.js'), 'export default { demo() {} };');+ const file = path.join(root, 'brand.json');+ const write = (raw) => fs.writeFileSync(file, JSON.stringify(raw));+ return { root, dir, file, write };+}++test('a shared look outside the project is loaded in Node and deep merged without changing the base', t => {+ const { dir, write } = fixture(t);+ const base = structuredClone(getTheme('paper'));+ write({ extends: 'paper', bg: '#fbfaf7', colors: { orange: '#e8590c' }, fonts: { display: { weight: 800 } }, stroke: { width: 3 }, code: { bg: '#1d1b16' }, terminal: { prompt: '#e8590c' }, caption: { active: '#e8590c' } });+ const project = loadProject(dir);+ const look = getTheme(project.config.theme, project.config.look);+ assert.equal(project.config.look.name, 'brand');+ assert.equal(project.paths.look, path.resolve(dir, '../brand.json'));+ assert.equal(look.bg, '#fbfaf7');+ assert.equal(look.colors.orange, '#e8590c');+ assert.equal(look.colors.blue, base.colors.blue);+ assert.deepEqual(look.fonts.display, { family: 'Kalam', weight: 800 });+ assert.equal(look.stroke.roughness, base.stroke.roughness);+ assert.equal(look.stroke.width, 3);+ assert.equal(look.code.bg, '#1d1b16');+ assert.equal(look.code.fg, base.code.fg);+ assert.equal(look.terminal.prompt, '#e8590c');+ assert.equal(look.terminal.bg, base.terminal.bg);+ assert.equal(look.caption.active, '#e8590c');+ assert.equal(look.caption.bg, base.caption.bg);+ assert.deepEqual(getTheme('paper'), base);+});++test('look defaults inherit each base texture, transition and music; explicit video settings win', t => {+ const { dir, write } = fixture(t);+ const expected = [['paper', 'paper', 'brush', 'warm'], ['clean', 'dots', 'slide', 'upbeat'], ['chalk', 'chalk', 'brush', 'calm'], ['blueprint', 'grid', 'wipe', 'tech'], ['midnight', 'glow', 'zoom', 'tech']];+ for (const [base, background, transition, music] of expected) {+ write({ extends: base });+ const cfg = loadProject(dir).config;+ const theme = getTheme(cfg.theme, cfg.look);+ assert.equal(theme.background, background);+ assert.equal(theme.transition, transition);+ assert.equal(cfg.transition, 'auto');+ assert.equal(cfg.music.style, music);+ assert.equal(normalizeConfig({ theme: base }).music.style, music);+ }+ write({ extends: 'clean', name: 'acme', background: 'plain', transition: 'fade', music: 'calm' });+ const cfg = loadProject(dir).config;+ assert.equal(getTheme(cfg.theme, cfg.look).background, 'plain');+ assert.equal(getTheme(cfg.theme, cfg.look).transition, 'fade');+ assert.equal(cfg.music.style, 'calm');+ for (const music of ['playful', { style: 'tech', volume: 0.2 }, false]) {+ const explicit = normalizeConfig({ theme: '../brand.json', transition: 'cut', music }, dir);+ assert.equal(explicit.transition, 'cut');+ assert.deepEqual(explicit.music, music === false ? null : { volume: 0.5, seed: 1, tempo: 1, ...(typeof music === 'string' ? { style: music } : music) });+ }+});++test('look fonts must be built in or listed by the video', t => {+ const { dir, write } = fixture(t);+ write({ extends: 'clean', fonts: { body: { family: 'Inter', weight: 500 } } });+ assert.equal(loadProject(dir).config.look.fonts.body.family, 'Inter');+ write({ extends: 'clean', fonts: { display: { family: 'Figtree', weight: 800 } } });+ assert.throws(() => loadProject(dir), /brand.json: fonts.display.family.*Built-in families:.*Inter/);+ const cfg = normalizeConfig({ theme: '../brand.json', fonts: [{ family: 'Figtree', src: 'assets/font.woff2' }] }, dir);+ assert.equal(getTheme(cfg.theme, cfg.look).fonts.display.family, 'Figtree');+});++test('look validation names the file and bad key for every kind of value', t => {+ const { dir, write } = fixture(t);+ const cases = [+ [[], 'look'], [null, 'look'], [{}, 'extends'], [{ extends: 'custom' }, 'extends'],+ [{ typo: true }, 'look.typo'], [{ name: 'clean' }, 'name'], [{ name: '' }, 'name'], [{ name: 2 }, 'name'], [{ name: null }, 'name'],+ [{ dark: 'false' }, 'dark'], [{ bg: 'red' }, 'bg'], [{ ink: '#fff' }, 'ink'], [{ muted: null }, 'muted'], [{ surface: '#gggggg' }, 'surface'],+ [{ accent: 'cyan' }, 'accent'], [{ background: 'clean' }, 'background'], [{ transition: 'auto' }, 'transition'], [{ music: false }, 'music'],+ [{ radius: -1 }, 'radius'], [{ radius: 201 }, 'radius'], [{ radius: '18' }, 'radius'],+ [{ colors: [] }, 'colors'], [{ colors: { cyan: '#000000' } }, 'colors.cyan'], [{ colors: { blue: 'rgba(1,2,3,0.5)' } }, 'colors.blue'],+ [{ fonts: null }, 'fonts'], [{ fonts: { title: {} } }, 'fonts.title'], [{ fonts: { body: [] } }, 'fonts.body'],+ [{ fonts: { body: { style: 'italic' } } }, 'fonts.body.style'], [{ fonts: { body: { family: '' } } }, 'fonts.body.family'],+ [{ fonts: { body: { weight: 0 } } }, 'fonts.body.weight'], [{ fonts: { body: { weight: 1001 } } }, 'fonts.body.weight'], [{ fonts: { body: { weight: 1.5 } } }, 'fonts.body.weight'],+ [{ stroke: null }, 'stroke'], [{ stroke: { wat: 3 } }, 'stroke.wat'], [{ stroke: { rough: 1 } }, 'stroke.rough'],+ [{ stroke: { fillStyle: 'fake' } }, 'stroke.fillStyle'], [{ stroke: { texture: 'paper' } }, 'stroke.texture'],+ [{ stroke: { width: 21 } }, 'stroke.width'], [{ stroke: { roughness: -1 } }, 'stroke.roughness'], [{ stroke: { bowing: '1' } }, 'stroke.bowing'],+ [{ stroke: { hachureGap: 0 } }, 'stroke.hachureGap'], [{ stroke: { fillWeight: 21 } }, 'stroke.fillWeight'], [{ stroke: { glow: 101 } }, 'stroke.glow'],+ [{ code: [] }, 'code'], [{ code: { unknown: '#000000' } }, 'code.unknown'], [{ terminal: { fg: 'white' } }, 'terminal.fg'],+ [{ caption: { bg: 'rgba(256,0,0,0.5)' } }, 'caption.bg'], [{ caption: { bg: 'rgba(1,2,3,1.1)' } }, 'caption.bg'],+ [{ code: { highlight: 'rgba(1,2,3,-1)' } }, 'code.highlight'], [{ code: { highlight: 'rgb(1,2,3)' } }, 'code.highlight'],+ [{ caption: { active: 'rgba(1,2,3,0.5)' } }, 'caption.active'],+ ];+ for (const [raw, key] of cases) {+ write(raw && !Array.isArray(raw) ? { extends: 'clean', ...raw } : raw);+ if (key === 'extends' && Object.keys(raw).length === 0) write(raw);+ assert.throws(() => loadProject(dir), e => e instanceof ProjectError && e.message.includes(`brand.json: ${key} `), JSON.stringify(raw));+ }+ write({ extends: 'clean', caption: { bg: 'rgba(1, 2, 3, .5)' }, code: { highlight: '#abcdef' } });+ assert.equal(loadProject(dir).config.look.caption.bg, 'rgba(1, 2, 3, .5)');+ for (const theme of ['/tmp/look.json', 'C:\\look.json', 'look.txt', 3, null]) assert.throws(() => normalizeConfig({ theme }), /relative path/);+});++test('missing and malformed look files have friendly errors', t => {+ const { dir, file } = fixture(t);+ assert.throws(() => loadProject(dir), /brand.json: theme file is missing/);+ fs.writeFileSync(file, '{');+ assert.throws(() => loadLook(dir, '../brand.json'), /brand.json: theme file could not be read as JSON/);+});++test('editing a look changes the state version and reloads its values', t => {+ const { dir, file, write } = fixture(t);+ write({ extends: 'clean', bg: '#ffffff' });+ const first = makeState(loadProject(dir), {});+ const stamp = fs.statSync(file);+ write({ extends: 'clean', bg: '#eeeeee' });+ fs.utimesSync(file, stamp.atime, stamp.mtime);+ const next = makeState(loadProject(dir), {});+ assert.notEqual(first.version, next.version);+ assert.equal(next.config.look.bg, '#eeeeee');+ assert.deepEqual(THEMES, ['paper', 'clean', 'chalk', 'blueprint', 'midnight']);+});