Files
RuneStone/tests/smoke/editor/imageNavigation.smoke.mjs
T
Knotty Wyvern e433bed28e Move the tests from scripts/ to tests/ by feature
Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
2026-10-27 19:47:39 -07:00

210 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";
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 = [];
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 svg = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>';
files.set("images/picture (#1).svg", btoa(svg));
files.set("images/replacement.svg", btoa(svg));
files.set("notes/welcome.md", "Above.\n\nBelow.\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_write_bytes") {
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
if (window.__TEST__.failWrite) throw new Error("Image write failed");
files.set(args.rel, args.base64); return;
}
if (command === "workspace_read_data_url") {
if (!files.has(args.rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + files.get(args.rel);
}
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_reveal") return;
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
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 };
});
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.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
async function dragFromTree(selector = ".cm-content", cancel = false) {
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
await page.mouse.move(from.x + 60, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
await page.getByText("Insert image", { exact: true }).waitFor();
assert.equal(await page.locator(".image-drop-target").count(), 1);
if (cancel) await page.keyboard.press("Escape");
await page.mouse.up();
}
async function imageMenu() {
await page.locator(".md-image-frame").first().click({ button: "right" });
await page.getByRole("menu", { name: "Image actions" }).waitFor();
}
try {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
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" }).click();
await writer();
await page.locator('[data-tree-rel="images"]').click();
await dragFromTree();
await page.locator(".md-image-frame img").waitFor();
const linked = await source();
assert.ok(linked.startsWith("![](../images/picture%20%28%231%29.svg)\n\nAbove."), linked);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => ["workspace_write_bytes", "workspace_rename"].includes(c.command)).length), 0);
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
// Neither caret movement nor selection exposes an image's Markdown.
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: 0, head: 38 } }));
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
await page.locator(".md-image-frame img").click();
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Image actions" }).waitFor();
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
await page.screenshot({ path: ".audit/image-context-menu.png" });
await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click();
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "![](../images/picture%20%28%231%29.svg)");
await imageMenu();
await page.getByRole("menuitem", { name: "Copy image", exact: true }).click();
await page.waitForFunction(async () => (await navigator.clipboard.read()).some(item => item.types.includes("image/png")));
await imageMenu();
await page.getByRole("menuitem", { name: "Show in Explorer", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "workspace_reveal" && c.args.rel === "images/picture (#1).svg"));
await imageMenu();
await page.getByRole("menuitem", { name: "Remove image", exact: true }).click();
assert.ok(!(await source()).includes("picture%20"));
assert.ok(await page.evaluate(() => window.__TEST__.files.has("images/picture (#1).svg")));
await page.keyboard.press("Control+z");
assert.equal(await source(), linked);
await page.locator(".md-image-frame").hover();
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
await page.locator(".cm-line").filter({ hasText: "picture%20" }).waitFor();
assert.equal(await page.locator(".md-image-frame img").count(), 1);
await page.getByRole("button", { name: "Hide image source", exact: true }).click();
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
await imageMenu();
await page.getByRole("menuitem", { name: "Swap image…", exact: true }).click();
await page.getByRole("textbox", { name: "Image path relative to this note, or https URL" }).fill("../images/replacement.svg");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.waitForFunction(() => window.__CM__.state.doc.toString().includes("replacement.svg"));
assert.equal(await page.locator(".cm-line").filter({ hasText: "replacement.svg" }).count(), 0);
await imageMenu();
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
await page.getByRole("tab", { name: "replacement.svg", exact: true }).waitFor();
await page.getByRole("tab", { name: /welcome.md/ }).click();
await writer();
const beforeCancel = await source();
await dragFromTree(".cm-content", true);
assert.equal(await source(), beforeCancel);
assert.equal(await page.locator(".image-drop-target").count(), 0);
// Inline images remain independently selectable without hiding adjacent prose.
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "Before ![](../images/replacement.svg) between ![[../images/replacement.svg]] after.\n" }, selection: { anchor: 0 } });
});
await page.waitForFunction(() => document.querySelectorAll(".md-image-frame").length === 2);
assert.ok((await page.locator(".cm-content").innerText()).includes("Before"));
assert.ok(!(await page.locator(".cm-content").innerText()).includes("![]"));
await page.locator(".md-image-frame img").nth(1).click();
await page.keyboard.press("Delete");
assert.equal(await source(), "Before ![](../images/replacement.svg) between after.\n");
await page.keyboard.press("Control+z");
assert.ok((await source()).includes("![[../images/replacement.svg]]"));
// Reference-image editing affects only the selected embed, not its definition.
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "![Reference][pic]\n\nBelow.\n\n[pic]: ../images/replacement.svg\n" }, selection: { anchor: 0 } });
});
await page.locator(".md-image-frame").hover();
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
await page.locator(".cm-line").filter({ hasText: "![Reference]" }).waitFor();
await page.keyboard.press("Escape");
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
// The same navigator drag works in the source editor.
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await page.locator(".monaco-editor textarea").waitFor();
await dragFromTree(".monaco-editor .view-lines");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0);
assert.deepEqual(errors, []);
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
} catch (error) {
await page.screenshot({ path: ".audit/image-navigation-failure.png" });
console.error(errors); throw error;
} finally { await browser.close(); }