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.

Suggest a readable color when check finds low-contrast text (#12)

Vincent Schmalbach3c9c9b89ca38
diff --git a/AGENTS.md b/AGENTS.md
index ff571a8..10d3c9b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1031,7 +1031,7 @@ font roles are `display`, `body`, `hand` and `mono`.
only, not its label, so an arrow that leaves downward crosses the label.
- Colored text in `paper` and `clean`. Green, orange and red are light enough
for shapes but often too light for text. `check` warns about low contrast.
- Use `ink`, `accent` or a darker hex color for text.
+ It suggests a readable color and shows its contrast ratio.
- Long video clips fill `build/clips/` with frames. Trim footage to the part
you show before you add it. Deleting `build/clips/` is safe.
- Screen recordings often have a variable frame rate. explainroo converts
diff --git a/engine/runtime.js b/engine/runtime.js
index 5059310..81045be 100644
--- a/engine/runtime.js
+++ b/engine/runtime.js
@@ -2,11 +2,11 @@
// and scenes, then exposes frame rendering, checks and the soundtrack.
import rough from '/vendor/rough.js';
import { Stage, SceneError } from './stage.js';
-import { getTheme, makeBackground, fontString } from './themes.js';
+import { getTheme, makeBackground, fontString, colorOf } from './themes.js';
import { Pen } from './pen.js';
import { drawTransition } from './transitions.js';
import { buildPhrases, drawCaptions } from './captions.js';
-import { hashStr, mulberry32, suggest, contrast, opaque, withAlpha } from './util.js';
+import { hashStr, mulberry32, suggest, suggestColor, contrast, opaque, withAlpha, parseColor, rgba } from './util.js';
import { layoutAreas } from './layout.js';
import { loadClips, ClipFrames } from './clips.js';
import { UI } from './ui.js';
@@ -392,6 +392,22 @@ export class Engine {
const margin = Math.round(Math.min(W, H) * 0.035);
const minSize = Math.round(Math.min(W, H) * 0.022);
const uiMinSize = Math.round(Math.min(W, H) * 0.015);
+ const colors = Object.fromEntries(['ink', 'accent', ...Object.keys(this.theme.colors)].map(name => [name, colorOf(this.theme, name)]));
+ let colorCtx;
+ const cssColor = color => {
+ if (parseColor(color)) return color;
+ if (!colorCtx) {
+ const canvas = document.createElement('canvas');
+ canvas.width = canvas.height = 1;
+ colorCtx = canvas.getContext('2d');
+ }
+ colorCtx.clearRect(0, 0, 1, 1);
+ colorCtx.fillStyle = '#000000';
+ colorCtx.fillStyle = color;
+ colorCtx.fillRect(0, 0, 1, 1);
+ const [r, g, b, a] = colorCtx.getImageData(0, 0, 1, 1).data;
+ return rgba({ r, g, b, a: a / 255 });
+ };
const reported = new Set();
const once = (key, fn) => {
if (reported.has(key)) return;
@@ -440,7 +456,10 @@ export class Engine {
const least = tx.ui ? uiMinSize : minSize;
if (!tx.block && Math.round(tx.size) < least) once(`small:${sc.id}:${tx.text}`, () => add('warn', sc.id, t, `"${label}" is ${Math.round(tx.size)}px, hard to read (use at least ${least}px)`));
const bg = opaque(tx.bg || this.theme.bg, this.theme.bg);
- if (typeof tx.fg === 'string' && contrast(tx.fg, bg) < 3) once(`contrast:${sc.id}:${tx.text}`, () => add('warn', sc.id, t, `"${label}" has low contrast against its background`));
+ if (typeof tx.fg === 'string' && contrast(tx.fg, bg) < 3) once(`contrast:${sc.id}:${tx.text}`, () => {
+ const suggestion = suggestColor(cssColor(tx.fg), cssColor(bg), tx.size, Object.fromEntries(Object.entries(colors).map(([name, c]) => [name, cssColor(c)])));
+ add('warn', sc.id, t, `"${label}" has low contrast against its background (${contrast(tx.fg, bg).toFixed(1)}:1); use color: '${suggestion.color}' (${suggestion.ratio.toFixed(1)}:1)`);
+ });
}
// Overlaps only count when both are fully shown, not mid-fade.
const solid = texts.filter((x) => x.alpha > 0.95);
diff --git a/engine/util.js b/engine/util.js
index 1f040e6..a0d4eca 100644
--- a/engine/util.js
+++ b/engine/util.js
@@ -118,6 +118,58 @@ export function contrast(c1, c2) {
return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
}
+function hsl(c) {
+ const { r, g, b } = parseColor(c);
+ const [R, G, B] = [r, g, b].map(v => v / 255);
+ const max = Math.max(R, G, B), min = Math.min(R, G, B);
+ const d = max - min, l = (max + min) / 2;
+ const h = !d ? 0 : max === R ? ((G - B) / d + 6) % 6 : max === G ? (B - R) / d + 2 : (R - G) / d + 4;
+ return { h: h * 60, s: d ? d / (1 - Math.abs(2 * l - 1)) : 0, l };
+}
+
+function hslHex({ h, s, l }) {
+ const a = s * Math.min(l, 1 - l);
+ const channel = n => {
+ const k = (n + h / 30) % 12;
+ const v = l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
+ return Math.round(clamp(v) * 255).toString(16).padStart(2, '0');
+ };
+ return '#' + channel(0) + channel(8) + channel(4);
+}
+
+export function suggestColor(fg, bg, size = 0, colors = {}) {
+ if (!parseColor(fg) || !parseColor(bg)) return null;
+ const min = size >= 48 ? 3 : 4.5;
+ const result = color => ({ color, ratio: contrast(colors[color] || color, bg) });
+ if (contrast(fg, bg) >= min) return { color: fg, ratio: contrast(fg, bg) };
+ const source = hsl(fg);
+ const named = Object.entries(colors).filter(([, c]) => parseColor(c) && contrast(c, bg) >= min)
+ .map(([name, c]) => {
+ const p = hsl(c);
+ const diff = Math.abs(source.h - p.h);
+ const hue = Math.min(diff, 360 - diff);
+ // Hue is undefined for grays, so match them only with other grays.
+ const gray = source.s <= 0.1 && p.s <= 0.1;
+ const close = gray || source.s > 0.1 && p.s > 0.1 && hue <= 15;
+ return { name, close, distance: (gray ? 0 : hue / 180) ** 2 + (source.s - p.s) ** 2 + (source.l - p.l) ** 2 };
+ }).filter(p => p.close).sort((a, b) => a.distance - b.distance);
+ if (named.length) return result(named[0].name);
+ const candidates = [];
+ for (const end of [0, 1]) {
+ if (contrast(hslHex({ ...source, l: end }), bg) < min) continue;
+ let fail = source.l, pass = end;
+ // Check rounded hex values so the suggested color itself meets the target.
+ for (let i = 0; i < 24; i++) {
+ const l = (fail + pass) / 2;
+ if (contrast(hslHex({ ...source, l }), bg) >= min) pass = l;
+ else fail = l;
+ }
+ candidates.push({ l: pass, color: hslHex({ ...source, l: pass }) });
+ }
+ candidates.sort((a, b) => Math.abs(a.l - source.l) - Math.abs(b.l - source.l));
+ return result(candidates[0].color);
+}
+
export function levenshtein(a, b) {
const m = a.length;
const n = b.length;
diff --git a/test/contrast-browser.test.js b/test/contrast-browser.test.js
new file mode 100644
index 0000000..85e1aa3
--- /dev/null
+++ b/test/contrast-browser.test.js
@@ -0,0 +1,63 @@
+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';
+import { contrast } from '../engine/util.js';
+import { colorOf, getTheme } from '../engine/themes.js';
+
+let chrome;
+try { chrome = findChrome(); } catch {}
+
+for (const theme of ['paper', 'midnight']) {
+ test(`check suggests usable colors on ${theme} without changing the warning threshold`, { skip: !chrome }, async t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'explainroo-contrast-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(dir, 'video.json'), JSON.stringify({ theme, captions: false, music: false, sfx: false }));
+ fs.writeFileSync(path.join(dir, 'script.md'), '## demo {min=2}');
+ const fg = theme === 'paper' ? '#ffaaaa' : '#002233';
+ const bg = getTheme(theme).bg;
+ const texts = [
+ { text: 'Small label', size: 40, color: fg },
+ { text: 'Large label', size: 48, color: fg },
+ { text: 'Own background', size: 40, color: '#bbbbbb', bg: 'rgba(255,255,255,0.95)' },
+ { text: 'Above threshold', size: 40, color: '#888888', bg: '#ffffff' },
+ { text: 'CSS color', size: 40, color: 'hsl(0, 100%, 83%)', bg: '#ffffff' },
+ ];
+ fs.writeFileSync(path.join(dir, 'scenes.js'), `export default { demo(s) {
+ ${JSON.stringify(texts)}.forEach((o, i) => s.text(o.text, { ...o, y: 200 + i * 140, at: 0, enter: 'none' }));
+ } };`);
+ const project = loadProject(dir);
+ await withEngine(project, buildTimeline(project, {}), { scale: 0.5 }, async page => {
+ const issues = await page.evaluate(() => window.explainroo.check());
+ const warnings = issues.filter(i => i.message.includes('low contrast against its background'));
+ assert.equal(warnings.length, 4);
+ assert.equal(issues.length, 4);
+ for (const label of ['Small label', 'Large label']) {
+ const warning = warnings.find(i => i.message.startsWith(`"${label}"`));
+ const match = /background \((\d+\.\d):1\); use color: '([^']+)' \((\d+\.\d):1\)$/.exec(warning.message);
+ assert.ok(match, warning.message);
+ assert.equal(match[1], contrast(fg, bg).toFixed(1));
+ const ratio = contrast(colorOf(getTheme(theme), match[2]), bg);
+ assert.ok(ratio >= (label === 'Large label' ? 3 : 4.5));
+ assert.equal(match[3], ratio.toFixed(1));
+ }
+ assert.match(warnings.find(i => i.message.startsWith('"Own background"')).message, /use color: '#/);
+ assert.match(warnings.find(i => i.message.startsWith('"CSS color"')).message, /use color: '#/);
+ const fixed = await page.evaluate(async warnings => {
+ const { Engine, fetchState } = await import('/engine/runtime.js');
+ const state = await fetchState();
+ const colors = warnings.map(w => /use color: '([^']+)'/.exec(w.message)[1]);
+ const engine = new Engine({ canvas: document.createElement('canvas'), state, scenes: { demo(s) {
+ colors.forEach((color, i) => s.text(`Fixed ${i}`, { color, bg: i >= 2 ? '#ffffff' : undefined, size: i === 1 ? 48 : 40, y: 200 + i * 140, at: 0, enter: 'none' }));
+ } }, icons: {}, images: new Map() });
+ return engine.check();
+ }, warnings);
+ assert.deepEqual(fixed, []);
+ });
+ });
+}
diff --git a/test/contrast.test.js b/test/contrast.test.js
new file mode 100644
index 0000000..82cff5d
--- /dev/null
+++ b/test/contrast.test.js
@@ -0,0 +1,80 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { contrast, parseColor, suggestColor } from '../engine/util.js';
+
+test('suggestion darkens text on a light background while keeping hue and saturation', () => {
+ const { color, ratio } = suggestColor('#ffaaaa', '#ffffff');
+ const { r, g, b } = parseColor(color);
+ assert.match(color, /^#[0-9a-f]{6}$/);
+ assert.equal(g, b);
+ assert.equal(g, 0);
+ assert.ok(r < 255);
+ assert.ok(ratio >= 4.5);
+ assert.equal(ratio, contrast(color, '#ffffff'));
+ assert.ok(contrast(`#${(r + 1).toString(16)}0000`, '#ffffff') < 4.5);
+});
+
+test('suggestion lightens text on a dark background while keeping hue and saturation', () => {
+ const { color, ratio } = suggestColor('#550000', '#0b1020');
+ const { r, g, b } = parseColor(color);
+ assert.equal(g, b);
+ assert.equal(g, 0);
+ assert.ok(r > 85);
+ assert.ok(ratio >= 4.5);
+ assert.equal(ratio, contrast(color, '#0b1020'));
+ assert.ok(contrast(`#${(r - 1).toString(16)}0000`, '#0b1020') < 4.5);
+});
+
+test('already passing text keeps its color', () => {
+ for (const [fg, bg] of [['#123456', '#ffffff'], ['#abcdef', '#000000']]) {
+ assert.deepEqual(suggestColor(fg, bg, 32, { ink: '#000000' }), { color: fg, ratio: contrast(fg, bg) });
+ }
+});
+
+test('a passing named color close in hue wins over a hex adjustment', () => {
+ const colors = { ink: '#222222', accent: '#990000', red: '#550000' };
+ const result = suggestColor('#ffaaaa', '#ffffff', 32, colors);
+ assert.equal(result.color, 'accent');
+ assert.equal(result.ratio, contrast(colors.accent, '#ffffff'));
+ assert.equal(suggestColor('#aaaaaa', '#ffffff', 32, colors).color, 'ink');
+});
+
+test('named colors must pass the target and match the hue', () => {
+ const result = suggestColor('#ffaaaa', '#ffffff', 32, { red: '#ff8888', blue: '#000099', ink: '#000000' });
+ assert.match(result.color, /^#/);
+ assert.ok(result.ratio >= 4.5);
+});
+
+test('named hue matching wraps around red at zero degrees', () => {
+ const result = suggestColor('#ffaaaa', '#ffffff', 32, { pink: '#990019' });
+ assert.equal(result.color, 'pink');
+});
+
+test('48px text targets 3:1 while smaller text targets 4.5:1', () => {
+ const small = suggestColor('#bbbbbb', '#ffffff', 47.99);
+ const large = suggestColor('#bbbbbb', '#ffffff', 48);
+ assert.equal(small.color, '#767676');
+ assert.equal(large.color, '#949494');
+ assert.ok(small.ratio >= 4.5);
+ assert.ok(large.ratio >= 3 && large.ratio < 4.5);
+ assert.equal(suggestColor('#888888', '#ffffff', 48).color, '#888888');
+ assert.equal(suggestColor('#bbbbbb', '#ffffff', 48, { gray: '#888888' }).color, 'gray');
+ assert.match(suggestColor('#bbbbbb', '#ffffff', 47, { gray: '#888888' }).color, /^#/);
+});
+
+test('the closest passing lightness can be on either side of a middle background', () => {
+ assert.equal(suggestColor('#767676', '#767676').color, '#040404');
+ assert.equal(suggestColor('#999999', '#767676').color, '#fefefe');
+});
+
+test('suggestions meet the target after hex rounding across hues and backgrounds', () => {
+ for (const fg of ['#fcba03', '#32aa70', '#79d4ea', '#8870ba', '#dd7f9e', '#808080']) {
+ for (const bg of ['#f7f3ea', '#0b1020', '#777777']) {
+ for (const size of [32, 48]) {
+ const result = suggestColor(fg, bg, size);
+ assert.ok(result.ratio >= (size >= 48 ? 3 : 4.5), `${fg} on ${bg}: ${result.color}`);
+ assert.equal(result.ratio, contrast(result.color, bg));
+ }
+ }
+ }
+});