Files
RuneStone/scripts/characterThemes.smoke.mjs
T

232 lines
16 KiB
JavaScript

import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const output = '.audit/character-themes';
const errors = [];
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugins_snapshot') return { root: 'C:/theme-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\theme-smoke';
if (command === 'workspace_open') return { root: 'C:\\theme-smoke', name: 'theme-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Theme.md', rel_path: 'Theme.md', kind: 'file' }, { name: 'Theme.py', rel_path: 'Theme.py', kind: 'file' }];
if (command === 'workspace_read' && args.rel === 'Theme.py') return '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n';
if (command === 'workspace_read') return '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n';
if (command === 'workspace_search') return [];
if (command === 'theme_export') { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; }
if (command === 'plugin:event|listen') return args.handler;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const ide = await context.newPage();
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
for (const page of [main, settings, ide]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
await main.getByText('theme-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Theme.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await ide.goto(origin);
await ide.getByText('theme-smoke', { exact: true }).waitFor();
await ide.keyboard.press('Control+p');
await ide.getByRole('textbox', { name: 'Find a file' }).fill('Theme.py');
await ide.getByRole('textbox', { name: 'Find a file' }).press('Enter');
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(`${origin}/?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();
};
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 });
const variant = label;
await choose('Color theme', variant);
for (const page of [main, settings, ide]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
}
const colors = await settings.evaluate(async theme => {
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
return exportAppearanceTheme(theme);
}, theme);
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(colors[mode]));
assert.deepEqual(actual, colors[mode]);
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.getByRole('button', { name: 'Export theme template' }).click();
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), colors);
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[mode]['syntax-keyword'], RuneStone: colors[mode]['syntax-string'], 42: colors[mode]['syntax-number'], print: colors[mode]['syntax-keyword'], '# Character colors': colors[mode]['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, colors[mode].selection, 'File selection uses the same warm selection color');
assert.equal(selectedRow.fill, 'rgb(72, 39, 20)', 'The selected file paints the warm fill');
await main.screenshot({ path: `${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: `${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),
'rgb(72, 39, 20)', 'IDE selection uses the same warm fill');
await ide.screenshot({ path: `${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: `${output}/${theme}-${mode}-ide.png` });
await settings.screenshot({ path: `${output}/${theme}-${mode}-settings.png` });
await main.screenshot({ path: `${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(), variant);
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: variant, 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: `${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: `${output}/${theme}-${mode}-360-focus.png` });
await settings.evaluate(async () => {
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: 16 }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
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: `${output}/${theme}-${mode}-360-long-navigation.png` });
await settings.evaluate(async () => { const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]); });
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();
for (const page of [main, settings, ide]) {
await page.waitForFunction(mode => document.documentElement.dataset.palette === 'default' && document.documentElement.dataset.theme === mode, 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: `${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: `${output}/default-${mode}-360-settings.png` });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
}
assert.deepEqual(errors, []);
console.log('Character theme smoke passed.');
} catch (error) {
console.error('Page errors:', errors);
for (const context of browser.contexts()) {
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `${output}/failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }