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
@@ -0,0 +1,142 @@
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 browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const output = '.audit/background-frames';
const report = [];
await mkdir(output, { recursive: true });
try {
for (const theme of ['light', 'dark']) {
const page = await browser.newPage({ viewport: { width: 1280, height: 820 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = 'C:/background-test';
const files = new Map([
['welcome.md', '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24)],
['hello.ts', '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n'],
]);
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
invoke: async (command, args = {}) => {
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'background-test', watch_mode: 'native' };
if (command === 'workspace_list') return [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('missing'); return files.get(args.rel); }
if (command === 'workspace_search') return [];
if (command === 'plugins_snapshot') return { root, plugins: [] };
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('.welcome-actions button').first().waitFor();
await page.getByText('background-test', { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const { backgroundHub } = await import('/src/lib/plugins/backgrounds.ts');
const make = (first, second) => {
const canvas = document.createElement('canvas'); canvas.width = 1200; canvas.height = 800;
const ctx = canvas.getContext('2d'); const gradient = ctx.createLinearGradient(0, 0, 1200, 800);
gradient.addColorStop(0, first); gradient.addColorStop(1, second); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1200, 800);
ctx.strokeStyle = '#ffffff88'; ctx.lineWidth = 12;
for (let x = 0; x < 1400; x += 200) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x - 300, 800); ctx.stroke(); }
return canvas.toDataURL();
};
const saved = make('#bd486c', '#438f67');
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
const urls = await Promise.all([make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(async url => URL.createObjectURL(await (await fetch(url)).blob())));
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
const background = page.locator('.workarea-background');
assert.equal(await background.count(), 1);
assert.equal(await page.locator('.empty h1, .empty > p').count(), 0);
assert.equal(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage), 'none');
const bounds = await background.boundingBox();
assert.equal(bounds.x, 0); assert.equal(bounds.y, 36); assert.equal(bounds.width, 1280); assert.equal(bounds.height, 762);
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
assert.match(await page.locator('.left').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.right').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.match(await page.locator('.welcome-actions button').first().evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
assert.doesNotMatch(await page.locator('header.header').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
await page.locator('.welcome-actions button').first().focus();
await page.keyboard.press('Tab');
assert(await page.locator('.welcome-actions').evaluate(node => node.contains(document.activeElement)));
await page.screenshot({ path: `${output}/${theme}-splash.png` });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[0], blurredUrl: urls[1], overlay: 0.15, position: 'top', size: 'contain' });
});
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundPosition), '50% 50%, 50% 0%, 50% 50%');
await page.screenshot({ path: `${output}/${theme}-portrait-layers.png` });
await page.setViewportSize({ width: 390, height: 700 });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
await page.screenshot({ path: `${output}/${theme}-portrait-layers-narrow.png` });
await page.setViewportSize({ width: 1280, height: 820 });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[1], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[0], overlay: 0.15, position: 'center', size: 'cover' }, transitionMs: 2000 });
});
await page.waitForTimeout(180);
const opacity = await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity));
assert(opacity > 0 && opacity < 1, `Fade has an intermediate opacity: ${opacity}`);
await page.waitForTimeout(900);
assert.ok(await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity) < 1), 'The fade remains active after one second');
await page.waitForTimeout(1100);
assert.equal(await background.evaluate(node => getComputedStyle(node, '::after').opacity), '1');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.match(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.9|90%)/);
await page.screenshot({ path: `${output}/${theme}-writer.png` });
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button', { name: 'Read', exact: true }).click();
await page.locator('.md-page').waitFor();
const beforeScroll = await background.boundingBox();
await page.locator('.md-page').evaluate(node => { node.scrollTop = 600; });
assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` });
await page.getByRole('button', { name: 'Split', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
assert.equal(await page.locator('.monaco-editor-background').first().evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await page.getByRole('button', { name: 'Edit', exact: true }).click();
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
await page.getByRole('button', { name: 'IDE', exact: true }).click();
await page.locator('.monaco-editor').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
await page.setViewportSize({ width: 680, height: 720 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.screenshot({ path: `${output}/${theme}-ide-narrow.png` });
await page.keyboard.press('Control+t');
await page.locator('.welcome-actions').waitFor();
await page.setViewportSize({ width: 480, height: 640 });
assert(await page.locator('.empty').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundImage), 'none');
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.locator('.editor > .body').waitFor();
assert.equal(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), await page.locator('.shell').evaluate(node => getComputedStyle(node).backgroundColor));
await page.screenshot({ path: output + '/' + theme + '-removed.png' });
assert.deepEqual(errors, []);
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'IDE transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
await page.close();
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
}
await writeFile(`${output}/report.json`, JSON.stringify(report, null, 2));
} finally { await browser.close(); }
@@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
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 context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (!files.has(args.from)) throw new Error('Missing file');
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const errors = [];
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
await mkdir('output/appearance-pass3', { recursive: true });
async function background() { return main.locator('.empty').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); }
async function decoded(page, url) {
return page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
}
try {
await main.goto(origin); await main.locator('.empty').waitFor();
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const image = await main.evaluate(() => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
const ctx = canvas.getContext('2d'), pixels = ctx.createImageData(700, 700);
let seed = 23;
for (let i = 0; i < pixels.data.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels.data[i] = i % 4 === 3 ? 255 : seed >>> 24; }
ctx.putImageData(pixels, 0, 0); return canvas.toDataURL();
});
const bytes = Buffer.from(image.split(',')[1], 'base64');
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
let url = await background();
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
await main.reload(); await main.locator('.empty').waitFor();
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const large = Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]);
await writeFile('output/appearance-pass3/50MiB.png', large);
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/50MiB.png'));
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.empty')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
await writeFile('output/appearance-pass3/too-large.png', Buffer.alloc(50 * 1024 * 1024 + 1));
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/too-large.png'));
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId), acceptedId);
assert.equal(await settings.locator('input[type=color]').count(), 0);
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('0.55'));
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('255, 255, 255, 0.4'));
for (const mode of ['dark', 'light']) {
await settings.locator('.picker').and(settings.getByRole('button', { name: 'Appearance', exact: true })).click();
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'Dark' : 'Light', exact: true }).click();
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
await main.screenshot({ path: `output/appearance-pass3/background-${mode}.png` });
for (const name of ['Color theme', 'Appearance']) {
await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).click();
const menu = settings.getByRole('menu', { name, exact: true });
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '30px');
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 0);
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
await settings.screenshot({ path: `output/appearance-pass3/${name.replaceAll(' ', '-')}-${mode}.png` });
await settings.keyboard.press('Escape');
assert.equal(await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).evaluate(node => node === document.activeElement), true);
}
}
await settings.setViewportSize({ width: 360, height: 480 });
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
await settings.screenshot({ path: 'output/appearance-pass3/menu-narrow.png' });
await settings.keyboard.press('Escape');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
await settings.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
});
for (const theme of ['light', 'dark']) {
await settings.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, theme);
await settings.setViewportSize({ width: 360, height: 600 });
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
await settings.screenshot({ path: `output/appearance-pass3/long-plugin-list-${theme}-narrow.png` });
await main.setViewportSize({ width: 600, height: 700 });
await main.keyboard.press('F1');
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
assert.equal(await main.locator('.help-card details[open]').count(), 0);
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 1);
await main.keyboard.press('Enter');
await main.screenshot({ path: `output/appearance-pass3/help-${theme}-narrow.png` });
await main.getByRole('button', { name: 'Close help', exact: true }).click();
}
assert.deepEqual(errors, []);
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
} finally { await browser.close(); }
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
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 context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command) => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const screenshots = [];
await mkdir('output/todo-background', { recursive: true });
try {
await main.goto(origin);
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
const button = settings.getByRole('button', { name: control, exact: true });
await button.click();
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
assert.equal(await button.evaluate(node => node === document.activeElement), true);
}
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('0% 0%'));
const layout = () => main.locator('.empty').evaluate(node => {
const style = getComputedStyle(node), box = node.getBoundingClientRect();
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
});
const before = await layout();
assert.equal(before.size, '100% 100%, auto');
await main.locator('.empty').evaluate(node => {
const content = document.createElement('div'); content.style.cssText = 'height:2000px;flex-shrink:0;width:100%'; node.append(content);
});
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
await main.reload();
await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
assert.equal((await layout()).position, before.position);
assert.equal((await layout()).size, before.size);
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
await settings.keyboard.press('End');
await settings.keyboard.press('Enter');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('100% 100%'));
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 700 });
const file = `output/todo-background/settings-${mode}-${width}.png`;
await settings.screenshot({ path: file }); screenshots.push(file);
const pane = settings.locator('.content');
assert.equal(await pane.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
}
}
await writeFile('output/todo-background-report.json', JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
} finally { await browser.close(); }
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
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 } : { channel: 'chrome' }) });
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async command => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const settings = await context.newPage();
const errors = [];
settings.on('pageerror', error => errors.push(error.message));
await mkdir('output/round4-overlay', { recursive: true });
try {
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
name: 'image.png', mimeType: 'image/png',
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'),
});
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay);
await input.fill('-37');
assert.equal(await slider.inputValue(), '-37');
assert.equal(await saved(), -0.37);
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal(await input.inputValue(), '-37');
await input.fill('');
assert.equal(await saved(), -0.37);
await input.blur();
assert.equal(await input.inputValue(), '-37');
await input.fill('150');
await input.blur();
assert.equal(await input.inputValue(), '100');
assert.equal(await saved(), 1);
await slider.fill('24');
assert.equal(await input.inputValue(), '24');
assert.equal(await saved(), 0.24);
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 780 });
await input.focus();
assert.equal(await input.evaluate(node => node === document.activeElement), true);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
await settings.screenshot({ path: `output/round4-overlay/${mode}-${width}.png` });
}
}
assert.deepEqual(errors, []);
await writeFile('output/round4-overlay-report.json', JSON.stringify({
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
screenshotFolder: 'output/round4-overlay',
native: 'Native desktop acceptance remains pending.',
}, null, 2));
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
} finally { await browser.close(); }
@@ -0,0 +1,231 @@
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(); }
+104
View File
@@ -0,0 +1,104 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
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: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.setDefaultTimeout(30000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const url = process.env.SMOKE_URL || "http://127.0.0.1:5174";
const row = page.locator('[data-tree-rel="note.md"]');
try {
await page.goto(url);
await row.waitFor();
await row.click();
await page.locator('.writer-table table').waitFor();
const alignment = await page.evaluate(() => ({header:document.querySelector('.header-left').getBoundingClientRect().right, content:document.querySelector('.center').getBoundingClientRect().left}));
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
const table = await page.locator('.writer-table table').evaluate(el => ({width:el.getBoundingClientRect().width, heights:[...el.rows].map(row=>row.getBoundingClientRect().height), radius:getComputedStyle(el.parentElement).borderRadius}));
assert.ok(table.width < 400, JSON.stringify(table));
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
assert.equal(table.radius, '0px');
await row.focus();
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'visible');
await page.locator('.cm-content').click({position:{x:80,y:100}});
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'hidden');
assert.equal(await row.getAttribute('aria-selected'), 'true');
const line = page.locator('.cm-line').filter({hasText:'A second paragraph.'});
await line.hover();
assert.equal(await line.evaluate(el=>getComputedStyle(el,'::before').width), '3px');
assert.equal(await page.locator('.line-history').count(),0);
await page.evaluate(async()=>{
const {pluginHost}=await import('/src/lib/plugins/registry.ts');
window.blameCalls=[];
window.removeGit=pluginHost.register('ui-test','git',{blame:async(path,line)=>{
window.blameCalls.push({path,line});
return {commit:'123456789abcdef',author:'UI test',date:'2026-10-07T12:34:00Z',summary:`Changed line ${line}`};
}});
});
await line.click();
await page.locator('.line-history').waitFor();
assert.match(await page.locator('.line-history').getAttribute('title'), /Line 5 · UI test/);
await page.keyboard.type('x');
await page.locator('.line-history').waitFor({state:'hidden'});
await page.keyboard.press('Control+z');
await page.locator('.line-history').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const tab = await page.locator('.tab.active').evaluate(el=>({background:getComputedStyle(el).backgroundColor,border:getComputedStyle(el).borderBottomColor,shadow:getComputedStyle(el).boxShadow}));
const pane = await page.locator('.chrome-bar').evaluate(el=>getComputedStyle(el).backgroundColor);
assert.equal(tab.background,pane);
assert.equal(tab.border,'rgba(0, 0, 0, 0)');
assert.equal(tab.shadow,'none');
await line.hover();
await page.screenshot({path:`.audit/ui-cards/writer-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('ArrowRight');
await page.locator('.md-page .reading').waitFor();
const paragraph=page.locator('.md-page p').filter({hasText:'A second paragraph.'});
await paragraph.hover();
assert.equal(await paragraph.evaluate(el=>getComputedStyle(el,'::before').width),'3px');
assert.ok((await page.locator('.md-page table').boundingBox()).width<400);
await page.screenshot({path:`.audit/ui-cards/read-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('Home');
}
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('Home');
await page.locator('.monaco-editor').waitFor();
await page.locator('.line-history').waitFor();
await page.evaluate(()=>window.removeGit());
await page.locator('.line-history').waitFor({state:'hidden'});
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('End');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:760,height:640});
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const dimensions=await page.locator('.header-left .icon-btn').evaluateAll(els=>els.map(el=>({width:el.getBoundingClientRect().width,svg:el.querySelector('svg').getBoundingClientRect().width})));
assert.ok(dimensions.every(size=>size.width>=28 && size.svg>=16),JSON.stringify(dimensions));
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`.audit/ui-cards/narrow-${theme}.png`});
}
assert.deepEqual(errors,[]);
console.log('PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width');
} finally {await browser.close();}
+206
View File
@@ -0,0 +1,206 @@
// Run against the development server with an isolated browser storage context.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const findings = [];
const output = ".audit";
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const secondSettings = await context.newPage();
for (const page of [main, settings, secondSettings]) {
page.setDefaultTimeout(10000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
}
async function syntaxColors() {
return main.locator(".view-line span").evaluateAll(spans => Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
})));
}
async function waitForSyntax(expected = null) {
await main.waitForFunction(expected => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
}));
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected);
}
const themeName = (theme, mode) => theme === 'sakura' ? 'Sakura' : `${({ default: 'RuneStone', claude: 'Claude' })[theme]} ${mode === 'light' ? 'Light' : 'Dark'}`;
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
async function choose(page, theme, mode) {
await picker(page, 'Color theme').click();
await page.getByRole('menuitemradio', { name: themeName(theme, mode), exact: true }).click();
}
async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await picker(page, "Color theme").waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
const workarea = document.querySelector('.editor > .body');
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === 'rgba(0, 0, 0, 0)')
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}.png` });
await main.screenshot({ path: `${output}/appearance-editor-${theme}-${mode}.png` });
if (theme === 'sakura') {
const keywordColor = await main.locator('.view-line span').evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === 'def');
return keyword ? getComputedStyle(keyword).color : null;
});
assert.equal(keywordColor, 'rgb(152, 85, 108)', 'Sakura keywords use Plum Wine');
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector('h2')).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue('--rs-font-prose').trim(),
}));
if (theme === 'claude') {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-accent').trim()), '#d97757');
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
await picker(settings, 'Color theme').click();
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone Light', 'RuneStone Dark', 'Claude Light', 'Claude Dark', 'Sakura', 'Harvest Moon', 'Crimson Pilot', 'Silver Serpent']);
await settings.keyboard.press('Escape');
assert.equal(await picker(settings, 'Appearance').count(), 0);
assert.equal(await picker(secondSettings, 'Appearance').count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
assert.deepEqual(sakura, { bg: '#fefcfc', border: '#f8dbe6', selection: '#ffc9dc', 'bg-active': '#dbeacb', 'syntax-parameter': '#cb6b91', 'syntax-keyword': '#98556c', 'syntax-local': '#618c71', 'syntax-static': '#69a2bd', 'syntax-instance': '#607fa9', 'syntax-global': '#687788' });
for (const [theme, savedMode, expectedTheme, mode] of [
['gpt', 'light', 'default', 'light'],
['terminal', 'dark', 'default', 'dark'],
['sakura', 'dark', 'sakura', 'light'],
]) {
await settings.evaluate(value => localStorage.setItem('runestone.appearance', JSON.stringify(value)), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance'))), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose(settings, theme, mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme']) {
const control = picker(settings, name);
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
}
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}-360.png` });
}
assert.deepEqual(errors, []);
assert.deepEqual(findings, [], 'Appearance findings');
await context.close();
console.log('Appearance smoke passed: supported palettes, modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.');
} catch (error) {
console.error('Browser errors:', errors);
for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) {
await page.screenshot({ path: `${output}/appearance-failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
await mkdir('.audit/host-ui', { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.on('pageerror', error => errors.push(error.message));
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
for (const [theme, mode] of [['default','dark'],['default','light'],['claude','dark'],['claude','light'],['sakura','light'],['harvest-moon','dark'],['crimson-pilot','dark'],['silver-serpent','dark']]) {
await page.evaluate(async ({theme,mode}) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({theme,mode,transparency:{enabled:true,amount:18}});
window.dispatchEvent(new Event('focus'));
},{theme,mode});
const slider = page.locator('#surface-transparency');
await slider.fill('100');
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount),100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(),'0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(),'100');
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-focus.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).uncheck();
assert(await slider.isDisabled());
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-disabled.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).check();
await page.setViewportSize({width:360,height:740}); await slider.scrollIntoViewIfNeeded();
assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-narrow.png`});
await page.setViewportSize({width:1100,height:800});
}
await page.evaluate(async () => {
const {installTheme} = await import('/src/lib/theme/customThemes.ts');
const {saveAppearance,exportAppearanceTheme} = await import('/src/lib/theme/appearance.ts');
const theme = exportAppearanceTheme('default'); theme.fonts = {ui:'Arial, sans-serif',prose:'Georgia, serif',heading:'Georgia, serif',mono:'Consolas, monospace'};
installTheme(theme); saveAppearance({theme:'custom:my-theme',mode:'dark'}); window.dispatchEvent(new Event('focus'));
});
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily),/Georgia/);
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui),/Arial/);
await page.screenshot({path:'.audit/host-ui/custom-fonts.png'});
const main = await context.newPage(); await main.goto(origin);
await main.bringToFront();
await main.getByRole('button',{name:'Files',exact:true}).waitFor();
await main.evaluate(async () => {
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
const {pluginTools,refreshPlugins} = await import(loaded || '/src/lib/plugins/external.ts');
await refreshPlugins();
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command,args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command,args);
const commands = [{owner:'runestone.background-slideshow',id:'next-image',title:'Next background image',kind:'command',surface:'commands',icon:'skip-forward'},{owner:'runestone.background-slideshow',id:'pause-resume',title:'Pause or resume background slideshow',kind:'command',surface:'commands',icon:'pause'}];
pluginTools.set(commands);
});
for (const mode of ['dark','light']) {
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
const button = main.getByRole('button',{name:'Commands',exact:true});
assert.equal(await button.getAttribute('title'),null);
await button.hover(); await main.waitForTimeout(1100);
assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await main.screenshot({path:`.audit/host-ui/${mode}-single-tooltip.png`});
await main.keyboard.press('Escape'); assert.equal(await main.locator('[role=tooltip]:visible').count(),0);
await main.mouse.move(400,400);
await button.evaluate(node => node.blur());
await button.focus(); await main.waitForTimeout(600); assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await button.click(); await main.getByRole('menu').waitFor();
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
await main.screenshot({path:`.audit/host-ui/${mode}-slideshow-command-icons.png`}); await main.keyboard.press('Escape');
}
assert.deepEqual(errors,[]);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
} finally { await browser.close(); }
@@ -0,0 +1,166 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugins_snapshot') return { root: 'C:/theme-test-plugins', plugins: [] };
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
try {
await mkdir('output/october15-appearance', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=' } });
}, mode);
const tab = page.getByRole('tab', { name: /welcome\.md/ });
assert.equal(await tab.getAttribute('title'), null);
await page.mouse.move(600, 600);
await tab.hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /welcome\.md/);
await page.screenshot({ path: `output/october15-appearance/${mode}-tab-tooltip.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await tab.focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
await page.keyboard.press('Escape');
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
await writer.click(); await page.keyboard.press('Control+a');
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement);
return { selection: root.getPropertyValue('--rs-selection'), bg: getComputedStyle(node, '::selection').backgroundColor,
text: getComputedStyle(node).color, image: root.getPropertyValue('--rs-new-tab-image'), pluginBg: root.getPropertyValue('--rs-workarea-plugin-bg') };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
assert.notEqual(colors.image.trim(), 'none');
assert.equal(colors.pluginBg.trim(), 'transparent');
console.log(mode, colors);
await page.screenshot({ path: `output/october15-appearance/${mode}-selection.png` });
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.locator('.empty').waitFor();
await page.screenshot({ path: `output/october15-appearance/${mode}-zero-background.png` });
await page.getByRole('tab', { name: /welcome\.md/ }).click();
}
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode });
window.dispatchEvent(new Event('focus'));
}, mode);
const slider = page.locator('#surface-transparency');
for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 800 });
await slider.fill('0'); const zero = await slider.boundingBox();
for (const amount of ['1', '9', '11', '18', '99', '100']) {
await slider.fill(amount); const current = await slider.boundingBox();
assert.equal(current.x, zero.x); assert.equal(current.width, zero.width);
}
await page.screenshot({ path: `output/october15-appearance/${mode}-${width}-slider.png` });
}
}
await page.evaluate(() => {
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_choose'
? Promise.resolve([{ token: 'theme-test', source: 'C:/Downloads/example.zip', error: null,
manifest: { id: 'example', name: 'Theme example', version: '0.1.0', description: 'Theme control test', author: 'RuneStone', entry: 'main.js' } }])
: invoke(command, args);
});
await page.getByRole('button', { name: 'Plug-ins', exact: true }).click();
for (const [theme, mode] of [['harvest-moon', 'dark'], ['default', 'light']]) {
await page.evaluate(async ({ theme, mode }) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode }); window.dispatchEvent(new Event('focus'));
}, { theme, mode });
await page.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
const checkbox = page.getByRole('checkbox', { name: 'Theme example', exact: true });
await checkbox.waitFor();
assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => {
const probe = document.createElement('span'); probe.style.color = 'var(--rs-accent)'; document.body.append(probe);
const color = getComputedStyle(probe).color; probe.remove(); return color;
}));
await checkbox.focus();
await page.screenshot({ path: `output/october15-appearance/${theme}-${mode}-install-checkbox.png` });
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
}
assert.deepEqual(errors, []);
console.log('PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.');
} catch (error) {
await page.screenshot({ path: 'output/october15-appearance/failure.png' });
throw error;
} finally { await browser.close(); }
+145
View File
@@ -0,0 +1,145 @@
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(); }