Give themes named color roles, theme data files, and file format 3

Phase 5a-1 and 5a-2.

- roles.ts names 51 color roles. One derivation rule fills the roles
  that a theme does not give, for all themes. tokens.css keeps only the
  root defaults, without theme blocks.
- Each built-in theme is one data file in src/lib/theme/themes/. No code
  outside the theme data names a theme ID. characterThemes.ts is gone.
- New roles: link, focus, on-accent, highlight, scrim, the syntax roles,
  and 16 terminal (ANSI) roles. Stray colors in components use the roles.
- contrast.ts checks each theme against the readability rules of
  docs/ui-color.md. The tests mark the known palette failures as todo,
  and a second test fails when a known failure starts to pass.
- Theme files use schema 3 with a mode and an optional built-in base.
  A short file gets the missing colors and fonts from the base. Schema 1
  and 2 files still import. Old syntax names convert on import.
- Docs: ui-color.md, plugin-development.md (theme tokens), ui-design.md,
  guides/themes.md, and UI-041 and UI-042 in design-decisions.md.

The applied colors stay the same for every built-in theme, except three
small changes: the conflict line uses the warn color, the Write
highlight uses the highlight role, and two dialog backdrops use the
scrim role.

pnpm check passes. pnpm test: 447 pass, 31 todo, 0 fail. Full smoke
suite: 93 passed, 2 known. appearance/palettes read the old syntax
names and passed 3 of 3 times after the fix. workspace/manageTemplates
failed one time and passed on retry.
This commit is contained in:
Knotty Wyvern
2026-10-28 15:50:45 -07:00
parent af68d92969
commit 5bd616d7fd
55 changed files with 928 additions and 355 deletions
@@ -76,13 +76,13 @@ await runSmoke('appearance/characterThemes', async ({ browser }) => {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose('Color theme', label);
await waitForAppearance(theme, mode);
// The export is now one theme template, { schema, id, name, colors, fonts }, for the theme's own mode (src/lib/theme/appearance.ts:76-91).
// The export is one schema 3 theme file with every role, for the theme's own mode (exportAppearanceTheme in src/lib/theme/appearance.ts).
const template = await settings.evaluate(async theme => {
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
return exportAppearanceTheme(theme);
}, theme);
const colors = template.colors;
// The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203).
// The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts).
const applied = { ...colors, selection: `${colors.selection.slice(0, 7)}a6` };
const actual = await settings.evaluate(keys => {
const css = getComputedStyle(document.documentElement);
+3 -3
View File
@@ -128,10 +128,10 @@ await runSmoke("appearance/palettes", async ({ browser }) => {
assert.equal(await picker(secondSettings, "Appearance").count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-keyword", "syntax-variable", "syntax-property", "syntax-constant", "syntax-punctuation"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
// The applied selection color caps its alpha at a6 so text backgrounds show through (src/lib/theme/appearance.ts:197-203).
assert.deepEqual(sakura, { bg: "#fefcfc", border: "#f8dbe6", selection: "#ffc9dca6", "bg-active": "#dbeacb", "syntax-parameter": "#cb6b91", "syntax-keyword": "#98556c", "syntax-local": "#618c71", "syntax-static": "#69a2bd", "syntax-instance": "#607fa9", "syntax-global": "#687788" });
// The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts).
assert.deepEqual(sakura, { bg: "#fefcfc", border: "#f8dbe6", selection: "#ffc9dca6", "bg-active": "#dbeacb", "syntax-keyword": "#98556c", "syntax-variable": "#618c71", "syntax-property": "#607fa9", "syntax-constant": "#687788", "syntax-punctuation": "#687788" });
for (const [theme, savedMode, expectedTheme, mode] of [
["gpt", "light", "default", "light"],
["terminal", "dark", "default", "dark"],
+2 -2
View File
@@ -19,8 +19,8 @@ await runSmoke("appearance/themeExport", async ({ page }) => {
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await exportButton.click();
await page.getByRole("status").filter({ hasText: "Theme saved to" }).waitFor();
// Exported templates use theme schema 2 (src/lib/theme/appearance.ts:90).
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 2);
// Exported templates use theme schema 3 (exportAppearanceTheme in src/lib/theme/appearance.ts).
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 3);
await page.evaluate(() => { window.__TEST__.state.exportResult = null; });
await exportButton.click();
await page.getByText("Export canceled.", { exact: true }).waitFor();
+18 -4
View File
@@ -1,4 +1,4 @@
// Import a custom theme JSON in Settings > Appearance; its dark and light backgrounds apply.
// Import custom theme files in Settings > Appearance: schema 1 palettes for each mode, and a short schema 3 file with a base theme.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -15,8 +15,9 @@ await runSmoke(name, async ({ page }) => {
await page.goto(smokeUrl + "/?settingsWindow=true");
await page.getByRole("button", { name: "Appearance", exact: true }).click();
const theme = { schema: 1, id: "smoke", name: "Smoke theme", light: { bg: "#fefefe", text: "#222222", accent: "#334499" }, dark: { bg: "#181820", text: "#eeeeee", accent: "#aabbff" } };
const importTheme = () => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(theme)) });
const background = () => page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
const importTheme = (file = theme) => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(file)) });
const token = name => page.evaluate(name => getComputedStyle(document.documentElement).getPropertyValue(`--rs-${name}`).trim(), name);
const background = () => token("bg");
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#181820");
@@ -29,5 +30,18 @@ await runSmoke(name, async ({ page }) => {
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#fefefe");
await page.screenshot({ path: path.join(output, "custom-theme-light.png") });
console.log("PASS: custom theme import applies its dark and light backgrounds");
// A short schema 3 file takes the missing colors and fonts from its base theme. An earlier theme ID names the base.
await importTheme({ schema: 3, id: "short", name: "Short theme", mode: "dark", base: "holo", colors: { accent: "#00c8ff" } });
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:short");
assert.deepEqual([await background(), await token("accent"), await token("link"), await token("syntax-keyword")], ["#251b17", "#00c8ff", "#00c8ff", "#ff6740"]);
assert.match(await token("font-ui"), /Candara/);
assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), "dark");
await page.screenshot({ path: path.join(output, "custom-theme-short.png") });
// A base without a palette in the file's mode stops the installation with an error.
await importTheme({ schema: 3, id: "wrong", name: "Wrong base", mode: "dark", base: "sakura", colors: {} });
await page.getByRole("alert").filter({ hasText: "Use a built-in theme with a dark palette as the base." }).waitFor();
assert.equal(await page.evaluate(() => document.documentElement.dataset.palette), "custom:short");
console.log("PASS: custom theme import applies schema 1 palettes, a short schema 3 file with a base, and rejects a wrong base");
}, { timeout: 15000 });
+13 -10
View File
@@ -65,14 +65,17 @@ await runSmoke('appearance/typography', async ({ browser }) => {
await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme);
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home');
await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); });
// The theme sets its fonts as inline properties of the root. Put back those values after each temporary change.
for (const page of [main, settings]) {
await page.evaluate(font => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
}, oldFont);
const saved = await page.evaluate(font => ['ui', 'prose', 'heading'].map(role => {
const value = document.documentElement.style.getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
return value;
}), oldFont);
await page.screenshot({ path: path.join(output, `${theme}-before-${page === main ? 'document' : 'settings'}.png`) });
await page.evaluate(() => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`);
});
await page.evaluate(saved => {
['ui', 'prose', 'heading'].forEach((role, index) => document.documentElement.style.setProperty(`--rs-font-${role}`, saved[index]));
}, saved);
}
const roles = {
ui: await rendered(settings, selectors.ui),
@@ -118,14 +121,14 @@ await runSmoke('appearance/typography', async ({ browser }) => {
// Drop the first family from each stack and check that the fallback still renders glyphs.
const fallback = {};
for (const [role, page] of [['ui', settings], ['prose', main], ['heading', main]]) {
await page.evaluate(role => {
const css = getComputedStyle(document.documentElement);
const stack = css.getPropertyValue(`--rs-font-${role}`);
const stack = await page.evaluate(role => {
const stack = getComputedStyle(document.documentElement).getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
return stack;
}, role);
fallback[role] = await rendered(page, selectors[role]);
assert(fallback[role].rendered.length > 0);
await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role);
await page.evaluate(([role, stack]) => document.documentElement.style.setProperty(`--rs-font-${role}`, stack), [role, stack]);
}
report.push({ theme, oldFont, roles, fallback });
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
+2 -2
View File
@@ -18,7 +18,7 @@ test('Migration reads the four old keys and the theme backup, and normalizes eac
assert.deepEqual(sections, {
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true },
language: 'fr',
customThemes: [custom],
customThemes: [{ ...custom, schema: 3, mode: 'dark' }],
customThemesLegacy: [{ schema: 1, id: 'kept' }],
// The mode comes from the migrated custom theme, not from a store that is still empty.
appearance: { theme: 'custom:night', mode: 'dark', transparency: { enabled: true, amount: 100 } },
@@ -32,7 +32,7 @@ test('Migration of version 1 themes keeps the saved palette and adds the origina
'runestone.custom-themes': JSON.stringify([legacy]),
'runestone.custom-themes.legacy': JSON.stringify([legacy]),
}));
assert.deepEqual(sections.customThemes, [{ schema: 2, id: 'old', name: 'Old', colors: legacy.light }]);
assert.deepEqual(sections.customThemes, [{ schema: 3, id: 'old', name: 'Old', mode: 'light', colors: legacy.light }]);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:old', mode: 'light' });
});
+9 -29
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
import { SYNTAX_ROLES } from '../../../src/lib/theme/roles.ts';
import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
test('Removed palettes preserve the saved mode with the default palette', () => {
@@ -33,37 +33,17 @@ test('Removed character themes retain the saved background', () => {
}
});
function luminance(color: string) {
const rgb = color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
}
function contrast(foreground: string, background: string) {
const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Character palettes restore one appearance and export readable surfaces and syntax', () => {
for (const theme of Object.keys(CHARACTER_THEMES) as (keyof typeof CHARACTER_THEMES)[]) {
const exported = exportAppearanceTheme(theme);
// tests/unit/theme/contrast.spec.ts checks the readability of every palette.
test('Single-mode palettes restore their one appearance and export a valid theme', () => {
for (const { id } of BUILTIN_THEMES.filter(item => themeModes(item.id).length === 1)) {
const [only] = themeModes(id);
const exported = exportAppearanceTheme(id);
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode });
const colors = exported.colors;
for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
if (foreground === 'accent' && background === 'selection') continue;
assert(contrast(colors[foreground]!, colors[background]!) >= 4.5, `${theme} ${mode}: ${foreground} on ${background}`);
}
}
assert.deepEqual(parseAppearance(JSON.stringify({ theme: id, mode })), { theme: id, mode: only });
}
assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.equal(exported.schema, 2);
assert.equal(exported.schema, 3);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) {
for (const background of ['bg', 'bg-active'] as const) {
assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
}
}
assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7);
for (const role of SYNTAX_ROLES) assert.match(exported.colors[`syntax-${role}`] ?? '', /^#[0-9a-f]{6}$/);
assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
}
});
+16 -9
View File
@@ -1,7 +1,14 @@
// Character palettes: WCAG contrast of text and syntax colors on opaque and image-tinted surfaces, plus per-theme palette rules.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
import { SYNTAX_ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
/** Every role of a dark character palette, with the derived roles. */
function characterTheme(theme: string) {
const palette = BUILTIN_THEMES.find(item => item.id === theme);
return palette && 'dark' in palette.variants ? resolveColors(palette.variants.dark, 'dark') : undefined;
}
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16));
const mix = (foreground: string, background: string, opacity: number) => '#' + rgb(foreground)
@@ -19,13 +26,13 @@ function contrast(foreground: string, background: string) {
/** Named foreground groups and surfaces of a palette. Image surfaces are tinted over a white image. */
function roles(theme: string) {
const palette = characterTheme(theme)!;
const [bg, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
const { bg, 'bg-elevated': elevated, 'bg-active': active, 'text-dim': dim, text, 'text-strong': strong, accent, selection } = palette;
const editorOnWhite = mix(bg, '#ffffff', 0.9);
const panelOnWhite = mix(elevated, '#ffffff', 0.82);
const foregrounds = {
ui: { dim, text, strong },
accents: { accent, secondary: palette.secondary },
syntax: Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])),
accents: { accent, secondary: palette['accent-2'] },
syntax: Object.fromEntries(SYNTAX_ROLES.map(role => [`syntax-${role}`, palette[`syntax-${role}`]])),
};
const surfaces = {
bg, elevated, active, selection, editorOnWhite, panelOnWhite,
@@ -69,14 +76,14 @@ for (const { theme, name, checks } of readable) {
test('Harvest Moon uses the warm character colors for all palette roles', () => {
const palette = characterTheme('harvest-moon')!;
for (const color of [...palette.surfaces, palette.secondary, ...palette.syntax]) {
const identity = ['bg', 'bg-elevated', 'bg-active', 'border', 'text', 'text-dim', 'text-strong', 'accent', 'accent-2', 'selection', ...SYNTAX_ROLES.map(role => `syntax-${role}` as const)] as const;
for (const role of identity) {
const color = palette[role];
assert.match(color, /^#[0-9a-f]{6}$/i);
const [red, green, blue] = rgb(color);
assert(red >= green && green >= blue, `${color} must follow the copper, amber, red, or cream palette`);
assert(red >= green && green >= blue, `${role} ${color} must follow the copper, amber, red, or cream palette`);
}
assert.equal(palette.mode, 'dark');
assert.equal(Object.keys(characterSyntax('harvest-moon')).length, SYNTAX_ROLES.length);
assert.deepEqual(characterSyntax('unknown'), {});
assert.deepEqual(Object.keys(BUILTIN_THEMES.find(item => item.id === 'harvest-moon')!.variants), ['dark']);
});
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
+79
View File
@@ -0,0 +1,79 @@
// Readability rules for every built-in theme (src/lib/theme/contrast.ts), and the rule that only theme data names a theme.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
import { BASE_ROLES, resolveColors, type Mode } from '../../../src/lib/theme/roles.ts';
import { RULES, checkTheme } from '../../../src/lib/theme/contrast.ts';
import { composite, contrast, distance, formatHex, mix, parseHex } from '../../../src/lib/theme/color.ts';
// Rules that a palette fails today. Stages 5a-3 and 5a-4 redesign these palettes and remove each entry.
const KNOWN_FAILURES: Record<string, readonly string[]> = {
'default/dark': ['text', 'syntax-variety'],
'default/light': ['text', 'syntax', 'syntax-variety', 'light-page'],
'claude/dark': ['accent-text', 'status-text', 'syntax', 'status-distinct', 'syntax-variety'],
'claude/light': ['accent-text', 'status-text', 'syntax', 'ansi', 'focus', 'selection-outline', 'syntax-variety', 'light-page'],
'sakura/light': ['text', 'accent-text', 'status-text', 'syntax', 'ansi', 'syntax-variety', 'light-page'],
'harvest-moon/dark': ['status-text', 'status-distinct'],
'crimson-pilot/dark': ['status-distinct'],
'silver-serpent/dark': ['status-text', 'status-distinct'],
};
const variants = BUILTIN_THEMES.flatMap(theme => Object.entries(theme.variants).map(([mode, colors]) => ({ key: `${theme.id}/${mode}`, mode: mode as Mode, colors: colors! })));
for (const variant of variants) {
const findings = checkTheme(resolveColors(variant.colors, variant.mode), variant.mode);
for (const rule of RULES) {
const results = findings.filter(finding => finding.rule === rule.id);
if (!results.length) continue;
const known = KNOWN_FAILURES[variant.key]?.includes(rule.id);
const failures = results.filter(finding => !finding.pass).map(finding => `${finding.subject}: ${finding.value.toFixed(2)} (minimum ${finding.min})`);
test(`${variant.key} passes the ${rule.id} rule`, known ? { todo: 'Known palette failure. Stages 5a-3 and 5a-4 redesign this palette.' } : {}, () => {
assert.deepEqual(failures, []);
});
if (known) test(`${variant.key} still fails the known ${rule.id} rule`, () => {
assert(failures.length > 0, `Remove ${rule.id} from KNOWN_FAILURES['${variant.key}'].`);
});
}
}
test('Each known failure names a built-in variant and a rule', () => {
for (const [key, rules] of Object.entries(KNOWN_FAILURES)) {
assert(variants.some(variant => variant.key === key), key);
for (const rule of rules) assert(RULES.some(item => item.id === rule), `${key}: ${rule}`);
}
});
test('Every built-in variant gives all base roles as hex colors', () => {
for (const variant of variants) {
for (const role of BASE_ROLES) assert.match(variant.colors[role] ?? '', /^#[0-9a-f]{6}$/, `${variant.key}: ${role}`);
}
});
test('Color arithmetic matches CSS and WCAG', () => {
assert.deepEqual(parseHex('#0f08'), [0, 255, 0, 136 / 255]);
assert.equal(formatHex([255, 0, 0, 1]), '#ff0000');
assert.equal(mix('#82aaff', '#141414', 0.8), '#6c8cd0');
assert.equal(mix('#82aaff', '#0000', 0.2), '#82aaff33');
assert.equal(composite('#ffffff80', '#000000'), '#808080');
assert.equal(contrast('#000000', '#ffffff').toFixed(1), '21.0');
assert(distance('#ff0000', '#ff0000') === 0 && distance('#000000', '#ffffff') > 0.99);
});
test('Only theme data names a theme ID', () => {
const root = fileURLToPath(new URL('../../../src', import.meta.url));
const ids = BUILTIN_THEMES.flatMap(theme => [theme.id, ...('legacyIds' in theme ? theme.legacyIds : [])]).filter(id => id !== 'default');
const pattern = new RegExp(`(['"\`])(?:${ids.join('|')})\\1|data-palette=`);
const files = (function walk(folder: string): string[] {
return readdirSync(folder).flatMap(name => {
const path = join(folder, name);
return statSync(path).isDirectory() ? walk(path) : /\.(ts|svelte|css)$/.test(name) ? [path] : [];
});
})(root);
const found = files.filter(file => !relative(root, file).startsWith(join('lib', 'theme', 'themes')) && !file.endsWith('messages.ts'))
.filter(file => pattern.test(readFileSync(file, 'utf8')))
.map(file => relative(root, file));
assert.deepEqual(found, []);
});
+41 -7
View File
@@ -1,11 +1,44 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { COLOR_TOKENS, parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { ROLES } from '../../../src/lib/theme/roles.ts';
import { BUILTIN_THEMES as THEME_DATA } from '../../../src/lib/theme/themes/index.ts';
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, resolveTheme, BUILTIN_THEMES, themeModes } from '../../../src/lib/theme/appearance.ts';
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette };
test('Fixed theme palettes retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), theme);
test('Schema 2 palettes convert to schema 3 and retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), { ...theme, schema: 3, mode: 'dark' });
assert.equal(parseCustomTheme({ ...theme, colors: { ...palette, bg: '#fafafa' } }).mode, 'light');
});
test('Old syntax names convert to the schema 3 roles', () => {
const colors = { ...palette, 'syntax-local': '#111111', 'syntax-instance': '#222222', 'syntax-global': '#333333', 'syntax-parameter': '#444444', 'syntax-static': '#555555', 'syntax-keyword': '#666666' };
assert.deepEqual(parseCustomTheme({ ...theme, colors }).colors, {
...palette, 'syntax-variable': '#111111', 'syntax-property': '#222222', 'syntax-constant': '#333333', 'syntax-punctuation': '#333333', 'syntax-keyword': '#666666',
});
assert.throws(() => parseCustomTheme({ ...theme, colors: { ...palette, 'syntax-variable': '#111111' } }), /Unknown theme color/);
});
test('Schema 3 files name their mode and can take missing colors from a built-in base', () => {
const file = { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', base: 'holo', colors: { accent: '#00ff00', 'ansi-blue': '#0000ff' } };
assert.deepEqual(parseCustomTheme(file), { ...file, base: 'harvest-moon' });
assert.deepEqual(parseCustomTheme({ ...file, base: undefined, colors: {} }), { schema: 3, id: 'amber', name: 'Amber', mode: 'dark', colors: {} });
for (const invalid of [{ mode: 'dim' }, { mode: undefined }, { base: 'sakura' }, { base: 'unknown' }, { base: 4 }, { colors: [] }, { colors: { 'accent-x': '#000' } }, { colors: { accent: 'red' } }]) {
assert.throws(() => parseCustomTheme({ ...file, ...invalid }), JSON.stringify(invalid));
}
const previous = globalThis.localStorage;
try {
const stored = new Map([['runestone.custom-themes', JSON.stringify([file])]]);
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
const resolved = resolveTheme('custom:amber', 'light');
const harvest = THEME_DATA.find(item => item.id === 'harvest-moon')!;
assert.equal(resolved.mode, 'dark');
assert.equal(resolved.colors.bg, harvest.variants.dark.bg);
assert.equal(resolved.colors.accent, '#00ff00');
assert.equal(resolved.colors['syntax-keyword'], harvest.variants.dark['syntax-keyword']);
assert.equal(resolved.colors.link, '#00ff00', 'A derived role follows the colors of the file');
assert.equal(resolved.colors['ansi-blue'], '#0000ff');
assert.match(resolved.fonts.ui, /Candara/);
assert.deepEqual(themeModes('custom:amber'), ['dark']);
} finally { globalThis.localStorage = previous; }
});
test('Legacy import selects the current appearance and validates both palettes', () => {
const light = { ...palette, bg: '#fff' };
@@ -20,10 +53,11 @@ test('Theme files reject CSS injection, unknown tokens, and incomplete palettes'
}
assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' }));
});
test('Every built-in template contains every current color token and one palette', () => {
test('Every built-in template contains every role and one palette', () => {
for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) {
const exported = exportAppearanceTheme(item.id, mode);
assert.deepEqual(Object.keys(exported.colors).sort(), [...COLOR_TOKENS].sort());
assert.deepEqual(Object.keys(exported.colors), [...ROLES]);
assert.equal(exported.mode, mode);
assert.deepEqual(parseCustomTheme(exported), exported);
assert.equal('light' in exported, false);
assert.equal('dark' in exported, false);
@@ -86,7 +120,7 @@ test('Saved legacy light themes migrate once and preserve both original palettes
const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const old = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
const sections = migrateLegacyPreferences(key => old.get(key) ?? null);
assert.equal((sections.customThemes as { schema: number }[])[0].schema, 2);
assert.equal((sections.customThemes as { schema: number }[])[0].schema, 3);
assert.deepEqual(sections.customThemesLegacy, [legacy]);
assert.deepEqual(sections.appearance, { theme: 'custom:saved-light', mode: 'light' });
// The browser preview store reads the sections from their old keys.