Move the tests from scripts/ to tests/ by feature

Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+106
View File
@@ -0,0 +1,106 @@
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 { 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 });
}
});
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);
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(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.equal(exported.schema, 2);
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);
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);
});
+44
View File
@@ -0,0 +1,44 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
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);
}
test('Crimson Pilot text and syntax remain readable in active and selected states', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
const foregrounds = { dim, text, strong, accent, secondary: palette.secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) };
for (const [role, foreground] of Object.entries(foregrounds)) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${role} on ${surface} needs 4.5:1 contrast`);
}
}
});
test('Crimson Pilot text remains readable on image-tinted editor and panel surfaces', () => {
const palette = characterTheme('crimson-pilot')!;
const [background, elevated, , , dim, text, strong] = palette.surfaces;
const editor = mix(background, '#ffffff', 0.9);
const codeBlock = mix(elevated, editor, 0.82);
const panel = mix(elevated, '#ffffff', 0.82);
for (const foreground of palette.syntax) {
for (const surface of [editor, codeBlock]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const foreground of [dim, text, strong]) {
assert(contrast(foreground, panel) >= 4.5, `${foreground} on image panel ${panel} needs 4.5:1 contrast`);
}
});
+155
View File
@@ -0,0 +1,155 @@
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 { BackgroundFrame, PluginApi } from '../../../src/lib/plugins/sdk.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('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
let api!: PluginApi;
let finishRead!: (value: Uint8Array) => void;
let finishList!: (value: { name: string }[]) => void;
let finishPicker!: (value: string | null) => void;
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() },
backgrounds: {
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
list: () => new Promise(resolve => { finishList = resolve; }),
read: () => new Promise(resolve => { finishRead = resolve; }),
},
}, () => {}, () => {});
let notifications = 0;
await session.start({ activate(value) {
api = value;
api.backgrounds!.subscribe(() => { notifications++; });
api.backgrounds!.set('app', frame);
api.backgrounds!.set('pm-all', frame);
api.onDispose(() => {
assert.equal(backgroundHub.get('app'), null);
assert.equal(backgroundHub.get('pm-all'), null);
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
});
} });
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
const rejected = pending.map(request => assert.rejects(request, /disabled/));
await session.stop();
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
await Promise.all(rejected);
assert.equal(notifications, 2);
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
assert.equal(backgroundHub.get('app'), null);
});
test('background commands are allowed in main and settings windows', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
for (const scope of ['default', 'settings']) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
}
}
});
+111
View File
@@ -0,0 +1,111 @@
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';
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('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 current color token 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(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 legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
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.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2);
assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
test('Legacy migration storage failure leaves the original palette available', 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 raw = JSON.stringify([legacy]);
const previous = globalThis.localStorage;
let original = raw;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.equal(original, raw);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
const rgb = (hex: string) => hex.match(/[0-9a-f]{2}/gi)!.map(channel => parseInt(channel, 16));
const luminance = (hex: string) => rgb(hex).map(channel => channel / 255)
.map(channel => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4)
.reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);
const contrast = (a: string, b: string) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
const mix = (a: string, b: string, ratio: number) => '#' + rgb(a)
.map((channel, index) => Math.round(channel * ratio + rgb(b)[index] * (1 - ratio)).toString(16).padStart(2, '0')).join('');
test('Silver Serpent text and syntax remain readable on opaque and image surfaces', () => {
const { surfaces, syntax, secondary } = CHARACTER_THEMES['silver-serpent'];
const [bg, elevated, active, , dim, text, strong, accent, selection] = surfaces;
const panelOnWhite = mix(elevated, '#ffffff', .82);
const editorOnWhite = mix(bg, '#ffffff', .9);
const backgrounds = {
bg, elevated, active, selection,
panelOnWhite,
editorOnWhite,
menuHoverOnWhite: mix(active, panelOnWhite, .82),
controlHoverOnWhite: mix(active, '#ffffff', .92),
codeBlockOnWhite: mix(elevated, editorOnWhite, .82),
};
const foregrounds = { dim, text, strong, accent, secondary,
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, syntax[index]])) };
for (const [backgroundName, background] of Object.entries(backgrounds)) {
for (const [foregroundName, foreground] of Object.entries(foregrounds)) {
assert(contrast(foreground, background) >= 4.5, `${foregroundName} on ${backgroundName}`);
}
}
});
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
const [bg, elevated, , , , , , accent, selection] = CHARACTER_THEMES['silver-serpent'].surfaces;
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');
});
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from '../../../src/lib/theme/characterThemes.ts';
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255);
function luminance(color: string) {
return rgb(color).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 values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
return (values[0] + 0.05) / (values[1] + 0.05);
}
test('Harvest Moon text and syntax stay readable on editor, panel, and selected surfaces', () => {
const palette = characterTheme('harvest-moon')!;
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
for (const foreground of [dim, text, strong, accent, palette.secondary]) {
for (const surface of [background, elevated, active, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
}
}
for (const [index, foreground] of palette.syntax.entries()) {
for (const surface of [background, elevated, selection]) {
assert(contrast(foreground, surface) >= 4.5, `${SYNTAX_ROLES[index]} on ${surface} needs 4.5:1 contrast`);
}
}
});
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]) {
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.equal(palette.mode, 'dark');
assert.equal(Object.keys(characterSyntax('harvest-moon')).length, SYNTAX_ROLES.length);
assert.deepEqual(characterSyntax('unknown'), {});
});