Files
RuneStone/tests/smoke/appearance/backgroundImages.smoke.mjs
T
Knotty Wyvern e433bed28e 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.
2026-10-27 19:47:39 -07:00

155 lines
12 KiB
JavaScript

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(); }