Files
RuneStone/tests/smoke/_harness/index.mjs
T
Knotty Wyvern 9cf82503d0 Show one view control and name the file once
Phase 5-3.

- One radio group shows Write, Source, and Read at all times, with an
  icon and a name. Narrow panes show only the icons. The arrow keys
  move the choice, and the group has one Tab stop. The current choice
  gets the selection fill and an accent bar. Hover gets only a fill.
- A Split toggle shows Read beside Write or Source. Each document pane
  keeps a split flag beside its reading flag. Read ends Split.
- Ctrl+Shift+E switches between Read and the editor. Ctrl+E still
  switches between Write and Source.
- "IDE" becomes "Source" in the Chrome type, the tab menu (a View
  submenu), the status bar, the catalog, the tests, and the docs.
- Settings, General, File name title hides the title in Write and
  Read. It is on by default.
- The breadcrumb shows only the folder of the file. The status bar
  shows the view, not the path.
- ModeSwitcher.svelte and its hover test are gone. The new test
  layout/viewModes covers the control.
- The command palette from 5-2 gets its row in docs/menu-surfaces.json.
- The user guide Format table is whole again. The 5-2 edit had put
  the Paragraph and Insert rows under the shortcut table.
- 8 new catalog rows and 10 removed rows, in French, Japanese, and
  Simplified Chinese.
- Docs: UI-049, the user guide, ui-design.md, document-tools.md,
  development.md, and the README feature list.

Tests: the new layout/viewModes, new cases in documentPanes.spec.ts
and settings.spec.ts, and the chooseView harness helper. 21 smoke
tests use the new control. Tests that read the full path from the
breadcrumb now read its tooltip.
2026-10-28 19:45:08 -07:00

330 lines
17 KiB
JavaScript

