Files
RuneStone/scripts/codeBlocks.smoke.mjs
T

136 lines
7.3 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 = [];
await mkdir(".audit", { 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 };
});
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();
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
const cursor = () => page.evaluate(() => window.__CM__.state.selection.main.head);
async function select(anchor, head = anchor) {
await page.evaluate(({ anchor, head }) => {
window.__CM__.dispatch({ selection: { anchor, head }, scrollIntoView: true });
window.__CM__.focus();
}, { anchor, head });
}
for (const block of ["```js\nconst value = 123;\nsecond line\n```", "~~~text\nconst value = 123;\nsecond line\n~~~", " const value = 123;\n second line"]) {
const original = `Above.\n\n${block}\n\nBelow.\n`;
await page.evaluate(value => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } });
}, original);
await page.locator(".writer-code-line").first().click();
await page.locator(".writer-code-source").first().waitFor();
const position = original.indexOf("123") + 1;
await select(position);
await page.keyboard.press("Backspace");
assert.equal(await contents(), original.slice(0, position - 1) + original.slice(position));
await page.keyboard.press("Control+z");
assert.equal(await contents(), original);
await select(position);
await page.keyboard.press("Delete");
assert.equal(await contents(), original.slice(0, position) + original.slice(position + 1));
await page.keyboard.press("Control+z");
assert.equal(await contents(), original);
await select(position);
await page.keyboard.press("ArrowRight");
assert.equal(await cursor(), position + 1);
await page.keyboard.press("ArrowLeft");
assert.equal(await cursor(), position);
await page.keyboard.type("X");
assert.equal(await contents(), original.slice(0, position) + "X" + original.slice(position));
await page.keyboard.press("Control+z");
assert.equal(await contents(), original);
await select(position - 1, position + 2);
await page.keyboard.press("Backspace");
const edited = original.slice(0, position - 1) + original.slice(position + 2);
assert.equal(await contents(), edited);
await select(0);
assert.ok((await page.locator(".writer-code-line").allTextContents()).join("\n").includes("const value = ;"));
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited);
}
assert.deepEqual(errors, []);
console.log("PASS: Fenced and indented code editing, character deletion, selection deletion, cursor movement, undo, preview and save.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: ".audit/code-blocks-failure.png" });
throw error;
} finally { await browser.close(); }