RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+86
View File
@@ -0,0 +1,86 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.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', () => {
for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) {
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
}
}
assert.deepEqual(THEMES, ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent']);
assert.deepEqual(BUILTIN_THEMES.map(theme => theme.id), THEMES);
});
test('Renamed palettes preserve saved choices and backgrounds', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const [previous, theme] of [['holo', 'harvest-moon'], ['asuka', 'crimson-pilot'], ['malfoid', 'silver-serpent']]) {
for (const mode of ['light', 'dark']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme: previous, mode, newTabBackground })), { theme, mode: 'dark', newTabBackground });
}
}
for (const theme of ['constructor', '__proto__', 'toString']) {
assert.deepEqual(normalizeAppearance({ theme, mode: 'light' }), { theme: 'default', mode: 'light' });
}
});
test('Removed character themes retain the saved background', () => {
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
for (const theme of ['renamon', 'asuka-school']) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode: 'light', newTabBackground })), { theme: 'default', mode: 'light', newTabBackground });
}
});
// 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: id, mode })), { theme: id, mode: only });
}
assert.equal(exported.schema, 3);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) assert.match(exported.colors[`syntax-${role}`] ?? '', /^#[0-9a-f]{6}$/);
assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
}
});
test('Sakura cannot restore or save a dark appearance', () => {
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
assert.deepEqual(normalizeAppearance({ theme: 'sakura', mode: 'dark' }), { theme: 'sakura', mode: 'light' });
});
test('Malformed storage returns a valid default appearance', () => {
for (const raw of [null, '', '{', 'null', '42', '[]']) {
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
}
});
test('Saved image layout restores valid choices and rejects CSS injection', () => {
const imageId = '01234567-89ab-cdef-0123-456789abcdef';
const restored = parseAppearance(JSON.stringify({ newTabBackground: { imageId, position: 'top left', size: 'auto', overlay: -0.4 } }));
assert.deepEqual(restored.newTabBackground, { imageId, position: 'top left', size: 'auto', overlay: -0.4 });
const invalid = normalizeAppearance({ newTabBackground: { imageId, position: 'url(https://example.com)', size: '100000px', overlay: Infinity } });
assert.deepEqual(invalid.newTabBackground, { imageId, position: 'center', size: 'cover', overlay: 0 });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId } }).newTabBackground, { imageId, overlay: 0, position: 'center', size: 'cover' });
});
test('New tab backgrounds keep supported image data and reject active or remote content', () => {
const value = { theme: 'claude', mode: 'light', newTabBackground: { image: 'data:image/png;base64,YQ==', overlay: 0, position: 'center', size: 'cover' } };
assert.deepEqual(parseAppearance(JSON.stringify(value)), value);
for (const image of ['https://example.com/photo.png', 'javascript:alert(1)', 'data:image/svg+xml;base64,YQ==', 'data:image/png;base64,' + 'A'.repeat(3_000_000)]) {
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: '#224466', image } }).newTabBackground, undefined);
}
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: 'red' } }).newTabBackground, undefined);
assert.equal(normalizeAppearance({ ...value, newTabBackground: undefined }).newTabBackground, undefined);
});
test('Background image references clamp the overlay and discard obsolete colors', () => {
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
const layout = { position: 'center', size: 'cover' };
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, color: '#224466', overlay: 3 } }).newTabBackground, { imageId, overlay: 1, ...layout });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: -3 } }).newTabBackground, { imageId, overlay: -1, ...layout });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0, ...layout });
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
});
+159
View File
@@ -0,0 +1,159 @@
import test from 'node:test';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
import { BackgroundHub, backgroundHub } from '../../../src/lib/plugins/backgrounds.ts';
import { ExternalSession } from '../../../src/lib/plugins/externalSession.ts';
import type { PluginApi } from '../../../src/lib/plugins/sdk.ts';
import type { BackgroundFrame } from '../../../src/lib/plugins/backgroundContracts.ts';
const frame: BackgroundFrame = { url: 'blob:http://localhost/example', overlay: 0.3, position: 'center', size: 'cover' };
test('frames retain ownership, reveal earlier owners, and cannot mutate hub state', () => {
const hub = new BackgroundHub(() => undefined);
const first = Symbol(), second = Symbol();
const events: string[] = [];
hub.subscribe(target => events.push(target));
hub.set(first, 'pm-all', frame);
const received = hub.get('pm-all')!;
received.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.url, frame.url);
hub.set(second, 'pm-all', { ...frame, overlay: -0.4 });
hub.set(first, 'app', frame);
assert.equal(hub.get('pm-all')!.overlay, -0.4);
hub.removeOwner(second);
assert.equal(hub.get('pm-all')!.overlay, 0.3);
hub.removeOwner(first);
assert.equal(hub.get('pm-all'), null);
assert.equal(hub.get('app'), null);
assert.deepEqual(events, ['pm-all', 'pm-all', 'app', 'pm-all', 'pm-all', 'app']);
});
test('app override uses body properties and removes them without changing current root appearance', () => {
const root = new Map([['--rs-background-image', 'saved image']]);
const properties = new Map<string, string>();
const style = {
getPropertyValue: (key: string) => properties.get(key) ?? '',
getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value),
removeProperty: (key: string) => { properties.delete(key); },
};
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement);
const owner = Symbol();
hub.set(owner, 'app', frame);
assert.match(properties.get('--rs-background-image')!, /blob:http/);
assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)');
root.set('--rs-background-image', 'new saved image');
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
hub.removeOwner(owner);
assert.equal(properties.size, 0);
assert.equal(root.get('--rs-background-image'), 'new saved image');
});
test('invalid frames and targets do not enter the hub', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
for (const target of ['pm-board:../../x', 'unknown', 'pm-board:']) assert.throws(() => hub.set(owner, target, frame), /target/);
for (const invalid of [{ ...frame, url: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'blob:bad")' }, { ...frame, overlay: NaN }, { ...frame, overlay: 2 }, { ...frame, url: 'blob:bad")' }]) {
assert.throws(() => hub.set(owner, 'app', invalid), /frame/);
}
hub.set(owner, 'pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1', frame);
hub.removeOwner(owner);
});
test('portrait frames retain a contained foreground and cover underlay through transitions and cleanup', () => {
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => properties.set(key, value), removeProperty: (key: string) => properties.delete(key) };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', { ...frame, size: 'contain', blurredUrl: 'blob:blurred', previous: frame, transitionMs: 2000 });
assert.equal(properties.get('--rs-background-layer-sizes'), '100% 100%, contain, cover');
assert.equal(properties.get('--rs-background-layer-positions'), 'center, center, center');
assert.equal(properties.get('--rs-background-previous-layer-sizes'), '100% 100%, cover');
assert.match(properties.get('--rs-background-image')!, /blob:blurred/);
const received = hub.get('app')!;
received.blurredUrl = 'blob:changed';
assert.equal(hub.get('app')!.blurredUrl, 'blob:blurred');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
});
test('fade frames validate previous images and keep nested data private', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
const fading = { ...frame, previous: { ...frame, url: 'blob:previous' }, transitionMs: 800 };
hub.set(owner, 'pm-all', fading);
fading.previous.url = 'blob:mutated';
const received = hub.get('pm-all')!;
assert.equal(received.previous!.url, 'blob:previous');
received.previous!.url = 'blob:changed';
assert.equal(hub.get('pm-all')!.previous!.url, 'blob:previous');
for (const invalid of [
{ ...frame, previous: { ...frame, url: 'https://example.com/image.png' } },
{ ...frame, transitionMs: NaN }, { ...frame, transitionMs: -1 }, { ...frame, transitionMs: 5001 },
]) assert.throws(() => hub.set(owner, 'pm-all', invalid), /frame/);
});
test('subscriber errors do not prevent frame cleanup or remaining notifications', () => {
const hub = new BackgroundHub(() => undefined), owner = Symbol();
let events = 0;
hub.subscribe(() => { throw new Error('Subscriber failure'); });
hub.subscribe(() => { events++; });
hub.set(owner, 'pm-all', frame);
hub.removeOwner(owner);
assert.equal(events, 2);
assert.equal(hub.get('pm-all'), null);
});
test('plugins get no background API, and the frames stay with the host', async () => {
let api!: PluginApi;
const session = new ExternalSession('org.test.backgrounds', {
workspace: { list: async () => [], read: async () => '', write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
// Project Management was the last plugin user of `api.backgrounds`. It reads `backgroundHub` as a native feature.
assert.equal('backgrounds' in api, false);
const owner = Symbol();
backgroundHub.set(owner, 'pm-all', frame);
await session.stop();
assert.deepEqual(backgroundHub.get('pm-all'), frame);
backgroundHub.removeOwner(owner);
});
test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];
const scopes: Record<string, string[]> = { default: all, settings: all, browser: ['background_folder', 'background_list', 'background_read', 'background_read_sidecar'] };
for (const [scope, commands] of Object.entries(scopes)) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of all) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert.equal(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), commands.includes(command), `${scope} and ${command}`);
}
assert.equal(capability.permissions.some((permission: string) => permission.startsWith('allow-backgrounds-')), false, `${scope} has no old plugin command`);
}
assert.equal(/"backgrounds_/.test(build), false);
});
test('a new app frame changes only the custom properties with a new value', () => {
const writes: string[] = [];
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => { writes.push(key); properties.set(key, value); }, removeProperty: (key: string) => { properties.delete(key); } };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', frame);
assert.equal(writes.length, 20);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, ['--rs-background-image']);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, [], 'The same frame writes nothing');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
writes.length = 0;
hub.set(owner, 'app', frame);
assert.equal(writes.length, 20, 'After a removal, the next frame writes every property again');
hub.removeOwner(owner);
});
+101
View File
@@ -0,0 +1,101 @@
// 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 { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
import { SYNTAX_ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
import { SURFACES, appliedColors } from '../../../src/lib/theme/contrast.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)
.map((value, index) => Math.round(value * opacity + rgb(background)[index] * (1 - opacity)).toString(16).padStart(2, '0')).join('');
function luminance(color: string) {
return rgb(color).map(value => value / 255)
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
.reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
}
function contrast(foreground: string, background: string) {
const [high, low] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (high + 0.05) / (low + 0.05);
}
/** 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, 'bg-elevated': elevated, 'bg-active': active, 'text-dim': dim, text, 'text-strong': strong, accent } = palette;
// The app draws text selection at most 65% opaque over the page (UI-029).
const selection = SURFACES.selection(appliedColors(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['accent-2'] },
// A menu or pane row shows interface text and the main accent. Syntax and the second accent show only in documents.
rows: { dim, text, strong, accent },
syntax: Object.fromEntries(SYNTAX_ROLES.map(role => [`syntax-${role}`, palette[`syntax-${role}`]])),
};
const surfaces = {
bg, elevated, active, selection, editorOnWhite, panelOnWhite,
codeBlockOnWhite: mix(elevated, editorOnWhite, 0.82),
// Over an image, a hovered menu or pane row is a 6% veil of text-strong on the tinted panel (UI-061).
hoverOnWhite: mix(strong, panelOnWhite, 0.06),
controlHoverOnWhite: mix(active, '#ffffff', 0.92),
};
return { foregrounds, surfaces };
}
type Roles = ReturnType<typeof roles>;
type Check = [foregrounds: (keyof Roles['foregrounds'])[], surfaces: (keyof Roles['surfaces'])[]];
// Every listed foreground needs 4.5:1 contrast on every listed surface.
const readable: { theme: string; name: string; checks: Check[] }[] = [
{ theme: 'harvest-moon', name: 'Harvest Moon', checks: [
[['ui', 'accents'], ['bg', 'elevated', 'active', 'selection']],
[['syntax'], ['bg', 'elevated', 'selection']],
] },
{ theme: 'crimson-pilot', name: 'Crimson Pilot', checks: [
[['ui', 'accents', 'syntax'], ['bg', 'elevated', 'active', 'selection']],
[['syntax'], ['editorOnWhite', 'codeBlockOnWhite']],
[['ui'], ['panelOnWhite']],
] },
{ theme: 'silver-serpent', name: 'Silver Serpent', checks: [
[['ui', 'accents', 'syntax'], ['bg', 'elevated', 'active', 'selection', 'panelOnWhite', 'editorOnWhite', 'controlHoverOnWhite', 'codeBlockOnWhite']],
[['rows'], ['hoverOnWhite']],
] },
];
for (const { theme, name, checks } of readable) {
test(`${name} text and syntax remain readable on opaque and image surfaces`, () => {
const { foregrounds, surfaces } = roles(theme);
for (const [groups, surfaceNames] of checks) {
for (const [role, foreground] of groups.flatMap(group => Object.entries(foregrounds[group]))) {
for (const surface of surfaceNames) {
assert(contrast(foreground, surfaces[surface]) >= 4.5, `${role} ${foreground} on ${surface} ${surfaces[surface]} needs 4.5:1 contrast`);
}
}
}
});
}
test('Harvest Moon uses the warm character colors for all palette roles', () => {
const palette = characterTheme('harvest-moon')!;
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, `${role} ${color} must follow the copper, amber, red, or cream palette`);
}
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', () => {
const { surfaces: { bg, elevated, selection }, foregrounds: { accents: { accent } } } = roles('silver-serpent');
assert(contrast(accent, selection) >= 3, 'selection perimeter');
assert(contrast(selection, bg) >= 1.5, 'selection against the editor');
assert(contrast(selection, elevated) >= 1.5, 'selection against a panel');
});
+56
View File
@@ -0,0 +1,56 @@
// 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';
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 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`, () => {
assert.deepEqual(failures, []);
});
}
}
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, []);
});
+149
View File
@@ -0,0 +1,149 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
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('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' };
const legacy = { schema: 1, id: theme.id, name: theme.name, light, dark: palette };
assert.deepEqual(parseCustomTheme(legacy).colors, palette);
assert.deepEqual(parseCustomTheme(legacy, 'light').colors, light);
assert.throws(() => parseCustomTheme({ ...legacy, light: {} }));
});
test('Theme files reject CSS injection, unknown tokens, and incomplete palettes', () => {
for (const colors of [{ ...palette, bg: 'url(https://invalid.test)' }, { ...palette, position: 'fixed' }, { bg: '#000' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, colors }));
}
assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' }));
});
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), [...ROLES]);
assert.equal(exported.mode, mode);
assert.deepEqual(parseCustomTheme(exported), exported);
assert.equal('light' in exported, false);
assert.equal('dark' in exported, false);
}
assert.notDeepEqual(exportAppearanceTheme('default', 'light').colors, exportAppearanceTheme('default', 'dark').colors);
});
test('Transparency normalizes old, invalid, and extreme saved values', () => {
assert.equal(normalizeAppearance(null).transparency, undefined);
assert.deepEqual(normalizeAppearance({ transparency: { enabled: false, amount: 27 } }).transparency, { enabled: false, amount: 27 });
for (const [amount, expected] of [[-10, 0], [55, 55], [100, 100], [120, 100], [NaN, 18], [Infinity, 18], [12.8, 13]]) {
assert.equal(normalizeAppearance({ transparency: { amount } }).transparency?.amount, expected);
}
});
test('Theme font roles round-trip and reject CSS injection', () => {
const fonts = { ui: 'Arial, sans-serif', prose: '"Times New Roman", serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
assert.deepEqual(parseCustomTheme({ ...theme, fonts }).fonts, fonts);
for (const fonts of [{ ui: 'url(https://example.test)' }, { ui: 'Arial; color: red' }, { unknown: 'Arial' }, { ui: '' }, { ui: 'Arial,,serif' }, { ui: '"Arial' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, fonts }));
}
for (const item of BUILTIN_THEMES) {
const exported = exportAppearanceTheme(item.id);
assert.deepEqual(Object.keys(exported.fonts!).sort(), ['heading', 'mono', 'prose', 'ui']);
assert.deepEqual(parseCustomTheme(exported), exported);
}
assert.match(exportAppearanceTheme('claude').fonts!.heading!, /Poppins/);
assert.match(exportAppearanceTheme('harvest-moon').fonts!.ui!, /Candara/);
});
test('Full transparency range produces valid surface opacity values', () => {
const values = new Map<string, string>();
const root = { dataset: {}, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
for (const amount of [0, 18, 40, 55, 99, 100]) {
applyTransparency({ enabled: true, amount }, root);
assert.equal(values.get('--rs-surface-opacity'), `${100 - amount}%`);
for (const key of ['--rs-surface-opacity', '--rs-editor-surface-opacity', '--rs-hover-surface-opacity']) {
const opacity = parseFloat(values.get(key)!);
assert(opacity >= 0 && opacity <= 100);
}
}
});
test('Opaque mode retains background ownership and the amount for re-enabling', () => {
const values = new Map<string, string>();
const root = { dataset: {} as Record<string, string>, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
applyTransparency({ enabled: false, amount: 32 }, root);
assert.equal(values.get('--rs-surface-opacity'), '100%');
assert.equal(values.get('--rs-editor-surface-opacity'), '100%');
assert.equal(values.get('--rs-transparent-plugin-bg'), 'transparent');
assert.equal(root.dataset.transparency, 'off');
applyTransparency({ enabled: true, amount: 18 }, root);
assert.equal(values.get('--rs-surface-opacity'), '82%');
assert.equal(values.get('--rs-editor-surface-opacity'), '90%');
assert.equal(root.dataset.transparency, 'on');
});
test('Saved legacy light themes migrate once and preserve both original palettes', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const { migrateLegacyPreferences } = await import('../../../src/lib/settings/migration.ts');
const { LEGACY_KEYS } = await import('../../../src/lib/settings/store.ts');
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, 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.
const stored = new Map(Object.entries(sections).map(([section, value]) => [LEGACY_KEYS[section as keyof typeof LEGACY_KEYS], JSON.stringify(value)]));
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as unknown as Storage;
assert.deepEqual(customThemes()[0].colors, legacy.light);
assert.deepEqual(themeModes('custom:saved-light'), ['light']);
assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light');
assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff');
assert.deepEqual(customThemes('dark')[0].colors, legacy.light, 'The converted theme keeps its palette in both modes');
} finally { globalThis.localStorage = previous; }
});
test('Reading custom themes never writes, and an unconverted version 1 theme uses the requested palette', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../../../src/lib/theme/customThemes.ts');
const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette };
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? JSON.stringify([legacy]) : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.deepEqual(customThemes('dark')[0].colors, palette);
assert.deepEqual(customThemes()[0].colors, palette, 'Without a saved appearance, the dark palette applies');
} finally { globalThis.localStorage = previous; }
});
+47
View File
@@ -0,0 +1,47 @@
// The theme editor model (src/lib/theme/themeEditor.ts): role groups, drafts, saved files, and the results of each role.
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { ROLE_GROUPS, builtinDraft, customDraft, draftColors, draftFindings, draftTheme, roleStatus, uniqueThemeId } from '../../../src/lib/theme/themeEditor.ts';
import { ROLES, resolveColors } from '../../../src/lib/theme/roles.ts';
import { parseCustomTheme } from '../../../src/lib/theme/customThemes.ts';
import { BUILTIN_THEMES } from '../../../src/lib/theme/themes/index.ts';
test('The editor groups show every role once', () => {
const shown = ROLE_GROUPS.flatMap(group => group.roles);
assert.equal(new Set(shown).size, shown.length);
assert.deepEqual([...shown].sort(), [...ROLES].sort());
});
test('A built-in draft has the colors of its theme', () => {
for (const theme of BUILTIN_THEMES) for (const [mode, colors] of Object.entries(theme.variants)) {
const draft = builtinDraft(theme.id, mode as 'light' | 'dark', theme.name);
assert.deepEqual(draftColors(draft), resolveColors(colors!, mode as 'light' | 'dark'));
}
});
test('A saved draft is a short schema 3 theme that the parser accepts and that keeps its colors', () => {
const draft = { ...builtinDraft('harvest-moon', 'dark', 'Harvest Moon copy'), overrides: { accent: '#00c8ff', selection: '#20406080' } };
const theme = draftTheme(draft, 'harvest-moon-copy', 'Harvest Moon copy');
assert.deepEqual(theme, { schema: 3, id: 'harvest-moon-copy', name: 'Harvest Moon copy', mode: 'dark', base: 'harvest-moon', colors: { accent: '#00c8ff', selection: '#20406080' } });
const parsed = parseCustomTheme(theme);
assert.deepEqual(draftColors(customDraft(parsed)), draftColors(draft));
});
test('Theme IDs from names are valid and unique', () => {
assert.equal(uniqueThemeId('RuneStone Dark copy', []), 'runestone-dark-copy');
assert.equal(uniqueThemeId('RuneStone Dark copy', ['runestone-dark-copy', 'runestone-dark-copy-2']), 'runestone-dark-copy-3');
assert.equal(uniqueThemeId('2026 theme', []), 't-2026-theme');
assert.equal(uniqueThemeId('桜', []), 'theme');
for (const name of ['RuneStone Dark copy', '2026 theme', '桜', 'x'.repeat(100), '--Ünïcode--']) assert.match(uniqueThemeId(name, []), /^[a-z][a-z0-9-]{0,63}$/);
});
test('A role shows the results where it is the color, the surface, or one of a pair', () => {
const draft = { ...builtinDraft('default', 'dark', 'Test'), overrides: { 'text-dim': '#3a3a3a', ok: '#55dcf5' } };
const findings = draftFindings(draft);
const dim = roleStatus('text-dim', findings);
assert(dim.failures.length > 0 && dim.failures.every(finding => finding.subject.startsWith('text-dim on ')));
assert(dim.lowest && dim.lowest.value < 4.5);
assert(roleStatus('bg', findings).failures.some(finding => finding.subject === 'text-dim on bg'), 'A surface shows the text that fails on it');
assert(roleStatus('ok', findings).failures.some(finding => finding.subject === 'accent and ok'), 'A status color shows a pair that is too close');
assert.deepEqual(roleStatus('syntax-keyword', findings).failures, []);
});