Files
RuneStone/scripts/browserFields.smoke.mjs
T

154 lines
9.5 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();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await mkdir('.audit/browser-fields', { recursive: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: `.audit/browser-fields/caret-${process.env.BROWSER_TEST_SCALE || 1}x.png` });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), Number(process.env.BROWSER_TEST_SCALE || 1), 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
}