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.
181 lines
13 KiB
JavaScript
181 lines
13 KiB
JavaScript
import { createRequire } from 'node:module';
|
|
import { spawn } from 'node:child_process';
|
|
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import assert from 'node:assert/strict';
|
|
const runtime = path.resolve('browser-runtime');
|
|
const require = createRequire(path.join(runtime, 'package.json'));
|
|
const { chromium } = require('playwright');
|
|
const electron = require('electron');
|
|
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
|
|
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
|
|
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
|
|
});
|
|
let sequence = 0, page, pendingFrame, painting = false;
|
|
const pending = new Map();
|
|
const commands = [];
|
|
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
|
|
const id = ++sequence;
|
|
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
|
|
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
|
child.send({ id, command, args });
|
|
});
|
|
async function paint() {
|
|
if (painting || !page || !pendingFrame) return;
|
|
painting = true;
|
|
const frame = pendingFrame; pendingFrame = undefined;
|
|
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
|
|
painting = false;
|
|
if (pendingFrame) void paint();
|
|
}
|
|
const ready = new Promise((resolve, reject) => {
|
|
child.on('error', reject);
|
|
child.on('message', message => {
|
|
if (message.ready) resolve();
|
|
if (message.id) {
|
|
const callback = pending.get(message.id); pending.delete(message.id);
|
|
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
|
|
}
|
|
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
|
|
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
|
|
});
|
|
});
|
|
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
|
const errors = [];
|
|
try {
|
|
await ready;
|
|
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
|
|
page.on('pageerror', error => errors.push(error.message));
|
|
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
|
|
await page.addInitScript(() => {
|
|
window.isTauri = true;
|
|
const callbacks = new Map(), listeners = new Map(); let next = 0;
|
|
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
|
|
window.__TAURI_INTERNALS__ = {
|
|
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
|
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
|
|
invoke: async (command, args = {}) => {
|
|
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
|
|
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
|
|
if (command === 'browser_connect') return 'test-session';
|
|
if (command === 'browser_stop' || command === 'plugins_release') return;
|
|
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
|
|
if (command === 'workspace_last_path') return null;
|
|
if (command === 'workspace_recent') return [];
|
|
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
|
if (command.startsWith('plugin:window|')) return false;
|
|
throw Error(`Unhandled IPC: ${command}`);
|
|
},
|
|
};
|
|
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
|
|
});
|
|
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
|
|
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
|
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
|
await page.locator('[data-browser-state="ready"]').waitFor();
|
|
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
|
|
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
|
|
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
|
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
|
|
const initialBox = await surface.boundingBox();
|
|
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
|
await page.keyboard.type('Hello World!');
|
|
await page.waitForTimeout(200);
|
|
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!');
|
|
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
|
|
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
|
|
await page.waitForTimeout(200);
|
|
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!Hello World!');
|
|
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
|
|
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
|
|
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
|
|
});
|
|
await page.waitForTimeout(100);
|
|
assert.ok((await evaluate('document.querySelector("#typing").value')).endsWith('日本語'));
|
|
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
|
|
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
|
|
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
|
|
await page.waitForTimeout(100);
|
|
assert.equal(await evaluate('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart'), 27);
|
|
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
|
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
|
|
await page.keyboard.press('Escape');
|
|
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
|
|
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
|
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
|
|
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
|
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
|
|
await page.waitForTimeout(100);
|
|
assert.equal(await evaluate('document.querySelector("#typing").value'), 'https://example.com/');
|
|
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
|
|
await page.locator('.surface img').waitFor();
|
|
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
|
|
await page.waitForTimeout(3000);
|
|
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
|
|
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
|
|
const beforeWheels = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
|
|
await surface.evaluate(node => {
|
|
const bounds = node.getBoundingClientRect();
|
|
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
|
|
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
|
|
}));
|
|
});
|
|
await page.waitForTimeout(200);
|
|
const wheelBurstCalls = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length - beforeWheels;
|
|
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
|
|
await evaluate('window.testAnimate=false;true;');
|
|
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
|
|
await page.locator('.surface img').waitFor();
|
|
const box = await surface.boundingBox();
|
|
const x = box.x + 220, y = box.y + 180;
|
|
await page.mouse.click(x, y, { button: 'middle' });
|
|
await page.mouse.move(x + 90, y + 120);
|
|
await page.waitForTimeout(1500);
|
|
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
|
|
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
|
|
await page.keyboard.press('Escape');
|
|
await page.waitForTimeout(350);
|
|
const stopped = await evaluate('scrollY');
|
|
await page.waitForTimeout(200);
|
|
assert.equal(await evaluate('scrollY'), stopped);
|
|
assert.equal(await page.locator('.scroll-anchor').count(), 0);
|
|
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
|
|
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
|
|
await page.waitForTimeout(100);
|
|
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
|
|
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
|
|
await page.mouse.click(x, y, { button: 'middle' });
|
|
await page.mouse.click(x, y, { button: 'left' });
|
|
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
|
|
await page.mouse.click(x, y, { button: 'middle' });
|
|
await page.getByRole('textbox', { name: 'Address or search' }).focus();
|
|
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
|
|
const beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
|
|
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
|
|
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
|
|
await page.waitForTimeout(100);
|
|
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
|
|
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
|
|
await mkdir('output', { recursive: true });
|
|
for (const theme of ['dark', 'light']) {
|
|
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
|
|
await page.mouse.click(x, y, { button: 'middle' });
|
|
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
|
|
await page.keyboard.press('Escape');
|
|
}
|
|
await page.setViewportSize({ width: 420, height: 650 });
|
|
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
|
await page.setViewportSize({ width: 1280, height: 800 });
|
|
await page.keyboard.press('Control+t');
|
|
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
|
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
|
|
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
|
|
assert.deepEqual(errors, []);
|
|
await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
|
|
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
|
|
} finally {
|
|
await browser.close();
|
|
await rpc('shutdown').catch(() => {}); child.kill();
|
|
}
|