RuneStone 1.0.0
This commit is contained in:
@@ -0,0 +1,390 @@
|
||||
// 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_CSV_Viewer"). */
|
||||
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 "Read beside" (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 === "Read beside") return scope.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true }).click();
|
||||
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the image source of Background, so that the saved image of `appearance.newTabBackground` shows
|
||||
* (src/lib/features/backgroundSettings.ts). Call it after the test saves an image. It waits until the frame is on the body.
|
||||
*/
|
||||
export async function showSavedImage(page) {
|
||||
await page.evaluate(async () => {
|
||||
const { readBackground, writeBackground } = await import("/src/lib/features/backgroundSettings.ts");
|
||||
await writeBackground({ ...readBackground(), source: "image" });
|
||||
});
|
||||
await page.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image").includes("blob:"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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), pty, 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_*`), tab transfers (`tab_transfer_*`), an installed browser engine
|
||||
* (`browser_engine_status`), and the shells of the Terminal feature (`pty_*`). `commands` can replace them.
|
||||
* The mock shell sends "READY 🪨" and a cursor position query through the channel of `pty_open`, before the open returns.
|
||||
* `test.pty.output(id, text)` and `test.pty.exit(id, code)` send more to an open session. `pty_running` counts the open
|
||||
* sessions of all pages of the context.
|
||||
* 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", "features", "background", "terminal", "projectManagement"];
|
||||
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;
|
||||
};
|
||||
// The terminal sessions of this page (src-tauri/src/pty.rs). The count of each page is in localStorage, so `pty_running`
|
||||
// in a Settings page sees the shells of the main page. A page that unloads takes its count with it.
|
||||
const PTY_COUNTS = "runestone.smoke.pty-sessions";
|
||||
const channels = new Map();
|
||||
const countSessions = () => {
|
||||
const counts = readJson(PTY_COUNTS, {});
|
||||
if (channels.size) counts[pageId] = channels.size; else delete counts[pageId];
|
||||
localStorage.setItem(PTY_COUNTS, JSON.stringify(counts));
|
||||
};
|
||||
addEventListener("pagehide", () => { channels.clear(); countSessions(); });
|
||||
const pty = {
|
||||
channels,
|
||||
output: (id, text) => channels.get(id)?.onmessage(new TextEncoder().encode(text).buffer),
|
||||
exit: (id, code) => channels.get(id)?.onmessage({ exit: code }),
|
||||
};
|
||||
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 = {
|
||||
// src-tauri/src/browser_engine.rs. Tests of the engine setup replace it.
|
||||
browser_engine_status: () => ({ state: "installed", version: "0.1.8", bytes: 160612374, received: 0, error: null }),
|
||||
settings_read: () => snapshot(),
|
||||
// src-tauri/src/features.rs: no old plugin package of a native feature is installed.
|
||||
features_legacy: () => [],
|
||||
// src-tauri/src/pty.rs: one shell. Tests of the terminal replace `pty_profiles` to show more profiles.
|
||||
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }],
|
||||
pty_open: async ({ id, page, channel }) => {
|
||||
if (!channel || typeof channel.onmessage !== "function") throw "pty_open needs an output channel";
|
||||
if (typeof page !== "string" || !page) throw "Invalid terminal page ID";
|
||||
if (channels.has(id)) throw "terminal already exists";
|
||||
channels.set(id, channel);
|
||||
countSessions();
|
||||
const data = new TextEncoder().encode("READY 🪨\r\n\x1b[6n");
|
||||
// Split the emoji between two messages, as a real shell can.
|
||||
channel.onmessage(data.slice(0, 8).buffer);
|
||||
channel.onmessage(data.slice(8).buffer);
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return null;
|
||||
},
|
||||
pty_write: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
|
||||
pty_resize: ({ id }) => { if (!channels.has(id)) throw "terminal is not open"; return null; },
|
||||
pty_close: ({ id }) => { channels.delete(id); countSessions(); return null; },
|
||||
pty_running: () => Object.values(readJson(PTY_COUNTS, {})).reduce((sum, count) => sum + count, 0),
|
||||
pty_new_window: () => null,
|
||||
pty_dictation: () => null,
|
||||
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
|
||||
git_blame: () => null,
|
||||
// src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these.
|
||||
background_folder: () => null,
|
||||
background_migrate: () => null,
|
||||
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, pty, 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Installed plugin packages for the smoke tests: the `plugins_*` commands of src-tauri/src/plugins.rs, without plugin code.
|
||||
|
||||
/** An installed package of the old Table Formulas plugin. RuneStone now includes the feature and must not load this code. */
|
||||
export const oldTableFormulasRow = {
|
||||
manifest: { schemaVersion: 1, id: "runestone.table-formulas", name: "Table Formulas", author: "RuneStone Team", description: "Calculate formulas in Markdown tables.", version: "0.1.3", apiVersion: 1, entry: "main.js", access: "full-app" },
|
||||
hash: "old-hash", enabled: true, path: "C:\AppData\RuneStone\plugins\runestone.table-formulas", error: null, removal: false,
|
||||
};
|
||||
|
||||
/**
|
||||
* Serve `rows` as the installed packages. All pages of a context share them through localStorage, and a change sends
|
||||
* `plugins-changed`. Enable, disable, and remove work. `plugins_load` fails, because the rows have no code.
|
||||
* Call it after `mockTauri`, because it wraps the IPC mock.
|
||||
*/
|
||||
export async function mockInstalledPlugins(surface, rows = []) {
|
||||
await surface.addInitScript(rows => {
|
||||
const key = "test.installed-plugins";
|
||||
const root = "C:\AppData\RuneStone\plugins";
|
||||
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(rows));
|
||||
const write = next => { localStorage.setItem(key, JSON.stringify(next)); window.__TEST__?.emit("plugins-changed", {}); };
|
||||
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(rows));
|
||||
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
|
||||
const original = window.__TAURI_INTERNALS__.invoke;
|
||||
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
|
||||
if (!command.startsWith("plugins_")) return original(command, args);
|
||||
window.__TEST__?.calls.push({ command, args });
|
||||
if (command === "plugins_snapshot") return { root, plugins: read() };
|
||||
if (command === "plugins_load" || command === "plugins_asset") throw new Error(`No code for ${args.id}`);
|
||||
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
|
||||
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
|
||||
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
|
||||
if (command === "plugins_data") return "null";
|
||||
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
|
||||
throw new Error(`Unhandled plugin IPC: ${command}`);
|
||||
};
|
||||
}, rows);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// Shared setup of the Project Management smoke tests (tests/smoke/features/pm*.smoke.mjs): a workspace with two boards
|
||||
// and five cards in hidden storage, a mock that keeps the workspace files through a page reload, and small helpers.
|
||||
import { mockTauri, smokeUrl } from "./index.mjs";
|
||||
|
||||
export const roadmap = "6f4c2a3e-6a0b-4d57-9a3e-1c2b3d4e5f60";
|
||||
export const bugs = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
|
||||
export const catalogPath = ".runestone/pm/workspace.json";
|
||||
export const deletedPath = ".runestone/pm/deleted-cards.json";
|
||||
const hex = id => Buffer.from(id).toString("hex");
|
||||
export const cardPath = id => `.runestone/pm/cards/${hex(id)}.md`;
|
||||
export const draftPath = id => `.runestone/pm/drafts/${hex(id)}.json`;
|
||||
|
||||
/** The local date `offset` days from today, as YYYY-MM-DD. */
|
||||
export function localDay(offset = 0) {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() + offset);
|
||||
return [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(part => String(part).padStart(2, "0")).join("-");
|
||||
}
|
||||
|
||||
/** A board with the three default lists and one review list. `review` gives the ID, the name, and the limit of that list. */
|
||||
export function board(id, review = { id: "review", name: "Review" }) {
|
||||
return {
|
||||
schema: 1, kind: "board", id,
|
||||
lists: [
|
||||
{ id: "todo", name: "To do", status: "todo", collapsed: false },
|
||||
{ id: "doing", name: "In progress", status: "doing", collapsed: false },
|
||||
{ id: "done", name: "Done", status: "done", collapsed: false },
|
||||
{ collapsed: false, status: null, ...review },
|
||||
],
|
||||
defaults: { todo: "todo", doing: "doing", done: "done" },
|
||||
};
|
||||
}
|
||||
|
||||
/** A card file. `placements` maps a board ID to a list ID. `extra` adds lines to the front matter. */
|
||||
export function card(id, title, { placements = {}, status = "todo", order = id.slice(-1), extra = [] } = {}) {
|
||||
const lines = ["---", "runestone_pm:", " schema: 1", ` id: ${id}`, " kind: task", ` title: ${title}`,
|
||||
' createdAt: "2026-10-01T08:30:00.000Z"', ` order: "${order}"`, ` status: ${status}`, " tags: []", " sessions: []", " archived: false", ...extra];
|
||||
if (Object.keys(placements).length) {
|
||||
lines.push(" placements:");
|
||||
for (const [boardId, listId] of Object.entries(placements)) lines.push(` ${boardId}:`, ` listId: ${listId}`, ` order: "${order}"`);
|
||||
}
|
||||
return [cardPath(id), [...lines, "---", `Body of ${title}.`, ""].join("\n")];
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace files. Roadmap: Card A and Card B in To do, Shared card in To do, and a limit of 2 on Review.
|
||||
* Bugs: Card C in its "review" list, Shared card in To do. Loose card has no board. Card B has planned dates and a deadline.
|
||||
*/
|
||||
export function pmFiles({ boards = true, defaultBoardId } = {}) {
|
||||
const catalog = { schema: 1, boards: [
|
||||
{ name: "Roadmap", value: board(roadmap, { id: "review", name: "Review", maxCards: 2 }) },
|
||||
{ name: "Bugs", value: board(bugs, { id: "qa", name: "review" }) },
|
||||
], ...(defaultBoardId ? { defaultBoardId, defaultBoardPath: `pm-board:${defaultBoardId}` } : {}) };
|
||||
return Object.fromEntries([
|
||||
["note.md", "# Note\n"],
|
||||
[".runestone/pm/.gitignore", "# RuneStone Project Management local data\n*\n"],
|
||||
[".runestone/pm/cards/.gitignore", "*\n"],
|
||||
...boards ? [[catalogPath, JSON.stringify(catalog, null, 2) + "\n"]] : [],
|
||||
card("card-a", "Card A", { placements: { [roadmap]: "todo" }, order: "a" }),
|
||||
card("card-b", "Card B", { placements: { [roadmap]: "todo" }, order: "b", extra: [
|
||||
" due:", ` date: "${localDay(2)}"`, " plan:", ` start: "${localDay(0)}"`, ` end: "${localDay(4)}"`] }),
|
||||
card("card-c", "Card C", { placements: { [bugs]: "qa" }, order: "c" }),
|
||||
card("card-d", "Shared card", { placements: { [roadmap]: "todo", [bugs]: "todo" }, order: "d" }),
|
||||
card("card-e", "Loose card", { order: "e" }),
|
||||
]);
|
||||
}
|
||||
|
||||
// This function runs in the page. Keep it self-contained. The files stay in localStorage, so a reload keeps them.
|
||||
function pmCommands(test) {
|
||||
const KEY = "runestone.smoke.pm-files";
|
||||
let saved = null;
|
||||
try { saved = JSON.parse(localStorage.getItem(KEY)); } catch { saved = null; }
|
||||
const workspace = test.workspace({ root: "C:\\pm-smoke", files: new Map(saved ?? Object.entries(test.state.files)) });
|
||||
test.files = workspace.files;
|
||||
const keep = () => localStorage.setItem(KEY, JSON.stringify([...workspace.files]));
|
||||
const kept = handler => args => { const result = handler(args); keep(); return result; };
|
||||
return {
|
||||
...workspace,
|
||||
workspace_read: args => {
|
||||
if (!workspace.files.has(args.rel) && args.missingOk) return null;
|
||||
return workspace.workspace_read(args);
|
||||
},
|
||||
workspace_write: kept(workspace.workspace_write),
|
||||
workspace_delete: kept(workspace.workspace_delete),
|
||||
workspace_create: kept(({ rel, kind, contents }) => {
|
||||
if (workspace.files.has(rel)) throw new Error("Destination exists");
|
||||
if (kind === "file") workspace.files.set(rel, contents ?? "");
|
||||
else workspace.folders.add(rel);
|
||||
return null;
|
||||
}),
|
||||
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
|
||||
workspace_download_image: ({ url }) => {
|
||||
if (url.includes("offline")) throw new Error("Cannot reach the image server");
|
||||
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
|
||||
},
|
||||
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
|
||||
spelling_menu_install: () => null,
|
||||
"plugin:window|is_maximized": () => false,
|
||||
};
|
||||
}
|
||||
|
||||
/** Mock the host with the files of `pmFiles()`, load the app, and wait for the file tree. */
|
||||
export async function loadWorkspace(page, files = pmFiles()) {
|
||||
await mockTauri(page, { state: { files }, commands: pmCommands });
|
||||
await page.goto(smokeUrl);
|
||||
await page.locator('[data-tree-rel="note.md"]').waitFor();
|
||||
}
|
||||
|
||||
/** The Project Management ribbon button. */
|
||||
export const ribbon = page => page.locator(".plugin-ribbon").getByRole("button", { name: "Project Management", exact: true });
|
||||
/** The visible Project Management view. */
|
||||
export const pane = page => page.locator(".plugin-editor-pane:visible .rs-pm");
|
||||
/** A Kanban column by its accessible name. */
|
||||
export const column = (page, name) => pane(page).locator(`section.pm-column[aria-label="${name}"]`);
|
||||
|
||||
/** Open All tasks with the ribbon button, then open a board through the board scope menu when `name` is given. */
|
||||
export async function openBoard(page, name) {
|
||||
if (!await pane(page).count()) {
|
||||
await ribbon(page).click();
|
||||
await pane(page).locator(".pm-board").waitFor();
|
||||
}
|
||||
if (!name) return;
|
||||
await pane(page).locator(".pm-scope").click();
|
||||
await page.getByRole("menuitemradio", { name, exact: true }).click();
|
||||
await page.getByRole("tab", { name, exact: true }).waitFor();
|
||||
await pane(page).locator(".pm-scope-label", { hasText: new RegExp(`^${name}$`) }).waitFor();
|
||||
await pane(page).locator(".pm-column").first().waitFor();
|
||||
}
|
||||
|
||||
/** Use the dark or the light mode of the default theme. */
|
||||
export async function setTheme(page, mode) {
|
||||
await page.evaluate(async value => {
|
||||
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
|
||||
saveAppearance({ theme: "default", mode: value });
|
||||
}, mode);
|
||||
await page.waitForFunction(value => document.documentElement.dataset.theme === value, mode);
|
||||
}
|
||||
|
||||
/** The text of a workspace file, or undefined. */
|
||||
export const fileText = (page, path) => page.evaluate(rel => window.__TEST__.files.get(rel), path);
|
||||
/** Wait until a workspace file matches `pattern`. */
|
||||
export const waitForFile = (page, path, pattern) =>
|
||||
page.waitForFunction(([rel, source, flags]) => new RegExp(source, flags).test(window.__TEST__.files.get(rel) ?? ""), [path, pattern.source, pattern.flags]);
|
||||
/** The saved boards of the catalog. */
|
||||
export const savedBoards = async page => JSON.parse(await fileText(page, catalogPath)).boards;
|
||||
/** The element that has focus, as its accessible name or text. */
|
||||
export const focusedName = page => page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.textContent?.trim());
|
||||
Reference in New Issue
Block a user