Middle-click scrolling in the built-in browser showed the text arrow "↕" at 20 px in a 24 px circle. The look of that glyph depends on the font, and the circle cut it. It also showed only two directions, but the scroll moves in four. The marker now uses the four-way scroll icon of Project Management, which the shared Icon component also gets. The marker has the size of the Project Management marker: a 26 px circle with a 20 px icon. The interaction smoke test checks the icon and keeps screenshots in both themes. Card ac49c9ec.
222 lines
16 KiB
JavaScript
222 lines
16 KiB
JavaScript
// Embedded browser input with the real Electron engine: typing, clipboard, composition, page menus, autoscroll, input coalescing, and new tabs.
|
|
// @requires electron
|
|
import { createRequire } from 'node:module';
|
|
import { spawn } from 'node:child_process';
|
|
import { createServer } from 'node:http';
|
|
import { mkdtemp, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import assert from 'node:assert/strict';
|
|
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
|
|
|
|
const runtime = path.join(repoRoot, 'browser-runtime');
|
|
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
|
|
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
|
|
|
|
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
|
|
async function startEngine() {
|
|
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 },
|
|
});
|
|
const engine = { page: undefined, commands: [], child };
|
|
let sequence = 0, pendingFrame, painting = false;
|
|
const pending = new Map();
|
|
engine.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 || !engine.page || !pendingFrame) return;
|
|
painting = true;
|
|
const frame = pendingFrame; pendingFrame = undefined;
|
|
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
|
|
painting = false;
|
|
if (pendingFrame) void paint();
|
|
}
|
|
await 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 && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
|
|
});
|
|
});
|
|
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
|
|
return engine;
|
|
}
|
|
|
|
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
|
|
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
|
|
|
|
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
|
|
async function startFixture() {
|
|
let gifServed = false;
|
|
const server = createServer((request, response) => {
|
|
if (request.url === '/once.gif') {
|
|
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
|
|
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
|
|
}
|
|
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
|
|
});
|
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
|
|
}
|
|
|
|
await runSmoke('browser/interaction', async ({ browser }) => {
|
|
const engine = await startEngine();
|
|
const fixture = await startFixture();
|
|
const { rpc, commands } = engine;
|
|
try {
|
|
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
|
|
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 mockTauri(page, {
|
|
commands: () => ({
|
|
browser_connect: () => 'test-session',
|
|
browser_request: ({ command, args }) => window.browserRpc(command, args),
|
|
workspace_last_path: () => null,
|
|
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
|
|
'plugin:window|is_maximized': () => false,
|
|
}),
|
|
});
|
|
const output = await outputDir('browser/interaction');
|
|
await page.goto(smokeUrl);
|
|
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
|
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
|
const ready = page.locator('[data-browser-state="ready"]');
|
|
await ready.waitFor();
|
|
// The browser toolbar has no new-tab button. The header globe button opens browser tabs
|
|
// (src/lib/layout/Workbench.svelte:1300; docs/user-guide.md:177).
|
|
assert.equal(await ready.getByRole('button', { name: /New browser tab/ }).count(), 0);
|
|
const tabId = await ready.getAttribute('data-browser-tab');
|
|
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
|
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
|
|
await rpc('navigate', { tabId, input: fixture.url });
|
|
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
|
|
// Input reaches the engine asynchronously, so poll the page for up to five seconds before asserting.
|
|
async function expectRemote(code, expected) {
|
|
for (let attempt = 0; attempt < 100 && await evaluate(code) !== expected; attempt++) 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"><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 expectRemote('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 expectRemote('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 expectRemote('document.querySelector("#typing").value.endsWith("日本語")', true);
|
|
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 expectRemote('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 expectRemote('document.querySelector("#typing").value', 'https://example.com/');
|
|
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
|
|
const gifUrl = `${fixture.url}once.gif`;
|
|
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
|
|
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
|
|
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
|
|
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
|
|
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
|
|
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
|
|
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
|
|
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 wheelCount = () => commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
|
|
const beforeWheels = wheelCount();
|
|
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 = wheelCount() - 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' });
|
|
// The marker draws the four-way scroll icon, not a text glyph that depends on the font.
|
|
const marker = page.locator('.scroll-anchor');
|
|
assert.equal(await marker.locator('svg path').count(), 1);
|
|
assert.equal(await marker.evaluate(node => node.textContent.trim()), '');
|
|
for (const theme of ['light', 'dark']) {
|
|
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).applyAppearance({ theme: 'default', mode }), theme);
|
|
await page.screenshot({ path: path.join(output, `scroll-marker-${theme}.png`), clip: { x: x - 30, y: y - 30, width: 60, height: 60 } });
|
|
}
|
|
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: page.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 motionCount = () => commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
|
|
const beforeMotion = motionCount();
|
|
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 pointerBurstCalls = motionCount() - beforeMotion;
|
|
assert.ok(pointerBurstCalls < 10, `Pointer bursts must not queue hundreds of native calls: ${pointerBurstCalls}`);
|
|
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: path.join(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(page.errors, []);
|
|
await writeFile(path.join(output, `browser-interaction-${scale}x.json`), JSON.stringify({ decodedFps, scrolled, pointerBurstCalls, 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 engine.stop();
|
|
await fixture.close();
|
|
}
|
|
});
|