// Shared setup for the browser smoke tests: Playwright, the Tauri IPC mock, and output folders.
// Run a test with `pnpm smoke <name>`, or run its file with Node while `pnpm dev` serves the app.
import { createRequire } from "node:module";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path from "node:path";
export const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
export const smokeUrl = process.env.SMOKE_URL || "http://127.0.0.1:1420";
/** The path of a sibling plugin checkout, for example pluginRepo("RuneStone_Git"). */
export function pluginRepo(folder) {
return path.resolve(process.env.RUNESTONE_PLUGIN_REPOS || path.join(repoRoot, ".."), folder);
}
/** Playwright, from PLAYWRIGHT_MODULE or the project dependency. */
export function playwright() {
return createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
}
/** True in CSP mode (`pnpm smoke --csp`). The dev server then sends the app's content security policy. */
export const cspMode = process.env.RUNESTONE_CSP === "1";
/** The content security policy violations of all pages in CSP mode. `runSmoke` fails when this list is not empty. */
export const cspViolations = [];
const CSP_PREFIX = "[csp-violation] ";
// This function runs in each page and frame. Violations inside workers do not reach it.
function reportCspViolations(prefix) {
addEventListener("securitypolicyviolation", event => {
console.error(prefix + JSON.stringify({ directive: event.effectiveDirective, blocked: event.blockedURI, source: event.sourceFile, line: event.lineNumber, sample: event.sample, page: location.href }));
}, true);
}
/** Record the violations of a browser context or a page. */
async function watchCsp(target) {
await target.addInitScript(reportCspViolations, CSP_PREFIX);
target.on("console", message => {
if (message.text().startsWith(CSP_PREFIX)) cspViolations.push(message.text().slice(CSP_PREFIX.length));
});
}
/** Start headless Chromium. CHROME_PATH selects an installed browser. In CSP mode, each new context and page records violations. */
export async function launchBrowser(options = {}) {
const executablePath = process.env.CHROME_PATH;
const browser = await playwright().chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), ...options });
if (cspMode) {
const { newContext, newPage } = { newContext: browser.newContext.bind(browser), newPage: browser.newPage.bind(browser) };
browser.newContext = async (...args) => { const context = await newContext(...args); await watchCsp(context); return context; };
browser.newPage = async (...args) => { const page = await newPage(...args); await watchCsp(page); return page; };
}
return browser;
}
/**
* Open a page that collects uncaught page errors in `page.errors`, and console errors and warnings in `page.console`.
* `target` is a browser or a browser context. A context page keeps the context viewport unless `viewport` is given.
*/
export async function openPage(target, { viewport, timeout = 10000, ...options } = {}) {
const isContext = typeof target.browser === "function";
const page = isContext ? await target.newPage() : await target.newPage({ viewport: viewport ?? { width: 1440, height: 1000 }, ...options });
if (isContext && viewport) await page.setViewportSize(viewport);
page.setDefaultTimeout(timeout);
page.errors = [];
page.console = [];
page.on("pageerror", error => page.errors.push(error.message));
page.on("console", message => {
if (["error", "warning"].includes(message.type())) page.console.push(`${message.type()}: ${message.text()}`);
});
return page;
}
/** Create and return output/smoke/<name>/ for screenshots and reports. */
export async function outputDir(name) {
const dir = path.join(repoRoot, "output", "smoke", name);
await mkdir(dir, { recursive: true });
return dir;
}
/** Wait two animation frames, so layout and Svelte updates settle. */
export function settle(page) {
return page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
/**
* Choose "Write", "Source", or "Read" in the view control of a document pane, or toggle "Split" (src/lib/layout/ViewModes.svelte).
* `scope` is the page, or a pane locator when the window shows more than one document pane.
*/
export async function chooseView(scope, name) {
if (name === "Split") return scope.locator(".chrome-bar").getByRole("button", { name: "Split", exact: true }).click();
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
}
/**
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
*
* `commands(test)` runs in the page and returns a map from command name to handler `(args, test) => result`.
* It cannot use variables from the test file. Pass data through `state`, which must be JSON.
* `test` is also `window.__TEST__`: `{ state, calls, emit(event, payload), label, workspace(options), settings(section), writeSettings(section, value) }`.
* A command without a handler throws "Unhandled IPC", or returns null when `strict` is false.
*
* Default handlers serve the settings file (`settings_*`) and tab transfers (`tab_transfer_*`). `commands` can replace them.
* All pages of one browser context share their state: the settings file and the offers are in localStorage under
* test keys, and a BroadcastChannel sends `settings-changed` to every page and `tab-transfer-accepted` to the source page.
* Without a settings file, the app migrates the old localStorage keys, so a test can seed preferences there before the first load.
* `test.settings(section)` reads a section of the file. `test.writeSettings(section, value)` acts as a write from another window.
*/
export function mockTauri(target, { label = "main", state = {}, commands, strict = true } = {}) {
const options = JSON.stringify({ label, state, strict });
// Tests find module URLs in the resource entries. The default buffer of 250 entries is too small for the app.
return target.addInitScript(`performance.setResourceTimingBufferSize(5000); (${installMock})(${options}, ${commands ? commands.toString() : "undefined"});`);
}
// This function runs in the page. Keep it self-contained.
function installMock(options, commands) {
let sequence = 0;
const callbacks = new Map();
const listeners = new Map();
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
// An in-memory workspace: `files` maps workspace paths to text. Folders come from the paths and `folders`.
// Create, rename, and delete emit "workspace-event". Writes emit it only when `writeEvents` is true.
const workspace = ({ root = "C:\\workspace", name = root.split(/[\\/]/).pop(), files = {}, folders = [], watchMode = "native", recent = [], writeEvents = false } = {}) => {
const store = files instanceof Map ? files : new Map(Object.entries(files));
const dirs = new Set(folders);
const parentOf = rel => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
const allFolders = () => {
const result = new Set(dirs);
for (const rel of store.keys()) for (let dir = parentOf(rel); dir; dir = parentOf(dir)) result.add(dir);
return result;
};
const changed = (kind, paths) => emit("workspace-event", { root, kind, paths });
const handlers = {
workspace_last_path: () => root,
workspace_recent: () => recent,
workspace_open: () => ({ root, name, watch_mode: watchMode }),
workspace_list: ({ rel = "" }) => {
const children = [];
for (const dir of allFolders()) if (parentOf(dir) === rel) children.push({ name: dir.split("/").pop(), rel_path: dir, kind: "folder" });
for (const file of store.keys()) if (parentOf(file) === rel) children.push({ name: file.split("/").pop(), rel_path: file, kind: "file" });
return children;
},
workspace_list_markdown: () => [...store.keys()].filter(rel => /\.md$/i.test(rel)).sort(),
workspace_read: ({ rel }) => {
if (!store.has(rel)) throw new Error(`Missing file: ${rel}`);
return store.get(rel);
},
workspace_read_many: ({ paths }) => paths.map(rel => store.has(rel) ? { path: rel, source: store.get(rel) } : { path: rel, error: "Missing file" }),
workspace_write: ({ rel, contents }) => {
store.set(rel, contents);
if (writeEvents) changed("modify", [rel]);
return null;
},
workspace_create: ({ rel, kind }) => {
if (store.has(rel) || allFolders().has(rel)) throw new Error("Destination exists");
if (kind === "folder") dirs.add(rel); else store.set(rel, "");
changed("create", [rel]);
return null;
},
workspace_rename: ({ from, to }) => {
if (store.has(to) || allFolders().has(to)) throw new Error("Destination exists");
for (const [rel, text] of [...store]) {
if (rel === from || rel.startsWith(from + "/")) { store.delete(rel); store.set(to + rel.slice(from.length), text); }
}
for (const dir of [...dirs]) if (dir === from || dir.startsWith(from + "/")) { dirs.delete(dir); dirs.add(to + dir.slice(from.length)); }
changed("rename", [from, to]);
return null;
},
workspace_delete: ({ rel }) => {
for (const key of [...store.keys()]) if (key === rel || key.startsWith(rel + "/")) store.delete(key);
for (const dir of [...dirs]) if (dir === rel || dir.startsWith(rel + "/")) dirs.delete(dir);
changed("remove", [rel]);
return null;
},
workspace_search: ({ query }) => {
const hits = [];
for (const [rel, text] of store) text.split("\n").forEach((line, index) => {
if (query && line.toLowerCase().includes(query.toLowerCase())) hits.push({ rel_path: rel, line: index + 1, text: line });
});
return hits;
},
workspace_abs_path: ({ rel }) => `${root}\\${rel.replaceAll("/", "\\")}`,
};
return Object.assign(handlers, { files: store, folders: dirs, root, name });
};
// The settings file and the tab transfer offers of the desktop host (src-tauri/src/preferences.rs, tab_transfer.rs).
// `crypto.randomUUID` needs a secure context, which `about:blank` is not.
const pageId = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel("runestone-smoke-host") : { postMessage() {} };
channel.addEventListener?.("message", ({ data }) => { if ((!data.target || data.target === pageId) && (!data.label || data.label === options.label)) emit(data.event, data.payload); });
// `target` is a page ID. Without it, every page of the context receives the event, this page too. `label` limits the event to pages with that window label.
const broadcast = (event, payload, target) => {
if (!target || target === pageId) emit(event, payload);
if (target !== pageId) channel.postMessage({ event, payload, target });
};
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => {
const file = settingsFile();
return { exists: !!file, revision: file?.revision ?? 0, sections: Object.fromEntries(SECTIONS.filter(name => file && name in file).map(name => [name, file[name]])) };
};
const writeSettings = (section, value) => {
if (!SECTIONS.includes(section)) throw `Unknown settings section: ${section}`;
const file = settingsFile() ?? { schema: 1, revision: 0 };
file.revision += 1;
if (value === null || value === undefined) delete file[section]; else file[section] = value;
localStorage.setItem(SETTINGS_FILE, JSON.stringify(file));
const change = { section, revision: file.revision, value: value ?? null };
broadcast("settings-changed", change);
return change;
};
const offers = () => {
const list = readJson(TRANSFERS, {});
for (const [id, offer] of Object.entries(list)) if (Date.now() - offer.created >= (offer.taker ? 240000 : 120000)) delete list[id];
return list;
};
const saveOffers = list => localStorage.setItem(TRANSFERS, JSON.stringify(list));
const expired = "This tab transfer expired. Drag the tab again.";
const defaults = {
settings_read: () => snapshot(),
settings_migrate: ({ sections }) => {
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
return snapshot();
},
settings_write: ({ section, value }) => writeSettings(section, value),
tab_transfer_offer: ({ id, root, payload }) => {
const list = offers();
if (list[id]) throw "Invalid tab transfer.";
list[id] = { source: pageId, root, payload, created: Date.now(), taker: null };
saveOffers(list);
return id;
},
tab_transfer_take: ({ id, root }) => {
const list = offers(), offer = list[id];
if (!offer || offer.taker) throw expired;
if (offer.root !== root) throw "Move tabs only between windows of the same workspace.";
offer.taker = pageId;
saveOffers(list);
return offer.payload;
},
tab_transfer_finish: ({ id, accepted }) => {
const list = offers(), offer = list[id];
if (!offer || offer.taker !== pageId) throw expired;
if (accepted) delete list[id]; else offer.taker = null;
saveOffers(list);
if (accepted) broadcast("tab-transfer-accepted", { id }, offer.source);
return null;
},
tab_transfer_cancel: ({ id }) => {
const list = offers();
if (list[id]?.source === pageId && !list[id].taker) { delete list[id]; saveOffers(list); }
return null;
},
};
const test = { state: options.state, calls: [], emit, label: options.label, workspace, settings: section => settingsFile()?.[section], writeSettings };
// Look up the test's handlers first. A test can return a Proxy, so do not copy its keys.
const table = commands ? commands(test) || {} : {};
window.isTauri = true;
window.__TEST__ = test;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: options.label }, currentWebview: { label: options.label } },
transformCallback: callback => {
const id = ++sequence;
callbacks.set(id, callback);
return id;
},
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
test.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 null; }
// An app event reaches every window. A targeted event reaches the windows with the target label (Tauri emit and emitTo).
if (command === "plugin:event|emit") { broadcast(args.event, args.payload); return null; }
if (command === "plugin:event|emit_to") {
const label = typeof args.target === "string" ? args.target : args.target?.label;
if (!label || label === options.label) emit(args.event, args.payload);
channel.postMessage({ event: args.event, payload: args.payload, label });
return null;
}
const handler = typeof table[command] === "function" ? table[command] : defaults[command];
if (typeof handler === "function") {
const result = await handler(args, test);
return result === undefined ? null : result;
}
if (options.strict) throw new Error(`Unhandled IPC: ${command}`);
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
}
/**
* Run one smoke test: start the browser, run `body`, fail on page errors, and close the browser.
* `body({ browser, page })` returns nothing. Set `allowPageErrors` for tests that expect page errors.
* On failure, the test saves `failure.png` in its output folder and prints the console errors and warnings.
*/
export async function runSmoke(name, body, { viewport, timeout, allowPageErrors = false } = {}) {
const browser = await launchBrowser();
let page;
try {
page = await openPage(browser, { viewport, timeout });
await body({ browser, page });
if (!allowPageErrors && page.errors.length) throw new Error(`Page errors:\n${page.errors.join("\n")}`);
if (cspViolations.length) throw new Error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
console.log(`PASS ${name}`);
} catch (error) {
console.error(`FAIL ${name}`);
console.error(error);
if (cspViolations.length && !String(error?.message).startsWith("Content security policy violations")) {
console.error(`Content security policy violations:\n${[...new Set(cspViolations)].join("\n")}`);
}
if (page) {
if (page.console.length) console.error(`Console:\n${page.console.join("\n")}`);
const file = path.join(await outputDir(name), "failure.png");
if (await page.screenshot({ path: file }).then(() => true, () => false)) console.error(`Screenshot: ${file}`);
}
process.exitCode = 1;
} finally {
await browser.close();
}
}