Files
RuneStone/scripts/unifiedFind.smoke.mjs
T

201 lines
12 KiB
JavaScript

// 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 = [];
const output = ".audit/todo-2026-10-14/unified-find";
await mkdir(output, { 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: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 === "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 };
});
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
async function mode(group, value) {
await page.getByRole("group", { name: group, exact: true }).hover();
await page.getByRole("button", { name: value, exact: true }).click();
}
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget');
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
const pane = await page.locator('.editor.pane-active').boundingBox();
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.monaco-editor'));
return page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0);
window.__MONACO__.focus();
});
}
try {
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();
for (const theme of ['dark', 'light']) {
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode: theme });
}, theme);
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.evaluate(async sample => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.live-writer > .cm-editor .cm-content'));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: sample }, selection: { anchor: 0 } });
window.__CM__.focus();
}, sample);
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.screenshot({ path: `${output}/writer-${theme}.png` });
await page.keyboard.press('Escape');
await page.locator('.live-writer td').first().dblclick();
await page.locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Control+f');
await onePanel();
assert.equal(await find.evaluate(node => node === document.activeElement), true, 'Table focus opens the document find');
assert.equal(await page.locator('.writer-cell-editor .rs-find-bar').count(), 0);
await find.fill('Last Alpha');
await page.keyboard.press('Enter');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/);
await page.screenshot({ path: `${output}/table-focus-${theme}.png` });
await page.keyboard.press('Escape');
await mode('Editor layout', 'IDE');
await sourceEditor();
await page.evaluate(() => { window.__MONACO__.getModel().setValue('Alpha alpha alphabet\r\nAlpha second\r\nAlpha third'); window.__MONACO__.setPosition({ lineNumber: 1, column: 1 }); });
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.keyboard.press('Enter');
const first = await page.evaluate(() => window.__MONACO__.getSelection().toString());
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
await page.keyboard.press('Shift+Enter');
assert.equal(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
await page.getByRole('checkbox', { name: 'Match case' }).check();
await page.getByRole('checkbox', { name: 'Whole word' }).check();
await replace.fill('Gamma');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getValue().replace(/\r\n/g, '\n')), 'Gamma alpha alphabet\nGamma second\nGamma third');
await page.getByRole('checkbox', { name: 'Regex' }).check();
await find.fill('[');
assert.equal(await find.getAttribute('aria-invalid'), 'true');
assert.equal(await page.getByRole('button', { name: 'Replace all', exact: true }).isDisabled(), true);
await find.fill('(?<=G)(amma)');
await page.getByRole('checkbox', { name: 'Whole word' }).uncheck();
await replace.fill('$1!');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.match(await page.evaluate(() => window.__MONACO__.getValue()), /^Gamma! alpha/);
await page.getByRole('checkbox', { name: 'Regex' }).uncheck();
await find.fill('Gamma');
await page.getByRole('button', { name: 'Select all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__MONACO__.getSelections().length), 3);
await page.screenshot({ path: `${output}/source-${theme}.png` });
await find.focus(); await page.keyboard.press('Escape');
assert.equal(await find.count(), 0);
assert.equal(await page.evaluate(() => window.__MONACO__.hasTextFocus()), true);
await page.keyboard.press('Control+h');
assert.equal(await replace.evaluate(node => node === document.activeElement), true);
await find.fill('Gamma');
await page.keyboard.press('Enter');
await page.keyboard.press('F3');
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
await page.setViewportSize({ width: 800, height: 700 });
await onePanel();
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
await find.focus(); await page.keyboard.press('Escape');
await page.evaluate(sample => window.__MONACO__.getModel().setValue(sample), sample);
await mode('Document view', 'Read');
await page.locator('.reading').focus();
await page.keyboard.press('Control+f');
await find.fill('Alpha'); await page.keyboard.press('Enter');
await onePanel();
assert.equal(await replace.count(), 0, 'Reading search does not offer replacement');
assert.equal(await page.evaluate(() => window.getSelection().toString()), 'Alpha');
const anchor = await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML);
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML), anchor);
await page.screenshot({ path: `${output}/reading-${theme}.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true);
await mode('Document view', 'Edit');
await mode('Editor layout', 'Writer');
}
assert.deepEqual(errors, []);
console.log('PASS: one full-width document Find in Writer, nested table focus, IDE/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: `${output}/failure.png` });
throw error;
} finally { await browser.close(); }