Files
RuneStone/scripts/editorInteractions.smoke.mjs
T

153 lines
11 KiB
JavaScript

import { createRequire } from "node:module";
import { mkdir } from "node:fs/promises";
import assert from "node:assert/strict";
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: 1280, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-interactions-smoke";
const files = new Map([
["note.md", "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n"],
["other.md", "# Other document\n\nKeep the original tab.\n"],
]);
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
window.editorTest = { files, calls: [], emit };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.editorTest.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") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-interactions-smoke", 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") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".runestone/")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:opener|open_url" || command.startsWith("spelling_menu_")) return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function top() {
await writer();
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.locator('[data-tree-rel="note.md"]').dblclick();
await writer();
const code = page.locator(".writer-code-line").filter({ hasText: "pnpm install" });
await code.scrollIntoViewIfNeeded();
const points = await page.evaluate(() => {
const view = window.writerView, from = view.state.doc.toString().indexOf("pnpm install");
return { from: view.coordsAtPos(from), to: view.coordsAtPos(from + 12) };
});
await page.mouse.move(points.from.left + 1, (points.from.top + points.from.bottom) / 2);
await page.mouse.down();
await page.mouse.move(points.to.left, (points.to.top + points.to.bottom) / 2, { steps: 8 });
await page.mouse.up();
assert.match(await page.evaluate(() => { const view = window.writerView; return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); }), /pnpm install/);
await page.getByRole("button", { name: "Copy code", exact: true }).first().click();
assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, "\n"), "pnpm install --frozen-lockfile\npnpm check\npnpm test\n");
console.log("PASS: first drag selects code and the copy button copies only the code body");
await page.evaluate(() => { const view = window.writerView; view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("preserve =") + 5 }, scrollIntoView: true }); view.focus(); });
await page.keyboard.type("X");
await page.waitForTimeout(250);
const saved = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.ok(saved.scroll > 1000);
await page.locator('[data-tree-rel="other.md"]').dblclick();
await writer();
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await writer();
await page.waitForTimeout(250);
const restored = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.equal(restored.head, saved.head);
assert.equal(restored.doc, saved.doc);
assert.ok(Math.abs(restored.caret.top - saved.caret.top) < 3, JSON.stringify({ saved, restored }));
await page.evaluate(() => { window.dispatchEvent(new Event("blur")); window.dispatchEvent(new Event("focus")); });
await page.waitForTimeout(150);
assert.equal(await page.evaluate(() => window.writerView.state.selection.main.head), saved.head);
console.log("PASS: code edit, caret, and scroll survive tab and window focus changes");
await top();
await page.locator('.writer-link[data-href="other.md"]').click({ modifiers: ["Control"] });
await page.getByRole("tab", { name: "other.md", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "note.md", exact: true }).count(), 1);
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await top();
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
await page.waitForFunction(() => window.editorTest.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
const linkPoint = await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
const position = view.getModel().getPositionAt(view.getValue().indexOf("[Local]") + 3);
view.revealPositionInCenter(position);
view.setPosition(position); view.focus();
return position;
});
await page.waitForTimeout(300);
const point = await page.evaluate(async position => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected), rect = view.getDomNode().getBoundingClientRect(), coords = view.getScrolledVisiblePosition(position);
return { x: rect.left + coords.left + 2, y: rect.top + coords.top + coords.height / 2 };
}, linkPoint);
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
console.log("PASS: Writer and IDE Ctrl+click open workspace links while retaining the source tab");
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await page.keyboard.press("Control+e");
await top();
await mkdir(".audit", { recursive: true });
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { applyAppearance, parseAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ ...parseAppearance(null), mode });
}, theme);
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
await page.screenshot({ path: `.audit/editor-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
assert.deepEqual(writing, reading);
await page.screenshot({ path: `.audit/reader-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.screenshot({ path: ".audit/editor-typography-narrow.png" });
assert.ok(await page.locator(".cm-content").evaluate(node => node.getBoundingClientRect().width <= node.closest(".cm-scroller").getBoundingClientRect().width + 1));
const spelling = await page.evaluate(async () => {
const { isSpellingTarget } = await import("/src/lib/editor/spellingMenu.ts");
const area = document.createElement("textarea"); area.spellcheck = true; document.body.append(area);
const active = isSpellingTarget(area); area.readOnly = true; const readOnly = isSpellingTarget(area); area.remove();
return { active, readOnly };
});
assert.deepEqual(spelling, { active: true, readOnly: false });
assert.deepEqual(errors, []);
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
} finally { await browser.close(); }