Files
RuneStone/tests/smoke/appearance/characterThemes.smoke.mjs
T
Knotty Wyvern 5d5ba9e1f7 Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
2026-10-27 23:56:00 -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 => window.__TEST__.writeSettings('appearance', { 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(() => window.__TEST__.settings('appearance').theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => window.__TEST__.writeSettings('appearance', { 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;
}
});