Files
RuneStone/tests/smoke/appearance/characterThemes.smoke.mjs
T
Knotty Wyvern 69f90df571 Move the smoke tests onto the shared harness
Each smoke test now uses tests/smoke/_harness/ for Playwright, the Tauri
IPC mock, the in-memory workspace, and output folders, instead of its
own copy. The tests keep their interactions and assertions. Mock
handlers that the app never calls are gone.

- Split the four mixed regression scripts into 18 feature tests.
- Update tests that broke when the app changed on purpose. Each update
  cites the app source that shows the new behavior.
- Mark two real app defects with @known-issue: the settings window
  controls are 1px shorter than the main window controls, and plugin
  tabs cannot be reordered by dragging without a workspace.
- Merge three palette unit tests into one table-driven test.
- The native tests load Playwright through the harness and read
  NATIVE_CDP_URL, with their old variable names as fallbacks.
- A failed smoke test saves a screenshot and prints the console errors.
- The runner runs failed tests once more, alone, and reports a test
  that then passes as flaky.

Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78
passed.
2026-10-27 20:58:55 -07:00

225 lines
16 KiB
JavaScript

// Character themes: colors, fonts, IDE syntax, export, window sync, narrow menus, selection fills, and legacy or removed theme IDs.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/characterThemes', async ({ browser }) => {
const output = await outputDir('appearance/characterThemes');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\theme-smoke',
files: {
'Theme.md': '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n',
'Theme.py': '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n',
},
}),
plugins_snapshot: () => ({ root: 'C:/theme-smoke-plugins', plugins: [] }),
theme_export: args => { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; },
}),
});
const main = await openPage(context);
const settings = await openPage(context);
const ide = await openPage(context);
const pages = [main, settings, ide];
try {
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
async function openFile(page, name) {
await page.goto(smokeUrl);
await page.getByText('theme-smoke', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
}
await openFile(main, 'Theme.md');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await openFile(ide, 'Theme.py');
await ide.locator('.monaco-editor textarea').waitFor();
const editorIds = () => ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
const choose = async (name, value) => {
await picker(name).click();
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
};
const waitForAppearance = (theme, mode) => Promise.all(pages.map(page => page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode })));
// Settings and the app import external.ts with a version query, so reuse the loaded module URL.
const setPluginTools = count => settings.evaluate(async count => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
await openSettings();
await picker('Color theme').click();
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
}
await settings.keyboard.press('Escape');
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
];
for (const [theme, label, mode, expectedFonts] of cases) {
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).
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).
const applied = { ...colors, selection: `${colors.selection.slice(0, 7)}a6` };
const actual = await settings.evaluate(keys => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(keys.map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
}, Object.keys(applied));
assert.deepEqual(actual, applied);
const fonts = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return { ui: css.getPropertyValue('--rs-font-ui'), prose: getComputedStyle(document.querySelector('.preview-prose')).fontFamily,
heading: getComputedStyle(document.querySelector('.preview-document strong')).fontFamily,
code: getComputedStyle(document.querySelector('.preview-code')).fontFamily };
});
for (const key of ['ui', 'prose', 'heading']) assert(fonts[key].includes(expectedFonts[key]), `${theme}: ${key} uses its font`);
assert(fonts.code.includes('Cascadia Mono'), 'Code retains the shared monospace font');
const { root } = await fontSession.send('DOM.getDocument');
const { nodeId } = await fontSession.send('DOM.querySelector', { nodeId: root.nodeId, selector: '.preview-prose' });
const rendered = await fontSession.send('CSS.getPlatformFontsForNode', { nodeId });
assert(rendered.fonts.some(item => item.glyphCount > 0), 'The font renders visible glyphs');
console.log(`${theme} rendered fonts: ${rendered.fonts.map(item => item.familyName).join(', ')}`);
await settings.evaluate(() => { window.exportedTheme = undefined; });
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.waitForFunction(() => window.exportedTheme);
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), template);
await ide.waitForFunction(expected => {
const spans = [...document.querySelectorAll('.view-line span')].filter(node => !node.children.length);
return Object.entries(expected).every(([text, color]) => {
const node = spans.find(node => node.textContent.replaceAll('\u00a0', ' ').includes(text));
const probe = document.createElement('i');
probe.style.color = color; document.body.append(probe);
const target = getComputedStyle(probe).color; probe.remove();
return node && getComputedStyle(node).color === target;
});
}, { return: colors['syntax-keyword'], RuneStone: colors['syntax-string'], 42: colors['syntax-number'], print: colors['syntax-keyword'], '# Character colors': colors['syntax-comment'] });
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
if (theme === 'harvest-moon') {
const normalized = await settings.evaluate(async () => {
const { normalizeAppearance } = await import('/src/lib/theme/appearance.ts');
return normalizeAppearance({ theme: 'harvest-moon', mode: 'light' });
});
assert.equal(normalized.mode, 'dark', 'Harvest Moon keeps its fixed dark appearance');
await main.locator('[data-tree-rel="Theme.md"]').click();
const selectedRow = await main.locator('[data-tree-rel="Theme.md"]').evaluate(node => {
const css = getComputedStyle(node);
return { selected: node.getAttribute('aria-selected'), fill: css.backgroundColor,
selection: getComputedStyle(document.documentElement).getPropertyValue('--rs-item-selection-bg').trim() };
});
assert.equal(selectedRow.selected, 'true');
assert.equal(selectedRow.selection, applied.selection, 'File selection uses the same warm selection color');
// Selection fills use the capped a6 (0.65) alpha (src/lib/theme/appearance.ts:197-203).
const warmFill = 'rgba(72, 39, 20, 0.65)';
assert.equal(selectedRow.fill, warmFill, 'The selected file paints the warm fill');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-file-selection.png`) });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
let text;
while ((text = walker.nextNode()) && !text.textContent.includes('A calm surface')) {}
const range = document.createRange(); range.selectNodeContents(text);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-writer-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
editor.setSelection(new monaco.Selection(1, 1, 3, 21)); editor.focus();
});
await ide.locator('.selected-text').first().waitFor();
assert.equal(await ide.locator('.selected-text').first().evaluate(node => getComputedStyle(node).backgroundColor),
warmFill, 'IDE selection uses the same warm fill');
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide-selection.png`) });
await ide.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setPosition({ lineNumber: 1, column: 1 });
});
}
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide.png`) });
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-settings.png`) });
await main.screenshot({ path: path.join(output, `${theme}-${mode}-document.png`) });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal((await picker('Color theme').textContent()).trim(), label);
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
await picker('Color theme').scrollIntoViewIfNeeded();
await picker('Color theme').focus();
await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => document.activeElement === node), 'The menu focuses the current theme');
const bounds = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 480, 'The menu stays within the viewport');
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-menu.png`) });
await settings.keyboard.press('ArrowDown');
await settings.keyboard.press('ArrowUp');
assert(await current.evaluate(node => document.activeElement === node));
await settings.keyboard.press('Escape');
assert(await picker('Color theme').evaluate(node => document.activeElement === node), 'Dismissal returns focus');
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-focus.png`) });
await setPluginTools(16);
const navigation = settings.locator('dialog aside');
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await navigation.boundingBox()).height <= bodyBounds.height * 0.4 + 1, 'Long plugin navigation leaves room for settings');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-long-navigation.png`) });
await setPluginTools(0);
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
await openSettings();
assert.equal((await picker('Color theme').textContent()).trim(), label);
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
await waitForAppearance('default', mode);
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: path.join(output, `${removed}-fallback-${mode}-settings.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: path.join(output, `default-${mode}-360-settings.png`) });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
} catch (error) {
for (const [index, page] of pages.entries()) await page.screenshot({ path: path.join(output, `failure-${index}.png`) }).catch(() => {});
throw error;
}
});