Files
RuneStone/scripts/themeTypography.smoke.mjs
T

146 lines
9.7 KiB
JavaScript

import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const output = '.audit/theme-typography';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const report = [];
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:/font-smoke-plugins', plugins: [] };
if (command === 'workspace_last_path') return 'C:\\font-smoke';
if (command === 'workspace_open') return { root: 'C:\\font-smoke', name: 'font-smoke', watch_mode: 'native' };
if (command === 'workspace_list') return [{ name: 'Typography.md', rel_path: 'Typography.md', kind: 'file' }];
if (command === 'workspace_read') return '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n';
if (command === 'workspace_search') return [];
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();
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
await main.goto(origin);
await main.getByText('font-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Typography.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const sessions = new Map();
async function rendered(page, selector) {
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
let session = sessions.get(page);
if (!session) {
session = await context.newCDPSession(page);
await session.send('DOM.enable'); await session.send('CSS.enable'); sessions.set(page, session);
}
const { root } = await session.send('DOM.getDocument');
const { nodeId } = await session.send('DOM.querySelector', { nodeId: root.nodeId, selector });
assert(nodeId, selector);
const { fonts } = await session.send('CSS.getPlatformFontsForNode', { nodeId });
const style = await page.locator(selector).first().evaluate(node => {
const css = getComputedStyle(node);
return { family: css.fontFamily, size: css.fontSize, weight: css.fontWeight, lineHeight: css.lineHeight };
});
return { ...style, rendered: fonts.filter(font => font.glyphCount).map(({ familyName, postScriptName, glyphCount, isCustomFont }) => ({ familyName, postScriptName, glyphCount, isCustomFont })) };
}
const cases = [
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
['silver-serpent', 'Silver Serpent', 'Palatino Linotype', 'Corbel', 'Palatino Linotype', 'Palatino Linotype'],
];
for (const [theme, label, oldFont, ui, prose, heading] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
const picker = settings.locator('.picker').and(settings.getByRole('button', { name: 'Color theme', exact: true }));
await picker.click();
await settings.getByRole('menuitemradio', { name: label, exact: true }).click();
await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme);
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home');
await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); });
for (const page of [main, settings]) {
await page.evaluate(font => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
}, oldFont);
await page.screenshot({ path: `${output}/${theme}-before-${page === main ? 'document' : 'settings'}.png` });
await page.evaluate(() => {
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`);
});
}
const roles = {
ui: await rendered(settings, '.picker[aria-label="Color theme"]'),
prose: await rendered(main, '.cm-line:not(.writer-heading):not(.writer-blank)'),
heading: await rendered(main, '.writer-h1'),
mono: await rendered(settings, '.preview-code'),
};
for (const [role, family] of Object.entries({ ui, prose, heading })) {
assert(roles[role].family.includes(family), `${theme}: ${role} CSS family`);
assert(roles[role].rendered.some(font => font.familyName === family), `${theme}: ${role} actually renders ${family}: ${JSON.stringify(roles[role])}`);
}
assert.equal(roles.ui.size, '13px');
assert.equal(roles.prose.size, '15px');
assert(roles.mono.family.includes('Cascadia Mono'));
assert(roles.mono.rendered.some(font => font.familyName === 'Cascadia Mono'));
await settings.screenshot({ path: `${output}/${theme}-after-settings.png` });
await main.screenshot({ path: `${output}/${theme}-after-document.png` });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const paragraph = [...node.querySelectorAll('.cm-line')].find(line => line.textContent.includes('Read the next chapter'));
const range = document.createRange(); range.selectNodeContents(paragraph);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert((await main.evaluate(() => getSelection().toString())).includes('Read the next chapter'));
await main.screenshot({ path: `${output}/${theme}-selected-prose.png` });
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
await picker.scrollIntoViewIfNeeded(); await picker.focus(); await settings.keyboard.press('Enter');
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
await current.waitFor();
assert(await current.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: `${output}/${theme}-narrow-menu.png` });
await settings.keyboard.press('Escape');
assert(await picker.evaluate(node => node === document.activeElement));
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.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
});
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: `${output}/${theme}-narrow-long-plugins.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([]);
});
const fallback = {};
for (const [role, page, selector] of [['ui', settings, '.picker[aria-label="Color theme"]'], ['prose', main, '.cm-line:not(.writer-heading):not(.writer-blank)'], ['heading', main, '.writer-h1']]) {
await page.evaluate(role => {
const css = getComputedStyle(document.documentElement);
const stack = css.getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
}, role);
fallback[role] = await rendered(page, selector);
assert(fallback[role].rendered.length > 0);
await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role);
}
report.push({ theme, oldFont, roles, fallback });
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
}
assert.deepEqual(errors, []);
await writeFile(`${output}/rendered-fonts.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }