RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+390
View File
@@ -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();
}
}
+36
View File
@@ -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);
}
+147
View File
@@ -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());
@@ -0,0 +1,143 @@
// Workarea backgrounds in both themes: splash, writer, reader, split, Source, narrow layouts, fades, reduced motion, and removal.
// The saved image shows through the Background feature (src/lib/features/background/). The test also sets its own frames.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, showSavedImage, smokeUrl } from '../_harness/index.mjs';
const viewport = { width: 1280, height: 820 };
await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
const output = await outputDir('appearance/backgroundFrames');
const report = [];
for (const theme of ['light', 'dark']) {
const page = await openPage(browser, { viewport });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: 'C:/background-test',
files: {
'welcome.md': '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24),
'hello.ts': '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n',
},
}),
plugins_snapshot: () => ({ root: 'C:/background-test', plugins: [] }),
}),
});
await page.goto(smokeUrl);
await page.locator('.welcome-actions button').first().waitFor();
await page.getByText('background-test', { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const { backgroundHub } = await import('/src/lib/plugins/backgrounds.ts');
const make = (first, second) => {
const canvas = document.createElement('canvas'); canvas.width = 1200; canvas.height = 800;
const ctx = canvas.getContext('2d'); const gradient = ctx.createLinearGradient(0, 0, 1200, 800);
gradient.addColorStop(0, first); gradient.addColorStop(1, second); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1200, 800);
ctx.strokeStyle = '#ffffff88'; ctx.lineWidth = 12;
for (let x = 0; x < 1400; x += 200) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x - 300, 800); ctx.stroke(); }
return canvas.toDataURL();
};
const saved = make('#bd486c', '#438f67');
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
// Decode the data URLs without fetch: the content security policy does not permit `data:` in connect-src.
const blob = url => new Blob([Uint8Array.from(atob(url.split(',')[1]), character => character.charCodeAt(0))], { type: 'image/png' });
const urls = [make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(url => URL.createObjectURL(blob(url)));
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
await showSavedImage(page);
const background = page.locator('.workarea-background');
const style = (locator, property, pseudo) => locator.evaluate((node, [property, pseudo]) => getComputedStyle(node, pseudo)[property], [property, pseudo]);
async function openWelcome() {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
}
assert.equal(await background.count(), 1);
assert.equal(await page.locator('.empty h1, .empty > p').count(), 0);
assert.equal(await style(page.locator('.empty'), 'backgroundImage'), 'none');
const bounds = await background.boundingBox();
assert.equal(bounds.x, 0); assert.equal(bounds.y, 36); assert.equal(bounds.width, 1280); assert.equal(bounds.height, 762);
assert.match(await style(background, 'backgroundImage'), /blob:/);
assert.match(await style(page.locator('.left'), 'backgroundColor'), /(?:0\.82|82%)/);
assert.match(await style(page.locator('.right'), 'backgroundColor'), /(?:0\.82|82%)/);
assert.match(await style(page.locator('.welcome-actions button').first(), 'backgroundColor'), /(?:0\.82|82%)/);
assert.doesNotMatch(await style(page.locator('header.header'), 'backgroundColor'), /(?:0\.82|82%)/);
await page.locator('.welcome-actions button').first().focus();
await page.keyboard.press('Tab');
assert(await page.locator('.welcome-actions').evaluate(node => node.contains(document.activeElement)));
await page.screenshot({ path: `${output}/${theme}-splash.png` });
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[0], blurredUrl: urls[1], overlay: 0.15, position: 'top', size: 'contain' });
});
assert.equal(await style(background, 'backgroundSize'), '100% 100%, contain, cover');
assert.equal(await style(background, 'backgroundPosition'), '50% 50%, 50% 0%, 50% 50%');
await page.screenshot({ path: `${output}/${theme}-portrait-layers.png` });
await page.setViewportSize({ width: 390, height: 700 });
assert.equal(await style(background, 'backgroundSize'), '100% 100%, contain, cover');
await page.screenshot({ path: `${output}/${theme}-portrait-layers-narrow.png` });
await page.setViewportSize(viewport);
await page.evaluate(() => {
const { hub, owner, urls } = window.backgroundTest;
hub.set(owner, 'app', { url: urls[1], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[0], overlay: 0.15, position: 'center', size: 'cover' }, transitionMs: 2000 });
});
await page.waitForTimeout(180);
const opacity = Number(await style(background, 'opacity', '::after'));
assert(opacity > 0 && opacity < 1, `Fade has an intermediate opacity: ${opacity}`);
await page.waitForTimeout(900);
assert.ok(Number(await style(background, 'opacity', '::after')) < 1, 'The fade remains active after one second');
await page.waitForTimeout(1100);
assert.equal(await style(background, 'opacity', '::after'), '1');
await openWelcome();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.match(await style(page.locator('.editor > .body'), 'backgroundColor'), /(?:0\.9|90%)/);
await page.screenshot({ path: `${output}/${theme}-writer.png` });
await chooseView(page, 'Read');
await page.locator('.md-page').waitFor();
const beforeScroll = await background.boundingBox();
await page.locator('.md-page').evaluate(node => { node.scrollTop = 600; });
assert.deepEqual(await background.boundingBox(), beforeScroll);
await page.screenshot({ path: `${output}/${theme}-reader.png` });
// Split shows the Write editor beside Read.
await chooseView(page, 'Read beside');
await page.locator('.live-writer .cm-content').waitFor();
assert.equal(await style(page.locator('.live-writer .cm-editor').first(), 'backgroundColor'), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `${output}/${theme}-split.png` });
await chooseView(page, 'Read beside');
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.screenshot({ path: `${output}/${theme}-ide.png` });
await page.setViewportSize({ width: 680, height: 720 });
// The side panes give way in a narrow window and come back in a wide one (src/lib/layout/Workbench.svelte).
await page.screenshot({ path: `${output}/${theme}-ide-narrow.png` });
await page.keyboard.press('Control+t');
await page.locator('.welcome-actions').waitFor();
await page.setViewportSize({ width: 480, height: 640 });
assert(await page.locator('.empty').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
assert.equal(await background.evaluate(node => node.getAnimations({ subtree: true }).length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
// The frame of Background (the saved image) shows again, without a fade.
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), 'none');
assert.match(await style(background, 'backgroundImage'), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage === 'none');
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-image')), '', 'Without an image, the body has no background properties');
await openWelcome();
await page.locator('.editor > .body').waitFor();
assert.equal(await style(page.locator('.editor > .body'), 'backgroundColor'), await style(page.locator('.shell'), 'backgroundColor'));
await page.screenshot({ path: `${output}/${theme}-removed.png` });
assert.deepEqual(page.errors, []);
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'Source transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
await page.close();
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
}
await writeFile(`${output}/report.json`, JSON.stringify(report, null, 2));
});
@@ -0,0 +1,138 @@
// New-tab background images: large uploads, cross-window sync, reload, theme reuse, removal, picker menus, and narrow settings.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// Background (src/lib/features/background/) loads after the first render, so each check waits for the image.
const waitForImage = page => page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await runSmoke('appearance/backgroundImages', async ({ browser }) => {
const output = await outputDir('appearance/backgroundImages');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => {
const workspace = test.workspace({
root: 'C:\\host-todo-test',
files: {
'a.md': '# Note\n\nOriginal text.',
'.runestone/templates/Daily.md': '# Daily\n\n## Tasks',
'.runestone/marks.json': JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } }),
},
});
return {
...workspace,
workspace_list: args => workspace.workspace_list(args).filter(entry => entry.rel_path !== '.runestone'),
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
};
},
});
const main = await openPage(context), settings = await openPage(context);
const imageInput = () => settings.getByLabel('Background image file', { exact: true });
const background = () => main.locator('.workarea-background').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]);
const decoded = (page, url) => page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
const savedImageId = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.imageId);
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
await main.goto(smokeUrl); await main.locator('.empty').waitFor();
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const image = await main.evaluate(() => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
const ctx = canvas.getContext('2d'), pixels = ctx.createImageData(700, 700);
let seed = 23;
for (let i = 0; i < pixels.data.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels.data[i] = i % 4 === 3 ? 255 : seed >>> 24; }
ctx.putImageData(pixels, 0, 0); return canvas.toDataURL();
});
const bytes = Buffer.from(image.split(',')[1], 'base64');
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
await imageInput().setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
let url = await background();
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const largeFile = path.join(output, '50MiB.png');
await writeFile(largeFile, Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]));
await imageInput().setInputFiles(largeFile);
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => JSON.stringify(window.__TEST__.settings('appearance')).length < 500), 'Image bytes stay outside the settings file');
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await savedImageId();
const tooLargeFile = path.join(output, 'too-large.png');
await writeFile(tooLargeFile, Buffer.alloc(50 * 1024 * 1024 + 1));
await imageInput().setInputFiles(tooLargeFile);
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
assert.equal(await savedImageId(), acceptedId);
assert.equal(await settings.locator('input[type=color]').count(), 0);
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('0.55'));
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('255, 255, 255, 0.4'));
// A theme card chooses the theme and its light or dark mode together (src/lib/theme/ThemePicker.svelte).
for (const mode of ['dark', 'light']) {
await settings.getByRole('radio', { name: mode === 'dark' ? 'RuneStone Dark' : 'RuneStone Light', exact: true }).click();
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
await main.screenshot({ path: `${output}/background-${mode}.png` });
// The image position menu is a shared menu of Appearance settings.
for (const name of ['Image position']) {
await picker(name).click();
const menu = settings.getByRole('menu', { name, exact: true });
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
// Shared menu rows are 24px high (src/lib/theme/tokens.css:31, --rs-menu-row-height).
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '24px');
// The current choice shows a check mark in the icon column (src/lib/ui/actionMenu.ts).
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 1);
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
await settings.screenshot({ path: `${output}/${name.replaceAll(' ', '-')}-${mode}.png` });
await settings.keyboard.press('Escape');
assert.equal(await picker(name).evaluate(node => node === document.activeElement), true);
}
}
await settings.setViewportSize({ width: 360, height: 480 });
await picker('Image position').scrollIntoViewIfNeeded();
await picker('Image position').click();
const box = await settings.getByRole('menu', { name: 'Image position', exact: true }).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
await settings.screenshot({ path: `${output}/menu-narrow.png` });
await settings.keyboard.press('Escape');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage === 'none');
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
await settings.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
});
for (const theme of ['light', 'dark']) {
await settings.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, theme);
await settings.setViewportSize({ width: 360, height: 600 });
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
await settings.screenshot({ path: `${output}/long-plugin-list-${theme}-narrow.png` });
await main.setViewportSize({ width: 600, height: 700 });
await main.keyboard.press('F1');
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
// The shortcut list is open by default (src/lib/layout/SettingsDialog.svelte).
assert.equal(await main.locator('.help-card details[open]').count(), 1);
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 2);
await main.keyboard.press('Enter');
await main.screenshot({ path: `${output}/help-${theme}-narrow.png` });
await main.getByRole('button', { name: 'Close help', exact: true }).click();
}
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
});
@@ -0,0 +1,70 @@
// Background image position and size: menu choices, a stable surface under overflow, persistence, keyboard choice, both themes, narrow settings.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// The controls are in Appearance → Background (src/lib/features/background/BackgroundSettings.svelte).
await runSmoke('appearance/backgroundLayout', async ({ browser }) => {
const output = await outputDir('appearance/backgroundLayout');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: () => ({
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const main = await openPage(context), settings = await openPage(context);
const screenshots = [];
await main.goto(smokeUrl);
await main.locator('.empty').waitFor();
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
const button = settings.getByRole('button', { name: control, exact: true });
await button.click();
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
assert.equal(await button.evaluate(node => node === document.activeElement), true);
}
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundPosition.endsWith('0% 0%'));
const layout = () => main.locator('.workarea-background').evaluate(node => {
const style = getComputedStyle(node), box = node.getBoundingClientRect();
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
});
const before = await layout();
assert.equal(before.size, '100% 100%, auto');
await main.locator('.empty').evaluate(node => {
const content = document.createElement('div'); content.style.cssText = 'height:2000px;flex-shrink:0;width:100%'; node.append(content);
});
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
await main.reload();
await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
assert.equal((await layout()).position, before.position);
assert.equal((await layout()).size, before.size);
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
await settings.keyboard.press('End');
await settings.keyboard.press('Enter');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundPosition.endsWith('100% 100%'));
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.readAppearance(), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 700 });
const file = path.join(output, `settings-${mode}-${width}.png`);
await settings.screenshot({ path: file }); screenshots.push(file);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
}
}
await writeFile(path.join(output, 'report.json'), JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
});
@@ -0,0 +1,64 @@
// Background image overlay: signed numeric entry, slider sync, persistence, clamping, both themes, narrow settings, keyboard focus.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/backgroundOverlay', async ({ page: settings }) => {
const output = await outputDir('appearance/backgroundOverlay');
await settings.setViewportSize({ width: 1100, height: 780 });
await mockTauri(settings, {
commands: () => ({
plugins_snapshot: () => ({ root: 'C:/plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
await settings.goto(smokeUrl + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
name: 'image.png', mimeType: 'image/png',
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'),
});
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
const saved = () => settings.evaluate(() => window.__TEST__.settings('appearance').newTabBackground.overlay);
await input.fill('-37');
assert.equal(await slider.inputValue(), '-37');
assert.equal(await saved(), -0.37);
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal(await input.inputValue(), '-37');
await input.fill('');
assert.equal(await saved(), -0.37);
await input.blur();
assert.equal(await input.inputValue(), '-37');
await input.fill('150');
await input.blur();
assert.equal(await input.inputValue(), '100');
assert.equal(await saved(), 1);
await slider.fill('24');
assert.equal(await input.inputValue(), '24');
assert.equal(await saved(), 0.24);
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.readAppearance(), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 780 });
await input.focus();
assert.equal(await input.evaluate(node => node === document.activeElement), true);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
await settings.screenshot({ path: path.join(output, `${mode}-${width}.png`) });
}
}
await writeFile(path.join(output, 'report.json'), JSON.stringify({
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
screenshotFolder: output,
native: 'Native desktop acceptance remains pending.',
}, null, 2));
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
});
@@ -0,0 +1,216 @@
// Character themes: colors, fonts, Source syntax, export, window sync, narrow theme cards, selection fills, and legacy or removed theme IDs.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/characterThemes', async ({ browser }) => {
const output = await outputDir('appearance/characterThemes');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\theme-smoke',
files: {
'Theme.md': '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n',
'Theme.py': '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n',
},
}),
plugins_snapshot: () => ({ root: 'C:/theme-smoke-plugins', plugins: [] }),
theme_export: args => { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; },
}),
});
const main = await openPage(context);
const settings = await openPage(context);
const ide = await openPage(context);
const pages = [main, settings, ide];
try {
const fontSession = await context.newCDPSession(settings);
await fontSession.send('DOM.enable');
await fontSession.send('CSS.enable');
async function openFile(page, name) {
await page.goto(smokeUrl);
await page.getByText('theme-smoke', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
}
await openFile(main, 'Theme.md');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await openFile(ide, 'Theme.py');
await ide.locator('.source-editor .cm-content').waitFor();
// Mark each mounted editor once. A new editor has no mark, so it gets a new identifier.
const editorIds = () => ide.evaluate(() => [...document.querySelectorAll('.source-editor .cm-editor')]
.map(node => node.dataset.smokeId ||= String(window.__editorSerial = (window.__editorSerial || 0) + 1)));
const initialEditors = await editorIds();
const openSettings = async () => {
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
};
// The Color theme cards are one radio group (src/lib/theme/ThemePicker.svelte).
const card = name => settings.getByRole('radiogroup', { name: 'Color theme', exact: true }).getByRole('radio', { name, exact: true });
const choose = async (_, value) => { await card(value).click(); };
const waitForAppearance = (theme, mode) => Promise.all(pages.map(page => page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode })));
// Settings and the app import external.ts with a version query, so reuse the loaded module URL.
const setPluginTools = count => settings.evaluate(async count => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
await openSettings();
assert.equal(await card('Renamon').count(), 0);
assert.equal(await card('Asuka School Uniform').count(), 0);
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
assert.equal(await card(label).count(), 0);
}
const cases = [
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
];
for (const [theme, label, mode, expectedFonts] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose('Color theme', label);
await waitForAppearance(theme, mode);
// The export is one schema 3 theme file with every role, for the theme's own mode (exportAppearanceTheme in src/lib/theme/appearance.ts).
const template = await settings.evaluate(async theme => {
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
return exportAppearanceTheme(theme);
}, theme);
const colors = template.colors;
// The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts).
const applied = { ...colors, selection: `${colors.selection.slice(0, 7)}a6` };
const actual = await settings.evaluate(keys => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(keys.map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
}, Object.keys(applied));
assert.deepEqual(actual, applied);
const fonts = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return { ui: css.getPropertyValue('--rs-font-ui'), prose: getComputedStyle(document.querySelector('.preview-prose')).fontFamily,
heading: getComputedStyle(document.querySelector('.preview-document strong')).fontFamily,
code: getComputedStyle(document.querySelector('.preview-code')).fontFamily };
});
for (const key of ['ui', 'prose', 'heading']) assert(fonts[key].includes(expectedFonts[key]), `${theme}: ${key} uses its font`);
assert(fonts.code.includes('Cascadia Mono'), 'Code retains the shared monospace font');
const { root } = await fontSession.send('DOM.getDocument');
const { nodeId } = await fontSession.send('DOM.querySelector', { nodeId: root.nodeId, selector: '.preview-prose' });
const rendered = await fontSession.send('CSS.getPlatformFontsForNode', { nodeId });
assert(rendered.fonts.some(item => item.glyphCount > 0), 'The font renders visible glyphs');
console.log(`${theme} rendered fonts: ${rendered.fonts.map(item => item.familyName).join(', ')}`);
await settings.evaluate(() => { window.exportedTheme = undefined; });
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.waitForFunction(() => window.exportedTheme);
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), template);
await ide.waitForFunction(expected => {
const spans = [...document.querySelectorAll('.source-editor .cm-line span')].filter(node => !node.children.length);
return Object.entries(expected).every(([text, color]) => {
const node = spans.find(node => node.textContent.replaceAll('\u00a0', ' ').includes(text));
const probe = document.createElement('i');
probe.style.color = color; document.body.append(probe);
const target = getComputedStyle(probe).color; probe.remove();
return node && getComputedStyle(node).color === target;
});
}, { return: colors['syntax-keyword'], RuneStone: colors['syntax-string'], 42: colors['syntax-number'], print: colors['syntax-function'], '# Character colors': colors['syntax-comment'] });
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
if (theme === 'harvest-moon') {
const normalized = await settings.evaluate(async () => {
const { normalizeAppearance } = await import('/src/lib/theme/appearance.ts');
return normalizeAppearance({ theme: 'harvest-moon', mode: 'light' });
});
assert.equal(normalized.mode, 'dark', 'Harvest Moon keeps its fixed dark appearance');
await main.locator('[data-tree-rel="Theme.md"]').click();
const selectedRow = await main.locator('[data-tree-rel="Theme.md"]').evaluate(node => {
const css = getComputedStyle(node);
return { selected: node.getAttribute('aria-selected'), fill: css.backgroundColor,
selection: getComputedStyle(document.documentElement).getPropertyValue('--rs-item-selection-bg').trim() };
});
assert.equal(selectedRow.selected, 'true');
assert.equal(selectedRow.selection, applied.selection, 'File selection uses the same warm selection color');
// Selection fills use the capped a6 (0.65) alpha (src/lib/theme/appearance.ts:197-203).
const warmFill = 'rgba(82, 40, 20, 0.65)';
assert.equal(selectedRow.fill, warmFill, 'The selected file paints the warm fill');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-file-selection.png`) });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
let text;
while ((text = walker.nextNode()) && !text.textContent.includes('A calm surface')) {}
const range = document.createRange(); range.selectNodeContents(text);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
await main.screenshot({ path: path.join(output, `${theme}-${mode}-writer-selection.png`) });
await ide.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
view.dispatch({ selection: { anchor: 0, head: view.state.doc.line(3).from + 20 } }); view.focus();
});
await ide.locator('.source-editor .cm-selectionBackground').first().waitFor();
assert.equal(await ide.locator('.source-editor .cm-selectionBackground').first().evaluate(node => getComputedStyle(node).backgroundColor),
warmFill, 'Source selection uses the same warm fill');
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide-selection.png`) });
await ide.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')).dispatch({ selection: { anchor: 0 } });
});
}
await ide.screenshot({ path: path.join(output, `${theme}-${mode}-ide.png`) });
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-settings.png`) });
await main.screenshot({ path: path.join(output, `${theme}-${mode}-document.png`) });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal(await card(label).getAttribute('aria-checked'), 'true');
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
// The current card is the one Tab stop of the group, and its focus outline shows.
const current = card(label);
await current.scrollIntoViewIfNeeded();
await current.focus();
// Reach the card with the keyboard, so :focus-visible applies.
await settings.keyboard.press('Shift+Tab');
await settings.keyboard.press('Tab');
assert(await current.evaluate(node => document.activeElement === node), 'Tab returns to the current card');
assert.equal(await current.getAttribute('tabindex'), '0');
assert.notEqual(await current.evaluate(node => getComputedStyle(node).outlineStyle), 'none', 'Keyboard focus shows an outline');
const bounds = await settings.getByRole('radiogroup', { name: 'Color theme', exact: true }).boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360, 'The cards stay within the viewport');
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-focus.png`) });
await setPluginTools(16);
const navigation = settings.locator('dialog aside');
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await navigation.boundingBox()).height <= bodyBounds.height * 0.4 + 1, 'Long plugin navigation leaves room for settings');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
await settings.screenshot({ path: path.join(output, `${theme}-${mode}-360-long-navigation.png`) });
await setPluginTools(0);
console.log(`PASS: ${theme} ${mode}, colors, fonts, Source syntax, export, saved state, window sync, narrow theme cards, keyboard and focus`);
}
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
await settings.evaluate(theme => window.__TEST__.writeSettings('appearance', { theme, mode: 'dark' }), previous);
await openSettings();
assert.equal(await card(label).getAttribute('aria-checked'), 'true');
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
await choose('Color theme', label);
assert.equal(await settings.evaluate(() => window.__TEST__.settings('appearance').theme), theme);
}
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
await settings.evaluate(({ theme, mode }) => window.__TEST__.writeSettings('appearance', { theme, mode }), { theme: removed, mode });
await settings.setViewportSize({ width: 1100, height: 780 });
await openSettings();
await waitForAppearance('default', mode);
assert.equal(await card(`RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`).getAttribute('aria-checked'), 'true');
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
await settings.screenshot({ path: path.join(output, `${removed}-fallback-${mode}-settings.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: path.join(output, `default-${mode}-360-settings.png`) });
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
} catch (error) {
for (const [index, page] of pages.entries()) await page.screenshot({ path: path.join(output, `failure-${index}.png`) }).catch(() => {});
throw error;
}
});
@@ -0,0 +1,42 @@
// The Color theme cards in Settings work from the keyboard, Settings has no color inputs, and the main window's empty tab uses the new theme background.
import assert from "node:assert/strict";
import { mockTauri, openPage, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/colorThemeMenu", async ({ browser }) => {
// The settings window changes the main window through the mock settings file, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\color-theme-menu", files: { "a.md": "# Note\n\nOriginal text." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
}),
});
const page = await openPage(context);
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor();
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
// Cards name the mode ("RuneStone Dark" is the default). The next card is Claude Light, and an arrow key selects it (src/lib/theme/ThemePicker.svelte).
await settings.getByRole("radio", { name: "RuneStone Dark", exact: true }).focus();
await settings.keyboard.press("ArrowDown");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude");
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), "claude");
assert.equal(await settings.locator("input[type=color]").count(), 0);
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor();
await page.waitForFunction(() => document.documentElement.dataset.palette === "claude");
// The empty tab is transparent over the work area layer, which paints the theme background (src/lib/layout/Workbench.svelte:1258, :1548).
assert.equal(await page.locator(".empty").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.equal(await page.locator(".workarea-background").evaluate(node => {
const reference = document.createElement("span");
reference.style.color = "var(--rs-bg)";
node.append(reference);
const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color;
reference.remove();
return matches;
}), true);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: keyboard theme selection, no color inputs, and the empty tab uses the theme background");
});
+93
View File
@@ -0,0 +1,93 @@
// Compact layout: pane-aligned ribbon, square tables, focus-only tree outline, joined tabs, line hover marker, Git line history, narrow width.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/density", async ({ page }) => {
const output = await outputDir("appearance/density");
await page.setViewportSize({ width: 1280, height: 800 });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "D:\\LayoutTest",
files: { "note.md": "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n" },
}),
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
// The Git feature asks the host for the line history. The test turns the answer on with `blameOn`.
git_blame: ({ path, line }) => {
if (!window.blameOn) return null;
window.blameCalls.push({ path, line });
return { commit: "123456789abcdef", author: "UI test", date: "2026-10-07T12:34:00Z", summary: `Changed line ${line}` };
},
}),
});
const row = page.locator('[data-tree-rel="note.md"]');
// The checked choice of the view control. Arrow keys, Home, and End move the choice (src/lib/layout/ViewModes.svelte).
const view = () => page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { checked: true });
const setTheme = theme => page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
await page.goto(smokeUrl);
await row.waitFor();
await row.click();
await page.locator(".writer-table table").waitFor();
const alignment = await page.evaluate(() => ({ header: document.querySelector(".header-left").getBoundingClientRect().right, content: document.querySelector(".center").getBoundingClientRect().left }));
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
const table = await page.locator(".writer-table table").evaluate(el => ({ width: el.getBoundingClientRect().width, heights: [...el.rows].map(row => row.getBoundingClientRect().height), radius: getComputedStyle(el.parentElement).borderRadius }));
assert.ok(table.width < 400, JSON.stringify(table));
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
assert.equal(table.radius, "0px");
await row.focus();
assert.equal(await row.locator(".selection-outline").evaluate(el => getComputedStyle(el).visibility), "visible");
await page.locator(".cm-content").click({ position: { x: 80, y: 100 } });
assert.equal(await row.locator(".selection-outline").evaluate(el => getComputedStyle(el).visibility), "hidden");
assert.equal(await row.getAttribute("aria-selected"), "true");
const line = page.locator(".cm-line").filter({ hasText: "A second paragraph." });
await line.hover();
assert.equal(await line.evaluate(el => getComputedStyle(el, "::before").width), "3px");
assert.equal(await page.locator(".line-history").count(), 0);
await page.evaluate(() => { window.blameCalls = []; window.blameOn = true; });
await line.click();
await page.locator(".line-history").waitFor();
assert.match(await page.locator(".line-history").getAttribute("title"), /Line 5 · UI test/);
await page.keyboard.type("x");
await page.locator(".line-history").waitFor({ state: "hidden" });
await page.keyboard.press("Control+z");
await page.locator(".line-history").waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(theme);
const tab = await page.locator(".tab.active").evaluate(el => ({ background: getComputedStyle(el).backgroundColor, border: getComputedStyle(el).borderBottomColor, shadow: getComputedStyle(el).boxShadow }));
const pane = await page.locator(".chrome-bar").evaluate(el => getComputedStyle(el).backgroundColor);
assert.equal(tab.background, pane);
assert.equal(tab.border, "rgba(0, 0, 0, 0)");
assert.equal(tab.shadow, "none");
await line.hover();
await page.screenshot({ path: path.join(output, `writer-${theme}.png`) });
await view().press("End");
await page.locator(".md-page .reading").waitFor();
const paragraph = page.locator(".md-page p").filter({ hasText: "A second paragraph." });
await paragraph.hover();
assert.equal(await paragraph.evaluate(el => getComputedStyle(el, "::before").width), "3px");
assert.ok((await page.locator(".md-page table").boundingBox()).width < 400);
await page.screenshot({ path: path.join(output, `read-${theme}.png`) });
await view().press("Home");
}
await view().press("ArrowRight");
await page.locator(".source-editor .cm-content").waitFor();
await page.locator(".line-history").waitFor();
// Git off removes the line history at once.
await page.evaluate(() => { window.blameOn = false; window.__TEST__.writeSettings("features", { git: false }); });
await page.locator(".line-history").waitFor({ state: "hidden" });
await view().press("Home");
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.setViewportSize({ width: 760, height: 640 });
for (const theme of ["dark", "light"]) {
await setTheme(theme);
const dimensions = await page.locator(".header-left .icon-btn").evaluateAll(els => els.map(el => ({ width: el.getBoundingClientRect().width, svg: el.querySelector("svg").getBoundingClientRect().width })));
assert.ok(dimensions.every(size => size.width >= 28 && size.svg >= 16), JSON.stringify(dimensions));
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
await page.screenshot({ path: path.join(output, `narrow-${theme}.png`) });
}
console.log("PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width");
}, { timeout: 30000 });
@@ -0,0 +1,52 @@
// The empty tab background image: set it in Settings, keep it after a reload, and remove it. The source stays Image.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/newTabBackground";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
// The settings window changes the main window through the mock settings file and shared IndexedDB, so both pages need one context.
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\new-tab-background", files: { "a.md": "# Note\n\nOriginal text." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
}),
});
const page = await openPage(context);
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').waitFor();
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor();
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=", "base64");
// The image lives on the work area layer behind the empty tab (src/lib/theme/background.css).
const layer = ".workarea-background";
await settings.getByLabel("Background image file", { exact: true }).setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png });
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
assert.equal(await page.evaluate(() => window.__TEST__.settings("background").source), "image", "A chosen image selects the image source");
await page.reload();
await page.locator(".empty").waitFor();
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
await settings.getByRole("button", { name: "Remove image", exact: true }).click();
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer);
for (const mode of ["light", "dark"]) {
await settings.evaluate(async mode => {
const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ ...readAppearance(), theme: "default", mode });
window.dispatchEvent(new Event("focus"));
}, mode);
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) });
}
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).count(), 0);
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Image");
assert.equal(await settings.getByRole("button", { name: "Choose image…", exact: true }).count(), 1);
await page.waitForFunction(() => !window.__TEST__.settings("appearance").newTabBackground);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: background image applies, survives a reload, and is removed; the image source stays selected");
});
+164
View File
@@ -0,0 +1,164 @@
// Built-in palettes: modes, light-only Sakura, migration, persistence, typography, cross-window sync, source editor updates, and narrow settings.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/palettes", async ({ browser }) => {
const output = await outputDir("appearance/palettes");
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: "C:\\appearance-smoke",
files: Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])),
}),
plugins_snapshot: () => ({ root: "C:/appearance-smoke-plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
}),
});
const main = await openPage(context);
const settings = await openPage(context);
const secondSettings = await openPage(context);
const pages = [main, settings, secondSettings];
try {
await main.goto(smokeUrl);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".source-editor .cm-content").waitFor();
await main.waitForFunction(file => document.querySelector(".editor .breadcrumb")?.title.endsWith(file)
&& document.querySelector(".source-editor .cm-content")?.dataset.language === "python", `theme-${index}.py`);
await main.locator(".source-editor .cm-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
// Mark each mounted editor once. A new editor has no mark, so it gets a new identifier.
return main.evaluate(() => [...document.querySelectorAll(".source-editor .cm-editor")]
.map(node => node.dataset.smokeId ||= String(window.__editorSerial = (window.__editorSerial || 0) + 1)));
}
// Wait until "RuneStone", "def", and "42" have three distinct syntax colors.
async function waitForSyntax() {
await main.waitForFunction(() => {
const spans = [...document.querySelectorAll(".source-editor .cm-line span")];
const colors = ["RuneStone", "def", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return span ? getComputedStyle(span).color : null;
});
return colors.every(Boolean) && new Set(colors).size === 3;
});
}
const themeName = (theme, mode) => theme === "sakura" ? "Sakura" : `${({ default: "RuneStone", claude: "Claude" })[theme]} ${mode === "light" ? "Light" : "Dark"}`;
const picker = (page, name) => page.locator(".picker").filter({ has: page.locator("svg") }).and(page.getByRole("button", { name, exact: true }));
// The Color theme cards are one radio group (src/lib/theme/ThemePicker.svelte).
const card = (page, name) => page.getByRole("radiogroup", { name: "Color theme", exact: true }).getByRole("radio", { name, exact: true });
async function choose(page, theme, mode) {
await card(page, themeName(theme, mode)).click();
}
async function openAppearance(page) {
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await page.getByRole("radiogroup", { name: "Color theme", exact: true }).waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal(await card(secondSettings, themeName(theme, mode)).getAttribute("aria-checked"), "true");
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".source-editor .cm-editor")];
const workarea = document.querySelector(".editor > .body");
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === "rgba(0, 0, 0, 0)")
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await choose(settings, theme, mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing source editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new source editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme, mode });
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}.png`) });
await main.screenshot({ path: path.join(output, `appearance-editor-${theme}-${mode}.png`) });
if (theme === "sakura") {
const keywordColor = await main.locator(".source-editor .cm-line span").evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === "def");
return keyword ? getComputedStyle(keyword).color : null;
});
assert.equal(keywordColor, "rgb(160, 68, 107)", "Sakura keywords use the Rose Garden hue");
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector("h2")).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue("--rs-font-prose").trim(),
}));
if (theme === "claude") {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim()), mode === "light" ? "#ab4e2f" : "#ed8968");
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new source editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
assert.deepEqual((await settings.getByRole("radiogroup", { name: "Color theme", exact: true }).getByRole("radio").allTextContents()).map(name => name.trim()), ["RuneStone Light", "RuneStone Dark", "Claude Light", "Claude Dark", "Sakura", "Harvest Moon", "Crimson Pilot", "Silver Serpent"]);
assert.equal(await picker(settings, "Appearance").count(), 0);
assert.equal(await picker(secondSettings, "Appearance").count(), 0);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(["bg", "border", "selection", "bg-active", "syntax-keyword", "syntax-variable", "syntax-property", "syntax-constant", "syntax-punctuation"].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
// The applied selection color caps its alpha at a6 so text backgrounds show through (appliedColors in src/lib/theme/contrast.ts).
assert.deepEqual(sakura, { bg: "#fefcfc", border: "#efd3dd", selection: "#ffc9dca6", "bg-active": "#f8dbe6", "syntax-keyword": "#a0446b", "syntax-variable": "#513346", "syntax-property": "#47658e", "syntax-constant": "#316a83", "syntax-punctuation": "#566575" });
for (const [theme, savedMode, expectedTheme, mode] of [
["gpt", "light", "default", "light"],
["terminal", "dark", "default", "dark"],
["sakura", "dark", "sakura", "light"],
]) {
await settings.evaluate(value => window.__TEST__.writeSettings("appearance", value), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => window.__TEST__.settings("appearance")), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [["default", "dark"], ["claude", "light"], ["claude", "dark"], ["sakura", "light"]]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await choose(settings, theme, mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "Narrow settings do not overflow the viewport");
assert(await settings.locator("dialog .content").evaluate(node => node.scrollWidth <= node.clientWidth), "Appearance controls do not overflow the content area");
const control = card(settings, themeName(theme, mode));
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, "The current theme card remains reachable at 360px");
await settings.screenshot({ path: path.join(output, `appearance-${theme}-${mode}-360.png`) });
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
} catch (error) {
for (const [index, page] of pages.entries()) await page.screenshot({ path: path.join(output, `appearance-failure-${index}.png`) }).catch(() => {});
throw error;
}
});
@@ -0,0 +1,116 @@
// Theme picker cards and the theme editor tab: keyboard selection, the check mark, a live preview, contrast badges, Save, Discard, Duplicate, and narrow windows.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/themeEditor", async ({ browser }) => {
const output = await outputDir("appearance/themeEditor");
const context = await browser.newContext({ viewport: { width: 1200, height: 820 } });
const commands = test => ({
...test.workspace({ root: "C:\\theme-editor", files: { "a.md": "# Note\n\nSome text with a [link](https://example.com).\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
});
// The Settings window label names the window that opened it (src-tauri/src/settings.rs).
const main = await openPage(context);
await mockTauri(main, { label: "main", commands });
const settings = await openPage(context);
await mockTauri(settings, { label: "settings-main", commands });
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="a.md"]').waitFor();
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const token = (page, role) => page.evaluate(role => getComputedStyle(document.documentElement).getPropertyValue(`--rs-${role}`).trim(), role);
// Picker cards: one radio group with a check mark on the current theme.
const cards = settings.getByRole("radiogroup", { name: "Color theme", exact: true });
const card = name => cards.getByRole("radio", { name, exact: true });
assert.equal(await card("RuneStone Dark").getAttribute("aria-checked"), "true");
assert.equal(await card("RuneStone Dark").locator(".card-name svg").count(), 1, "The current card shows a check mark");
assert.equal(await card("Claude Light").locator(".card-name svg").count(), 0);
await card("RuneStone Dark").focus();
await settings.keyboard.press("ArrowRight");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "claude" && document.documentElement.dataset.theme === "light");
assert.equal(await card("Claude Light").evaluate(node => node === document.activeElement && node.getAttribute("aria-checked") === "true"), true);
await settings.keyboard.press("ArrowLeft");
await settings.waitForFunction(() => document.documentElement.dataset.palette === "default" && document.documentElement.dataset.theme === "dark");
await main.waitForFunction(() => document.documentElement.dataset.palette === "default");
await settings.screenshot({ path: path.join(output, "picker-cards.png") });
// Edit theme opens the editor tab in the window that opened Settings.
await settings.getByRole("button", { name: "Edit theme", exact: true }).click();
const editor = main.getByRole("region", { name: "Theme editor", exact: true });
await editor.waitFor();
await main.getByRole("tab", { name: /Theme editor/ }).waitFor();
assert.equal(await editor.getByRole("textbox", { name: "Theme name", exact: true }).inputValue(), "RuneStone Dark copy");
assert.match(await editor.getByRole("status").textContent(), /All readability checks pass/);
// A change shows at once in this window, and not in Settings before a save.
const hex = role => editor.getByRole("textbox", { name: `Hex value of ${role}`, exact: true });
await hex("accent").fill("#ff7a1a");
await hex("accent").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#ff7a1a");
assert.equal(await token(settings, "accent"), "#55dcf5");
await main.getByRole("tab", { name: "• Theme editor", exact: true }).waitFor();
// A color that fails a rule shows the failure on its row and in the summary. Reset takes the base color again.
await hex("text-dim").fill("#3a3a3a");
await hex("text-dim").press("Tab");
await editor.getByRole("status").filter({ hasText: /readability checks fail/ }).waitFor();
const dimRow = hex("text-dim").locator("xpath=..");
assert.equal(await dimRow.locator(".badge.fail").count(), 1);
await main.screenshot({ path: path.join(output, "editor-failing-role.png") });
await editor.getByRole("button", { name: "Reset text-dim", exact: true }).click();
assert.equal(await dimRow.locator(".badge.fail").count(), 0);
assert.equal(await token(main, "text-dim"), "#ababab");
// Save copies the built-in theme to a custom theme with a base, and every window selects it.
await editor.getByRole("button", { name: "Save", exact: true }).click();
await editor.getByRole("status").filter({ hasText: "Saved RuneStone Dark copy." }).waitFor();
await settings.waitForFunction(() => document.documentElement.dataset.palette === "custom:runestone-dark-copy");
assert.equal(await token(settings, "accent"), "#ff7a1a");
const saved = await main.evaluate(() => window.__TEST__.settings("customThemes"));
assert.deepEqual(saved.map(theme => [theme.id, theme.base, theme.mode, theme.colors]), [["runestone-dark-copy", "default", "dark", { accent: "#ff7a1a" }]]);
assert.equal(await card("RuneStone Dark copy").getAttribute("aria-checked"), "true");
await main.getByRole("tab", { name: "Theme editor", exact: true }).waitFor();
// Discard returns to the saved colors.
await hex("bg").fill("#202040");
await hex("bg").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim() === "#202040");
await editor.getByRole("button", { name: "Discard", exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim() === "#151617");
// Duplicate saves a copy and selects it.
await editor.getByRole("button", { name: "Duplicate", exact: true }).click();
await editor.getByRole("status").filter({ hasText: "Saved RuneStone Dark copy copy." }).waitFor();
await settings.waitForFunction(() => document.documentElement.dataset.palette === "custom:runestone-dark-copy-copy");
assert.equal((await main.evaluate(() => window.__TEST__.settings("customThemes"))).length, 2);
// A narrow pane keeps the editor inside the window, and keyboard focus is visible.
// A 520-pixel window without the outline leaves the editor about 215 pixels, below its 240-pixel breakpoint.
await main.getByRole("button", { name: "Hide outline", exact: true }).click();
await main.setViewportSize({ width: 520, height: 760 });
assert.ok(await editor.evaluate(node => node.clientWidth <= 240));
await hex("accent").focus();
assert.equal(await editor.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true, "The editor does not scroll sideways in a narrow pane");
assert.notEqual(await hex("accent").evaluate(node => getComputedStyle(node).outlineStyle), "none");
await main.screenshot({ path: path.join(output, "editor-narrow.png") });
await main.setViewportSize({ width: 1200, height: 820 });
await settings.setViewportSize({ width: 360, height: 640 });
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "Narrow settings do not overflow");
const box = await cards.boundingBox();
assert(box.x >= 0 && box.x + box.width <= 360, "The cards fit at 360 pixels");
await settings.screenshot({ path: path.join(output, "picker-cards-360.png") });
// Closing the editor with a change keeps the saved theme in the window.
await hex("accent").fill("#00ff00");
await hex("accent").press("Tab");
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#00ff00");
await main.getByRole("button", { name: /^Close .*Theme editor$/ }).click();
await editor.waitFor({ state: "detached" });
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-accent").trim() === "#ff7a1a");
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log("PASS: picker cards, the editor tab, live preview, contrast badges, Save, Discard, Duplicate, and narrow windows");
});
@@ -0,0 +1,31 @@
// Export theme template in Settings > Appearance: success, cancel, and an export error.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/themeExport", async ({ page }) => {
await mockTauri(page, {
state: { exportResult: "C:\\exports\\my-theme.json", exportError: "" },
commands: test => ({
...test.workspace({ root: "C:\\theme-export" }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
theme_export: () => {
if (test.state.exportError) throw new Error(test.state.exportError);
return test.state.exportResult;
},
}),
});
const exportButton = page.getByRole("button", { name: "Export theme template" });
await page.goto(smokeUrl + "/?settingsWindow=true");
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await exportButton.click();
await page.getByRole("status").filter({ hasText: "Theme saved to" }).waitFor();
// Exported templates use theme schema 3 (exportAppearanceTheme in src/lib/theme/appearance.ts).
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.calls.find(call => call.command === "theme_export").args.contents).schema), 3);
await page.evaluate(() => { window.__TEST__.state.exportResult = null; });
await exportButton.click();
await page.getByText("Export canceled.", { exact: true }).waitFor();
await page.evaluate(() => { window.__TEST__.state.exportError = "Disk is full"; });
await exportButton.click();
await page.getByRole("alert").filter({ hasText: "Disk is full" }).waitFor();
console.log("PASS: theme export success, cancel, and error");
}, { viewport: { width: 1200, height: 850 } });
@@ -0,0 +1,46 @@
// Import custom theme files in Settings > Appearance: schema 1 palettes for each mode, and a short schema 3 file with a base theme.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/themeImport";
await runSmoke(name, async ({ page }) => {
const output = await outputDir(name);
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\theme-import", files: { "a.md": "# Alpha\n" } }),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
}),
});
await page.goto(smokeUrl + "/?settingsWindow=true");
await page.getByRole("button", { name: "Appearance", exact: true }).click();
const theme = { schema: 1, id: "smoke", name: "Smoke theme", light: { bg: "#fefefe", text: "#222222", accent: "#334499" }, dark: { bg: "#181820", text: "#eeeeee", accent: "#aabbff" } };
const importTheme = (file = theme) => page.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: "smoke.json", mimeType: "application/json", buffer: Buffer.from(JSON.stringify(file)) });
const token = name => page.evaluate(name => getComputedStyle(document.documentElement).getPropertyValue(`--rs-${name}`).trim(), name);
const background = () => token("bg");
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#181820");
// A custom theme now keeps one palette. A schema 1 file converts with the current mode (src/lib/theme/customThemes.ts:38,
// src/lib/theme/AppearanceSettings.svelte), and the light/dark select became the Color theme cards (src/lib/theme/ThemePicker.svelte).
await page.getByRole("radio", { name: "RuneStone Light", exact: true }).click();
await page.waitForFunction(() => document.documentElement.dataset.palette !== "custom:smoke");
await importTheme();
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:smoke");
assert.equal(await background(), "#fefefe");
await page.screenshot({ path: path.join(output, "custom-theme-light.png") });
// A short schema 3 file takes the missing colors and fonts from its base theme. An earlier theme ID names the base.
await importTheme({ schema: 3, id: "short", name: "Short theme", mode: "dark", base: "holo", colors: { accent: "#00c8ff" } });
await page.waitForFunction(() => document.documentElement.dataset.palette === "custom:short");
assert.deepEqual([await background(), await token("accent"), await token("link"), await token("syntax-keyword")], ["#1c0f0a", "#00c8ff", "#00c8ff", "#f38c48"]);
assert.match(await token("font-ui"), /Candara/);
assert.equal(await page.evaluate(() => document.documentElement.dataset.theme), "dark");
await page.screenshot({ path: path.join(output, "custom-theme-short.png") });
// A base without a palette in the file's mode stops the installation with an error.
await importTheme({ schema: 3, id: "wrong", name: "Wrong base", mode: "dark", base: "sakura", colors: {} });
await page.getByRole("alert").filter({ hasText: "Use a built-in theme with a dark palette as the base." }).waitFor();
assert.equal(await page.evaluate(() => document.documentElement.dataset.palette), "custom:short");
console.log("PASS: custom theme import applies schema 1 palettes, a short schema 3 file with a base, and rejects a wrong base");
}, { timeout: 15000 });
@@ -0,0 +1,93 @@
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, plugin command icons,
// and the native Background commands in the command palette.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/themeVariants', async ({ browser }) => {
const output = await outputDir('appearance/themeVariants');
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\appearance-smoke',
files: Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])),
}),
plugins_snapshot: () => ({ root: 'C:/appearance-smoke-plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const page = await openPage(context);
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
const transparent = page.getByRole('switch', { name: 'Transparent surfaces', exact: true });
for (const [theme, mode] of [['default', 'dark'], ['default', 'light'], ['claude', 'dark'], ['claude', 'light'], ['sakura', 'light'], ['harvest-moon', 'dark'], ['crimson-pilot', 'dark'], ['silver-serpent', 'dark']]) {
await page.evaluate(async ({ theme, mode }) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode, transparency: { enabled: true, amount: 18 } });
window.dispatchEvent(new Event('focus'));
}, { theme, mode });
const slider = page.locator('#surface-transparency');
await slider.fill('100');
assert.equal(await page.evaluate(() => window.__TEST__.settings('appearance').transparency.amount), 100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(), '0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(), '100');
await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-focus.png`) });
await transparent.uncheck();
assert(await slider.isDisabled());
await page.screenshot({ path: path.join(output, `${theme}-${mode}-slider-disabled.png`) });
await transparent.check();
await page.setViewportSize({ width: 360, height: 740 }); await slider.scrollIntoViewIfNeeded();
assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({ path: path.join(output, `${theme}-${mode}-narrow.png`) });
await page.setViewportSize({ width: 1100, height: 800 });
}
await page.evaluate(async () => {
const { installTheme } = await import('/src/lib/theme/customThemes.ts');
const { saveAppearance, exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
const theme = exportAppearanceTheme('default'); theme.fonts = { ui: 'Arial, sans-serif', prose: 'Georgia, serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
installTheme(theme); saveAppearance({ theme: 'custom:my-theme', mode: 'dark' }); window.dispatchEvent(new Event('focus'));
});
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily), /Georgia/);
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui), /Arial/);
await page.screenshot({ path: path.join(output, 'custom-fonts.png') });
const main = await openPage(context); await main.goto(smokeUrl);
await main.bringToFront();
await main.getByRole('button', { name: 'Files', exact: true }).waitFor();
// The commands of the native Background feature (src/lib/features/catalog.ts) are in the command palette, without the feature code.
await main.keyboard.press('Control+Shift+P');
const palette = main.getByRole('dialog', { name: 'Commands', exact: true });
await palette.getByRole('textbox', { name: 'Find a command', exact: true }).fill('background');
for (const title of ['Next background image', 'Pause background']) await palette.getByRole('button').filter({ hasText: title }).first().waitFor();
assert.equal(await main.evaluate(async () => (await import('/src/lib/features/loader.ts')).featureRequested('background')), false, 'The palette lists the commands without the feature code');
await main.keyboard.press('Escape');
// A third-party plugin with command icons. The Commands menu lists plugin commands only (src/lib/plugins/PluginAccessMenu.svelte).
await main.evaluate(async () => {
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
const { pluginTools, refreshPlugins } = await import(loaded || '/src/lib/plugins/external.ts');
await refreshPlugins();
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command, args);
const commands = [{ owner: 'org.test.slideshow', id: 'next-image', title: 'Next test image', kind: 'command', surface: 'commands', icon: 'skip-forward' }, { owner: 'org.test.slideshow', id: 'pause-resume', title: 'Pause or resume test slideshow', kind: 'command', surface: 'commands', icon: 'pause' }];
pluginTools.set(commands);
});
const visibleTooltips = () => main.locator('[role=tooltip]:visible').count();
for (const mode of ['dark', 'light']) {
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
const button = main.getByRole('button', { name: 'Commands', exact: true });
assert.equal(await button.getAttribute('title'), null);
await button.hover(); await main.waitForTimeout(1100);
assert.equal(await visibleTooltips(), 1);
await main.screenshot({ path: path.join(output, `${mode}-single-tooltip.png`) });
await main.keyboard.press('Escape'); assert.equal(await visibleTooltips(), 0);
await main.mouse.move(400, 400);
await button.evaluate(node => node.blur());
await button.focus(); await main.waitForTimeout(600); assert.equal(await visibleTooltips(), 1);
await button.click(); await main.getByRole('menu').waitFor();
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
await main.screenshot({ path: path.join(output, `${mode}-plugin-command-icons.png`) }); await main.keyboard.press('Escape');
}
assert.deepEqual([...page.errors, ...main.errors], []);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
});
@@ -0,0 +1,53 @@
// Shared tooltips (attachTooltip) in both themes: no title attribute, rounded corners, Escape and focus, and placement inside a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "appearance/tooltipPlacement";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\tooltip-placement", files: { "sample.md": "# Tooltip sample\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
await page.goto(smokeUrl);
await page.getByText("tooltip-placement", { exact: true }).waitFor();
await page.evaluate(async theme => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode: theme });
const { attachTooltip } = await import("/src/lib/ui/tooltip.ts");
const cell = document.createElement("button");
cell.id = "tooltip-test";
cell.textContent = "Formula cell";
Object.assign(cell.style, { position: "fixed", left: "20px", top: "100px", zIndex: "2000" });
document.body.append(cell);
window.disposeTip = attachTooltip(cell, () => "B6 · Click to edit · Type = for a formula");
}, theme);
const target = page.locator("#tooltip-test");
const tooltip = page.locator(".rs-tooltip:popover-open");
await target.hover();
await tooltip.waitFor();
assert.equal(await target.getAttribute("title"), null);
assert.equal(await tooltip.evaluate(node => getComputedStyle(node).borderRadius), "5px");
await page.screenshot({ path: path.join(output, `${theme}-tooltip.png`) });
await page.keyboard.press("Escape");
assert.equal(await page.locator(".rs-tooltip:popover-open").count(), 0);
await target.focus();
await tooltip.waitFor();
await page.setViewportSize({ width: 390, height: 620 });
await page.locator("header").first().hover();
await target.hover();
await tooltip.waitFor();
const bounds = await tooltip.boundingBox();
assert(bounds.x >= 8 && bounds.x + bounds.width <= 382);
await page.screenshot({ path: path.join(output, `${theme}-narrow-tooltip.png`) });
await page.evaluate(() => { window.disposeTip(); document.getElementById("tooltip-test").remove(); });
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} tooltip`);
}
});
@@ -0,0 +1,118 @@
// Tab tooltips, translucent text selection, zero-transparency backgrounds, a stable transparency slider, and the themed install checkbox.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const output = await outputDir("appearance/tooltipsAndSelection");
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"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",
},
}),
plugins_snapshot: () => ({ root: "C:/theme-test-plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
spelling_menu_install: () => null,
}),
});
const tooltip = page.locator(".rs-tooltip:popover-open");
try {
await page.goto(smokeUrl);
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();
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=" } });
}, mode);
await showSavedImage(page);
const tab = page.getByRole("tab", { name: /welcome\.md/ });
assert.equal(await tab.getAttribute("title"), null);
await page.mouse.move(600, 600);
await tab.hover();
await tooltip.waitFor();
assert.match(await tooltip.innerText(), /welcome\.md/);
await page.screenshot({ path: path.join(output, `${mode}-tab-tooltip.png`) });
await page.keyboard.press("Escape");
assert.equal(await tooltip.count(), 0);
await tab.focus();
await tooltip.waitFor();
await page.keyboard.press("Escape");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement), body = getComputedStyle(document.body);
// Background sets the image and the surfaces on the body (src/lib/plugins/backgrounds.ts).
return { selection: root.getPropertyValue("--rs-selection"), bg: getComputedStyle(node, "::selection").backgroundColor,
text: getComputedStyle(node).color, image: body.getPropertyValue("--rs-background-image"), pluginBg: body.getPropertyValue("--rs-workarea-plugin-bg") };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
assert.notEqual(colors.image.trim(), "none");
assert.equal(colors.pluginBg.trim(), "transparent");
console.log(mode, colors);
await page.screenshot({ path: path.join(output, `${mode}-selection.png`) });
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator(".empty").waitFor();
await page.screenshot({ path: path.join(output, `${mode}-zero-background.png`) });
await page.getByRole("tab", { name: /welcome\.md/ }).click();
}
await page.goto(`${smokeUrl}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode });
window.dispatchEvent(new Event("focus"));
}, mode);
const slider = page.locator("#surface-transparency");
for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 800 });
await slider.fill("0"); const zero = await slider.boundingBox();
for (const amount of ["1", "9", "11", "18", "99", "100"]) {
await slider.fill(amount); const current = await slider.boundingBox();
assert.equal(current.x, zero.x); assert.equal(current.width, zero.width);
}
await page.screenshot({ path: path.join(output, `${mode}-${width}-slider.png`) });
}
}
await page.evaluate(() => {
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command, args) => command === "plugins_choose"
? Promise.resolve([{ token: "theme-test", source: "C:/Downloads/example.zip", error: null,
manifest: { id: "example", name: "Theme example", version: "0.1.0", description: "Theme control test", author: "RuneStone", entry: "main.js" } }])
: invoke(command, args);
});
await page.getByRole("button", { name: "Plug-ins", exact: true }).click();
for (const [theme, mode] of [["harvest-moon", "dark"], ["default", "light"]]) {
await page.evaluate(async ({ theme, mode }) => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme, mode }); window.dispatchEvent(new Event("focus"));
}, { theme, mode });
await page.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
const checkbox = page.getByRole("checkbox", { name: "Theme example", exact: true });
await checkbox.waitFor();
assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => {
const probe = document.createElement("span"); probe.style.color = "var(--rs-accent)"; document.body.append(probe);
const color = getComputedStyle(probe).color; probe.remove(); return color;
}));
await checkbox.focus();
await page.screenshot({ path: path.join(output, `${theme}-${mode}-install-checkbox.png`) });
await page.getByRole("button", { name: "Cancel", exact: true }).click();
}
console.log("PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.");
} catch (error) {
await page.screenshot({ path: path.join(output, "failure.png") });
throw error;
}
});
+135
View File
@@ -0,0 +1,135 @@
// Character theme typography: CSS families and the fonts Chromium renders for UI, prose, headings, and code, plus narrow settings.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, settle, smokeUrl } from '../_harness/index.mjs';
await runSmoke('appearance/typography', async ({ browser }) => {
const output = await outputDir('appearance/typography');
const report = [];
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\font-smoke',
files: { 'Typography.md': '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n' },
}),
plugins_snapshot: () => ({ root: 'C:/font-smoke-plugins', plugins: [] }),
}),
});
const main = await openPage(context);
const settings = await openPage(context);
await main.goto(smokeUrl);
await main.getByText('font-smoke', { exact: true }).waitFor();
await main.keyboard.press('Control+p');
await main.getByRole('textbox', { name: 'Find a file' }).fill('Typography.md');
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const sessions = new Map();
// The CSS font of `selector` and the platform fonts Chromium used to draw its glyphs.
async function rendered(page, selector) {
await settle(page);
let session = sessions.get(page);
if (!session) {
session = await context.newCDPSession(page);
await session.send('DOM.enable'); await session.send('CSS.enable'); sessions.set(page, session);
}
const { root } = await session.send('DOM.getDocument');
const { nodeId } = await session.send('DOM.querySelector', { nodeId: root.nodeId, selector });
assert(nodeId, selector);
const { fonts } = await session.send('CSS.getPlatformFontsForNode', { nodeId });
const style = await page.locator(selector).first().evaluate(node => {
const css = getComputedStyle(node);
return { family: css.fontFamily, size: css.fontSize, weight: css.fontWeight, lineHeight: css.lineHeight };
});
return { ...style, rendered: fonts.filter(font => font.glyphCount).map(({ familyName, postScriptName, glyphCount, isCustomFont }) => ({ familyName, postScriptName, glyphCount, isCustomFont })) };
}
const setPluginTools = count => settings.evaluate(async count => {
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
pluginTools.set(Array.from({ length: count }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
}, count);
const selectors = { ui: '.theme-actions button', prose: '.cm-line:not(.writer-heading):not(.writer-blank)', heading: '.writer-h1' };
const cases = [
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
['silver-serpent', 'Silver Serpent', 'Palatino Linotype', 'Corbel', 'Palatino Linotype', 'Palatino Linotype'],
];
for (const [theme, label, oldFont, ui, prose, heading] of cases) {
await settings.setViewportSize({ width: 1100, height: 780 });
await settings.getByRole('radio', { name: label, exact: true }).click();
await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme);
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home');
await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); });
// The theme sets its fonts as inline properties of the root. Put back those values after each temporary change.
for (const page of [main, settings]) {
const saved = await page.evaluate(font => ['ui', 'prose', 'heading'].map(role => {
const value = document.documentElement.style.getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
return value;
}), oldFont);
await page.screenshot({ path: path.join(output, `${theme}-before-${page === main ? 'document' : 'settings'}.png`) });
await page.evaluate(saved => {
['ui', 'prose', 'heading'].forEach((role, index) => document.documentElement.style.setProperty(`--rs-font-${role}`, saved[index]));
}, saved);
}
const roles = {
ui: await rendered(settings, selectors.ui),
prose: await rendered(main, selectors.prose),
heading: await rendered(main, selectors.heading),
mono: await rendered(settings, '.preview-code'),
};
for (const [role, family] of Object.entries({ ui, prose, heading })) {
assert(roles[role].family.includes(family), `${theme}: ${role} CSS family`);
assert(roles[role].rendered.some(font => font.familyName === family), `${theme}: ${role} actually renders ${family}: ${JSON.stringify(roles[role])}`);
}
assert.equal(roles.ui.size, '13px');
assert.equal(roles.prose.size, '15px');
assert(roles.mono.family.includes('Cascadia Mono'));
assert(roles.mono.rendered.some(font => font.familyName === 'Cascadia Mono'));
await settings.screenshot({ path: path.join(output, `${theme}-after-settings.png`) });
await main.screenshot({ path: path.join(output, `${theme}-after-document.png`) });
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
node.focus();
const paragraph = [...node.querySelectorAll('.cm-line')].find(line => line.textContent.includes('Read the next chapter'));
const range = document.createRange(); range.selectNodeContents(paragraph);
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
});
assert((await main.evaluate(() => getSelection().toString())).includes('Read the next chapter'));
await main.screenshot({ path: path.join(output, `${theme}-selected-prose.png`) });
await settings.setViewportSize({ width: 360, height: 480 });
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
// The current theme card stays reachable from the keyboard in a narrow window.
const current = settings.getByRole('radio', { name: label, exact: true });
await current.scrollIntoViewIfNeeded(); await current.focus();
assert.equal(await current.getAttribute('aria-checked'), 'true');
assert(await current.evaluate(node => node === document.activeElement));
await settings.screenshot({ path: path.join(output, `${theme}-narrow-cards.png`) });
await setPluginTools(16);
const bodyBounds = await settings.locator('dialog .body').boundingBox();
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
await settings.screenshot({ path: path.join(output, `${theme}-narrow-long-plugins.png`) });
await setPluginTools(0);
// Drop the first family from each stack and check that the fallback still renders glyphs.
const fallback = {};
for (const [role, page] of [['ui', settings], ['prose', main], ['heading', main]]) {
const stack = await page.evaluate(role => {
const stack = getComputedStyle(document.documentElement).getPropertyValue(`--rs-font-${role}`);
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
return stack;
}, role);
fallback[role] = await rendered(page, selectors[role]);
assert(fallback[role].rendered.length > 0);
await page.evaluate(([role, stack]) => document.documentElement.style.setProperty(`--rs-font-${role}`, stack), [role, stack]);
}
report.push({ theme, oldFont, roles, fallback });
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
}
assert.deepEqual([...main.errors, ...settings.errors], []);
await writeFile(path.join(output, 'rendered-fonts.json'), JSON.stringify(report, null, 2));
});
+61
View File
@@ -0,0 +1,61 @@
// The built-in browser shows about:blank as a transparent surface with no frame image, and paints real pages, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "browser/blankPage";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\blank-page", files: { "sample.md": "# Sample\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
browser_request: args => {
if (args.command === "frameAck") window.blankAcks = (window.blankAcks || 0) + 1;
return window.browserSnapshot;
},
}),
});
await page.goto(smokeUrl);
await page.getByText("blank-page", { exact: true }).waitFor();
await page.evaluate(async theme => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode: theme });
const { mount } = await import("/node_modules/svelte/src/index-client.js");
const { default: Browser } = await import("/src/lib/browser/Browser.svelte");
const client = await import("/src/lib/browser/client.ts");
const container = document.createElement("div");
container.id = "browser-test";
Object.assign(container.style, { position: "fixed", inset: "50px 10px 20px", zIndex: "2000", background: "linear-gradient(120deg,#945975,#395c72)" });
document.body.append(container);
window.browserSnapshot = { profiles: [{ id: "user", name: "User" }], tabs: [{ id: "blank", profileId: "user", url: "about:blank", title: "", loading: false }], bookmarks: [], settings: {} };
client.state.set(window.browserSnapshot);
mount(Browser, { target: container, props: { initial: { tabId: "blank" }, onSessionChange() {}, async newTab() {} } });
window.browserClient = client;
}, theme);
const surface = page.locator("#browser-test .surface");
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
await page.evaluate(() => window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 1, width: 10, height: 10, mime: "image/png", data: "AA==" }));
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.equal(await surface.locator("img").count(), 0);
assert.equal(await page.evaluate(() => window.blankAcks), 1);
await page.screenshot({ path: path.join(output, `${theme}-blank-browser.png`) });
await page.evaluate(() => {
window.browserSnapshot.tabs[0].url = "https://example.com/minimal";
window.browserClient.state.set({ ...window.browserSnapshot });
const canvas = document.createElement("canvas");
canvas.width = 10;
canvas.height = 10;
const context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, 10, 10);
window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 2, width: 10, height: 10, mime: "image/png", data: canvas.toDataURL().split(",")[1] });
});
await surface.locator("img").waitFor();
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} blank and painted browser pages`);
}
});
+100
View File
@@ -0,0 +1,100 @@
// The built-in browser: navigation, profiles, independence from the legacy package, same-tab view replacement, a plug-in sidebar, and settings.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/builtin', async ({ page }) => {
await mockTauri(page, {
commands: test => {
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
const check = Object.assign(test, { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] });
let next = 0;
const plugin = (id, name, version, hash) => ({ manifest: { schemaVersion: 1, id, name, author: 'Test', description: '', version, apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash, enabled: true, installedAt: 1, path: '', error: null, removal: false });
return {
browser_connect: () => 'window-session',
workspace_last_path: () => null,
'plugin:window|is_maximized': () => false,
plugins_snapshot: () => ({ root: 'test', plugins: [
plugin('org.test.boards', 'Boards', '0.1.0', 'fixture'),
...(check.legacy && !check.removed ? [plugin('runestone.browser', 'Browser', '0.1.6', 'old')] : []),
] }),
plugins_load: ({ id }) => {
check.loads.push(id);
if (id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.__TEST__.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.__TEST__.cleanups.push(id); };
}});
api.registerView({ id:'sidebar', title:'Sidebar fixture', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Plugin sidebar fixture'; }});
}`;
},
browser_request: ({ session, command, args }) => {
if (session !== 'window-session') throw Error('Missing browser session');
check.commands.push(command);
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; tab.title = 'Example'; }
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/builtin');
const external = () => page.evaluate(() => performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const editorKeys = module => page.evaluate(async module => {
const { get } = await import('/node_modules/.vite/deps/svelte_store.js');
return get((await import(module)).pluginEditors).map(view => view.key);
}, module);
try {
await page.goto(smokeUrl);
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.__TEST__.commands.includes('navigate'));
await page.getByRole('button', { name: 'Browser profile' }).click();
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
await page.keyboard.press('Escape');
const module = await external();
await page.evaluate(async module => { window.__TEST__.legacy = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.evaluate(() => window.__TEST__.loads.includes('runestone.browser')), false);
await page.evaluate(async module => { window.__TEST__.removed = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async module => { (await import(module)).openPluginView('org.test.boards', 'board-a'); }, module);
const before = await editorKeys(module);
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.__TEST__.mounts.includes('board-b') && window.__TEST__.cleanups.includes('board-a'));
assert.deepEqual(await editorKeys(module), before);
await page.getByRole('button', { name: 'Sidebar fixture', exact: true }).click();
await page.getByText('Plugin sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `builtin-browser-${theme}.png`) });
}
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Search engine', exact: true }).waitFor({ state: 'visible' });
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `browser-settings-${theme}.png`) });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
} catch (error) {
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
const { calls, emit, workspace, ...state } = window.__TEST__;
return { state, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}).catch(reason => ({ diagnosticError: String(reason) })), page.errors);
throw error;
}
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
}, { viewport: { width: 1280, height: 800 } });
+112
View File
@@ -0,0 +1,112 @@
// The browser engine as a separate download: links without an engine, the setup panel in a tab, progress, cancel,
// failure and retry, the switch to the page, and Settings → Browser → Browser engine, in both themes and a narrow window.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/engine', async ({ page }) => {
await mockTauri(page, {
commands: test => {
const status = { state: 'missing', version: '0.1.8', bytes: 160612374, received: 0, error: null };
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
let next = 0;
Object.assign(test, { status, opened: [], requests: [], confirms: [] });
const copy = () => structuredClone(status);
test.setEngine = value => { Object.assign(status, value); test.emit('browser-engine', copy()); };
return {
workspace_last_path: () => null,
'plugin:window|is_maximized': () => false,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
browser_connect: () => 'engine-session',
browser_stop: () => null,
browser_engine_status: copy,
browser_engine_install: () => { Object.assign(status, { state: 'downloading', received: 0, error: null }); return copy(); },
browser_engine_install_file: copy,
browser_engine_cancel: () => { Object.assign(status, { state: 'missing', received: 0 }); return copy(); },
browser_engine_remove: () => { Object.assign(status, { state: 'missing' }); return copy(); },
'plugin:opener|open_url': ({ url }) => { test.opened.push(url); return null; },
'plugin:dialog|message': ({ message }) => { test.confirms.push(message); return 'Remove'; },
browser_request: ({ session, command, args }) => {
if (session !== 'engine-session') throw Error('Missing browser session');
if (status.state !== 'installed') throw Error('The browser engine is not installed.');
test.requests.push(command);
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: args.url || 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'webData') return { profileId: args.profileId, cookies: [], history: [] };
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/engine');
const shots = async name => {
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await page.screenshot({ path: path.join(output, `${name}-${mode}.png`) });
}
};
const panel = page.locator('.engine.tab');
await page.goto(smokeUrl);
// The welcome page shows this button when the browser contribution exists.
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
// A web link without an engine goes to the system browser. The contribution reports that it did not open the link.
assert.equal(await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').open('https://example.com/link')), false);
assert.deepEqual(await page.evaluate(() => window.__TEST__.requests), [], 'A link does not start the engine.');
// "Open link in app browser" opens a tab with the setup panel and a way out to the system browser.
await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').newTab('https://example.com/docs'));
await panel.waitFor();
assert.equal(await panel.getAttribute('data-engine-state'), 'missing');
await panel.getByText('The engine is a separate download of 161 MB.', { exact: false }).waitFor();
await panel.getByRole('button', { name: 'Open in default browser' }).click();
await page.waitForFunction(() => window.__TEST__.opened.includes('https://example.com/docs'));
const download = panel.getByRole('button', { name: 'Download the engine' });
await download.focus();
assert.equal(await download.evaluate(element => element.matches(':focus-visible') || document.activeElement === element), true);
await shots('missing');
// Download, progress, and cancel.
await download.click();
await page.locator('.engine.tab[data-engine-state="downloading"]').waitFor();
await page.evaluate(() => window.__TEST__.setEngine({ received: 80306187 }));
await panel.getByText('80 MB of 161 MB', { exact: false }).waitFor();
assert.equal(await panel.locator('progress').evaluate(element => element.value), 80306187);
await shots('downloading');
await panel.getByRole('button', { name: 'Cancel' }).click();
await page.locator('.engine.tab[data-engine-state="missing"]').waitFor();
// A failed download shows its cause and Retry.
await page.evaluate(() => window.__TEST__.setEngine({ state: 'missing', error: 'The download stopped: the connection was reset.' }));
await panel.getByRole('alert').getByText('the connection was reset', { exact: false }).waitFor();
await panel.getByRole('button', { name: 'Retry' }).waitFor();
await shots('failed');
// After the installation, the same tab opens the page.
await panel.getByRole('button', { name: 'Retry' }).click();
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installing' }));
await page.locator('.engine.tab[data-engine-state="installing"]').waitFor();
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installed', error: null, received: 0 }));
await page.locator('[data-browser-state="ready"]').waitFor();
assert.equal(await panel.count(), 0);
assert.ok((await page.evaluate(() => window.__TEST__.requests)).includes('newTab'));
assert.equal(await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').open('https://example.com/link')), true);
// Settings → Browser: the installed engine, Remove with a confirmation, and the missing engine.
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installed' }));
await page.getByRole('button', { name: 'Browser', exact: true }).click();
const section = page.locator('.engine.settings');
await section.getByText('Version 0.1.8 is installed.').waitFor();
await page.getByRole('button', { name: 'Search engine', exact: true }).waitFor();
await shots('settings-installed');
await section.getByRole('button', { name: 'Remove engine' }).click();
await page.locator('.engine.settings[data-engine-state="missing"]').waitFor();
assert.match((await page.evaluate(() => window.__TEST__.confirms))[0], /Your profiles, bookmarks, and history stay/);
assert.equal(await page.getByRole('button', { name: 'Search engine', exact: true }).count(), 0, 'Settings that need the engine are hidden.');
await page.getByText('The other browser settings show after the engine is installed.').waitFor();
await page.setViewportSize({ width: 360, height: 800 });
await shots('settings-missing-narrow');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
console.log('Browser engine setup, progress, failure, install, links, and Settings checks passed.');
}, { viewport: { width: 1280, height: 800 } });
+162
View File
@@ -0,0 +1,162 @@
// Embedded browser fields with the real Electron engine: visible caret, page focus, toolbar blur, inputs, rich text, iframes, and navigation.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/fields', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/fields');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: path.join(output, `caret-${scale}x.png`) });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), scale, 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(page.errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await engine.stop();
await fixture.close();
}
});
+239
View File
@@ -0,0 +1,239 @@
// Embedded browser input with the real Electron engine: typing, clipboard, composition, page menus, autoscroll, input coalescing, and new tabs.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/interaction', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/interaction');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
// The browser toolbar has no new-tab button. The header globe button opens browser tabs
// (src/lib/layout/Workbench.svelte:1300; docs/user-guide.md:177).
assert.equal(await ready.getByRole('button', { name: /New browser tab/ }).count(), 0);
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
// Input reaches the engine asynchronously, so poll the page for up to five seconds before asserting.
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100 && await evaluate(code) !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
const initialBox = await surface.boundingBox();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'Hello World!Hello World!');
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
});
await expectRemote('document.querySelector("#typing").value.endsWith("日本語")', true);
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
await expectRemote('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart', 27);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
await page.keyboard.press('Escape');
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
// A new browser tab opens in front. Close it, so that the next steps use the first tab again.
async function expectTab(url) {
for (let attempt = 0; attempt < 100 && !(await rpc('state')).tabs.some(tab => tab.url === url); attempt++) await page.waitForTimeout(50);
assert.ok((await rpc('state')).tabs.some(tab => tab.url === url), `A new browser tab opens ${url}`);
await page.keyboard.press('Control+w');
for (let attempt = 0; attempt < 100 && (await rpc('state')).tabs.length > 1; attempt++) await page.waitForTimeout(50);
assert.equal((await rpc('state')).tabs.length, 1);
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
}
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Open image in new tab', exact: true }).click();
await expectTab(gifUrl);
// A middle-click on a link opens the link in a new tab instead of scrolling.
const linked = `${fixture.url}linked`;
await evaluate(`document.body.innerHTML='<a href="${linked}" style="position:absolute;left:40px;top:300px;display:block;width:200px;height:40px">Linked page</a>';true;`);
await page.mouse.click(initialBox.x + 100, initialBox.y + 320, { button: 'middle' });
await expectTab(linked);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A middle-click on a link does not keep scrolling');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
const wheelCount = () => commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
const beforeWheels = wheelCount();
await surface.evaluate(node => {
const bounds = node.getBoundingClientRect();
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
}));
});
await page.waitForTimeout(200);
const wheelBurstCalls = wheelCount() - beforeWheels;
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
// The marker draws the four-way scroll icon, not a text glyph that depends on the font.
const marker = page.locator('.scroll-anchor');
assert.equal(await marker.locator('svg path').count(), 1);
assert.equal(await marker.evaluate(node => node.textContent.trim()), '');
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).applyAppearance({ theme: 'default', mode }), theme);
await page.screenshot({ path: path.join(output, `scroll-marker-${theme}.png`), clip: { x: x - 30, y: y - 30, width: 60, height: 60 } });
}
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors: page.errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(350);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const motionCount = () => commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
const beforeMotion = motionCount();
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i = 0; i < 500; i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX: x + i % 20, clientY: y, bubbles: true })); }, { x, y });
await page.waitForTimeout(100);
const pointerBurstCalls = motionCount() - beforeMotion;
assert.ok(pointerBurstCalls < 10, `Pointer bursts must not queue hundreds of native calls: ${pointerBurstCalls}`);
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: path.join(output, `browser-interaction-${theme}.png`) });
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(page.errors, []);
await writeFile(path.join(output, `browser-interaction-${scale}x.json`), JSON.stringify({ decodedFps, scrolled, pointerBurstCalls, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
} finally {
await engine.stop();
await fixture.close();
}
});
+179
View File
@@ -0,0 +1,179 @@
// Embedded browser sharpness with the real Electron engine: frames map one page pixel to one host pixel at each display scale,
// a display scale change (a move to another monitor) updates the frame scale, and pointer input lands on the page point under it.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scales = process.env.BROWSER_TEST_SCALE ? [Number(process.env.BROWSER_TEST_SCALE)] : [1, 1.25, 1.5, 2];
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-scale-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/**
* Serve a page and return the markup of the scale fixture. The engine gateway blocks local addresses, so the test writes the markup into the page.
* The fixture has 1-device-pixel black and white columns in its top-left 200 by 100 CSS pixels, and text below them.
* `draw()` draws the columns again for the current pixel ratio. The page records the position of each click.
*/
async function startFixture() {
const html = `<!doctype html><title>Scale fixture</title><body style="margin:0;background:#fff;color:#111;font:14px sans-serif">
<canvas id="stripes" style="display:block;width:200px;height:100px"></canvas><p style="margin:8px">Sharp text: The quick brown fox jumps over the lazy dog. 0123456789</p>
<script>
function draw(){const c=document.getElementById('stripes'),r=devicePixelRatio;c.width=Math.round(200*r);c.height=Math.round(100*r);const g=c.getContext('2d');g.fillStyle='#fff';g.fillRect(0,0,c.width,c.height);g.fillStyle='#000';for(let x=0;x<c.width;x+=2)g.fillRect(x,0,1,c.height);}
draw();window.clicks=[];addEventListener('mousedown',e=>clicks.push([e.clientX,e.clientY]));
</script>`;
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end(html); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { html, url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
/**
* Return the mean absolute difference between horizontal neighbours in the stripe area of the frame image, read from a screenshot of the whole host page.
* The value is 255 for an exact copy of the page pixels. Resampling blends neighbours and lowers it.
* The test does not measure an element screenshot, because a clip at a fractional device pixel resamples the screenshot itself.
*/
async function stripeContrast(page, png, scale) {
return page.evaluate(async ({ data, scale }) => {
const box = document.querySelector('.surface img').getBoundingClientRect();
const left = Math.round(box.left * devicePixelRatio), top = Math.round(box.top * devicePixelRatio);
const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode();
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
const width = Math.round(180 * scale), row = context.getImageData(left, top + Math.round(50 * scale), width, 1).data;
let sum = 0;
for (let x = 0; x < width - 1; x++) sum += Math.abs(row[x * 4] - row[x * 4 + 4]);
return sum / (width - 1);
}, { data: png.toString('base64'), scale });
}
await runSmoke('browser/scale', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const output = await outputDir('browser/scale');
const report = {};
try {
for (const scale of scales) {
const context = await browser.newContext({ viewport: { width: 1000, height: 700 }, deviceScaleFactor: scale });
const page = engine.page = await openPage(context, { timeout: 30000 });
await page.exposeFunction('browserRpc', (command, args) => engine.rpc(command, args));
// Keep each resolution media query list of the host, so the test can report a scale change to the host page.
await page.addInitScript(() => { const native = matchMedia.bind(window); window.__resolutionQueries = []; window.matchMedia = query => { const list = native(query); if (query.includes('resolution')) window.__resolutionQueries.push(list); return list; }; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => engine.rpc('testEvaluate', { tabId, code });
await engine.rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
await evaluate(`document.open();document.write(${JSON.stringify(fixture.html)});document.close();true;`);
await page.locator('.browser:not(.blank)[data-browser-state="ready"] .surface img').waitFor();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
/**
* Wait for the lossless frame of the current scale, then measure and save the host pixels of the surface.
* `cdp` takes the screenshot through a CDP session with its own scale override, because a Playwright screenshot applies the context scale again.
*/
async function measure(expected, name, cdp) {
for (let attempt = 0; attempt < 100 && await evaluate('devicePixelRatio') !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate('devicePixelRatio'), expected, `The page pixel ratio follows the host at ${name}`);
// Emulation in the engine also changes the ratio without a media query event, so draw the columns again.
await evaluate('draw();true;');
await page.waitForTimeout(400);
await page.waitForFunction(() => document.querySelector('.surface img')?.src.startsWith('data:image/png'));
let png;
if (cdp) png = Buffer.from((await cdp.send('Page.captureScreenshot', { format: 'png' })).data, 'base64');
else {
await surface.screenshot({ path: path.join(output, `surface-${name}.png`) });
png = await page.screenshot();
}
await writeFile(path.join(output, `window-${name}.png`), png);
return stripeContrast(page, png, expected);
}
const contrast = await measure(scale, `${scale}x`);
assert.ok(contrast > 240, `Frames must not be resampled at ${scale}x: neighbour contrast ${contrast.toFixed(1)}`);
const box = await surface.boundingBox();
await evaluate('clicks.length=0;true;');
for (const [x, y] of [[37, 61], [412, 233]]) await page.mouse.click(box.x + x, box.y + y);
for (let attempt = 0; attempt < 100 && (await evaluate('clicks.length')) < 2; attempt++) await page.waitForTimeout(50);
const clicks = await evaluate('clicks');
// Native input uses whole device pixels, and the frame can start up to one device pixel inside the surface. Allow one CSS pixel.
assert.ok(clicks.length === 2 && clicks.every(([x, y], index) => Math.abs(x - [37, 412][index]) <= 1 && Math.abs(y - [61, 233][index]) <= 1),
`Clicks land on the page point under the pointer at ${scale}x: ${JSON.stringify(clicks)}`);
report[`${scale}x`] = { contrast, clicks };
if (scale === 1.5) {
// A move to a monitor with a different scale changes devicePixelRatio but not the CSS size of the surface.
// Emulation changes the pixel ratio without a media query change event, so the test sends the event that a real display change sends.
const cdp = await page.context().newCDPSession(page);
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 700, deviceScaleFactor: 1.25, mobile: false });
await page.evaluate(() => { for (const list of [...window.__resolutionQueries]) list.dispatchEvent(new Event('change')); });
const moved = await measure(1.25, '1.5x-to-1.25x', cdp);
assert.ok(moved > 240, `Frames must follow a display scale change: neighbour contrast ${moved.toFixed(1)}`);
report['1.5x-to-1.25x'] = { contrast: moved };
}
assert.deepEqual(page.errors, []);
engine.page = undefined;
await engine.rpc('closeTab', { tabId });
await context.close();
}
await writeFile(path.join(output, 'browser-scale.json'), JSON.stringify(report, null, 2));
console.log(`PASS browser frames are sharp at ${scales.join(', ')}x, follow a scale change, and keep pointer positions`);
} finally {
await engine.stop();
await fixture.close();
}
});
@@ -0,0 +1,98 @@
// Browser settings choice menus: keyboard selection and dismissal, saving, long profile lists, both themes, narrow layout, and cleanup.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/settingsMenus', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
// `requests` records browser requests; `calls` records every IPC command.
Object.assign(test, { snapshot, requests: [] });
return {
browser_connect: () => 'menu-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: ({ command, args = {} }) => {
test.requests.push({ command, ...args });
if (command === 'webData') return { profileId: args.profileId, cookies: [], history: [] };
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/settingsMenus');
const shot = name => page.screenshot({ path: path.join(output, name) });
const menu = name => page.getByRole('menu', { name, exact: true });
const trigger = name => page.getByRole('button', { name, exact: true });
await page.goto(smokeUrl + '/?settingsWindow=true');
await trigger('Browser').click();
await trigger('Search engine').waitFor();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await trigger('Search engine').focus();
await page.keyboard.press('Enter');
const engines = menu('Search engine');
await engines.waitFor();
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
await shot(`search-${mode}.png`);
await page.keyboard.press('End');
await page.keyboard.press('Space');
assert.equal(await trigger('Search engine').innerText(), 'Bing');
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
await trigger('Search engine').click();
await page.keyboard.press('Home');
await page.keyboard.press('Enter');
await trigger('Profile').focus();
await page.keyboard.press('Space');
await menu('Profile').waitFor();
await shot(`profile-${mode}.png`);
await page.keyboard.press('ArrowDown');
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('button[aria-label="Profile"]')?.textContent === 'Work');
await page.waitForFunction(() => window.__TEST__.requests.some(request => request.command === 'webData' && request.profileId === 'work'));
await trigger('Profile').click();
await page.keyboard.press('Home');
await page.keyboard.press('Enter');
await page.setViewportSize({ width: 520, height: 700 });
await trigger('Search engine').click();
const bounds = await engines.boundingBox();
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
await shot(`narrow-${mode}.png`);
await page.keyboard.press('Escape');
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
await page.setViewportSize({ width: 1100, height: 850 });
}
await trigger('Search engine').click();
await menu('Search engine').getByRole('menuitemradio', { name: 'Google', exact: true }).click();
// A choice applies at once (src/lib/browser/Settings.svelte).
await page.waitForFunction(() => window.__TEST__.snapshot.settings.search === 'google');
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.__TEST__.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
await page.setViewportSize({ width: 520, height: 700 });
await trigger('Profile').click();
const profiles = menu('Profile');
assert.equal(await profiles.evaluate(node => node.scrollHeight > node.clientHeight), true, 'Long profile lists scroll');
await page.keyboard.press('End');
assert.equal(await profiles.getByRole('menuitemradio', { name: 'Profile 59', exact: true }).evaluate(node => node === document.activeElement), true);
await shot('profile-long-narrow.png');
await page.keyboard.press('Escape');
assert.equal(await trigger('Profile').evaluate(node => node === document.activeElement), true);
await trigger('Profile').click();
await trigger('Profile').evaluate(node => {
let parent = node.parentElement;
while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
if (!parent) throw Error('Settings need a scroll area');
parent.scrollTop -= 40;
});
await profiles.waitFor({ state: 'detached' });
await trigger('Search engine').click();
await trigger('General').click();
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
}, { viewport: { width: 1100, height: 850 }, timeout: 30000 });
+205
View File
@@ -0,0 +1,205 @@
// Browser web data settings: cookie and history lists, filters, removal, profile isolation, stale-response guards, and narrow layouts.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, settle as settleFrames, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/webData', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
// `requests` records browser requests; `hold` keys delay a request until the test releases it.
const check = Object.assign(test, { data, snapshot, requests: [], hold: [], pending: [], failNext: {} });
return {
browser_connect: () => 'web-data-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: async ({ session, command: operation, args: details = {} }) => {
if (session !== 'web-data-session') throw Error('Missing browser session');
const key = `${operation}:${details.profileId}`;
check.requests.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/webData');
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('button', { name: 'Profile', exact: true });
async function selectProfile(id) {
await profile.click();
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
}
const kind = section.getByRole('button', { name: 'Web data type', exact: true });
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.__TEST__.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.__TEST__.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.__TEST__;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await settleFrames(page);
}
try {
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await selectKind('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await selectProfile('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await selectKind('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await selectProfile('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await selectProfile('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await selectProfile('user');
await settle();
const readsBefore = await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.innerText(), 'Personal');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 0);
await page.evaluate(() => { window.__TEST__.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.__TEST__.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.__TEST__.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.__TEST__.requests.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#fdfdfa' : '#151617');
for (const dataType of ['cookies', 'history']) {
await selectKind(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: path.join(output, `browser-web-data-${dataType}-${theme}.png`) });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
}
}
} catch (error) {
console.error(await page.locator('body').innerText());
throw error;
}
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
}, { viewport: { width: 1100, height: 850 } });
+53
View File
@@ -0,0 +1,53 @@
// A browser window (`?browserWindow=true`): it adopts the moved tab, starts no installed plugin,
// and calls only the commands that src-tauri/capabilities/browser.json grants.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/window', async ({ page }) => {
await mockTauri(page, {
label: 'browser-smoke',
commands: test => {
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'moved', profileId: 'user', url: 'https://example.com', title: 'Example', loading: false, blocked: 0, canBack: false, canForward: false, transferToken: 'token' }], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
let next = 0;
return {
browser_connect: () => 'window-session',
browser_stop: () => null,
browser_request: ({ session, command, args }) => {
if (session !== 'window-session') throw Error('Missing browser session');
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; }
return structuredClone(snapshot);
},
// An installed plugin that a browser window must not load.
plugins_snapshot: () => ({ root: 'test', plugins: [{ manifest: { schemaVersion: 1, id: 'org.test.tasks', name: 'Tasks', author: 'Test', description: '', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'tasks', enabled: true, installedAt: 1, path: '', error: null, removal: false }] }),
spelling_menu_install: () => null,
spelling_menu_uninstall: () => null,
'plugin:window|is_maximized': () => false,
};
},
});
await page.goto(smokeUrl + '/?browserWindow=true&browserTab=moved');
await page.getByRole('application', { name: 'RuneStone browser' }).waitFor();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.org');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.keyboard.press('Control+t');
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'browser_request' && call.args.command === 'newTab'));
const capability = JSON.parse(await readFile(path.join(repoRoot, 'src-tauri/capabilities/browser.json'), 'utf8'));
const granted = new Set(capability.permissions);
const calls = await page.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
assert(!calls.includes('plugins_load'), 'A browser window loads no installed plugin.');
const missing = calls.filter(command => {
const plugin = /^plugin:([^|]+)\|(.+)$/.exec(command);
// core:default grants the event plugin and the read-only window commands. Window actions need their own permission.
if (plugin) return plugin[1] === 'window' && /^(destroy|close|minimize|toggle_maximize|start_dragging)$/.test(plugin[2])
? !granted.has(`core:window:allow-${plugin[2].replaceAll('_', '-')}`) : !['event', 'window', 'webview', 'app'].includes(plugin[1]);
return !granted.has(`allow-${command.replaceAll('_', '-')}`);
});
assert.deepEqual(missing, [], 'Every command of the browser window is in capabilities/browser.json.');
console.log(`Browser window commands: ${calls.join(', ')}`);
}, { viewport: { width: 1100, height: 750 } });
@@ -0,0 +1,87 @@
// Checklist entry: keyboard marker editing, checkbox toggles, and pasted HTML tables in both themes and a narrow layout.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/checklistEntry", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
}),
spelling_menu_install: () => null,
}),
});
const output = await outputDir("editor/checklistEntry");
await page.goto(smokeUrl);
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 source = '# Clipboard and tasks\n\n- [ ] CCNA lab\n- [x] CCNA course\n\nPaste here.\n';
const reset = async () => page.evaluate(source => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.indexOf('CCNA lab') } });
window.__CM__.focus();
}, source);
const count = () => page.locator('.writer-checkbox').count();
const clipboard = '<html><body><!--StartFragment--><table><thead><tr><th>Ticker</th><th>Name</th></tr></thead><tbody><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></tbody></table><!--EndFragment--></body></html>';
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
for (const width of [1440, 600]) {
if (width === 600) {
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
}
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
await reset();
assert.equal(await count(), 2, 'Caret at task text keeps both checkboxes');
await page.screenshot({ path: `${output}/${mode}-${width}-task-text.png` });
await page.keyboard.press('ArrowLeft');
assert.equal(await count(), 1, 'ArrowLeft from text reveals the marker');
await page.screenshot({ path: `${output}/${mode}-${width}-task-marker.png` });
await page.keyboard.press('Home');
assert.equal(await count(), 1, 'Home keeps the marker editable');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('Delete');
await page.keyboard.type('x');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[x\] CCNA lab/);
await page.keyboard.press('Home');
for (let i = 0; i < 6; i++) await page.keyboard.press('ArrowRight');
assert.equal(await count(), 2, 'Leaving the marker restores the checkbox');
await page.keyboard.type('New ');
assert.equal(await count(), 2, 'Typing task text keeps the checkbox');
await page.locator('.writer-checkbox').first().click();
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[ \] New CCNA lab/);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('Paste here.') } }); view.focus();
});
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, html) => {
const data = new DataTransfer(); data.setData('text/html', html); data.setData('text/plain', 'Ticker\tName\nADBE.US\tAdobe\nADSK.US\tAutodesk');
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}, clipboard);
await page.locator('.live-writer table').waitFor();
const pasted = await page.evaluate(() => window.__CM__.state.sliceDoc());
assert.doesNotMatch(pasted, /Fragment|<!--|-->/);
assert.match(pasted, /\| Ticker \| Name \|/);
assert.equal(await page.locator('.live-writer table tr').count(), 3);
await page.screenshot({ path: `${output}/${mode}-${width}-table-paste.png` });
if (width === 600) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
}
}
}
});
+83
View File
@@ -0,0 +1,83 @@
// Code blocks: editing fenced and indented code in the Writer, with undo, cursor movement, preview, and save.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/codeBlocks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
await page.goto(smokeUrl);
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);
}
console.log("PASS: Fenced and indented code editing, character deletion, selection deletion, cursor movement, undo, preview and save.");
});
+87
View File
@@ -0,0 +1,87 @@
// Dividers: thematic break syntax, width, source editing, keyboard navigation, selection, undo, and save.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/dividers", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
const output = await outputDir("editor/dividers");
await page.goto(smokeUrl);
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();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
const dividers = "content\n___\ncontent\n***\n\n---\n\n* * *\n\n_ _ _\n\n- - -\n\nHeading\n---\n\n`___`\n\n```text\n___\n```\n\n ***\n\nEnd\n";
await page.evaluate(async value => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } });
}, dividers);
await page.waitForFunction(() => document.querySelectorAll(".writer-divider").length === 6);
assert.equal(await page.getByRole("separator").and(page.locator(".writer-divider")).count(), 6);
const dividerStyle = await page.locator(".writer-divider").first().evaluate(node => ({
width: node.getBoundingClientRect().width,
lineWidth: node.parentElement.getBoundingClientRect().width,
border: getComputedStyle(node, "::after").borderTopWidth,
color: getComputedStyle(node, "::after").borderTopColor,
}));
assert.ok(Math.abs(dividerStyle.width - dividerStyle.lineWidth) < 2);
assert.equal(dividerStyle.border, "1px");
assert.notEqual(dividerStyle.color, "rgba(0, 0, 0, 0)");
await page.setViewportSize({ width: 1100, height: 900 });
await page.screenshot({ path: `${output}/markdown-dividers.png` });
await page.locator(".writer-divider").first().click();
assert.equal(await page.locator(".writer-divider").count(), 5);
assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___");
await page.keyboard.press("End");
await page.keyboard.press("Backspace");
await page.keyboard.press("Control+Home");
assert.equal(await page.locator(".writer-divider").count(), 5);
assert.ok((await writer.textContent()).includes("__"));
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+Home");
assert.equal(await page.locator(".writer-divider").count(), 6);
await page.keyboard.press("ArrowDown");
assert.equal(await page.locator(".writer-divider").count(), 5);
assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___");
await page.keyboard.press("Control+a");
assert.equal(await page.locator(".writer-divider").count(), 0);
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), dividers);
await page.keyboard.press("Control+Home");
assert.equal(await page.locator(".writer-divider").count(), 6);
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, dividers);
await page.evaluate(() => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "Above\n\n ___\n\n> ***\n\nEnd" }, selection: { anchor: 0 } });
});
assert.equal(await page.locator(".writer-divider").count(), 2);
for (const divider of await page.locator(".writer-divider").all()) {
assert.ok(await divider.evaluate(node => node.getBoundingClientRect().right <= node.parentElement.getBoundingClientRect().right + 1));
}
console.log("PASS: Divider syntax, width, source editing, keyboard navigation, selection, undo and save.");
});
+115
View File
@@ -0,0 +1,115 @@
// Writer text menu on empty and whitespace lines: submenus, disabled actions, links, the file picker, keyboard focus, both themes, a narrow window, and the Source.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/emptyMenu", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"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 output = await outputDir("editor/emptyMenu");
await page.goto(smokeUrl);
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 menu = () => page.getByRole('menu', { name: 'Markdown text actions', exact: true });
async function setSource(value, anchor = 0, head = anchor) {
await page.evaluate(({value,anchor,head}) => window.__CM__.dispatch({changes:{from:0,to:window.__CM__.state.doc.length,insert:value},selection:{anchor,head}}), {value,anchor,head});
}
async function openKeyboard() { await page.locator('.cm-content').focus(); await page.keyboard.press('Shift+F10'); await menu().waitFor(); }
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); }, theme);
await setSource('');
await page.locator('.cm-line').first().click({button:'right'});
await menu().waitFor();
for (const label of ['Add link','Add external link Ctrl+K','Format','Paragraph','Insert','Paste Ctrl+V','Paste as plain text','Select all Ctrl+A']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
assert.equal(await menu().getByRole('menuitem',{name:'Cut Ctrl+X',exact:true}).isDisabled(),true);
assert.equal(await menu().getByRole('menuitem',{name:'Copy Ctrl+C',exact:true}).isDisabled(),true);
await page.screenshot({path:`${output}/empty-${theme}.png`});
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
await page.keyboard.press('ArrowRight');
const format = page.getByRole('menu',{name:'Format',exact:true});
for (const label of ['Bold Ctrl+B','Italic Ctrl+I','Strikethrough Ctrl+Shift+X','Highlight Ctrl+Shift+H','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
await page.screenshot({path:`${output}/format-${theme}.png`});
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Escape');
assert.equal(await page.locator('.cm-content').evaluate(el=>el===document.activeElement),true);
await openKeyboard();
await menu().getByRole('menuitem',{name:'Paragraph',exact:true}).click();
await page.getByRole('menu',{name:'Paragraph',exact:true}).getByRole('menuitem',{name:'Heading 6',exact:true}).click();
assert.equal(await source(),'###### ');
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Insert',exact:true}).click();
await page.screenshot({path:`${output}/insert-${theme}.png`});
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
assert.match(await source(),/^```\nCode\n```/);
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await source(),'[]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1);
assert.equal(await page.getByRole('dialog').count(),0);
await setSource('label',0,5); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await source(),'[label]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8);
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.screenshot({path:`${output}/workspace-picker-${theme}.png`});
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
assert.equal(await source(),'[[/notes/second.md]]');
await setSource('Keep this text'); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).waitFor();
await page.keyboard.press('Escape');
await page.getByRole('dialog').waitFor({state:'detached'});
assert.equal(await source(),'Keep this text');
await setSource('Populated paragraph\n\n');
await page.locator('.cm-line').last().click({button:'right'});
await menu().waitFor();
await page.keyboard.press('Escape');
await setSource('');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:420});
await page.locator('.cm-scroller').click({button:'right',position:{x:60,y:180}});
await menu().waitFor();
const box = await menu().boundingBox(); assert.ok(box.x>=8 && box.y>=8 && box.x+box.width<=552 && box.y+box.height<=412);
await page.screenshot({path:`${output}/narrow-${theme}.png`});
await page.keyboard.press('Escape');
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Show outline',exact:true}).click();
}
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Shift+F10');
await menu().waitFor();
await menu().getByRole('menuitem',{name:'Add external link Ctrl+K',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
await page.locator('.source-editor .cm-content').focus();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await page.keyboard.press('Shift+F10');
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
await page.screenshot({path:`${output}/ide-links.png`});
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and Source.');
});
+126
View File
@@ -0,0 +1,126 @@
// Footnotes and heading folds: the footnote menu, Reader numbering and backlinks, nested folding, keyboard toggles, and source preservation.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/footnotes", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
const output = await outputDir("editor/footnotes");
await page.goto(smokeUrl);
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();
async function editor() {
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
await editor();
const source = "# First section\n\nParent text.[^long]\n\n## Child section\n\nChild content.\n\n### Nested section\n\nNested content.\n\n# Second section\n\nSecond content.[^long]\n\n## Last section\n\nFinal content.\n\n[^long]: A **bold** footnote.\n Continued on another line.\n";
async function setSource(value) {
await page.evaluate(value => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }), value);
}
await setSource(source);
const structural = "# Parent\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n```md\n# Not a heading\n```\n\n## Child\n\nText\n\n# Next\n\nNext text\n";
await setSource(structural);
assert.equal(await page.getByRole("button", { name: "Collapse Not a heading", exact: true }).count(), 0);
await page.getByRole("button", { name: "Collapse Parent", exact: true }).click();
assert.equal(await page.locator(".writer-table").count(), 0);
assert.equal(await page.getByRole("button", { name: "Collapse Child", exact: true }).count(), 0);
await page.getByRole("button", { name: "Expand Parent", exact: true }).click();
await page.locator(".writer-table").waitFor();
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), structural);
await setSource("Setext heading\n==============\n\nBody\n\n# Next\n\nNext body");
await page.getByRole("button", { name: "Collapse Setext heading", exact: true }).click();
await page.getByRole("button", { name: "Expand Setext heading", exact: true }).click();
await setSource(source);
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
assert.equal(await page.locator(".cm-content").textContent().then(text => text.includes("Child content.")), false);
await page.getByRole("button", { name: "Collapse First section", exact: true }).click();
assert.equal(await page.getByRole("button", { name: "Expand Child section", exact: true }).count(), 0);
await page.getByRole("button", { name: "Expand First section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: "Collapse Child section", exact: true }).waitFor();
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Collapse Child section');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), source);
// Insert from the real shared menu and edit the selected definition.
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 20 } }); window.__CM__.focus(); });
await page.keyboard.press("Shift+F10");
await page.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await page.getByRole("menuitem", { name: "Footnote", exact: true }).click();
await page.keyboard.type("New footnote");
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /\[\^1\]: New footnote/);
await page.keyboard.press("Control+z");
await setSource(source);
for (const theme of ["light", "dark"]) {
await page.evaluate(async theme => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode: theme }); }, theme);
await page.setViewportSize({ width: 760, height: 900 });
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
const bounds = button.getBoundingClientRect();
const pane = button.closest('.cm-scroller').getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
await page.screenshot({ path: `${output}/writer-${theme}-narrow.png` });
await page.keyboard.press("Space");
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
assert.ok(borders.every(border => border === "0px"));
assert.ok(await page.locator(".writer-heading").first().evaluate(heading => parseFloat(getComputedStyle(heading).paddingTop) > 8));
await chooseView(page, "Read");
await page.locator(".md-footnotes").waitFor();
assert.equal(await page.locator(".md-footnote-ref").count(), 2);
assert.equal(await page.locator(".md-footnotes li").count(), 1);
assert.equal(await page.locator(".md-footnote-back").count(), 2);
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
const bounds = button.getBoundingClientRect();
const pane = button.closest('.reading').parentElement.getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
assert.equal(await page.locator(".md-page").getByText("Child content.", { exact: true }).isVisible(), false);
await page.screenshot({ path: `${output}/reader-${theme}-narrow.png` });
await page.keyboard.press("Space");
assert.equal(await page.locator(".md-page").getByText("Child content.", { exact: true }).isVisible(), true);
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
await page.locator(".md-footnote-ref a").first().click();
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
await page.locator(".md-footnote-back").first().click();
assert.equal(await page.evaluate(() => document.activeElement?.id), "rs-fnref-1-1");
await chooseView(page, "Write");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
await editor();
}
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, source);
console.log("PASS: footnote menu, Writer edits, Reader numbering and backlinks, nested folding, keyboard toggles, source preservation, light/dark narrow screenshots.");
});
@@ -0,0 +1,153 @@
// Images dragged from the file tree: hidden source, selection, image menu actions, cancel, and source mode.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/imageNavigation", async ({ page }) => {
await mockTauri(page, {
commands: test => {
// Image files hold base64 SVG.
const svg = btoa('<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>');
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "Above.\n\nBelow.\n",
"notes/second.md": "# Second note\n",
"src/hello.py": "print('hello')\n",
"images/picture (#1).svg": svg,
"images/replacement.svg": svg,
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
workspace_reveal: () => null,
};
},
});
const output = await outputDir("editor/imageNavigation");
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();
}
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.goto(smokeUrl);
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: `${output}/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 chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
await dragFromTree(".source-editor .cm-content");
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);
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
});
+251
View File
@@ -0,0 +1,251 @@
// Image drops and pastes: unique attachments, live source, zoom, delayed writes, source mode, and undo.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/images", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
// Image files hold base64 SVG. Tests set `delay` to hold a write until `resume()`, or `failWrite` to reject it.
workspace_write_bytes: async args => {
if (test.delay) await new Promise(resolve => { test.resume = resolve; });
if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64);
},
// The download of a copied web image. The host adds the extension of the downloaded format.
workspace_save_image_url: args => {
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
const rel = args.rel + ".gif";
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
return rel;
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
};
},
});
const output = await outputDir("editor/images");
async function openNote(name = "welcome.md") {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator(".cm-content").waitFor();
}
async function source() {
return page.evaluate(() => window.__CM__.state.doc.toString());
}
async function save() {
await page.keyboard.press("Control+s");
await page.waitForTimeout(100);
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
}
async function drop(count = 1, selector = ".cm-content") {
await page.locator(selector).evaluate((element, count) => {
const data = new DataTransfer();
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
}, count);
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await openNote();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } });
});
const original = await source();
const acceptsDrag = await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg"));
const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data });
element.dispatchEvent(event); return event.defaultPrevented;
});
assert.ok(acceptsDrag);
await drop(2);
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2);
await page.locator(".md-image-frame img").first().waitFor();
assert.equal(await page.locator(".md-image-frame img").count(), 2);
const inserted = await source();
assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor");
const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]);
assert.notEqual(paths[0], paths[1]);
assert.ok(paths.every(path => path.startsWith("../attachments/")));
assert.equal(await save(), inserted);
// Selecting and editing Markdown leaves the image visible and updates its alt text.
await page.locator(".md-image-frame").first().hover();
await page.getByRole("button", { name: "Edit image source", exact: true }).first().click();
assert.equal(await page.locator(".md-image-frame img").count(), 2);
assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0])));
await page.evaluate(() => {
const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2;
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
});
await page.locator('img[alt="Edited alt"]').waitFor();
await page.screenshot({ path: `${output}/images-editing.png` });
await page.locator(".md-image-frame").first().hover();
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
const zoom = page.getByRole("dialog", { name: "Image zoom" });
await zoom.waitFor();
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
await page.screenshot({ path: `${output}/images-zoom.png` });
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("dialog").count(), 0);
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in");
// Undo the alt edit and the complete drop as separate operations.
await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
assert.equal(await source(), original);
await page.keyboard.press("Control+y");
assert.equal(await source(), inserted);
// Type and move the cursor during a slow import; the drop follows its original position.
await page.evaluate(() => { window.__TEST__.delay = true; });
await drop();
await page.waitForFunction(() => !!window.__TEST__.resume);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } });
window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null;
});
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3);
assert.ok((await source()).startsWith("Typed while saving.\n\n![]"));
// Typed local image paths load without changing views, including wiki syntax.
await page.evaluate(path => {
window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]);
const view = window.__CM__;
view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } });
}, "../attachments/typed.svg");
await page.locator('img[alt="Wiki image"]').waitFor();
await save();
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Write", exact: true }).focus();
await page.keyboard.press("End");
await page.locator(".md-page .md-image-frame").first().hover();
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
await page.keyboard.press("Escape");
// Source uses the same drop flow. The batch is one undo step.
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Read", exact: true }).focus();
await page.keyboard.press("Home");
await page.keyboard.press("Control+e");
await page.locator(".source-editor .cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
});
const sourceBefore = await source();
await drop(2, ".source-editor .cm-content");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 5);
await page.keyboard.press("Control+z");
assert.equal(await source(), sourceBefore);
await page.keyboard.press("Control+y");
assert.equal((await save()).match(/!\[\]/g).length, 5);
// A failed write leaves source unchanged and surfaces an error.
const beforeFailure = await source();
await page.evaluate(() => { window.__TEST__.failWrite = true; });
await drop(1, ".source-editor .cm-content");
await page.getByText("Image write failed", { exact: true }).waitFor();
assert.equal(await source(), beforeFailure);
await page.evaluate(() => { window.__TEST__.failWrite = false; });
// File drops over a rendered widget are handled by the editor's capture listener.
await page.keyboard.press("Control+e");
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"));
});
await drop(1, ".md-image-frame img >> nth=0");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6);
// Switching tabs while a write is pending cannot insert into the new document.
await page.evaluate(() => { window.__TEST__.delay = true; });
await drop();
await page.waitForFunction(() => !!window.__TEST__.resume);
await openNote("second.md");
await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); });
await page.waitForTimeout(100);
assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/"));
// Clipboard images are inserted and remain a single undo operation too.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'], "pasted.svg", { type: "image/svg+xml" }));
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
});
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
// A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
async function pasteWebImage(src) {
await page.locator(".cm-content").evaluate((element, src) => {
const data = new DataTransfer();
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
const writesBefore = await writes();
await pasteWebImage("https://media.example.com/cat.gif?size=large&amp;v=2");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
assert.equal(await writes(), writesBefore);
// When the download fails, the still copy stays.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
assert.equal(await writes(), writesBefore + 1);
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
// An empty file from a browser drag gives a message, not a broken image.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
});
await page.getByText("The image file is empty.", { exact: false }).waitFor();
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
});
+129
View File
@@ -0,0 +1,129 @@
// Writer interactions: code selection and copy, caret and scroll restore, Ctrl+click links, shared heading typography, and spelling targets.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/interactions", async ({ page }) => {
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\editor-interactions-smoke",
files: {
"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",
},
}),
"plugin:opener|open_url": () => null,
spelling_menu_install: () => null,
}),
});
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; });
}
await page.goto(smokeUrl);
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/);
// A selection inside a code block shows its source and hides the copy button (src/lib/editor/liveMarkdown.ts:246-247).
// Move the caret out of the block, as a reader would before copying.
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); });
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.__TEST__.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".source-editor .cm-content").waitFor();
const linkPoint = await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
const position = view.state.doc.toString().indexOf("[Local]") + 3;
view.dispatch({ selection: { anchor: position }, scrollIntoView: true }); view.focus();
return position;
});
await page.waitForTimeout(300);
const point = await page.evaluate(async position => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const coords = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content")).coordsAtPos(position);
return { x: coords.left + 2, y: (coords.top + coords.bottom) / 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 Source 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();
const output = await outputDir("editor/interactions");
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: `${output}/editor-typography-${theme}.png` });
await chooseView(page, "Read");
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: `${output}/reader-typography-${theme}.png` });
await chooseView(page, "Write");
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
// The outline gives way below 1100 pixels (UI-052). A click on "Hide outline" would race that change.
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
await page.screenshot({ path: `${output}/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 });
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
}, { viewport: { width: 1280, height: 900 }, timeout: 15000 });
@@ -0,0 +1,67 @@
// Mouse drag selection across a heading and a rendered link keeps the layout stable and selects the hidden link syntax.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/linkSelection", async ({ page }) => {
page.setDefaultTimeout(15000);
// The original mock returned null for commands it did not handle.
await mockTauri(page, {
strict: false,
commands: test => ({
...test.workspace({ root: "C:\\tab-menu-workspace", files: { "a.md": "# Links\n\nOriginal text.\n" }, folders: ["notes"] }),
workspace_search: () => [],
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_suggestions: () => ({ language: "en-US", words: [], misspelled: false }),
"plugin:dialog|message": () => "Cancel",
}),
});
const output = await outputDir("editor/linkSelection");
async function reset(text) {
await page.locator(".cm-content").evaluate(async (node, text) => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
view.focus();
}, text);
}
async function selected() {
return page.locator(".cm-content").evaluate(async node => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(node), range = view.state.selection.main;
return view.state.sliceDoc(range.from, range.to);
});
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Files", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
for (const theme of ["dark", "light"]) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.evaluate(async mode => (await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode }), theme);
for (const link of ["[gpt-oss-120b-heretic](https://huggingface.co/kldzj/gpt-oss-120b-heretic)", "[[models/gpt-oss-120b-heretic|gpt-oss-120b-heretic]]"]) {
const heading = "### Agentic Coding (DeepSWE 1.1)";
const text = "Outside.\n\n" + heading + "\n" + link + "\n\nEnd.";
for (const reverse of [false, true]) {
await reset(text);
const title = await page.locator(".cm-line").filter({ hasText: "Agentic Coding" }).boundingBox();
const label = await page.locator(".writer-link").boundingBox();
const start = { x: title.x + 1, y: title.y + title.height / 2 };
const end = { x: label.x + label.width + 2, y: label.y + label.height / 2 };
await page.mouse.move(reverse ? end.x : start.x, reverse ? end.y : start.y);
await page.mouse.down();
await page.mouse.move(reverse ? start.x : end.x, reverse ? start.y : end.y, { steps: 12 });
await page.mouse.up();
assert.equal(await selected(), heading + "\n" + link, `${theme}/${width}/${reverse}/${link}`);
await page.screenshot({ path: path.join(output, `${theme}-${width}-${reverse}-${link.startsWith("[[") ? "wiki" : "markdown"}.png`) });
}
await reset(text);
await page.locator(".writer-link").click({ position: { x: 30, y: 8 } });
assert.equal(await selected(), "", "A click places the caret without selecting the link");
assert.equal(await page.locator(".writer-link-source").count(), 1);
}
}
});
+116
View File
@@ -0,0 +1,116 @@
// List nesting: Tab and Shift+Tab in Write, nested labels in Write and Read, one undo history in Write and Source, and the 4-space indent in Source.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/listNesting", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/readme.md": "# Requirements\n\n1. Topic\n2. \n3. A\n",
"src/hello.py": "print('hello')\n",
},
}),
spelling_menu_install: () => null,
}),
});
const output = await outputDir("editor/listNesting");
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
async function open(name, editor) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("textbox", { name: 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 doc = () => page.evaluate(() => window.__CM__.state.doc.toString());
const caretAt = (text, offset = text.length) => page.evaluate(([text, offset]) => {
window.__CM__.dispatch({ selection: { anchor: window.__CM__.state.doc.toString().indexOf(text) + offset } });
window.__CM__.focus();
}, [text, offset]);
const labels = () => page.locator(".live-writer .writer-list-label").allTextContents();
await open("readme.md", "Writing editor");
await caretAt("2. ");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. \n2. A\n", "Tab nests the empty item and renumbers the next item");
assert.deepEqual(await labels(), ["a."], "The nested item shows a letter before it has text");
await page.keyboard.type("Sub item");
await page.keyboard.press("Enter");
await page.keyboard.type("Second");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n");
assert.deepEqual(await labels(), ["a.", "b."]);
for (const width of [1440, 600]) {
if (width === 600) {
await page.getByRole("button", { name: "Files", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
}
await page.setViewportSize({ width, height: 800 });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => (await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode }), mode);
await page.locator(".live-writer .cm-content").screenshot({ path: `${output}/writer-${mode}-${width}.png` });
}
}
await page.setViewportSize({ width: 1440, height: 900 });
await page.locator(".live-writer .cm-content").focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n2. Second\n3. A\n", "Shift+Tab moves the item up and renumbers the outer list");
assert.deepEqual(await labels(), ["a."]);
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "One undo step restores the nesting and the numbers");
await caretAt("1. Topic");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "The first item stays in place");
await chooseView(page, "Read");
await page.locator(".md-page ol ol").waitFor();
assert.equal(await page.locator(".md-page ol ol").evaluate(list => getComputedStyle(list).listStyleType), "lower-alpha");
assert.equal(await page.locator(".md-page > .reading > ol, .md-page ol").first().evaluate(list => getComputedStyle(list).listStyleType), "decimal");
await page.locator(".md-page").screenshot({ path: `${output}/reader.png` });
await chooseView(page, "Write");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
// Write and Source share the undo history of the document.
await caretAt("2. A");
await page.keyboard.type(" more");
await page.keyboard.press("Control+e");
await page.locator('.source-editor[data-chrome="Source"] .cm-gutters').waitFor();
assert.equal(await page.locator(".source-editor .cm-content").getAttribute("data-language"), "markdown");
await page.locator(".source-editor .cm-content").focus();
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A\n", "Source undoes the last edit from Write");
await page.keyboard.press("Control+Shift+KeyZ");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A more\n");
await caretAt("2. A more");
await page.keyboard.press("Tab");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n 3. A more\n", "Tab nests list items in Source too");
await page.keyboard.press("Control+e");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
assert.deepEqual(await labels(), ["a.", "b.", "c."]);
// Source indents code to the next 4-column stop.
await open("hello.py", "Editor");
await caretAt("print", 0);
await page.keyboard.press("Tab");
assert.equal(await doc(), " print('hello')\n");
await caretAt("print", 2);
await page.keyboard.press("Tab");
assert.equal(await doc(), " pr int('hello')\n", "Tab inside a line fills to the next stop");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
assert.equal(await doc(), "print('hello')\n");
await page.locator(".source-editor").screenshot({ path: `${output}/source-ide.png` });
// The history of a document stays while its tab stays open.
await open("readme.md", "Writing editor");
await page.locator(".live-writer .cm-content").focus();
await page.keyboard.press("Control+z");
assert.equal(await doc(), "# Requirements\n\n1. Topic\n 1. Sub item\n 2. Second\n2. A more\n", "Undo after a tab change reverts the Tab from Source");
console.log("PASS: Tab and Shift+Tab nesting, renumbering, Write labels, Read letters, shared undo in Write and Source and across tabs, Source list Tab, and 4-space code indent.");
});
+155
View File
@@ -0,0 +1,155 @@
// Markdown text menu in source and writing modes: formatting, paragraphs, tables, links, extraction, clipboard, and stale selections.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/markdownMenu", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
const output = await outputDir("editor/markdownMenu");
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "View", exact: true }).click();
await page.getByRole("menuitemradio", { name: "Source", exact: true }).click();
await page.locator(".source-editor .cm-content").waitFor();
}
async function waitForText(text) {
await page.evaluate(async () => { window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView; });
await page.waitForFunction(expected => [...document.querySelectorAll(".cm-content")].some(node => window.__EditorView.findFromDOM(node)?.state.doc.toString() === expected), text);
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const source = "First paragraph.\n\nSecond paragraph.\n";
await page.evaluate(async value => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: value } });
view.dispatch({ selection: { anchor: 0, head: 5 } }); view.focus();
}, source);
const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
await page.keyboard.press("Shift+F10");
await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Bold Ctrl+B", exact: true }).click();
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z"); await waitForText(source);
await page.getByRole("tab", { selected: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "View", exact: true }).click();
await page.getByRole("menuitemradio", { name: "Write", exact: true }).click();
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10"); await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Italic Ctrl+I", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Heading 2", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("## First paragraph."));
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+End");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Table", exact: true }).click();
await page.locator(".live-writer table").waitFor();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
// Mouse invocation must preserve the selection, too.
await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } });
await menu.waitFor();
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
await menu.getByRole("menuitem", { name: "Highlight Ctrl+Shift+H", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph."));
await page.keyboard.press("Control+End");
await page.locator(".writer-highlight").waitFor();
assert.equal(await page.locator(".writer-highlight").textContent(), "First");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+End");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await page.screenshot({ path: `${output}/markdown-insert-menu.png` });
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 760, height: 600 });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
await writer.focus();
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).focus();
await page.keyboard.press("ArrowRight");
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list");
const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox();
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600);
await page.screenshot({ path: `${output}/markdown-paragraph-menu.png` });
await page.keyboard.press("ArrowLeft");
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+Home");
await page.keyboard.press("Control+Shift+ArrowRight");
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Add external link Ctrl+K", exact: true }).click();
// External links insert `[label]()` with the caret in the URL, without a dialog (src/lib/editor/markdownMenu.ts:57, src/lib/editor/linkCommands.ts:3-8).
assert.equal(await page.getByRole("dialog").count(), 0);
await page.keyboard.type("https://example.com/a");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a) paragraph."));
// Undo the typed URL, then the link, which restores the selected label.
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+z");
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await page.waitForFunction(() => window.__CM__.state.sliceDoc().startsWith("First paragraph."));
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click();
await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[[/notes/extracted.md|First]] paragraph."));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/extracted.md")), "First\n");
await page.keyboard.press("Control+z");
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
await page.evaluate(() => navigator.clipboard.writeText("Pasted"));
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
await page.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Pasted paragraph."));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("Pasted paragraph."));
await page.evaluate(() => { navigator.clipboard.readText = () => new Promise(resolve => { window.__finishPaste = resolve; }); });
await page.keyboard.press("Shift+F10");
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
await writer.focus(); await page.keyboard.press("End"); await page.keyboard.type(" kept");
await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); });
assert.ok(!(await writer.textContent()).includes("STALE"));
assert.ok((await writer.textContent()).includes("kept"));
console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards.");
});
@@ -0,0 +1,54 @@
// Pasting large Markdown keeps the source exact and renders every bold span.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/markdownPaste", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
}),
});
await page.goto(smokeUrl);
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/.vite/deps/@codemirror_view.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
for (const count of [3, 1000, 5000]) {
const result = await page.evaluate(async count => {
const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js");
const view = window.__CM__;
const source = Array.from({ length: count }, (_, i) => "## Heading " + i + "\n\n**Bold** and *italic*\n\n").join("");
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } });
view.focus();
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", source);
view.contentDOM.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }));
view.dispatch({ selection: { anchor: 0 } });
// Import the module URL that the app loaded, so the language state is the same instance.
const languageUrl = performance.getEntriesByType("resource").map(entry => entry.name).find(name => new URL(name).pathname === "/node_modules/.vite/deps/@codemirror_language.js");
const { forceParsing, syntaxTree } = await import(languageUrl);
forceParsing(view, view.state.doc.length, 5000);
const nodes = [];
syntaxTree(view.state).iterate({ enter(node) { if (node.name === "StrongEmphasis") nodes.push(node.from); } });
const marks = [];
for (const set of view.state.facet(EditorView.decorations)) {
if (typeof set !== "function") set.between(0, view.state.doc.length, (from, to, decoration) => { if (decoration.spec.class === "writer-strong") marks.push(from); });
}
return { correctSource: view.state.sliceDoc() === source, nodes: nodes.length, marks: marks.length };
}, count);
console.log({ count, ...result });
assert.equal(result.correctSource, true);
assert.equal(result.nodes, count);
assert.equal(result.marks, count);
}
});
+98
View File
@@ -0,0 +1,98 @@
// Repeated copy and paste of formatted Markdown stays exact across saves, tab switches, Source switches, and line endings.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/pasteRepeat", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
async function open(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors: page.errors }); throw error; }
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
const formatted = '# Copied heading\n\n## Links\n\n[Reference](https://example.com) and [[second|Another note]]\n\n**Bold**, *italic*, and `code`.\n\n- A list item\n';
await page.evaluate(text => { window.__TEST__.files.set('notes/source.md', text); window.__TEST__.files.set('notes/pasted.md', ''); }, formatted);
await open('source.md');
await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+c');
await open('pasted.md');
await writer();
for (let iteration = 0; iteration < 12; iteration++) {
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await expectWriter('');
await page.keyboard.press('Control+v');
await expectWriter(formatted);
assert.equal(await page.locator('.live-writer .cm-editor').count(), 1, 'One mounted editor');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('notes/pasted.md').replace(/\r\n?/g, '\n')), formatted);
if (iteration === 5) {
await page.keyboard.press('Control+e');
await page.locator('.source-editor .cm-content').waitFor();
await page.keyboard.press('Control+e');
await expectWriter(formatted);
}
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'pasted.md', exact: true }).click();
await expectWriter(formatted);
}
// Clipboard formats can use different line endings than the destination.
for (const lineBreak of ['\n', '\r\n', '\r']) {
await page.evaluate(({ text, lineBreak }) => {
const view = window.__WRITER__;
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
const clipboardData = new DataTransfer();
clipboardData.setData('text/plain', text.replace(/\n/g, lineBreak));
view.contentDOM.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }));
}, { text: formatted, lineBreak });
await expectWriter(formatted);
assert.equal(await page.evaluate(() => window.__WRITER__.state.doc.lines), formatted.split('\n').length);
await page.keyboard.press('Control+s');
// The saved file keeps one line break. The Writer text with that line break is the saved source.
const synchronized = await page.evaluate(() => {
const saved = window.__TEST__.files.get('notes/pasted.md');
const lineBreak = saved.includes('\r\n') ? '\r\n' : '\n';
return window.__WRITER__.state.doc.sliceString(0, undefined, lineBreak) === saved;
});
assert.equal(synchronized, true, 'Writer and saved source agree');
}
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, Source reopen, and LF/CRLF/CR clipboard replacement');
});
+56
View File
@@ -0,0 +1,56 @@
// Front matter properties: first open, editing, undo, the saved selection, and both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/properties", async ({ page }) => {
await mockTauri(page, {
commands: test => test.workspace({
root: "C:\\smoke-workspace",
files: {
"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 output = await outputDir("editor/properties");
await page.goto(smokeUrl);
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.locator('.md-properties').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 original = await page.evaluate(() => window.__CM__.state.sliceDoc());
assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.head), original.indexOf('\n\n') + 1);
await page.locator('.md-properties summary').click();
assert.equal(await page.locator('.md-properties').getAttribute('open'), '');
assert.match(await page.locator('.md-properties pre').textContent(), /title: Welcome/);
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => {
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
applyAppearance({ theme: 'default', mode });
}, mode);
await page.setViewportSize({ width: 760, height: 900 });
await page.screenshot({ path: `${output}/properties-${mode}-narrow.png` });
}
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
assert.equal(await page.locator('.md-properties').count(), 0);
await page.keyboard.type('New ');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /title: New Welcome/);
await page.keyboard.press('Control+z');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), original);
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: window.__CM__.state.doc.length } }));
await page.locator('.md-properties').waitFor();
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
await chooseView(page, 'Read');
await page.locator('.reading .md-properties').waitFor();
await chooseView(page, 'Write');
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
assert.equal(await page.locator('.writer-preview .md-properties').count(), 0);
console.log('Properties first-open, editing, undo, saved selection, and both themes passed.');
});
@@ -0,0 +1,145 @@
// Scrolling in Write and Read through a large document with large tables, images, code blocks, and short lines keeps the text in place.
import assert from "node:assert/strict";
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
const words = "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua".split(" ");
const text = (seed, count) => Array.from({ length: count }, (_, i) => words[(seed * 7 + i * 3) % words.length]).join(" ");
/** A short first heading holds the caret when the document opens. Short code lines and fences have another line height than prose. */
function largeDocument() {
const parts = ["# Large\n"];
for (let section = 0; section < 10; section++) {
parts.push(`## Section ${section}\n`, `Short line ${section}\n`, " \n");
for (let p = 0; p < 5; p++) parts.push(`P${section}.${p} ${text(section + p, 30 + (p * 37) % 90)}\n`);
const rows = Array.from({ length: 25 + (section * 17) % 50 }, (_, r) => `| T${section}R${r} | ${text(r, 2)} | ${text(section + r, 6 + (r * 11) % 50)} |`);
parts.push(["| Row | Name | Description |", "| --- | --- | --- |", ...rows].join("\n") + "\n");
if (section % 2 === 0) parts.push(`![Picture ${section}](img${section}.svg)\n`);
if (section % 3 === 0) parts.push("```python\nx = 1\ny = 2\n```\n");
parts.push(`- item ${section} one\n- item ${section} two\n`);
}
return parts.join("\n");
}
await runSmoke("editor/scrollStability", async ({ page }) => {
await mockTauri(page, {
state: { source: largeDocument() },
commands: test => {
const svg = (width, height) => btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="#336"/></svg>`);
const files = { "notes/large.md": test.state.source };
for (let section = 0; section < 10; section += 2) files[`notes/img${section}.svg`] = svg(1400, 700 + section * 60);
const workspace = test.workspace({ root: "C:/smoke-workspace", files });
return {
...workspace,
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
};
},
});
await page.setViewportSize({ width: 1440, height: 1000 });
/** Wheel over the view. After each tick lands, the text must be where the tick put it. Returns the ticks where the text moved by itself, and the document heights. */
async function wheel(selector, delta, ticks) {
const box = await page.locator(selector).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.evaluate(selector => {
const scroller = document.querySelector(selector);
const unique = /^s*(Td+Rd+|Pd+.d+|Short line d+|item d+ (?:one|two)|Section d+)/;
const keyOf = element => unique.exec(element.textContent || "")?.[1] ?? "";
const items = () => [...scroller.querySelectorAll(".cm-line, tr, .reading p, .reading h2, .reading li")];
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
const atEdge = () => scroller.scrollTop <= 0 || scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;
let tracked = null;
window.__scroll = {
jumps: [], heights: [],
before(delta) {
const area = scroller.getBoundingClientRect(), margin = Math.abs(delta) + 60;
const element = items().find(item => { const rect = item.getBoundingClientRect(); return rect.height > 0 && rect.top >= area.top + margin && rect.top <= area.bottom - margin && keyOf(item); });
tracked = element ? { element, key: keyOf(element), top: element.getBoundingClientRect().top, delta, scrollTop: scroller.scrollTop } : null;
},
// A tick can land some frames later on a busy computer. Wait for it, then for the layout passes of the editor.
async after() {
for (let waited = 0; tracked && scroller.scrollTop === tracked.scrollTop && waited < 60; waited++) await frame();
for (let settled = 0; settled < 3; settled++) await frame();
this.heights.push(scroller.scrollHeight);
if (atEdge()) return true;
if (!tracked) return false;
const element = tracked.element.isConnected ? tracked.element : items().find(item => keyOf(item) === tracked.key);
if (!element) this.jumps.push(`${tracked.key} left the view`);
else {
const moved = Math.round(element.getBoundingClientRect().top - (tracked.top - tracked.delta));
if (Math.abs(moved) > 4) this.jumps.push(`${tracked.key} moved ${moved}`);
}
return false;
},
};
}, selector);
for (let tick = 0; tick < ticks; tick++) {
await page.evaluate(delta => window.__scroll.before(delta), delta);
await page.mouse.wheel(0, delta);
if (await page.evaluate(() => window.__scroll.after()) && tick > 0) break;
}
return page.evaluate(() => ({ jumps: window.__scroll.jumps, heights: window.__scroll.heights }));
}
const jump = (selector, fraction) => page.evaluate(({ selector, fraction }) => { const scroller = document.querySelector(selector); scroller.scrollTop = scroller.scrollHeight * fraction; }, { selector, fraction });
await page.goto(smokeUrl);
await page.getByText(/smoke-workspace/).first().waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("large.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "large.md" }).first().click();
await page.locator(".cm-content").waitFor();
await page.waitForTimeout(400);
// Text that was not on screen yet: the heights are estimates until the first draw.
await jump(".cm-scroller", .6);
await page.waitForTimeout(300);
const first = await wheel(".cm-scroller", -200, 120);
assert.deepEqual(first.jumps, [], "Wheel up through new tables and images");
const spread = heights => Math.max(...heights) - Math.min(...heights);
// Line heights are estimates, but tables and images have their heights before the first draw.
assert.ok(spread(first.heights) < Math.max(...first.heights) * .05, `The document keeps about its height at the first draw: ${Math.min(...first.heights)} to ${Math.max(...first.heights)}`);
// Text that was drawn before: images and tables come back with their heights.
await jump(".cm-scroller", 0);
await page.waitForTimeout(200);
const down = await wheel(".cm-scroller", 400, 130);
assert.deepEqual(down.jumps, [], "Wheel down to the end");
const up = await wheel(".cm-scroller", -400, 130);
assert.deepEqual(up.jumps, [], "Wheel up to the start");
assert.ok(spread(up.heights) < 200, `The document keeps its height on the way back: ${Math.min(...up.heights)} to ${Math.max(...up.heights)}`);
// A short heading with the caret and a code block with the caret have another line height too.
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
const heading = view.state.doc.toString().indexOf("## Section 3");
view.dispatch({ selection: { anchor: heading + 3 }, scrollIntoView: true });
});
await page.waitForTimeout(300);
const caret = await wheel(".cm-scroller", 300, 25);
assert.deepEqual(caret.jumps, [], "Wheel down with the caret in a short heading");
assert.ok(spread(caret.heights) < 200, `The document keeps its height with the caret in a short heading: ${Math.min(...caret.heights)} to ${Math.max(...caret.heights)}`);
// Images in Write keep their space before they load.
const image = page.locator(".cm-content img[data-md-src]").first();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
view.scrollDOM.scrollTop = view.lineBlockAt(view.state.doc.toString().indexOf("![Picture 0]")).top;
});
await image.waitFor();
assert.equal(await image.getAttribute("width"), "1400");
assert.equal(await image.getAttribute("height"), "700");
// Read shows the same document without virtual lines.
await chooseView(page, "Read");
await page.locator(".md-page > .reading").waitFor();
await page.waitForTimeout(300);
await jump(".md-page", .6);
await page.waitForTimeout(300);
const reading = await wheel(".md-page", -300, 60);
assert.deepEqual(reading.jumps, [], "Wheel up in Read");
assert.equal(await page.locator(".md-page img[data-md-src]").first().getAttribute("height"), "700", "Images in Read keep their space before they load");
}, { timeout: 30000 });
@@ -0,0 +1,47 @@
// Text selection uses --rs-selection in Writer (native and CodeMirror layers) and in Read view, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "editor/selectionColor";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\selection-color", files: { "sample.md": "# Selection sample\n\nThe same text color applies to each editor.\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
await page.goto(smokeUrl);
await page.getByText("selection-color", { exact: true }).waitFor();
await page.evaluate(async theme => (await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode: theme }), theme);
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("sample.md");
await page.getByRole("textbox", { name: "Find a file" }).press("Enter");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
await writer.click();
await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const probe = document.createElement("span");
probe.style.backgroundColor = "var(--rs-selection)";
node.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
return { expected, native: getComputedStyle(node, "::selection").backgroundColor,
layer: getComputedStyle(document.querySelector(".cm-selectionBackground")).backgroundColor };
});
assert.equal(colors.native, colors.expected);
assert.equal(colors.layer, colors.expected);
await page.screenshot({ path: path.join(output, `${theme}-writer-selection.png`) });
await chooseView(page, "Read");
const reader = page.locator(".reading");
await reader.waitFor();
assert.equal(await reader.evaluate(node => getComputedStyle(node, "::selection").backgroundColor), colors.expected);
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} Writer and Read view selection`);
}
});
+133
View File
@@ -0,0 +1,133 @@
// Editor menu surfaces: Writer, spelling, Source, and code menus share the file menu styles; and the code tint match in both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/surfaces", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`;
return {
...test.workspace({
root: "C:\\tab-menu-workspace",
files: { ...Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, note(name)])), "sample.txt": "const answer = 42;\n" },
folders: ["notes"],
}),
spelling_menu_install: () => null,
spelling_suggestions: ({ word }) => ({ language: "en-US", words: ["Corrected"], misspelled: word === "Original" }),
};
},
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = await outputDir("editor/surfaces");
const report = [];
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const styles = panel => panel.evaluate(node => {
const row = node.querySelector(':scope > button');
const a = getComputedStyle(node), b = getComputedStyle(row);
return [a.backgroundColor, a.borderRadius, a.padding, b.minHeight, b.padding, b.font];
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
for (const theme of ['dark', 'light']) {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const canvas = document.createElement('canvas');
canvas.width = 800; canvas.height = 600;
const c = canvas.getContext('2d');
const g = c.createLinearGradient(0, 0, 800, 600);
g.addColorStop(0, '#628ba8'); g.addColorStop(1, '#b47796');
c.fillStyle = g; c.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: .15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await page.locator('[data-tree-rel="a.md"]').click({ button: 'right' });
const reference = await styles(menu('File actions'));
await dismiss();
const text = page.getByText('Original text.', { exact: true });
await text.click({ button: 'right', position: { x: 20, y: 8 } });
const writer = menu('Markdown text actions');
assert.deepEqual(await styles(writer), reference);
for (const name of ['Add link', 'Add external link Ctrl+K', 'Format', 'Paragraph', 'Insert', 'Paste Ctrl+V', 'Select all Ctrl+A']) assert.equal(await item(name).count(), 1);
await item('Corrected').waitFor();
assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu');
assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected');
await page.screenshot({ path: `${output}/writer-menu-${theme}.png` });
await item('Corrected').focus(); await page.keyboard.press('Enter');
await page.getByText('Corrected text.', { exact: true }).waitFor();
await page.keyboard.press('Control+z');
await text.waitFor();
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await text.click({ button: 'right', position: { x: 20, y: 8 } });
await item('Corrected').waitFor();
await page.keyboard.press('Home');
assert.equal(await item('Corrected').evaluate(node => node === document.activeElement), true);
const spellingBounds = await writer.boundingBox();
assert.ok(spellingBounds.x >= 8 && spellingBounds.x + spellingBounds.width <= 552);
await page.screenshot({ path: `${output}/spelling-narrow-${theme}.png` });
await page.keyboard.press('Enter');
await page.getByText('Corrected text.', { exact: true }).waitFor();
await page.keyboard.press('Control+z');
await text.waitFor();
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
assert.deepEqual(await styles(writer), reference, 'Blank space uses the same actions');
await item('Format').focus(); await page.keyboard.press('ArrowRight');
await item('Bold Ctrl+B').click();
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
await page.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
assert.equal(await page.locator('.cm-content').textContent().then(s => s.includes('**')), false, 'Undo reverses the menu edit');
const tint = await page.locator('.writer-code-line').first().evaluate(node => getComputedStyle(node).backgroundColor);
assert.ok(tint.includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(tint), `Writer code tint: ${tint}`);
await page.screenshot({ path: `${output}/writer-code-${theme}.png` });
await chooseView(page, 'Read');
const readingTint = await page.locator('pre.md-code').evaluate(node => getComputedStyle(node).backgroundColor);
assert.equal(readingTint, tint, 'Reader and Writer use the same code tint');
await page.screenshot({ path: `${output}/reader-code-${theme}.png` });
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
assert.deepEqual(await styles(writer), reference, 'Markdown Source retains the same menu');
await dismiss();
await page.locator('[data-tree-rel="sample.txt"]').click();
await page.locator('.source-editor').click({ button: 'right', position: { x: 500, y: 400 } });
const code = menu('Code text actions');
assert.deepEqual(await styles(code), reference, 'Code Source uses the host menu');
// The host menu is the only menu. The editor adds no menu of its own.
assert.equal(await page.getByRole('menu').count(), 1);
assert.equal(await code.getByRole('menuitem', { name: 'Command palette F1', exact: true }).count(), 0);
await page.screenshot({ path: `${output}/ide-menu-${theme}.png` });
await dismiss();
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await page.locator('.source-editor').click({ button: 'right', position: { x: 100, y: 300 } });
await code.waitFor();
const bounds = await code.boundingBox();
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 560);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).evaluate(n => n === document.activeElement), true);
await page.screenshot({ path: `${output}/ide-narrow-${theme}.png` });
await page.keyboard.press('Enter');
await code.waitFor({ state: 'detached' });
// The keyboard choice runs the action: the selection covers the whole file.
assert.equal(await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
return view.state.selection.main.from === 0 && view.state.selection.main.to === view.state.doc.length;
}), true);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('[data-tree-rel="a.md"]').click();
await chooseView(page, 'Write');
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/Source parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'narrow keyboard menu'], nativeDesktop: 'not tested' });
}
console.log(JSON.stringify(report, null, 2));
}, { timeout: 15000 });
@@ -0,0 +1,101 @@
// Note templates and task lines: template creation, filename focus, task entry, checkbox toggles, lone hyphens, and Setext headings.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/templatesAndTasks", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
// The tree hides the root .runestone folder; its templates folder stays listable.
workspace_list: args => workspace.workspace_list(args).filter(entry => args.rel || entry.rel_path !== ".runestone"),
};
},
});
const output = await outputDir("editor/templatesAndTasks");
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
// Save the empty task lines from the reported template, then create through
// the normal note action so the filename receives the initial focus.
await page.evaluate(async () => {
const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts');
await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10));
});
await page.getByRole('button', { name: 'New tab (Ctrl+T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).last().click();
await page.getByRole('menuitem', { name: 'To Do', exact: true }).click();
const title = page.getByRole('textbox', { name: 'Note filename', exact: true });
await title.waitFor();
await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Note filename');
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const count = () => page.locator('.writer-checkbox').count();
const expectCount = async expected => {
await page.waitForFunction(expected => document.querySelectorAll('.writer-checkbox').length === expected, expected);
assert.equal(await count(), expected);
};
const setSource = source => page.evaluate(source => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.length } });
window.__CM__.focus();
}, source);
const plain = 'Some generic mobs or factions,\n-';
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
for (const width of [1440, 600]) {
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
// The side panes give way in a narrow window and come back in a wide one (src/lib/layout/Workbench.svelte).
await page.waitForFunction(width => !!document.querySelector('aside.left') === width >= 800, width);
if (!(await title.isVisible())) await page.getByRole('button', { name: 'Rename note', exact: true }).click();
await title.focus();
await expectCount(10);
await page.screenshot({ path: `${output}/${mode}-${width}-template-title.png` });
await page.keyboard.press('Escape');
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: 0 } }); view.focus();
});
await expectCount(9);
await page.keyboard.press('End');
await page.keyboard.type('First task');
await expectCount(10);
await page.locator('.writer-checkbox').first().click();
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /^- \[x\] First task/);
await page.screenshot({ path: `${output}/${mode}-${width}-template-edit.png` });
await setSource(plain);
assert.equal(await page.locator('.writer-h2').count(), 0, 'A lone hyphen must not enlarge preceding prose');
await page.screenshot({ path: `${output}/${mode}-${width}-single-hyphen.png` });
await page.keyboard.type(' Item');
assert.equal(await page.locator('.writer-h2').count(), 0, 'The hyphen continues into a list');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), plain + ' Item');
await setSource(plain + '-');
assert.equal(await page.locator('.writer-h2').count(), 1, 'Two hyphens retain Setext heading support');
await setSource('A normal heading\n===\n');
assert.equal(await page.locator('.writer-h1').count(), 1);
// Restore the template for the next theme and size without an active body caret.
await setSource('- [ ] \n'.repeat(10));
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
if (width === 600) {
await page.setViewportSize({ width: 1440, height: 1000 });
}
}
}
console.log('PASS: template creation, filename focus, keyboard task entry, checkbox toggle, lone hyphen, list continuation, and Setext headings in both themes and narrow layouts.');
});
+125
View File
@@ -0,0 +1,125 @@
// Undo history survives tab switches, window focus, Source edits, and table cell edits.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/undoHistory", async ({ page }) => {
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
test.files = workspace.files;
return {
...workspace,
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
};
},
});
async function open(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors: page.errors }); throw error; }
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('welcome.md');
const original = await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' first edit');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+s');
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
console.log('PASS: saved Writer edit survives tab switch with undo and redo');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
assert.equal(await page.evaluate(() => window.__WRITER__.state.selection.main.head), (original + ' first edit').length);
console.log('PASS: Writer undo and redo survive window focus refresh and restore the caret');
await page.keyboard.press('Control+e');
await page.locator('.source-editor .cm-content').waitFor();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
view.dispatch({ selection: { anchor: view.state.doc.length } });
view.focus();
window.__IDE__ = view;
});
await page.keyboard.type(' second edit');
assert.equal(await page.evaluate(() => window.__IDE__.dom.isConnected), true, 'Typing keeps the same Source editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.state.doc.toString()), original + ' first edit second edit');
await page.keyboard.press('Control+e');
await expectWriter(original + ' first edit second edit');
await page.locator('.cm-content').click();
// One burst of typing is one undo step, in Source as in Write.
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second edit');
console.log('PASS: Writer undo includes edits from Source mode');
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
await page.evaluate(source => {
window.__TEST__.files.set('table.md', source);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table.md'] });
}, tableSource);
await open('table.md');
await writer();
const cells = page.locator('.writer-table tbody td');
await cells.nth(0).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Alpha');
await cells.nth(1).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Beta');
await page.keyboard.press('Escape');
const editedTable = await writer();
assert.ok(editedTable.includes('Alpha') && editedTable.includes('Beta'));
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await writer();
await page.getByRole('tab', { name: 'table.md', exact: true }).click();
await writer();
await page.keyboard.press('Control+z');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+z');
await expectWriter(tableSource);
await page.keyboard.press('Control+y');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+y');
await expectWriter(editedTable);
console.log('PASS: table cell typing stays grouped per cell across tab switches');
});
+228
View File
@@ -0,0 +1,228 @@
// The native Background feature (src/lib/features/background/): a folder slideshow with mocked host commands, a fade,
// reduced motion, Next and Pause from the command palette, the targets, translucent menus and hover fills with an image,
// opaque menus and hover fills with Background off, a browser window, the settings section in both themes and at
// 360 pixels, the image source, and the first-start migration from seeded plugin settings and from a seeded image.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const SETTINGS_FILE = "runestone.smoke.settings-file";
const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=";
/**
* The host commands of the image folder (src-tauri/src/backgrounds.rs). Each image is a PNG of one color.
* The mock runs this function in the page, so it uses only `test`. `test.state.legacy` is an old plugin package.
*/
function folderCommands(test) {
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
return {
...test.workspace({ root: "C:\\background-feature", files: { "note.md": "# Note\n\nText.", "other.md": "# Other" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
spelling_menu_install: () => null,
spelling_menu_uninstall: () => null,
background_folder: () => test.state.folder,
background_choose_folder: () => test.state.folder,
background_clear_folder: () => { test.state.folder = null; return null; },
background_list: () => test.state.names,
background_read: async ({ name }) => {
const [width, height] = name.startsWith("portrait") ? [300, 600] : [640, 400];
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext("2d");
context.fillStyle = test.state.colors[name] ?? "#808080"; context.fillRect(0, 0, width, height);
return (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer();
},
background_read_sidecar: () => test.state.sidecar,
background_write_sidecar: ({ contents, expected }) => {
if (expected !== test.state.sidecar) throw "The sidecar file changed. Read it again before you save.";
test.state.sidecar = contents;
return null;
},
background_migrate: () => test.state.folder,
features_legacy: ({ ids }) => test.state.legacy ? ids.filter(id => id === test.state.legacy.id).map(() => test.state.legacy) : [],
browser_connect: () => "background-session",
browser_stop: () => null,
browser_request: () => structuredClone(snapshot),
};
}
const folderState = { folder: "D:\\Backgrounds", names: ["a.png", "b.png", "portrait.png"], colors: { "a.png": "#3a6ea5", "b.png": "#a5533a", "portrait.png": "#4f8a4b" }, sidecar: null };
const image = page => page.evaluate(() => document.body.style.getPropertyValue("--rs-background-image"));
const waitForChange = (page, old) => page.waitForFunction(old => { const value = document.body.style.getPropertyValue("--rs-background-image"); return value.includes("blob:") && value !== old; }, old, { timeout: 15000 });
async function command(page, title) {
await page.keyboard.press("Control+Shift+P");
const palette = page.getByRole("dialog", { name: "Commands", exact: true });
await palette.getByRole("textbox", { name: "Find a command", exact: true }).fill(title);
await palette.getByRole("button").filter({ hasText: title }).first().waitFor();
await page.keyboard.press("Enter");
}
// The open file shows the selection tint, so the hover check uses the other file.
async function hoverBackground(page) {
const row = page.locator('[data-tree-rel="other.md"]');
await row.hover();
return row.evaluate(node => getComputedStyle(node).backgroundColor);
}
async function menuBackground(page) {
await page.locator('[data-tree-rel="note.md"]').click({ button: "right" });
const menu = page.getByRole("menu", { name: "File actions", exact: true });
await menu.waitFor();
const color = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
await page.keyboard.press("Escape");
return color;
}
await runSmoke("features/background", async ({ browser }) => {
const output = await outputDir("features/background");
// A folder slideshow of 2 seconds, from a settings file that exists before the start.
const context = await browser.newContext({ viewport: { width: 1200, height: 820 } });
await mockTauri(context, { state: folderState, commands: folderCommands });
await context.addInitScript(([key, file]) => { if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(file)); }, [SETTINGS_FILE, {
schema: 1, revision: 1, features: { git: true, background: true },
background: { source: "folder", seconds: 2, order: "name", paused: false, targets: ["app"], overlay: 0.1, position: "center", size: "cover" },
}]);
const main = await openPage(context);
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="note.md"]').waitFor();
await waitForChange(main, "");
const first = await image(main);
assert.match(first, /rgba\(0,0,0,0\.1\)/, "The folder overlay applies");
// The timer shows the next image with a fade of 2 seconds.
await waitForChange(main, first);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 1, "The image fades in");
assert.notEqual(await main.evaluate(() => document.body.style.getPropertyValue("--rs-background-previous-image")), "none");
await main.screenshot({ path: path.join(output, "folder-fade.png") });
// Pause keeps the image. Next still works. The same command resumes.
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === true);
const paused = await image(main);
await main.waitForTimeout(3000);
assert.equal(await image(main), paused, "A paused slideshow keeps its image");
await command(main, "Next background image");
await waitForChange(main, paused);
// The folder has a portrait image after b.png. It shows in full over a blurred fill.
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-layer-sizes") === "100% 100%, contain, cover", null, { timeout: 15000 });
await main.screenshot({ path: path.join(output, "portrait.png") });
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === false);
// Reduced motion: the next image shows without a fade.
await main.emulateMedia({ reducedMotion: "reduce" });
const before = await image(main);
await command(main, "Next background image");
await waitForChange(main, before);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 0, "Reduced motion has no fade");
await main.emulateMedia({ reducedMotion: "no-preference" });
// With an image, menus use the surface transparency (82% by default) and blur it. Hover fills and the workspace button
// are a thin veil, so the image stays visible (UI-061).
assert.match(await menuBackground(main), /0\.82/);
const translucent = /(\/ 0\.06\)|, 0\.06\))$/;
assert.match(await hoverBackground(main), translucent, "A hovered row keeps the image visible");
assert.match(await main.locator(".workspace-button").evaluate(node => getComputedStyle(node).backgroundColor), translucent, "The workspace button keeps the image visible");
await main.screenshot({ path: path.join(output, "hover-over-image.png") });
// Targets: only the boards removes the workspace frame. The frame of all boards stays for Project Management.
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["pm-all"] }));
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.equal(await main.evaluate(async () => !!(await import("/src/lib/plugins/backgrounds.ts")).backgroundHub.get("pm-all")), true);
assert.match(await menuBackground(main), /^rgb\(/, "Without a workspace image, menus are opaque");
assert.match(await hoverBackground(main), /^rgb\(/, "Without a workspace image, hover fills are opaque");
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["app"] }));
await waitForChange(main, "");
// A browser window shows the background behind a blank tab, and calls only the commands that browser.json grants.
const browserPage = await openPage(context);
await mockTauri(browserPage, { label: "browser-background", state: folderState, commands: folderCommands });
await browserPage.goto(smokeUrl + "/?browserWindow=true");
await browserPage.getByRole("application", { name: "RuneStone browser" }).waitFor();
assert.equal(await browserPage.evaluate(() => window.__TEST__.label), "browser-background");
await browserPage.waitForFunction(() => getComputedStyle(document.querySelector(".workarea-background")).backgroundImage.includes("blob:"), null, { timeout: 15000 });
await browserPage.screenshot({ path: path.join(output, "browser-window.png") });
const granted = new Set(JSON.parse(await readFile(path.join(repoRoot, "src-tauri/capabilities/browser.json"), "utf8")).permissions);
const calls = await browserPage.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
for (const call of calls.filter(name => name.startsWith("background_"))) assert(granted.has(`allow-${call.replaceAll("_", "-")}`), `browser.json grants ${call}`);
assert(calls.includes("background_read"), "The browser window reads the folder images");
await browserPage.close();
// The settings section in both themes and at 360 pixels.
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const section = settings.locator(".background-settings");
await section.waitFor();
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Folder");
assert.equal(await settings.getByRole("textbox", { name: "Image folder", exact: true }).inputValue(), "D:\\Backgrounds");
await settings.getByRole("status").filter({ hasText: "3 images." }).waitFor();
assert.equal(await settings.evaluate(async () => (await import("/src/lib/features/loader.ts")).featureRequested("background")), true, "The section loads the feature module");
assert.equal(await settings.evaluate(() => document.body.style.getPropertyValue("--rs-background-image")), "", "The slideshow does not run in the settings window");
await settings.locator("summary").filter({ hasText: "Per-image appearance" }).click();
await settings.getByRole("button", { name: "Image fit", exact: true }).waitFor();
await settings.waitForFunction(() => !document.querySelector('button[aria-label="Image fit"]').disabled);
for (const theme of ["dark", "light"]) {
await settings.evaluate(async mode => { const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ ...readAppearance(), theme: "default", mode }); }, theme);
for (const width of [1100, 360]) {
// A tall window shows the whole section, also the targets below the per-image editor.
await settings.setViewportSize({ width, height: 1800 });
await section.scrollIntoViewIfNeeded();
assert.equal(await settings.locator(".content").evaluate(node => node.scrollWidth <= node.clientWidth + 1), true, `No horizontal scroll at ${width} pixels`);
await section.screenshot({ path: path.join(output, `settings-${theme}-${width}.png`) });
}
}
await settings.setViewportSize({ width: 1100, height: 900 });
// The per-image editor saves only the changed values of the selected image.
await settings.getByRole("button", { name: "Image fit", exact: true }).click();
await settings.getByRole("menuitemradio", { name: "Fit", exact: true }).click();
await settings.getByRole("button", { name: "Save image appearance", exact: true }).click();
await settings.getByRole("status").filter({ hasText: "Image appearance saved." }).waitFor();
assert.deepEqual(JSON.parse(await settings.evaluate(() => window.__TEST__.state.sidecar)), { schema: 1, images: { "a.png": { fit: "contain" } } });
// Off applies at once in every window: the image goes away, and menus are opaque again.
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.match(await menuBackground(main), /^rgb\(/, "With Background off, menus are opaque");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await settings.getByText("Background is off. Turn it on in Settings → Features.", { exact: true }).waitFor();
await settings.screenshot({ path: path.join(output, "settings-off.png") });
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await waitForChange(main, "");
assert.deepEqual([...main.errors, ...settings.errors], []);
await context.close();
// The image source and the migration from a seeded image: the old image of Appearance shows without a timer.
const imageContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
await mockTauri(imageContext, { commands: test => ({ ...test.workspace({ root: "C:\\background-image", files: { "note.md": "# Note" } }), plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }) }) });
await imageContext.addInitScript(image => { if (!localStorage.getItem("runestone.smoke.settings-file")) localStorage.setItem("runestone.appearance", JSON.stringify({ theme: "default", mode: "dark", newTabBackground: { image, overlay: 0.2, position: "top", size: "contain" } })); }, `data:image/png;base64,${PNG}`);
const imagePage = await openPage(imageContext);
await imagePage.goto(smokeUrl);
await waitForChange(imagePage, "");
assert.deepEqual(await imagePage.evaluate(() => window.__TEST__.settings("background")), { source: "image", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" });
assert.equal(await imagePage.evaluate(() => document.body.style.getPropertyValue("--rs-background-position")), "top", "The image keeps its own layout");
assert.equal(await imagePage.evaluate(() => window.__TEST__.calls.some(call => call.command === "background_migrate")), false, "Without a plugin grant, no folder migrates");
assert.deepEqual(imagePage.errors, []);
await imageContext.close();
// The migration from the kept settings of an enabled Background Slideshow plugin.
const migrationContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
const legacy = { id: "runestone.bg-slideshow", installed: true, enabled: true,
settings: { grant: "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90", folder: "D:\\Old", enabled: true, seconds: 7, order: "random", targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" } };
await mockTauri(migrationContext, { state: { ...folderState, folder: "D:\\Old", legacy }, commands: folderCommands });
const migrated = await openPage(migrationContext);
await migrated.goto(smokeUrl);
await waitForChange(migrated, "");
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" });
// Each feature gets its switch. Background is on, and Git follows its old package (none here).
const switches = await migrated.evaluate(() => window.__TEST__.settings("features"));
assert.equal(switches.background, true);
assert.equal(switches.git, true);
assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1);
assert.deepEqual(migrated.errors, []);
await migrationContext.close();
console.log("PASS: folder slideshow, fade, pause and next, portrait fill, reduced motion, menus, targets, browser window, settings section, off switch, image source, and migrations.");
});
+115
View File
@@ -0,0 +1,115 @@
// The native Git feature: the module loads only at first need, the Source control pane stages, unstages, and commits,
// the diff and graph tabs open, errors show in the pane, and Off removes the feature at once.
// It replaces plugins/gitToolbar, which loaded the old Git plugin from its sibling checkout.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("features/git", async ({ page }) => {
const output = await outputDir("features/git");
await mockTauri(page, {
commands: test => {
// The handlers run in the page, so the history is defined here.
const commits = [
{ id: "c3".padEnd(40, "3"), parents: ["c1".padEnd(40, "1"), "c2".padEnd(40, "2")], refs: ["HEAD -> main"], summary: "Merge the feature", author: "Ada", date: "2026-10-29" },
{ id: "c2".padEnd(40, "2"), parents: ["c1".padEnd(40, "1")], refs: ["feature"], summary: "Add the feature", author: "Ada", date: "2026-10-28" },
{ id: "c1".padEnd(40, "1"), parents: [], refs: [], summary: "First commit", author: "Ada", date: "2026-10-27" },
];
test.git = { calls: [], changes: [
{ path: "staged.md", index: "M", worktree: " " },
{ path: "changed.md", index: " ", worktree: "M" },
{ path: "new.md", index: "?", worktree: "?" },
] };
const record = (command, value) => { test.git.calls.push([command, value]); return null; };
return {
...test.workspace({ root: "C:\\git-feature", files: { "staged.md": "A\n", "changed.md": "B\n", "new.md": "C\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
git_status: () => ({ available: true, repository: true, branch: "main", changes: test.git.changes }),
git_diff: ({ path, staged }) => `diff --git a/${path} b/${path}\n@@ -1 +1 @@\n-old line\n+new line${staged ? " (staged)" : ""}`,
git_stage: ({ paths }) => record("stage", paths),
git_unstage: ({ paths }) => record("unstage", paths),
git_commit: ({ message }) => record("commit", message),
git_push: () => { throw "The branch has no upstream branch."; },
git_pull: () => record("pull", null),
git_graph: () => ({ commits }),
git_commit_details: ({ commit }) => ({ id: commit, parents: commits.find(item => item.id === commit).parents, author: "Ada", date: "2026-10-29", message: "Details", files: [{ path: "one.md", status: "M" }, { path: "two.md", status: "A" }] }),
git_commit_diff: ({ path }) => `@@ -0,0 +1 @@\n+${path}`,
};
},
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="staged.md"]').waitFor();
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => new URL(entry.name).pathname === "/src/lib/features/git/index.ts"));
assert.equal(await loaded(), false, "The Git module does not load before first need");
const sourceControl = page.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.click();
const pane = page.locator(".source-control");
await pane.getByText("main", { exact: true }).waitFor();
assert.equal(await loaded(), true, "The Source control pane loads the Git module");
await pane.getByRole("heading", { name: "Staged changes (1)", exact: true }).waitFor();
await pane.getByRole("heading", { name: "Unstaged changes (2)", exact: true }).waitFor();
assert.equal(await pane.locator("summary").textContent(), "Changes (3)", "The section title counts all changes");
assert.equal(await pane.getByRole("heading", { name: "Changes (2)", exact: true }).count(), 0, "No group title repeats the section title");
await pane.getByRole("button", { name: "Stage new.md", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.git.calls.some(([command]) => command === "stage"));
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["stage", ["new.md"]]);
await pane.getByRole("button", { name: "Unstage all", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.git.calls.some(([command]) => command === "unstage"));
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["unstage", ["staged.md"]]);
const message = pane.getByRole("textbox", { name: "Commit message", exact: true });
const commit = pane.getByRole("button", { name: "Commit staged", exact: true });
assert.equal(await commit.isDisabled(), true, "Commit waits for a message");
await message.fill("Write the notes");
await message.press("Control+Enter");
await pane.getByText("Commit created.", { exact: true }).waitFor();
assert.deepEqual(await page.evaluate(() => window.__TEST__.git.calls.at(-1)), ["commit", "Write the notes"]);
await pane.getByRole("button", { name: "Push to the upstream branch", exact: true }).click();
await pane.locator(".notice.error", { hasText: "no upstream branch" }).waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.waitForTimeout(100);
await pane.screenshot({ path: path.join(output, `source-control-${theme}.png`) });
}
await pane.getByRole("button", { name: /^changed\.md — Modified$/ }).click();
const diff = page.locator(".git-diff");
await diff.getByText("changed.md · Working tree", { exact: true }).waitFor();
await diff.locator(".line.add", { hasText: "+new line" }).waitFor();
assert.equal(await diff.locator(".line.remove").count(), 1);
await page.screenshot({ path: path.join(output, "diff-tab.png") });
await pane.getByRole("button", { name: "Show Git graph", exact: true }).click();
const graph = page.locator(".git-graph");
const options = graph.getByRole("option");
await options.first().waitFor();
assert.equal(await options.count(), 3);
assert.equal(await options.first().getAttribute("aria-selected"), "true");
await graph.getByRole("button", { name: "one.md", exact: false }).first().waitFor();
await options.first().focus();
await page.keyboard.press("ArrowDown");
await page.waitForFunction(() => document.activeElement?.getAttribute("aria-selected") === "true" && document.activeElement?.textContent?.includes("Add the feature"));
await graph.locator(".line.add", { hasText: "+one.md" }).waitFor();
assert.equal(await graph.locator("path.boundary").count(), 0, "The full history has no dashed boundary line");
await page.screenshot({ path: path.join(output, "graph-tab.png") });
await page.setViewportSize({ width: 640, height: 720 });
await page.screenshot({ path: path.join(output, "graph-tab-640.png") });
await page.setViewportSize({ width: 1280, height: 800 });
// Off closes the Git tabs and the pane, and removes the button. The feature can start again.
await page.evaluate(() => window.__TEST__.writeSettings("features", { git: false }));
await sourceControl.waitFor({ state: "detached" });
await graph.waitFor({ state: "detached" });
await diff.waitFor({ state: "detached" });
await pane.waitFor({ state: "detached" });
await page.evaluate(() => window.__TEST__.writeSettings("features", { git: true }));
await sourceControl.click();
await pane.getByText("main", { exact: true }).waitFor();
console.log("PASS: Git loads at first need, stages, unstages, commits, shows errors, diffs, and the graph, and Off removes it");
}, { timeout: 60000 });
+317
View File
@@ -0,0 +1,317 @@
// The native PDF Viewer: the file tree marks PDF files without the module, the first PDF tab loads it, and each tab
// renders its pages in one column with selectable text, page controls, zoom, a typed zoom, rotation, scrolling by wheel and
// keyboard, and Reload. It also checks the opaque toolbar and the focus after Ctrl+Tab.
// It also checks two tabs, one worker for each open tab, a protected PDF, a damaged file, Off and On, no network request,
// no text read of a PDF, the owner ID of a tab transfer, a saved tab after a reload, both themes, and a narrow toolbar.
// It replaces tests/browser.mjs of the PDF Viewer plugin.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { passwordPdf, samplePdf } from "../../fixtures/pdf/fixtures.mjs";
await runSmoke("features/pdf", async ({ page }) => {
const output = await outputDir("features/pdf");
const origin = new URL(smokeUrl).origin;
const requests = [];
page.on("request", request => {
const url = request.url();
if (!url.startsWith(origin) && !/^(blob|data):/.test(url)) requests.push(url);
});
// Count the PDF.js workers that run (src/lib/features/pdf/engine.ts names them).
await page.addInitScript(() => {
const workers = new Set();
const NativeWorker = window.Worker;
window.Worker = class extends NativeWorker {
constructor(url, options) { super(url, options); if (options?.name === "PDF.js") workers.add(this); }
terminate() { workers.delete(this); super.terminate(); }
};
window.__PDF_WORKERS__ = workers;
});
await mockTauri(page, {
state: { sample: [...samplePdf()], password: [...passwordPdf()] },
commands: test => ({
...test.workspace({ root: "C:\\pdf-feature", files: { "Sample.pdf": "", "Other.PDF": "", "Broken.pdf": "", "Protected.pdf": "", "Slow.pdf": "", "note.md": "# Note\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
workspace_read_bytes: async ({ rel }) => {
if (rel === "Slow.pdf") await new Promise(resolve => setTimeout(resolve, 400));
const bytes = rel === "Broken.pdf" ? [1, 2, 3] : rel === "Protected.pdf" ? test.state.password : test.state.sample;
return new Uint8Array(bytes).buffer;
},
}),
});
// `window.requestClose()` sends the native close request, so the workbench saves its document tabs (tabs/lifecycle does the same).
await page.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
const { transformCallback, invoke } = internals;
const callbacks = new Map(), handlers = [];
internals.transformCallback = (callback, once) => { const id = transformCallback(callback, once); callbacks.set(id, callback); return id; };
internals.invoke = (command, args = {}) => {
if (command === "plugin:event|listen" && args.event === "tauri://close-requested") handlers.push(args.handler);
return invoke(command, args);
};
window.requestClose = async () => {
for (const id of handlers) await callbacks.get(id)?.({ event: "tauri://close-requested", id, payload: null });
};
});
await page.goto(smokeUrl);
const row = name => page.locator(`[data-tree-rel="${name}"]`);
await row("Sample.pdf").waitFor();
await row("Sample.pdf").locator(".document-icon").waitFor();
assert.equal(await row("Other.PDF").locator(".document-icon").count(), 1, "Any letter case of the extension is a PDF");
assert.equal(await row("note.md").locator(".document-icon").count(), 0);
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => {
const { pathname } = new URL(entry.name);
return pathname === "/src/lib/features/pdf/index.ts" || pathname.includes("pdfjs-dist");
}));
assert.equal(await loaded(), false, "The file tree marks PDF files without the module or PDF.js");
const workers = () => page.evaluate(() => window.__PDF_WORKERS__.size);
const active = page.locator(".plugin-editor-pane:visible");
const status = active.locator(".pdf-viewer .status");
const rendered = text => status.filter({ hasText: new RegExp(`^${text}$`) }).waitFor();
const button = name => active.getByRole("button", { name, exact: true });
const tab = name => page.getByRole("tab", { name, exact: true });
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await loaded(), true, "The first PDF tab loads the module");
await active.getByRole("img", { name: "PDF page 1", exact: true }).waitFor();
const sheet = number => active.locator(`.sheet[data-page="${number}"]`);
const scroll = active.locator(".scroll");
const scrollTop = () => scroll.evaluate(node => node.scrollTop);
await sheet(1).locator(".textLayer span").first().waitFor();
assert.match(await sheet(1).locator(".textLayer").innerText(), /Page one text selection/);
assert.equal(await active.locator(".sheet").count(), 2, "Each page has a sheet in the column");
assert.ok(await sheet(1).locator("canvas").evaluate(canvas => {
const data = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
let colored = 0;
for (let index = 0; index < data.length; index += 4) if (data[index] < 200 && data[index + 2] > 100) colored++;
return colored > 1000;
}), "The page shows its blue rectangle");
assert.equal(await active.getByRole("spinbutton", { name: "Page number", exact: true }).inputValue(), "1");
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "true");
assert.equal(await button("Previous page").isDisabled(), true);
assert.equal(await workers(), 1);
// The toolbar and the status line are opaque, so a background image does not show through them.
for (const selector of [".toolbar", ".status"]) {
assert.match(await active.locator(selector).evaluate(node => getComputedStyle(node).backgroundColor), /^rgb\(/, `${selector} has an opaque fill`);
}
// Both themes. The page stays white paper.
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.waitForTimeout(100);
await page.screenshot({ path: path.join(output, `viewer-${theme}.png`) });
}
// The tooltip of an icon button shows on keyboard focus.
await button("Rotate clockwise").focus();
await page.getByRole("tooltip", { name: "Rotate clockwise" }).waitFor();
await active.locator(".toolbar").screenshot({ path: path.join(output, "toolbar-focus.png") });
// A narrow window: the toolbar wraps and keeps every control inside the pane.
await page.setViewportSize({ width: 900, height: 720 });
await rendered("Page 1 of 2");
const toolbar = active.locator(".toolbar");
assert.equal(await toolbar.evaluate(node => node.scrollWidth > node.clientWidth), false, "No horizontal scroll in the toolbar");
const box = await toolbar.boundingBox();
for (const control of await toolbar.locator("button, input").all()) {
const item = await control.boundingBox();
assert.ok(item.x >= box.x - 1 && item.x + item.width <= box.x + box.width + 1, "Each control stays inside the toolbar");
}
await page.screenshot({ path: path.join(output, "viewer-900.png") });
await page.setViewportSize({ width: 1440, height: 1000 });
// Pages, zoom, rotation, and the keyboard.
await button("Next page").click();
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
assert.equal(await button("Next page").isDisabled(), true);
const zoomField = active.getByRole("textbox", { name: "Zoom percent", exact: true });
const zoomText = () => zoomField.inputValue();
const before = await zoomText();
await button("Zoom in").click();
await rendered("Page 2 of 2");
assert.notEqual(await zoomText(), before);
assert.equal(await button("Fit width").getAttribute("aria-pressed"), "false");
await button("Rotate clockwise").click();
await rendered("Page 2 of 2");
assert.ok(await sheet(2).locator("canvas").evaluate(canvas => canvas.width > canvas.height), "A rotated page is wider than high");
for (let turn = 0; turn < 3; turn++) await button("Rotate clockwise").click();
// A typed zoom.
await zoomField.fill("137");
await zoomField.press("Enter");
assert.equal(await zoomText(), "137%");
await zoomField.fill("text");
await zoomField.press("Enter");
assert.equal(await zoomText(), "137%", "Text that is not a number keeps the zoom");
await zoomField.fill("9000");
await zoomField.press("Enter");
assert.equal(await zoomText(), "400%", "A typed zoom stays in the limits");
const unfitted = button("Fit width").and(page.locator('[aria-pressed="false"]'));
await unfitted.waitFor();
const fitted = button("Fit width").and(page.locator('[aria-pressed="true"]'));
const input = active.getByRole("spinbutton", { name: "Page number", exact: true });
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
// Page Down and Page Up scroll. At 400%, a page is higher than the tab. They do not jump to the next page, and they do not draw a page again at the ends.
assert.equal(await scrollTop(), 0);
await scroll.focus();
const keepCanvas = number => sheet(number).locator("canvas").evaluate(canvas => { window.__PDF_CANVAS__ = canvas; });
const sameCanvas = number => sheet(number).locator("canvas").evaluate(canvas => window.__PDF_CANVAS__ === canvas);
await keepCanvas(1);
await page.keyboard.press("PageUp");
await page.waitForTimeout(300);
assert.equal(await scrollTop(), 0);
assert.equal(await sameCanvas(1), true, "Page Up at the start does not draw the page again");
await rendered("Page 1 of 2");
await page.keyboard.press("PageDown");
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
await page.waitForTimeout(400);
assert.ok(await scrollTop() < await sheet(2).evaluate(node => node.offsetTop - node.previousElementSibling.offsetTop), "Page Down scrolls less than one page");
await rendered("Page 1 of 2");
assert.equal(await input.inputValue(), "1");
await page.keyboard.press("End");
await rendered("Page 2 of 2");
assert.equal(await input.inputValue(), "2", "The page field follows the scroll position");
await page.waitForTimeout(400);
const end = await scrollTop();
await keepCanvas(2);
await page.keyboard.press("PageDown");
await page.waitForTimeout(300);
assert.equal(await scrollTop(), end);
assert.equal(await sameCanvas(2), true, "Page Down at the end does not draw the page again");
await rendered("Page 2 of 2");
// The wheel shows the other pages.
await page.keyboard.press("Home");
await rendered("Page 1 of 2");
await scroll.hover();
await page.mouse.wheel(0, 5000);
await rendered("Page 2 of 2");
await active.getByRole("img", { name: "PDF page 2", exact: true }).waitFor();
// Ctrl and the wheel change the zoom.
await button("Fit width").click();
await fitted.waitFor();
await scroll.hover();
await page.keyboard.down("Control");
await page.mouse.wheel(0, -100);
await page.keyboard.up("Control");
await unfitted.waitFor();
await button("Fit width").click();
await rendered("Page 2 of 2");
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
await input.fill("99");
await input.press("Enter");
await rendered("Page 2 of 2");
assert.equal(await input.inputValue(), "2", "A page number above the count goes to the last page");
// A second tab, one tab for each file, and one worker for each open tab.
await row("Other.PDF").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 2);
await row("Other.PDF").click();
assert.equal(await tab("Other").count(), 1, "A second open selects the same tab");
// The tabs are New tab, Sample, and Other. Ctrl+Tab and Ctrl+Shift+Tab give the keyboard to the page area of the PDF tab.
const focused = () => page.waitForFunction(() => document.activeElement?.matches(".pdf-viewer .scroll") && document.activeElement.offsetParent !== null);
await page.keyboard.press("Control+Shift+Tab");
await focused();
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
await input.fill("1");
await input.press("Enter");
await rendered("Page 1 of 2");
await page.keyboard.press("Control+Tab");
await focused();
await page.keyboard.press("Control+Shift+Tab");
await focused();
assert.equal(await tab("Sample").getAttribute("aria-selected"), "true");
await page.keyboard.press("PageDown");
await page.waitForFunction(() => document.activeElement.scrollTop > 0);
await page.keyboard.press("Control+Tab");
await rendered("Page 1 of 2");
assert.equal(await tab("Other").getAttribute("aria-selected"), "true");
await page.getByRole("button", { name: "Close Other", exact: true }).click();
await tab("Other").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes before its file arrives starts no worker.
await row("Slow.pdf").click();
await tab("Slow").waitFor();
await page.getByRole("button", { name: "Close Slow", exact: true }).click();
await page.waitForTimeout(600);
assert.equal(await workers(), 1);
// A protected PDF.
await row("Protected.pdf").click();
const password = active.getByLabel("PDF password");
await password.waitFor();
await status.filter({ hasText: "This PDF needs a password." }).waitFor();
assert.equal(await password.evaluate(node => node === document.activeElement), true, "The password field takes focus");
await password.fill("incorrect");
await active.getByRole("button", { name: "Unlock", exact: true }).click();
await status.filter({ hasText: "Incorrect password. Try again." }).waitFor();
await page.screenshot({ path: path.join(output, "password.png") });
await password.fill("reader");
await password.press("Enter");
await rendered("Page 1 of 2");
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// A tab that closes while it asks for the password stops its worker.
await row("Protected.pdf").click();
await active.getByLabel("PDF password").waitFor();
await page.getByRole("button", { name: "Close Protected", exact: true }).click();
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 1);
// Reload keeps the page and replaces the worker.
await tab("Sample").click();
await input.fill("2");
await input.press("Enter");
await rendered("Page 2 of 2");
await button("Reload PDF").click();
await rendered("Page 2 of 2");
assert.equal(await workers(), 1);
// A damaged file shows an error, and Reload stays available.
await row("Broken.pdf").click();
await active.getByRole("alert").filter({ hasText: "Cannot display this PDF." }).waitFor();
assert.equal(await button("Reload PDF").isDisabled(), false);
assert.equal(await button("Next page").isDisabled(), true);
await page.screenshot({ path: path.join(output, "damaged.png") });
// Off closes the PDF tabs, stops every worker, and removes the marks. On opens PDF files again.
const switches = await page.evaluate(() => window.__TEST__.settings("features"));
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: false });
await active.locator(".pdf-viewer").waitFor({ state: "detached" });
await page.waitForFunction(() => window.__PDF_WORKERS__.size === 0);
assert.equal(await page.locator(".pdf-viewer").count(), 0);
assert.equal(await tab("Sample").count(), 0);
await row("Sample.pdf").locator(".document-icon").waitFor({ state: "detached" });
await page.evaluate(value => window.__TEST__.writeSettings("features", value), { ...switches, pdf: true });
await row("Sample.pdf").locator(".document-icon").waitFor();
await row("Sample.pdf").click();
await rendered("Page 1 of 2");
assert.equal(await workers(), 1);
const textReads = await page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_read" && /\.pdf$/i.test(call.args.rel)));
assert.deepEqual(textReads, [], "A PDF is never read as text");
// A tab transfer names the old package and the document type. A reload reopens the saved PDF tab from its path.
const transfer = await page.evaluate(async () => {
const external = await import("/src/lib/plugins/external.ts");
let editors = [];
external.pluginEditors.subscribe(value => { editors = value; })();
const { owner, id, document } = external.pluginTabState(editors.find(view => view.document));
return { owner, id, document };
});
assert.deepEqual(transfer, { owner: "runestone.pdf-viewer", id: "pdf", document: { id: "Sample.pdf", path: "Sample.pdf" } });
await page.evaluate(() => window.requestClose());
await page.reload();
await rendered("Page 1 of 2");
assert.equal(await tab("Sample").count(), 1);
assert.deepEqual(requests, [], "No network request leaves the app");
console.log("PASS: PDF Viewer loads at first need, renders text and pages, scrolls, zooms, rotates, reloads, unlocks, reports a damaged file, keeps one worker per tab, restores its tab, and Off removes it");
}, { timeout: 60000, viewport: { width: 1440, height: 1000 } });
+160
View File
@@ -0,0 +1,160 @@
// The native Project Management feature: no module loads before the first use, the ribbon button opens All tasks,
// the board scope opens a board in the same tab with the board name, a card moves to another list through the host menu,
// and a card edit saves to the hidden card file. Settings → Project Management saves the priority levels and the default
// board, and the ribbon button then opens that board. It also checks both themes and the shared tooltip of the ribbon button.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const roadmap = "6f4c2a3e-6a0b-4d57-9a3e-1c2b3d4e5f60";
const bugs = "0c18bcdc-f41e-4a31-87f4-87c369f398c1";
const board = id => ({
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 },
],
defaults: { todo: "todo", doing: "doing", done: "done" },
});
const cardPath = id => `.runestone/pm/cards/${Buffer.from(id).toString("hex")}.md`;
const card = (id, title, boardId, order) => [cardPath(id), [
"---", "runestone_pm:", " schema: 1", ` id: ${id}`, " kind: task", ` title: ${title}`, " createdAt: 2026-10-01T00:00:00.000Z",
` order: "${order}"`, " status: todo", " tags: []", " sessions: []", " archived: false", " placements:",
` ${boardId}:`, " listId: todo", ` order: "${order}"`, "---", `Body of ${title}.`, "",
].join("\n")];
const files = Object.fromEntries([
["note.md", "# Note\n"],
[".runestone/pm/.gitignore", "# RuneStone Project Management local data\n*\n"],
[".runestone/pm/cards/.gitignore", "*\n"],
[".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards: [{ name: "Roadmap", value: board(roadmap) }, { name: "Bugs", value: board(bugs) }] }, null, 2) + "\n"],
card("card-a", "Card A", roadmap, "a"),
card("card-b", "Card B", roadmap, "b"),
card("card-c", "Card C", bugs, "c"),
]);
await runSmoke("features/pm", async ({ browser }) => {
const output = await outputDir("features/pm");
const mock = {
state: { files },
commands: test => {
const workspace = test.workspace({ root: "C:\\pm-feature", files: test.state.files });
test.files = workspace.files;
return {
...workspace,
workspace_read: args => {
if (!workspace.files.has(args.rel) && args.missingOk) return null;
return workspace.workspace_read(args);
},
workspace_create: ({ rel, kind, contents }) => {
if (workspace.files.has(rel)) throw new Error("Destination exists");
if (kind === "file") workspace.files.set(rel, contents ?? "");
return null;
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
};
},
};
// One context, so the settings window shares the settings file of the main window.
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, mock);
const page = await openPage(context);
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="note.md"]').waitFor();
const loaded = () => page.evaluate(() => performance.getEntriesByType("resource").some(entry => {
const { pathname } = new URL(entry.name);
return pathname.startsWith("/src/lib/features/pm/") || /\/deps\/yaml\b|\/node_modules\/yaml\//.test(pathname);
}));
const ribbon = page.locator(".plugin-ribbon").getByRole("button", { name: "Project Management", exact: true });
await ribbon.waitFor();
assert.equal(await loaded(), false, "No Project Management module and no YAML parser load before the first use");
assert.equal(await page.locator('[data-tree-rel="note.md"] .document-icon').count(), 0, "The file tree marks no Markdown file for Project Management");
await ribbon.hover();
await page.getByRole("tooltip").filter({ hasText: /^Project Management$/ }).waitFor();
// The ribbon button opens All tasks: no default board is set.
await ribbon.click();
const pane = page.locator(".plugin-editor-pane:visible");
await pane.locator(".pm-board").waitFor();
await page.getByRole("tab", { name: "Project Management", exact: true }).waitFor();
await page.waitForFunction(() => document.querySelectorAll(".plugin-editor-pane .pm-card").length === 3);
assert.equal(await loaded(), true, "The first use loads the feature");
assert.equal(await ribbon.getAttribute("aria-pressed"), "true", "The ribbon button shows the open view");
// The board scope opens a board in the same tab, with the board name as its title.
await pane.getByRole("button", { name: /^Board scope:/ }).click();
await page.getByRole("menuitemradio", { name: "Roadmap", exact: true }).click();
await page.getByRole("tab", { name: "Roadmap", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "Project Management", exact: true }).count(), 0, "The board replaces All tasks in its tab");
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-card")].filter(card => card.getClientRects().length).length === 2);
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
await page.screenshot({ path: path.join(output, `board-${theme}.png`) });
}
// Move a card to another list through the host action menu. The save writes only that card.
await pane.getByRole("button", { name: "Actions for Card A", exact: true }).click();
await page.getByRole("menuitem", { name: "Move to list", exact: true }).click();
await page.getByRole("menuitemradio", { name: "In progress", exact: true }).click();
await page.waitForFunction(path => /listId: doing/.test(window.__TEST__.files.get(path)), cardPath("card-a"));
const moved = await page.evaluate(path => window.__TEST__.files.get(path), cardPath("card-a"));
assert.match(moved, /status: doing/, "The list status applies to the card");
await pane.locator(".pm-column", { hasText: "In progress" }).locator(".pm-card", { hasText: "Card A" }).waitFor();
// Edit a card in its details and save it.
await pane.getByRole("button", { name: "Card B", exact: true }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("textbox", { name: "Title", exact: true }).fill("Card B edited");
await page.screenshot({ path: path.join(output, "card-editor-light.png") });
await editor.getByRole("button", { name: "Save card", exact: true }).click();
await editor.waitFor({ state: "detached" });
await page.waitForFunction(path => /title: Card B edited/.test(window.__TEST__.files.get(path)), cardPath("card-b"));
await pane.locator(".pm-card", { hasText: "Card B edited" }).waitFor();
assert.equal(await page.evaluate(path => window.__TEST__.files.get(path), cardPath("card-c")), files[cardPath("card-c")], "Other cards stay unchanged");
await page.screenshot({ path: path.join(output, "board-after-edit-light.png") });
// The board menu shows the same settings component as Settings → Project Management.
await pane.getByRole("button", { name: "More actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Project Management settings", exact: true }).click();
const popup = page.getByRole("dialog", { name: "Project Management settings", exact: true });
await popup.getByRole("button", { name: "Priority levels", exact: true }).waitFor();
await popup.getByRole("button", { name: "Default board", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "board-settings-light.png") });
await page.keyboard.press("Escape");
await popup.waitFor({ state: "detached" });
// Settings → Project Management in the settings window. Each page of the mock has its own copy of the workspace files.
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("button", { name: "Project Management", exact: true }).click();
await settings.getByRole("heading", { name: "Project Management", exact: true }).waitFor();
const levels = settings.getByRole("button", { name: "Priority levels", exact: true });
assert.equal(await levels.innerText(), "3 — High, Medium, and Low");
await levels.click();
await settings.getByRole("menuitemradio", { name: "5 — Highest through Lowest", exact: true }).click();
await settings.waitForFunction(() => window.__TEST__.settings("projectManagement")?.priorityLevels === 5);
const defaultBoard = settings.getByRole("button", { name: "Default board", exact: true });
await settings.waitForFunction(() => !document.querySelector('[aria-label="Default board"]').disabled);
assert.equal(await defaultBoard.innerText(), "All tasks");
await defaultBoard.click();
assert.deepEqual(await settings.getByRole("menuitemradio").allInnerTexts(), ["All tasks", "Roadmap", "Bugs"]);
await settings.getByRole("menuitemradio", { name: "Roadmap", exact: true }).click();
await settings.waitForFunction(id => JSON.parse(window.__TEST__.files.get(".runestone/pm/workspace.json")).defaultBoardId === id, roadmap);
await settings.screenshot({ path: path.join(output, "settings-light.png") });
await settings.close();
// With a default board, the ribbon button opens it.
await page.evaluate(([board, catalog]) => {
const value = JSON.parse(catalog);
window.__TEST__.files.set(".runestone/pm/workspace.json", JSON.stringify({ ...value, defaultBoardId: board, defaultBoardPath: `pm-board:${board}` }));
}, [bugs, files[".runestone/pm/workspace.json"]]);
await ribbon.click();
await page.getByRole("tab", { name: "Bugs", exact: true }).waitFor();
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-card")].some(card => card.getClientRects().length && card.textContent.includes("Card C")));
assert.deepEqual([...page.errors, ...settings.errors], [], "No page errors");
await context.close();
});
+165
View File
@@ -0,0 +1,165 @@
// Project Management board state: list capacity and its warning (UI-033), compact list collapse (UI-036), the separate
// collapse state of All tasks, new cards from the list composer, a page reload that keeps the state, the fixed default
// board of the workspace (UI-038), and the first board of a workspace without boards.
// Ports list-limits.spec.ts, list-collapse-create.spec.ts, kanban-cards.spec.ts, board-view-state.spec.ts,
// october-cards.spec.ts (default board and onboarding), and host-board-state.smoke.mjs of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { openPage, outputDir, runSmoke } from "../_harness/index.mjs";
import { bugs, catalogPath, column, fileText, loadWorkspace, openBoard, pane, pmFiles, ribbon, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const listOf = async (page, id, listId) => (await savedBoards(page)).find(item => item.value.id === id).value.lists.find(list => list.id === listId);
const width = async locator => (await locator.boundingBox()).width;
await runSmoke("features/pmBoard", async ({ browser, page }) => {
const output = await outputDir("features/pmBoard");
await loadWorkspace(page);
const catalog = await fileText(page, catalogPath);
// All tasks keeps its collapsed lists in the view state of the tab. The board files stay unchanged.
await openBoard(page);
const allTodo = column(page, "To do");
await allTodo.getByRole("button", { name: "Collapse To do", exact: true }).click();
await allTodo.getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await focusedLabel(page), "Expand To do", "Focus stays on the collapse control");
assert(await width(allTodo) < 60, "A collapsed list is a narrow strip");
assert.equal(await allTodo.locator(".pm-card").count(), 0, "A collapsed list hides its cards");
assert.equal(await allTodo.locator(".pm-count").innerText(), "4", "The strip keeps the card count");
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.pm.viewStates") ?? "{}").planning?.collapsedLists?.includes("list:to do"));
assert.equal(await fileText(page, catalogPath), catalog, "A collapse in All tasks does not write the boards");
// UI-033: All tasks has no list actions and no capacity of a merged list.
assert.equal(await pane(page).locator(".pm-list-actions, .pm-list-limit").count(), 0, "All tasks has no list actions and no list limits");
// A board list starts expanded: the board has its own collapse state.
await openBoard(page, "Roadmap");
const todo = column(page, "To do");
assert.equal(await todo.locator(".pm-card").count(), 3);
// UI-033: a limit below the maximum shows the plain indicator.
const review = column(page, "Review");
assert.equal(await review.locator(".pm-count").innerText(), "0/2");
assert.equal(await review.locator(".pm-list-limit").count(), 1);
assert.equal(await review.locator(".pm-list-limit-reached").count(), 0);
// Set a limit through the list menu. At the maximum, the list shows the warning.
await todo.getByRole("button", { name: "List actions for To do", exact: true }).click();
await page.getByRole("menu", { name: "List actions", exact: true }).getByRole("menuitem", { name: "Set list limit", exact: true }).click();
const limitForm = page.getByRole("dialog", { name: "Set list limit", exact: true });
await limitForm.getByLabel("Maximum cards", { exact: true }).fill("3");
await limitForm.getByRole("button", { name: "Save limit", exact: true }).click();
await limitForm.waitFor({ state: "detached" });
await waitForFile(page, catalogPath, /"maxCards": 3/);
assert.equal(await todo.locator(".pm-count").innerText(), "3/3");
const warning = todo.locator(".pm-list-limit-reached");
assert.match(await warning.getAttribute("aria-label"), /^Active cards in To do: 3\. The maximum is 3\. The list is at the limit\.$/);
// The limit warns but does not block: the composer adds a fourth card.
await todo.getByRole("button", { name: "Add a card", exact: true }).click();
const composer = todo.getByRole("textbox", { name: "Card title", exact: true });
await composer.fill("Composer card");
await composer.press("Enter");
await todo.getByRole("button", { name: "Composer card", exact: true }).waitFor();
await page.waitForFunction(() => [...window.__TEST__.files.values()].some(text => /title: Composer card/.test(text)));
await page.waitForFunction(() => document.querySelector('.plugin-editor-pane .pm-column[aria-label="To do"] .pm-count')?.textContent === "4/3");
assert.match(await warning.getAttribute("aria-label"), /The list is over the limit\.$/);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await warning.focus();
await page.getByRole("tooltip").filter({ hasText: /over the limit/ }).waitFor();
await page.screenshot({ path: path.join(output, `limit-warning-${theme}.png`) });
}
// UI-036: a keyboard collapse saves the board file, keeps the count, and keeps focus on the control.
await todo.getByRole("button", { name: "Collapse To do", exact: true }).focus();
await page.keyboard.press("Enter");
await todo.getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await focusedLabel(page), "Expand To do");
await waitForList(page, roadmap, "todo", list => list.collapsed === true);
assert(await width(todo) < 60);
assert.equal(await todo.locator(".pm-count").innerText(), "4/3", "The strip keeps the count and the limit");
assert.equal(await todo.locator(".pm-list-limit-reached").count(), 1, "The strip keeps the warning");
await column(page, "Done").getByRole("button", { name: "Collapse Done", exact: true }).click();
await waitForList(page, roadmap, "done", list => list.collapsed === true);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `collapsed-board-${theme}.png`) });
}
// A reload keeps the board state, the limits, and the collapsed lists of All tasks.
await page.reload();
await page.locator('[data-tree-rel="note.md"]').waitFor();
await openBoard(page, "Roadmap");
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).waitFor();
assert.equal(await column(page, "To do").locator(".pm-count").innerText(), "4/3");
await column(page, "Done").getByRole("button", { name: "Expand Done", exact: true }).waitFor();
assert.equal(await column(page, "In progress").getByRole("button", { name: "Collapse In progress", exact: true }).count(), 1);
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).click();
await waitForList(page, roadmap, "todo", list => list.collapsed === false);
await column(page, "To do").getByRole("button", { name: "Composer card", exact: true }).waitFor();
// The limit indicator opens the limit form. An empty field removes the limit.
await column(page, "To do").locator(".pm-list-limit").click();
await limitForm.getByLabel("Maximum cards", { exact: true }).fill("");
await limitForm.getByRole("button", { name: "Save limit", exact: true }).click();
await waitForList(page, roadmap, "todo", list => list.maxCards === undefined);
assert.equal(await column(page, "To do").locator(".pm-list-limit").count(), 0);
assert.equal(await column(page, "To do").locator(".pm-count").innerText(), "4");
await pane(page).locator(".pm-scope").click();
await page.getByRole("menuitemradio", { name: "All tasks", exact: true }).click();
await column(page, "To do").getByRole("button", { name: "Expand To do", exact: true }).waitFor();
// UI-038: the settings save a default board. The ribbon button then opens it.
await pane(page).getByRole("button", { name: "More actions", exact: true }).click();
await page.getByRole("menuitem", { name: "Project Management settings", exact: true }).click();
const settings = page.getByRole("dialog", { name: "Project Management settings", exact: true });
const defaultBoard = settings.getByRole("button", { name: "Default board", exact: true });
await page.waitForFunction(() => document.querySelector('.pm-settings-popup [aria-label="Default board"]')?.disabled === false);
assert.equal(await defaultBoard.innerText(), "All tasks");
await defaultBoard.click();
await page.getByRole("menuitemradio", { name: "Bugs", exact: true }).click();
await waitForFile(page, catalogPath, new RegExp(`"defaultBoardId": "${bugs}"`));
await page.keyboard.press("Escape");
await settings.waitFor({ state: "detached" });
await ribbon(page).click();
await page.getByRole("tab", { name: "Bugs", exact: true, selected: true }).waitFor();
await pane(page).locator(".pm-card", { hasText: "Card C" }).waitFor();
// An unavailable default opens All tasks.
await page.evaluate(rel => {
const value = JSON.parse(window.__TEST__.files.get(rel));
window.__TEST__.files.set(rel, JSON.stringify({ ...value, defaultBoardId: "missing-board", defaultBoardPath: "pm-board:missing-board" }));
}, catalogPath);
await ribbon(page).click();
await page.getByRole("tab", { name: "Project Management", exact: true, selected: true }).waitFor();
await pane(page).locator(".pm-scope-label", { hasText: /^All tasks$/ }).waitFor();
console.log("PASS: list limits, collapse, reload, and the default board");
// UI-038: a workspace without boards shows a visible action that creates the first board.
const context = await browser.newContext({ viewport: { width: 1280, height: 860 } });
const empty = await openPage(context);
await loadWorkspace(empty, pmFiles({ boards: false }));
await openBoard(empty);
const welcome = empty.getByRole("region", { name: "Create your first board", exact: true });
await welcome.waitFor();
await welcome.getByRole("button", { name: "Create your first board", exact: true }).click();
await empty.getByRole("textbox", { name: "Board name", exact: true }).fill("First board");
await empty.getByRole("dialog", { name: "Create board", exact: true }).getByRole("button", { name: "Create board", exact: true }).click();
await empty.getByRole("tab", { name: "First board", exact: true, selected: true }).waitFor();
await waitForFile(empty, catalogPath, /"name": "First board"/);
await empty.screenshot({ path: path.join(output, "first-board-light.png") });
assert.deepEqual(empty.errors, [], "No page errors in the workspace without boards");
await context.close();
}, { timeout: 15000 });
function focusedLabel(page) {
return page.evaluate(() => document.activeElement?.getAttribute("aria-label"));
}
/** Wait until a list of a saved board matches `test`. */
async function waitForList(page, boardId, listId, test) {
for (let attempt = 0; attempt < 50; attempt++) {
if (test(await listOf(page, boardId, listId))) return;
await page.waitForTimeout(100);
}
throw new Error(`The list ${listId} of ${boardId} did not change`);
}
+135
View File
@@ -0,0 +1,135 @@
// Project Management cards: open and edit a card, description drafts with Save, Cancel, and the unsaved marker (UI-037),
// a list choice that saves at once, the creation time, labels, priority, and delete with a confirmation, in both themes.
// Ports october-cards.spec.ts, description-indicator.spec.ts, card-details.spec.ts, labels.spec.ts, delete-card.spec.ts,
// and kanban-editing.spec.ts of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { cardPath, column, deletedPath, draftPath, fileText, focusedName, loadWorkspace, openBoard, pane, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const draft = async (page, id) => JSON.parse(await fileText(page, draftPath(id)) ?? "null")?.body;
await runSmoke("features/pmCards", async ({ page }) => {
const output = await outputDir("features/pmCards");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const editor = page.locator("dialog.pm-card-editor[open]");
// The source field is hidden outside edit mode, so select it by its label attribute.
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
const unsaved = editor.locator(".pm-description-unsaved");
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
const openCard = async title => {
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
await editor.waitFor();
};
const closeCard = async () => {
await editor.getByRole("button", { name: "Close card", exact: true }).click();
await editor.waitFor({ state: "detached" });
};
// The details show the saved creation time.
await openCard("Card A");
const created = editor.locator(".pm-created-at");
assert.match(await created.innerText(), /^Created: (?!Unknown)/);
assert.equal(await created.getAttribute("title"), "2026-10-01T08:30:00.000Z");
assert.equal(await editor.getByRole("textbox", { name: "Title", exact: true }).inputValue(), "Card A");
// UI-037: a description edit stays a draft when the card closes. The saved description does not change.
await editor.getByRole("button", { name: "Edit", exact: true }).click();
await description.fill("Draft text");
await unsaved.waitFor();
assert.equal(await unsaved.innerText(), "Unsaved changes");
await closeCard();
await page.waitForFunction(rel => /"body":"Draft text"/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-a"));
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
const marker = pane(page).locator('.pm-card[data-task-id="card-a"] .pm-card-unsaved');
await marker.waitFor();
assert.equal(await marker.innerText(), "Unsaved description");
// The card opens with the saved description and the marker. Edit shows the draft. Cancel restores the saved text.
await openCard("Card A");
await unsaved.waitFor();
assert.equal(await editor.getByRole("region", { name: "Description preview", exact: true }).innerText(), "Body of Card A.");
await editor.getByRole("button", { name: "Edit", exact: true }).click();
assert.equal(await description.inputValue(), "Draft text");
await descriptionAction("Cancel").click();
await unsaved.waitFor({ state: "hidden" });
assert.equal((await description.inputValue()).trim(), "Body of Card A.");
assert.equal(await draft(page, "card-a"), null, "Cancel removes the draft");
// Save commits the description at once. The creation time does not change.
await editor.getByRole("button", { name: "Edit", exact: true }).click();
await description.fill("Saved description");
await descriptionAction("Save").click();
await waitForFile(page, cardPath("card-a"), /\nSaved description\n?$/);
await unsaved.waitFor({ state: "hidden" });
assert.match(await fileText(page, cardPath("card-a")), /createdAt: "?2026-10-01T08:30:00.000Z"?/);
assert.equal(await draft(page, "card-a"), null);
await closeCard();
await marker.waitFor({ state: "hidden" });
// UI-037: a list choice in the details saves at once, before Save card.
await openCard("Shared card");
await editor.getByRole("button", { name: "List", exact: true }).click();
await page.getByRole("menu", { name: "List", exact: true }).getByRole("menuitemradio", { name: "Done", exact: true }).click();
await waitForFile(page, cardPath("card-d"), /listId: done/);
assert.match(await fileText(page, cardPath("card-d")), /status: done/, "The list status applies at once");
await closeCard();
await column(page, "Done").locator(".pm-card-title", { hasText: "Shared card" }).waitFor();
// Title, labels, and priority save with Save card.
await openCard("Card B");
await editor.getByRole("textbox", { name: "Title", exact: true }).fill("Card B edited");
const details = editor.getByRole("group", { name: "Card details", exact: true });
await details.getByRole("button", { name: "Labels", exact: true }).click();
const labels = page.getByRole("dialog", { name: "Choose labels", exact: true });
await labels.getByRole("button", { name: "Add label Bug", exact: true }).click();
await editor.getByRole("button", { name: "Remove label Bug", exact: true }).waitFor({ state: "attached" });
await page.keyboard.press("Escape");
await labels.waitFor({ state: "hidden" });
assert.equal(await editor.count(), 1, "Escape closes only the label choices");
const priority = details.getByRole("button", { name: "Priority", exact: true });
await priority.click();
await page.getByRole("menu", { name: "Choose priority", exact: true }).getByRole("menuitemradio", { name: "High priority", exact: true }).click();
await details.getByRole("button", { name: "High priority", exact: true }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `card-details-${theme}.png`) });
}
await editor.getByRole("button", { name: "Save card", exact: true }).click();
await editor.waitFor({ state: "detached" });
await waitForFile(page, cardPath("card-b"), /title: Card B edited/);
const saved = await fileText(page, cardPath("card-b"));
assert.match(saved, /priority: high/);
assert.match(saved, /labels:\n\s+- bug/);
const edited = pane(page).locator('.pm-card[data-task-id="card-b"]');
assert.equal(await edited.locator(".pm-priority").innerText(), "High priority");
assert.equal(await edited.locator(".pm-label-badge").innerText(), "Bug");
assert.match(await fileText(page, cardPath("card-c")), /title: Card C/, "Other cards stay unchanged");
// Delete asks for a confirmation. Cancel keeps the card and returns focus to the card menu.
const actions = pane(page).getByRole("button", { name: "Actions for Card A", exact: true });
const confirm = page.getByRole("dialog", { name: "Delete card", exact: true });
await actions.click();
await page.getByRole("menu", { name: "Card actions", exact: true }).getByRole("menuitem", { name: "Delete card", exact: true }).click();
await confirm.getByRole("heading", { name: "Delete “Card A”?", exact: true }).waitFor();
assert.equal(await focusedName(page), "Cancel", "The safe choice has focus");
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `delete-card-${theme}.png`) });
}
await confirm.getByRole("button", { name: "Cancel", exact: true }).click();
await confirm.waitFor({ state: "detached" });
assert.equal(await focusedName(page), "Actions for Card A");
assert.equal(await fileText(page, deletedPath), undefined, "Cancel deletes nothing");
await actions.click();
await page.getByRole("menu", { name: "Card actions", exact: true }).getByRole("menuitem", { name: "Delete card", exact: true }).click();
await confirm.getByRole("button", { name: "Delete card", exact: true }).click();
await confirm.waitFor({ state: "detached" });
await waitForFile(page, deletedPath, /"card-a"/);
await pane(page).locator('.pm-card[data-task-id="card-a"]').waitFor({ state: "detached" });
assert.equal(await focusedName(page), "More actions", "Focus moves to the board menu after the card is gone");
assert.equal(await column(page, "To do").locator(".pm-card").count(), 1);
console.log("PASS: card details, description drafts, labels, priority, and delete");
}, { timeout: 15000 });
@@ -0,0 +1,90 @@
// Project Management description drafts with images: an image pasted in an unsaved description survives a close,
// a reopen, and a reload of the card. Save writes the image file. Cancel removes the image data and writes no image file.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, draftPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
const draftImagesPath = id => draftPath(id).replace(/\.json$/, ".images.json");
const json = async (page, path) => JSON.parse(await fileText(page, path) ?? "null");
await runSmoke("features/pmDraftImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const editor = page.locator("dialog.pm-card-editor[open]");
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
const descriptionAction = name => editor.locator(".pm-description-actions").getByRole("button", { name, exact: true });
const openCard = async title => {
await pane(page).locator(".pm-card-title", { hasText: new RegExp(`^${title}$`) }).click();
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
};
const closeCard = async () => {
await editor.getByRole("button", { name: "Close card", exact: true }).click();
await editor.waitFor({ state: "detached" });
};
// Paste a 1 by 1 PNG into the description. Returns the image ID of the new reference.
const pasteImage = async name => {
await description.evaluate((element, name) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], name, { type: "image/png" }));
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, name);
const reference = new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await page.waitForFunction(source => new RegExp(source).test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value), reference.source);
return reference.exec(await description.inputValue())[1];
};
// Wait until the gallery thumbnail of `name` shows the decoded image.
const imageLoads = async name => {
await page.waitForFunction(alt => {
const image = document.querySelector(`dialog.pm-card-editor[open] .pm-card-images img[alt="${alt}"]`);
return !!image?.complete && image.naturalWidth > 0;
}, name);
assert.equal(await editor.locator(".pm-card-images .pm-error").allInnerTexts().then(texts => texts.join("")), "");
};
// A pasted image stays with the draft when the card closes. The image folder gets no file yet.
await openCard("Card A");
const first = await pasteImage("dot.png");
await imageLoads("dot.png");
await closeCard();
await waitForFile(page, draftPath("card-a"), new RegExp(`pm-image:${first}`));
assert.match((await json(page, draftImagesPath("card-a"))).images[first], /^data:image\/png;base64,iVBOR/);
assert.equal(await fileText(page, imageFile(first)), undefined, "Only a save writes the image file");
assert.match(await fileText(page, cardPath("card-a")), /\nBody of Card A\.\n$/, "Close keeps the saved description");
// The reopened card restores the draft and shows its image. Save writes the image file and ends the draft.
await openCard("Card A");
await imageLoads("dot.png");
assert.match(await description.inputValue(), new RegExp(`pm-image:${first}`));
await descriptionAction("Save").click();
await waitForFile(page, cardPath("card-a"), new RegExp(`!\\[dot\\.png\\]\\(pm-image:${first}\\)`));
assert.match(await fileText(page, imageFile(first)), /"data":"data:image\/png;base64,iVBOR/);
assert.equal((await json(page, draftPath("card-a"))).body, null);
assert.deepEqual((await json(page, draftImagesPath("card-a"))).images, {});
await closeCard();
await openCard("Card A");
await imageLoads("dot.png");
await closeCard();
// The draft saves after the paste, without another edit, so the image survives a reload of the app.
await openCard("Card B");
const second = await pasteImage("second.png");
await waitForFile(page, draftImagesPath("card-b"), new RegExp(second));
await waitForFile(page, draftPath("card-b"), new RegExp(`pm-image:${second}`));
await page.reload();
await page.locator('[data-tree-rel="note.md"]').waitFor();
await openBoard(page, "Roadmap");
await openCard("Card B");
await imageLoads("second.png");
// Cancel removes the draft and its image data. The image folder gets no file.
await descriptionAction("Cancel").click();
await page.waitForFunction(rel => /"body":null/.test(window.__TEST__.files.get(rel) ?? ""), draftPath("card-b"));
assert.deepEqual((await json(page, draftImagesPath("card-b"))).images, {});
assert.equal(await fileText(page, imageFile(second)), undefined);
assert.doesNotMatch(await fileText(page, cardPath("card-b")), /pm-image:/);
await closeCard();
console.log("PASS: a draft image survives a close, a reopen, and a reload. Save writes its file. Cancel leaves no image data.");
});
+70
View File
@@ -0,0 +1,70 @@
// Project Management drag and drop: a card to another list, a card to a new place in its list, and a list to a new
// place on the board. Each drop saves the files. All tasks has no drag and drop (UI-033).
// Ports card-placement.spec.ts, card-transfer.spec.ts (drag part), lists.spec.ts, and kanban-cards.spec.ts
// of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { cardPath, column, fileText, loadWorkspace, openBoard, pane, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
const titles = locator => locator.locator(".pm-card-title").allInnerTexts();
const columnIds = page => pane(page).locator("section.pm-column").evaluateAll(nodes => nodes.map(node => node.dataset.listId));
await runSmoke("features/pmDrag", async ({ page }) => {
const output = await outputDir("features/pmDrag");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
/** Drag `source` to a point of `target` with the mouse, and take a screenshot before the drop. */
async function drag(source, target, { x = 0.5, y = 0.5, shot }) {
const from = await source.boundingBox(), to = await target.boundingBox();
await page.mouse.move(from.x + from.width / 2, from.y + Math.min(12, from.height / 2));
await page.mouse.down();
await page.mouse.move(from.x + from.width / 2 + 20, from.y + 20, { steps: 4 });
await page.mouse.move(to.x + to.width * x, to.y + to.height * y, { steps: 8 });
if (shot) {
await pane(page).locator(".pm-drag-preview").waitFor();
await page.screenshot({ path: path.join(output, shot) });
}
await page.mouse.up();
}
// A card goes to another list. The list status applies, and only that card file changes.
await setTheme(page, "dark");
const cardC = await fileText(page, cardPath("card-c"));
await drag(pane(page).locator('.pm-card[data-task-id="card-a"]'), column(page, "In progress"), { y: 0.3, shot: "card-drag-dark.png" });
await waitForFile(page, cardPath("card-a"), /listId: doing/);
assert.match(await fileText(page, cardPath("card-a")), /status: doing/);
assert.deepEqual(await titles(column(page, "In progress")), ["Card A"]);
assert.deepEqual(await titles(column(page, "To do")), ["Card B", "Shared card"]);
assert.equal(await fileText(page, cardPath("card-c")), cardC, "Other cards stay unchanged");
assert.equal(await pane(page).locator(".pm-drag-preview, .pm-drop-target").count(), 0, "The drop removes the drag preview");
// A card goes above another card of the same list.
await drag(pane(page).locator('.pm-card[data-task-id="card-d"]'), pane(page).locator('.pm-card[data-task-id="card-b"]'), { y: 0.2 });
await page.waitForFunction(() => [...document.querySelectorAll('.plugin-editor-pane .pm-column[aria-label="To do"] .pm-card-title')].map(node => node.textContent).join() === "Shared card,Card B");
const order = async id => /\n {6}order: "([^"]+)"/.exec(await fileText(page, cardPath(id)))[1];
assert(await order("card-d") < await order("card-b"), "The saved order puts Shared card first");
// A list goes to a new place: the grip of Done goes to the left half of To do.
await setTheme(page, "light");
const grip = column(page, "Done").getByRole("button", { name: "Move list Done", exact: true });
await drag(grip, column(page, "To do"), { x: 0.2, y: 0.2, shot: "list-drag-light.png" });
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-column")].map(node => node.dataset.listId).join() === "done,todo,doing,review");
assert.deepEqual((await savedBoards(page)).find(item => item.value.id === roadmap).value.lists.map(list => list.id), ["done", "todo", "doing", "review"]);
assert.deepEqual(await columnIds(page), ["done", "todo", "doing", "review"]);
await page.screenshot({ path: path.join(output, "after-drops-light.png") });
// UI-033: All tasks has no drag and drop. Its cards and lists cannot move.
await pane(page).locator(".pm-scope").click();
await page.getByRole("menuitemradio", { name: "All tasks", exact: true }).click();
await pane(page).locator(".pm-scope-label", { hasText: /^All tasks$/ }).waitFor();
await pane(page).locator(".pm-card").first().waitFor();
assert.deepEqual([...new Set(await pane(page).locator(".pm-card").evaluateAll(nodes => nodes.map(node => node.draggable)))], [false]);
assert.equal(await pane(page).locator(".pm-list-grip").count(), 0);
const before = await fileText(page, cardPath("card-b"));
await drag(pane(page).locator('.pm-card[data-task-id="card-b"]'), column(page, "Done"), {});
await page.waitForTimeout(300);
assert.equal(await fileText(page, cardPath("card-b")), before, "A drag in All tasks changes nothing");
console.log("PASS: card and list drag and drop, and no drag in All tasks");
}, { timeout: 15000 });
+66
View File
@@ -0,0 +1,66 @@
// Project Management card images: a GIF copied in a web browser keeps its original file. A failed download keeps the still copy.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
await runSmoke("features/pmImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
await description.fill("");
// A browser puts a still PNG on the clipboard, with HTML that names the original GIF.
async function pasteWebImage(src) {
await description.evaluate((element, src) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body><!--StartFragment--><img src="${src}"/><!--EndFragment--></body></html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
const reference = name => new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await pasteWebImage("https://media.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.gif\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_download_image").args);
assert.equal(download.url, "https://media.example.com/cat.gif");
// When the download fails, the card gets the still PNG.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.png\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
await editor.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_download_image").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value.match(/!\[image\.gif\]/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.equal(await editor.getByText("The website refused the original image", { exact: false }).count(), 0, "A kept original clears the message");
// An empty file from a browser drag gives a message, not the size limit.
await description.evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }));
});
await editor.getByText("The image file is empty.", { exact: false }).waitFor();
assert.equal(await editor.getByText("Use an image between 1 byte and 50 MiB.").count(), 0);
await editor.locator(".pm-description-actions").getByRole("button", { name: "Save", exact: true }).click();
await waitForFile(page, cardPath("card-a"), /pm-image:.*\n?[\s\S]*pm-image:/);
const body = await fileText(page, cardPath("card-a"));
const gif = reference("image.gif").exec(body)[1], png = reference("image.png").exec(body)[1];
assert.match(await fileText(page, imageFile(gif)), /"data":"data:image\/gif;base64,R0lGOD/);
assert.match(await fileText(page, imageFile(png)), /"data":"data:image\/png;base64,iVBOR/);
console.log("PASS: a pasted web GIF keeps its original file, a copied original needs no download, and failures explain the cause");
});
@@ -0,0 +1,38 @@
// Project Management label colors: each color choice of Manage labels shows its color, and the card title keeps its own field style, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
const rgb = hex => `rgb(${hex.slice(1).match(/../g).map(value => parseInt(value, 16)).join(", ")})`;
await runSmoke("features/pmLabelColors", async ({ page }) => {
const output = await outputDir("features/pmLabelColors");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
// The card title is a transparent field. The default field rule of Project Management does not replace its background.
const title = editor.getByRole("textbox", { name: "Title", exact: true });
assert.equal(await title.evaluate(input => getComputedStyle(input).backgroundColor), "rgba(0, 0, 0, 0)");
await editor.getByRole("group", { name: "Card details", exact: true }).getByRole("button", { name: "Labels", exact: true }).click();
await page.getByRole("dialog", { name: "Choose labels", exact: true }).getByRole("button", { name: "Manage labels", exact: true }).click();
const manager = page.getByRole("dialog", { name: "Manage labels", exact: true });
await manager.waitFor();
const bug = manager.getByRole("group", { name: "Label Bug", exact: true });
const swatches = await bug.locator("input.pm-color-swatch").evaluateAll(inputs =>
inputs.map(input => ({ name: input.getAttribute("aria-label"), color: input.style.getPropertyValue("--pm-swatch-color"), shown: getComputedStyle(input).backgroundColor })));
assert.equal(swatches.length, 16);
for (const swatch of swatches) assert.equal(swatch.shown, rgb(swatch.color), `${swatch.name} shows its color`);
await bug.getByRole("radio", { name: "Blue", exact: true }).check();
await manager.locator(".pm-label-badge", { hasText: /^Bug$/ }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await bug.screenshot({ path: path.join(output, `label-colors-${theme}.png`) });
}
console.log("PASS: label color choices and the card title field");
});
+88
View File
@@ -0,0 +1,88 @@
// Project Management in French: a language change in the settings shows an open board again in the new language and
// closes its open menu. The controls, menus, card details, and All tasks show French text from the catalog
// (src/lib/i18n/messages.ts). Board names, list names, and card titles stay as the user typed them.
// A change back to English shows English again. New in RuneStone: the plugin had no translations.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { column, loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmLanguage", async ({ page }) => {
const output = await outputDir("features/pmLanguage");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const catalog = await page.evaluate(async () => (await import("/src/lib/i18n/messages.ts")).catalogs.fr);
/** The French text of a catalog key, with its values. */
const fr = (key, values = {}) => {
assert(Object.hasOwn(catalog, key), `The catalog has "${key}"`);
return catalog[key].replace(/\{(\w+)\}/g, (_, name) => values[name]);
};
const button = name => pane(page).getByRole("button", { name, exact: true });
const setLanguage = async language => {
await page.evaluate(value => window.__TEST__.writeSettings("language", value), language);
await page.waitForFunction(value => document.documentElement.lang === value, language);
};
// An open menu closes when the language changes. The board shows again in French.
await button("List actions for To do").click();
await page.getByRole("menu", { name: "List actions", exact: true }).waitFor();
await setLanguage("fr");
await page.locator(".rs-menu").waitFor({ state: "detached" });
await button(fr("More actions")).waitFor();
assert.equal(fr("More actions"), "Plus d’actions");
assert.equal(fr("Calendar"), "Calendrier");
const views = pane(page).getByRole("navigation", { name: fr("Project Management views"), exact: true });
assert.deepEqual(await views.getByRole("button").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), [fr("Kanban"), fr("Gantt"), fr("Calendar")]);
for (const name of [fr("Search tasks"), fr("Manage labels"), fr("Add a list"), fr("Board scope: {name}", { name: "Roadmap" }),
fr("List actions for {name}", { name: "To do" }), fr("Collapse {name}", { name: "To do" }), fr("Actions for {name}", { name: "Card A" })]) {
assert.equal(await button(name).count() > 0, true, `The board has the control "${name}"`);
}
assert.equal(await column(page, "To do").getByRole("button", { name: fr("Add a card"), exact: true }).count(), 1);
assert.equal(await button("More actions").count(), 0, "No English control name stays");
// The text that the user typed stays unchanged.
assert.equal(await pane(page).locator(".pm-scope-label").innerText(), "Roadmap");
await page.getByRole("tab", { name: "Roadmap", exact: true }).waitFor();
assert.deepEqual(await column(page, "To do").locator(".pm-card-title").allInnerTexts(), ["Card A", "Card B", "Shared card"]);
assert.deepEqual(await pane(page).locator(".pm-column-heading h2").allInnerTexts(), ["To do", "In progress", "Done", "Review"]);
// The shared menus show French items.
await button(fr("List actions for {name}", { name: "To do" })).focus();
await page.keyboard.press("Enter");
const listMenu = page.getByRole("menu", { name: fr("List actions"), exact: true });
await listMenu.waitFor();
assert.deepEqual((await listMenu.getByRole("menuitem").allInnerTexts()).slice(0, 2), [fr("Edit list"), fr("Set list limit")]);
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `board-menu-fr-${theme}.png`) });
}
await page.keyboard.press("Escape");
await listMenu.waitFor({ state: "detached" });
// The card details are in French. The card title stays.
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
assert.equal(await editor.getByRole("textbox", { name: fr("Title"), exact: true }).inputValue(), "Card A");
assert.ok((await editor.locator(".pm-created-at").innerText()).startsWith(fr("Created: {date}", { date: "" })));
await editor.getByRole("button", { name: fr("Save card"), exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "card-fr-light.png") });
await editor.getByRole("button", { name: fr("Close card"), exact: true }).click();
await editor.waitFor({ state: "detached" });
// All tasks: the catalog name of a group without a board translates. Board names stay.
await pane(page).locator(".pm-scope").click();
await page.getByRole("menu", { name: fr("Board scope"), exact: true }).getByRole("menuitemradio", { name: fr("All tasks"), exact: true }).click();
await pane(page).locator(".pm-scope-label", { hasText: fr("All tasks") }).waitFor();
await page.getByRole("tab", { name: "Project Management", exact: true }).waitFor();
assert.deepEqual(await column(page, "To do").locator(".pm-board-group-heading").allInnerTexts(), ["Bugs · Roadmap", "Roadmap", fr("No active board")]);
await page.screenshot({ path: path.join(output, "all-tasks-fr-light.png") });
// A change back to English shows the open view in English at once.
await setLanguage("en");
await button("More actions").waitFor();
assert.equal(await pane(page).locator(".pm-scope-label").innerText(), "All tasks");
assert.deepEqual(await column(page, "To do").locator(".pm-board-group-heading").allInnerTexts(), ["Bugs · Roadmap", "Roadmap", "No active board"]);
assert.equal(await button(fr("More actions")).count(), 0);
console.log("PASS: French controls, menus, and card details, with the typed names unchanged");
}, { timeout: 15000 });
+127
View File
@@ -0,0 +1,127 @@
// Project Management menus: the list actions, the card actions with the Move to list submenu, the board scope, and
// More actions. All use the shared host menu. Each opens with the keyboard, in the dark and the light theme, at a wide
// and a narrow width. The arrow keys move the focus, Enter runs an item, and Escape closes the menu and returns focus.
// Ports menu-audit.spec.ts, shared-menu.spec.ts, board-menu-api.spec.ts, and relations-menu.spec.ts (keyboard part)
// of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke, settle } from "../_harness/index.mjs";
import { cardPath, column, focusedName, loadWorkspace, openBoard, pane, roadmap, savedBoards, setTheme, waitForFile } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmMenus", async ({ page }) => {
const output = await outputDir("features/pmMenus");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
const listTrigger = column(page, "To do").getByRole("button", { name: "List actions for To do", exact: true });
const cardTrigger = pane(page).getByRole("button", { name: "Actions for Card A", exact: true });
const scope = pane(page).getByRole("button", { name: "Board scope: Roadmap", exact: true });
const moreTrigger = pane(page).getByRole("button", { name: "More actions", exact: true });
const menu = name => page.getByRole("menu", { name, exact: true });
const items = async name => menu(name).locator(":scope > button").evaluateAll(rows => rows.map(row => `${row.textContent.trim()}${row.disabled ? " (disabled)" : ""}`));
/** Open a menu with `key` on its focused trigger, and return the menu after its checks. */
async function open(trigger, key, name) {
await trigger.focus();
await page.keyboard.press(key);
const panel = menu(name);
await panel.waitFor();
assert.equal(await panel.evaluate(node => node.classList.contains("rs-menu")), true, `${name} uses the shared menu`);
const box = await panel.boundingBox(), viewport = page.viewportSize();
assert(box.x >= 0 && box.y >= 0 && box.x + box.width <= viewport.width + 1 && box.y + box.height <= viewport.height + 1, `${name} stays inside the window`);
return panel;
}
/** Press Escape, and make sure that the menu closes and the trigger has focus again. */
async function dismiss(name, trigger) {
await page.keyboard.press("Escape");
await menu(name).waitFor({ state: "detached" });
assert.equal(await focusedName(page), trigger, `Escape returns focus to ${trigger}`);
}
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
for (const width of [1440, 760]) {
await page.setViewportSize({ width, height: width === 1440 ? 1000 : 700 });
// A window resize closes an open menu. Let the resize event pass first.
await settle(page);
const shot = name => page.screenshot({ path: path.join(output, `${name}-${theme}-${width}.png`) });
// List actions: Enter opens the menu on the first item. The arrow keys skip a disabled item.
await column(page, "To do").scrollIntoViewIfNeeded();
await open(listTrigger, "Enter", "List actions");
assert.deepEqual(await items("List actions"), ["Edit list", "Set list limit", "Move left (disabled)", "Move right", "Archive all cards", "Delete list"]);
assert.equal(await focusedName(page), "Edit list");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Set list limit");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Move right", "ArrowDown skips the disabled item");
await shot("list-actions");
await dismiss("List actions", "List actions for To do");
// Card actions: ArrowDown on the card menu button opens the menu. ArrowRight opens the list submenu.
await open(cardTrigger, "ArrowDown", "Card actions");
assert.deepEqual(await items("Card actions"), ["Edit card", "Move to list", "Move to board", "Move up (disabled)", "Move down", "Remove from board", "Archive", "Delete card"]);
assert.equal(await focusedName(page), "Edit card");
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "Move to list");
await page.keyboard.press("ArrowRight");
const submenu = menu("Move to list");
await submenu.waitFor();
assert.equal(await submenu.getByRole("menuitemradio", { name: "To do", exact: true }).getAttribute("aria-checked"), "true");
assert.equal(await focusedName(page), "Unlisted");
await shot("card-actions");
await page.keyboard.press("ArrowLeft");
assert.equal(await focusedName(page), "Move to list", "ArrowLeft returns to the parent item");
await dismiss("Card actions", "Actions for Card A");
// Board scope: the boards are in name order, and the focus starts on the checked board.
await open(scope, "ArrowDown", "Board scope");
assert.deepEqual(await menu("Board scope").getByRole("menuitemradio").allInnerTexts(), ["All tasks", "Bugs", "Roadmap"]);
assert.equal(await focusedName(page), "Roadmap");
await page.keyboard.press("ArrowUp");
assert.equal(await focusedName(page), "Bugs");
await shot("board-scope");
await dismiss("Board scope", "Board scope: Roadmap");
// More actions: the board commands.
await open(moreTrigger, "Enter", "More actions");
assert.deepEqual(await items("More actions"), ["New board", "Archive board", "Delete board", "Rename board", "New card", "Add existing note", "Show archived", "Refresh", "Customize background", "Project Management settings"]);
assert.equal(await focusedName(page), "New board");
await page.keyboard.press("End");
assert.equal(await focusedName(page), "Project Management settings");
await shot("more-actions");
await dismiss("More actions", "More actions");
}
}
await page.setViewportSize({ width: 1440, height: 1000 });
await settle(page);
// Enter runs the focused item. Move right changes the list order.
await open(listTrigger, "Enter", "List actions");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("Enter");
await menu("List actions").waitFor({ state: "detached" });
await page.waitForFunction(() => [...document.querySelectorAll(".plugin-editor-pane .pm-column")].map(node => node.dataset.listId).join() === "doing,todo,done,review");
assert.deepEqual((await savedBoards(page)).find(item => item.value.id === roadmap).value.lists.map(list => list.id), ["doing", "todo", "done", "review"]);
// Enter on a submenu item moves the card to that list.
await open(cardTrigger, "ArrowDown", "Card actions");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowRight");
await menu("Move to list").waitFor();
// The submenu follows the new list order: Unlisted, In progress, To do, Done, Review.
await page.keyboard.press("ArrowDown");
assert.equal(await focusedName(page), "In progress");
await page.keyboard.press("Enter");
await waitForFile(page, cardPath("card-a"), /listId: doing/);
await column(page, "In progress").locator(".pm-card-title", { hasText: "Card A" }).waitFor();
// Enter on a board opens it in the same tab.
await open(scope, "ArrowDown", "Board scope");
await page.keyboard.press("ArrowUp");
await page.keyboard.press("Enter");
await page.getByRole("tab", { name: "Bugs", exact: true, selected: true }).waitFor();
await pane(page).getByRole("button", { name: "Board scope: Bugs", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "Roadmap", exact: true }).count(), 0);
console.log("PASS: list, card, board scope, and board menus with the keyboard in both themes");
}, { timeout: 15000 });
+92
View File
@@ -0,0 +1,92 @@
// Project Management views: All tasks with merged list columns and board dividers (UI-034, UI-035), then Gantt,
// Calendar (month, week, and day), and Kanban, in both themes. Each view keeps its own view state.
// Ports all-tasks.spec.ts, board-scope-alignment.spec.ts, board-view-state.spec.ts, and the Gantt and Calendar parts of
// workflow.spec.ts of RuneStone_Project_Management.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { card, column, loadWorkspace, openBoard, pane, pmFiles, roadmap, setTheme } from "../_harness/pmFixture.mjs";
await runSmoke("features/pmViews", async ({ page }) => {
const output = await outputDir("features/pmViews");
// One more card on the Review list of Roadmap, so that the merged review column has two boards.
await loadWorkspace(page, Object.fromEntries([...Object.entries(pmFiles()), card("card-f", "Review card", { placements: { [roadmap]: "review" }, order: "f" })]));
await openBoard(page);
const view = name => pane(page).getByRole("navigation", { name: "Project Management views", exact: true }).getByRole("button", { name, exact: true });
const shots = async name => {
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await page.screenshot({ path: path.join(output, `${name}-${theme}.png`) });
}
};
// UI-034: equal list names share one column. Case and outer spaces do not matter ("Review" and "review").
await pane(page).locator(".pm-card").first().waitFor();
assert.equal(await view("Kanban").getAttribute("aria-pressed"), "true");
const labels = await pane(page).locator("section.pm-column").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label")));
assert.deepEqual(labels.map(label => label.toLowerCase()), ["to do", "in progress", "done", "review"]);
// UI-035: each column groups its cards under board names. A shared card shows once, under the names of its boards.
const todo = column(page, "To do");
const headings = locator => locator.locator(".pm-board-group-heading").allInnerTexts();
assert.deepEqual(await headings(todo), ["Bugs · Roadmap", "Roadmap", "No active board"]);
assert.equal(await todo.locator(".pm-card-title", { hasText: /^Shared card$/ }).count(), 1, "A shared card shows once");
assert.deepEqual(await todo.getByRole("region", { name: "Roadmap", exact: true }).locator(".pm-card-title").allInnerTexts(), ["Card A", "Card B"]);
assert.deepEqual(await todo.getByRole("region", { name: "No active board", exact: true }).locator(".pm-card-title").allInnerTexts(), ["Loose card"]);
const review = pane(page).locator('section.pm-column[data-list-id="list:review"]');
assert.deepEqual(await headings(review), ["Bugs", "Roadmap"]);
// A merged column has no board limit. The board keeps its limit (checked below).
assert.equal(await review.locator(".pm-list-limit").count(), 0);
assert.equal(await review.locator(".pm-count").innerText(), "2");
assert.equal(await pane(page).locator(".pm-board-group-heading").evaluateAll(nodes => nodes.every(node => getComputedStyle(node).opacity === "1")), true, "Board names are opaque");
await shots("all-tasks");
// Gantt: a row for each card, a bar for the planned dates, and a deadline marker.
await view("Gantt").click();
assert.equal(await view("Gantt").getAttribute("aria-pressed"), "true");
const timeline = pane(page).getByRole("table", { name: "Task timeline", exact: true });
await timeline.waitFor();
assert.equal(await timeline.locator(".pm-gantt-row").count(), 7, "A heading row and six cards");
const bar = timeline.locator(".pm-gantt-bar", { hasText: "Card B" });
assert.match(await bar.getAttribute("title"), /^Card B: .+ to .+$/);
assert.equal(await timeline.locator(".pm-deadline").count(), 1);
assert.match(await timeline.locator(".pm-deadline").getAttribute("aria-label"), /^Card B, deadline /);
assert.equal(await timeline.getByRole("button", { name: /^Card A/ }).locator("small").innerText(), "Unscheduled");
await pane(page).getByRole("button", { name: "Next", exact: true }).click();
await pane(page).getByRole("button", { name: "Today", exact: true }).click();
await timeline.locator(".pm-gantt-bar").waitFor();
await shots("gantt");
// Calendar: the month shows the deadline. Week and Day show the hours.
await view("Calendar").click();
const period = name => pane(page).locator(".pm-date-nav").getByRole("button", { name, exact: true });
assert.equal(await period("Month").getAttribute("aria-pressed"), "true");
await pane(page).locator(".pm-month").waitFor();
assert.equal(await pane(page).locator(".pm-day-heading").count(), 7);
assert.equal(await pane(page).locator(".pm-month-day").count(), 42);
await pane(page).getByRole("button", { name: "◆ Due: Card B", exact: true }).waitFor();
await shots("calendar-month");
await period("Week").click();
assert.equal(await pane(page).locator(".pm-hour-day").count(), 7);
assert.equal(await period("Week").getAttribute("aria-pressed"), "true");
await shots("calendar-week");
await period("Day").click();
assert.equal(await pane(page).locator(".pm-hour-day").count(), 1);
assert.equal(await pane(page).locator(".pm-hour-day .pm-hour-slot").count(), 24);
await page.waitForFunction(() => {
const state = JSON.parse(localStorage.getItem("runestone.pm.viewStates") ?? "{}").planning;
return state?.view === "calendar" && state?.period === "day";
});
// Kanban again. A board in the same tab has its own view state and shows its limit.
await view("Kanban").click();
await pane(page).locator(".pm-board").waitFor();
await openBoard(page, "Roadmap");
assert.equal(await view("Kanban").getAttribute("aria-pressed"), "true", "A board starts in Kanban");
assert.equal(await column(page, "Review").locator(".pm-count").innerText(), "1/2");
assert.equal(await column(page, "Review").locator(".pm-list-limit").count(), 1);
await view("Calendar").click();
await pane(page).locator(".pm-month").waitFor();
await shots("board-calendar");
console.log("PASS: All tasks columns and dividers, Gantt, Calendar, and Kanban");
}, { timeout: 15000 });
+65
View File
@@ -0,0 +1,65 @@
// Settings → Features: the switch of each native feature, the migration default, search, keyboard use, both themes, and narrow windows.
// A switch in the Settings window changes the main window at once.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("features/settings", async ({ browser }) => {
const output = await outputDir("features/settings");
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({ root: "C:\\features-settings", files: { "note.md": "# Note\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
}),
});
const main = await openPage(context, { timeout: 10000 });
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="note.md"]').waitFor();
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true, terminal: true, pdf: true, pm: true });
const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("heading", { name: "Features", exact: true }).waitFor();
const git = settings.getByRole("switch", { name: "Git", exact: true });
assert.equal(await git.isChecked(), true);
assert.match(await git.getAttribute("aria-describedby"), /feature-git-description/);
await git.click();
await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true, terminal: true, pdf: true, pm: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus();
await settings.keyboard.press("Space");
await sourceControl.waitFor();
assert.equal(await git.isChecked(), true);
// The settings search finds the page by the name and the words of a feature.
const search = settings.getByRole("textbox", { name: "Search settings", exact: true });
await search.fill("source control");
assert.deepEqual(await settings.locator('nav[aria-label="Settings categories"] button').allInnerTexts(), ["Features"]);
await search.fill("");
for (const theme of ["dark", "light"]) {
await settings.evaluate(value => { document.documentElement.dataset.theme = value; }, theme);
for (const width of [1152, 540, 360]) {
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 520 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `No horizontal scroll at ${width} pixels`);
const row = settings.locator(".setting-row", { has: git });
const box = await row.boundingBox();
const toggle = await git.boundingBox();
assert(toggle.x + toggle.width <= box.x + box.width + 1, "The switch stays inside its row");
await settings.screenshot({ path: path.join(output, `features-${theme}-${width}.png`) });
}
}
await git.focus();
assert.equal(await git.evaluate(node => node.matches(":focus-visible")), true);
await settings.screenshot({ path: path.join(output, "features-focus.png") });
console.log("PASS: the Features page turns Git off and on in another window, with search, keyboard, both themes, and narrow widths");
}, { timeout: 60000 });
+474
View File
@@ -0,0 +1,474 @@
// The Terminal feature: lazy load, copy and paste, the theme and the --rs-ansi-* colors, splits, maximize, profiles, history pickers,
// tasks, run file and run selection, Settings → Terminal, the Off prompt, close and reopen, and the terminal window.
// The `pty_*` commands are mocks with channels (tests/smoke/_harness/index.mjs). They do not prove real shell behavior.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
await runSmoke("features/terminal", async ({ browser }) => {
const output = await outputDir("features/terminal");
const shot = name => path.join(output, name);
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await mockTauri(context, {
state: { confirm: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
files: {
"notes/welcome.md": "# Working notes\n\nFirst paragraph.\n",
"src/hello.py": "print('hello')\n",
},
});
test.files = workspace.files;
return {
...workspace,
pty_profiles: () => [{ id: "powershell", title: "PowerShell", kind: "powershell" }, { id: "cmd", title: "Command Prompt", kind: "cmd" }, { id: "git-bash", title: "Git Bash", kind: "bash" }, { id: "node", title: "JavaScript Debug Terminal", kind: "node" }],
settings_open_window: () => null,
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|destroy": () => null,
"plugin:dialog|message": args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return test.state.confirm; },
};
},
});
const page = await openPage(context);
const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command);
const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n });
const click = name => page.getByRole("button", { name, exact: true }).click();
const menu = name => page.getByRole("menuitem", { name, exact: true }).click();
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join(""));
const xtermLoaded = target => target.evaluate(() => performance.getEntriesByType("resource").some(entry => /xterm/i.test(entry.name)));
const appearance = (target, mode) => target.evaluate(async mode => {
const { applyAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ theme: "default", mode });
}, mode);
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
// The Terminal button shows from the static catalog. The feature module and xterm load at the first use.
assert.equal(await xtermLoaded(page), false, "xterm does not load at start");
await click("Terminal");
await waitCount("pty_open", 1);
const open = await page.evaluate(() => window.__TEST__.calls.find(c => c.command === "pty_open").args);
assert.equal(typeof open.page, "string", "Each open sends the page ID");
assert.equal(open.cwd, "C:\\smoke-workspace");
await page.locator(".xterm-rows > div > span").first().waitFor();
assert.equal(await xtermLoaded(page), true);
const terminalFont = await page.locator(".xterm-rows > div > span").first().evaluate(element => {
const style = getComputedStyle(element);
return { family: style.fontFamily, weight: style.fontWeight, size: style.fontSize };
});
assert.equal(terminalFont.weight, "300");
assert.equal(terminalFont.size, "13px");
assert.ok(terminalFont.family.startsWith('"Cascadia Mono"'));
// The input before the open finished includes the answer of xterm to the cursor position query.
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
// Copy: a drag selects without copy, a right-click copies and clears, Ctrl+C copies a selection, and without one it interrupts.
await page.evaluate(() => navigator.clipboard.writeText("before selection"));
const beforeSelection = await writes();
const firstText = await page.locator(".xterm-rows > div > span").first().boundingBox();
await page.mouse.move(firstText.x + 1, firstText.y + firstText.height / 2);
await page.mouse.down();
await page.mouse.move(firstText.x + firstText.width, firstText.y + firstText.height / 2, { steps: 10 });
await page.mouse.up();
assert.ok(await page.locator(".xterm-selection > div").count(), "Mouse drag selects terminal output.");
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "before selection", "Selection does not copy output.");
assert.equal(await writes(), beforeSelection, "Selection does not send input to the shell.");
await page.locator(".term").first().screenshot({ path: shot("terminal-copy-selection.png") });
await page.evaluate(() => {
window.__TEST__.writeText = navigator.clipboard.writeText.bind(navigator.clipboard);
navigator.clipboard.writeText = text => new Promise(resolve => {
window.__TEST__.finishCopy = async () => { await window.__TEST__.writeText(text); resolve(); };
});
});
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
assert.ok(await page.locator(".xterm-selection > div").count(), "Selection stays until the clipboard write succeeds.");
await page.evaluate(() => window.__TEST__.finishCopy());
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
await page.waitForFunction(() => !document.querySelector(".xterm-selection > div"));
assert.equal(await writes(), beforeSelection, "Right-click copy does not send input to the shell.");
await page.evaluate(() => navigator.clipboard.writeText("empty selection"));
await page.mouse.click(firstText.x + 10, firstText.y + firstText.height / 2, { button: "right" });
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "empty selection", "Right-click without selection keeps the clipboard.");
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
await page.evaluate(() => navigator.clipboard.writeText(""));
const beforeCopy = await writes();
await page.keyboard.press("Control+c");
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
assert.equal(await writes(), beforeCopy, "Copy does not send an interrupt to the shell.");
const beforeInterrupt = await writes();
await page.locator(".xterm-screen").first().click();
await page.keyboard.press("Control+c");
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join("").length > before.length, beforeInterrupt);
assert.equal((await writes()).slice(beforeInterrupt.length), "\u0003", "Ctrl+C without selection interrupts the shell.");
// A denied clipboard write keeps the selection for another try.
await page.mouse.dblclick(firstText.x + 10, firstText.y + firstText.height / 2);
await page.evaluate(() => { navigator.clipboard.writeText = () => Promise.reject(new Error("Clipboard denied for smoke test")); });
await page.locator(".xterm-screen").first().click({ button: "right" });
await page.getByText("Error: Clipboard denied for smoke test", { exact: true }).waitFor();
assert.ok(await page.locator(".xterm-selection > div").count(), "Failed copy keeps the selection.");
await page.evaluate(() => { navigator.clipboard.writeText = window.__TEST__.writeText; });
// The 16 ANSI colors come from the --rs-ansi-* tokens. A token change reaches the open terminal.
const id = open.id;
await page.evaluate(id => window.__TEST__.pty.output(id, "\x1b[31mANSI-RED\x1b[0m \x1b[94mANSI-BLUE\x1b[0m\r\n"), id);
const colorOf = text => page.evaluate(text => {
const span = [...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text));
return span && getComputedStyle(span).color;
}, text);
await page.waitForFunction(() => [...document.querySelectorAll(".xterm-rows span")].some(node => node.textContent.includes("ANSI-RED")));
const red = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-ansi-red").trim());
assert.ok(red, "The theme defines --rs-ansi-red");
await page.evaluate(() => {
document.documentElement.style.setProperty("--rs-ansi-red", "#12ab34");
document.documentElement.style.setProperty("--rs-ansi-bright-blue", "#3456cd");
});
await page.waitForFunction(() => {
const color = text => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes(text))).color;
return color("ANSI-RED") === "rgb(18, 171, 52)" && color("ANSI-BLUE") === "rgb(52, 86, 205)";
});
await page.evaluate(() => { for (const name of ["--rs-ansi-red", "--rs-ansi-bright-blue"]) document.documentElement.style.removeProperty(name); });
await page.waitForFunction(() => getComputedStyle([...document.querySelectorAll(".xterm-rows span")].find(node => node.textContent.includes("ANSI-RED"))).color !== "rgb(18, 171, 52)");
assert.notEqual(await colorOf("ANSI-RED"), "rgb(18, 171, 52)");
// Selection colors keep their hue and stay at most 65% opaque, in both themes and at two widths.
for (const theme of ["light", "dark"]) {
await appearance(page, theme);
for (const width of [620, 1440]) {
await page.setViewportSize({ width, height: 1000 });
await page.locator(".xterm-helper-textarea").first().focus();
const text = await (await page.waitForFunction(() => {
const node = [...document.querySelectorAll(".xterm-rows > div > span")].find(node => node.textContent.includes("READY"));
const rect = node?.getBoundingClientRect();
return rect?.width ? { x: rect.x, y: rect.y, width: rect.width, height: rect.height } : null;
})).jsonValue();
await page.mouse.move(text.x + 1, text.y + text.height / 2);
await page.mouse.down();
await page.mouse.move(text.x + text.width, text.y + text.height / 2, { steps: 10 });
await page.mouse.up();
await page.evaluate(() => navigator.clipboard.writeText(""));
await page.keyboard.press("Control+Shift+c");
await page.waitForFunction(async () => (await navigator.clipboard.readText()).includes("READY"));
const selectionColor = await page.locator(".xterm-selection > div").first().evaluate(node => getComputedStyle(node).backgroundColor);
const selectionAlpha = Number(selectionColor.match(/rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)\)/)?.[1] ?? 1);
assert.ok(selectionAlpha > 0 && selectionAlpha <= 0.65, `Terminal selection keeps transparency: ${selectionColor}`);
assert.ok(await page.locator(".xterm-rows .xterm-decoration-top").first().evaluate(node => getComputedStyle(node).backgroundColor === "rgba(0, 0, 0, 0)"), "Selected glyph backgrounds stay transparent.");
await page.locator(".term").first().screenshot({ path: shot(`terminal-theme-${theme}-${width}.png`) });
}
}
for (const [source, expected] of [["#ff8000", [255, 128, 0, 0.647]], ["rgba(0, 255, 128, 0.35)", [0, 255, 128, 0.35]]]) {
await page.evaluate(source => document.documentElement.style.setProperty("--rs-selection", source), source);
await page.waitForFunction(expected => {
const channels = getComputedStyle(document.querySelector(".xterm-selection > div")).backgroundColor.match(/[\d.]+/g).map(Number);
return channels.length === 4 && channels.slice(0, 3).every((channel, index) => Math.abs(channel - expected[index]) <= 2) && Math.abs(channels[3] - expected[3]) < 0.005;
}, expected);
}
await page.evaluate(() => document.documentElement.style.removeProperty("--rs-selection"));
// The panel surfaces are translucent, the xterm layers are transparent, and the ribbon controls fit at 620 pixels.
const surfaces = () => page.evaluate(() => {
const alpha = color => {
const canvas = document.createElement("canvas");
canvas.width = canvas.height = 1;
const context = canvas.getContext("2d");
context.fillStyle = color;
context.fillRect(0, 0, 1, 1);
return context.getImageData(0, 0, 1, 1).data[3] / 255;
};
return Object.fromEntries([".ribbon", ".term", ".xterm", ".xterm-viewport", ".rail", ".pane-label"].map(selector => {
const element = document.querySelector(`.dock ${selector}`);
if (!element) return [selector, null];
const style = getComputedStyle(element);
return [selector, { alpha: alpha(style.backgroundColor), opacity: style.opacity }];
}));
});
for (const mode of ["light", "dark"]) {
await appearance(page, mode);
await settle(page);
const colors = await surfaces();
// The ribbon and the panes use the translucent surface tokens, so a background image shows through them.
assert.ok(colors[".ribbon"].alpha > 0.5 && colors[".ribbon"].alpha < 1, `ribbon ${colors[".ribbon"].alpha}`);
assert.ok(colors[".term"].alpha > 0.5 && colors[".term"].alpha < 1, `term ${colors[".term"].alpha}`);
assert.equal(colors[".xterm"].alpha, 0);
assert.equal(colors[".xterm-viewport"].alpha, 0);
assert.equal(colors[".ribbon"].opacity, "1");
assert.equal(await page.locator(".bottom").evaluate(element => getComputedStyle(element).backgroundColor), "rgba(0, 0, 0, 0)");
for (const width of [620, 1440]) {
await page.setViewportSize({ width, height: 800 });
await page.locator(".xterm-helper-textarea").first().focus();
await settle(page);
await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).focus();
await page.getByRole("tooltip", { name: "Terminal profiles and tasks", exact: true }).waitFor();
const ribbonBounds = await page.locator(".dock .ribbon").boundingBox();
for (const button of await page.locator(".dock .ribbon button").all()) {
const bounds = await button.boundingBox();
assert.ok(bounds.x >= ribbonBounds.x && bounds.x + bounds.width <= ribbonBounds.x + ribbonBounds.width + 1);
assert.ok(bounds.width >= 28 && bounds.height >= 28);
}
await page.screenshot({ path: shot(`terminal-translucent-${mode}-${width}.png`) });
}
}
// Splits, maximize, hide and show without a close, profiles, and kill.
await page.setViewportSize({ width: 1440, height: 1000 });
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
const adjacent = await page.getByRole("button", { name: "New terminal", exact: true }).evaluate(button => { const buttons = [...button.closest(".actions").querySelectorAll("button")]; return buttons[buttons.indexOf(button) + 1]?.getAttribute("aria-label"); });
assert.equal(adjacent, "Terminal profiles and tasks");
await click("Split terminal (Ctrl+Shift+5)");
await waitCount("pty_open", 2);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 1);
assert.equal(await page.locator(".pane.shown").count(), 2);
const original = await page.locator(".pane.shown").first().boundingBox();
await click("Maximize panel");
const enlarged = await page.locator(".pane.shown").first().boundingBox();
assert.ok(enlarged.height > original.height + 100);
assert.equal(await count("pty_close"), 0);
await page.screenshot({ path: shot("terminal-splits.png") });
await click("Restore panel");
await page.keyboard.press("Control+j");
assert.equal(await count("pty_close"), 0);
await page.keyboard.press("Control+j");
assert.equal(await count("pty_open"), 2);
await click("Terminal profiles and tasks");
const splitProfile = page.getByRole("menuitem", { name: "Split terminal with profile", exact: true });
await splitProfile.focus();
await page.keyboard.press("ArrowRight");
const profileSubmenu = page.getByRole("menu", { name: "Split terminal with profile", exact: true });
assert(await profileSubmenu.getByRole("menuitem", { name: "PowerShell", exact: true }).evaluate(node => document.activeElement === node));
await page.keyboard.press("ArrowLeft");
assert(await splitProfile.evaluate(node => document.activeElement === node));
await page.keyboard.press("Escape");
assert(await page.getByRole("button", { name: "Terminal profiles and tasks", exact: true }).evaluate(node => document.activeElement === node));
await click("Terminal profiles and tasks");
await page.screenshot({ path: shot("terminal-profiles.png") });
await menu("Command Prompt");
await waitCount("pty_open", 3);
assert.equal(await page.locator(".pane.shown").count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "cmd");
await page.keyboard.press("Control+Shift+5");
await waitCount("pty_open", 4);
assert.equal(await page.locator(".pane.shown").count(), 2);
await click("Kill terminal");
await waitCount("pty_close", 1);
assert.equal(await page.locator(".pane.shown").count(), 1);
// OSC 633 and 133 shell integration fills the history pickers.
await page.evaluate(() => {
const id = window.__TEST__.calls.filter(c => c.command === "pty_open")[2].args.id;
const data = `\x1b]633;RSCommand;${btoa("echo history-check")}\x07\x1b]633;RSCwd;${btoa("C:\\two words")}\x07\x1b]133;A\x07C:\\two words>\x1b]133;B\x07`;
window.__TEST__.pty.output(id, data);
});
await click("More terminal actions");
assert(await page.getByRole("menuitem", { name: "Run the active file", exact: true }).isDisabled());
assert(await page.getByRole("menuitem", { name: "Run selected text", exact: true }).isDisabled());
await page.screenshot({ path: shot("terminal-actions.png") });
await menu("Run a recent command… Ctrl+Alt+R");
await page.getByRole("dialog").getByRole("option", { name: "echo history-check" }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo history-check")));
await page.keyboard.press("Control+g");
await page.getByRole("dialog").getByRole("option", { name: "C:\\two words" }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes('cd /d "C:\\two words"')));
// Settings → Terminal opens Settings. The page does not load xterm, and its changes reach the open panel.
await click("Terminal profiles and tasks");
await menu("Terminal settings");
await waitCount("settings_open_window", 1);
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
const dialog = settings.getByRole("dialog", { name: "Settings", exact: true });
await dialog.getByRole("button", { name: "Terminal", exact: true }).click();
await dialog.getByRole("heading", { name: "Terminal", exact: true }).waitFor();
assert.equal(await xtermLoaded(settings), false, "Settings → Terminal does not load xterm");
const fontSize = dialog.getByLabel("Font size", { exact: true });
assert.equal(await fontSize.inputValue(), "13");
await fontSize.fill("40");
await fontSize.press("Enter");
await fontSize.blur();
await dialog.getByText("Choose a whole number from 9 to 28.", { exact: true }).waitFor();
await fontSize.fill("16");
await fontSize.blur();
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.fontSize === 16);
await page.waitForFunction(() => getComputedStyle(document.querySelector(".pane.shown .xterm-rows > div > span")).fontSize === "16px");
for (const mode of ["light", "dark"]) {
await appearance(settings, mode);
for (const width of [1152, 360]) {
await settings.setViewportSize({ width, height: width === 360 ? 640 : 815 });
await settle(settings);
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `No horizontal scroll at ${width} pixels`);
await settings.screenshot({ path: shot(`settings-terminal-${mode}-${width}.png`) });
}
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
const profileMenu = settings.getByRole("menu", { name: "Default terminal profile", exact: true });
const current = profileMenu.getByRole("menuitemradio", { name: "PowerShell", exact: true });
assert.equal(await current.getAttribute("aria-checked"), "true");
assert.equal(await profileMenu.getByRole("menuitemradio", { name: "JavaScript Debug Terminal", exact: true }).count(), 0, "The debug terminal is not a default");
const bounds = await profileMenu.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 640);
await settings.screenshot({ path: shot(`settings-terminal-profile-${mode}-360.png`) });
await settings.keyboard.press("End");
assert(await profileMenu.getByRole("menuitemradio", { name: "Git Bash", exact: true }).evaluate(node => document.activeElement === node));
await settings.keyboard.press("Escape");
assert(await dialog.getByRole("button", { name: "Default profile", exact: true }).evaluate(node => document.activeElement === node));
}
await settings.setViewportSize({ width: 1152, height: 815 });
await dialog.getByRole("button", { name: "Default profile", exact: true }).click();
await settings.getByRole("menuitemradio", { name: "Git Bash", exact: true }).click();
await dialog.getByRole("switch", { name: "Blink cursor", exact: true }).uncheck();
await settings.waitForFunction(() => window.__TEST__.settings("terminal")?.defaultProfile === "git-bash" && window.__TEST__.settings("terminal")?.cursorBlink === false);
await page.bringToFront();
await click("New terminal");
await waitCount("pty_open", 5);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.profile), "git-bash");
// Tasks from .runestone/tasks.json, with the shared picker rows at 360 pixels in both themes.
await page.evaluate(() => window.__TEST__.files.set(".runestone/tasks.json", JSON.stringify({ tasks: [{ label: "Smoke task", command: "echo task-ok", profile: "powershell" }] })));
await click("Terminal profiles and tasks");
await menu("Run a task…");
for (const mode of ["light", "dark"]) {
await appearance(page, mode);
await page.setViewportSize({ width: 360, height: 640 });
const row = page.getByRole("option", { name: "Smoke task echo task-ok" });
const measurements = await row.evaluate(node => {
const css = getComputedStyle(node);
const root = getComputedStyle(document.documentElement);
return { fontSize: css.fontSize, minHeight: css.minHeight, padding: css.padding, radius: css.borderRadius,
tokenFont: root.getPropertyValue("--rs-menu-font-size").trim(), tokenHeight: root.getPropertyValue("--rs-menu-row-height").trim(),
tokenRadius: root.getPropertyValue("--rs-control-radius").trim(), tokenPadding: root.getPropertyValue("--rs-menu-row-padding").trim() };
});
assert.equal(measurements.fontSize, measurements.tokenFont);
assert.equal(measurements.minHeight, measurements.tokenHeight);
assert.equal(measurements.radius, measurements.tokenRadius);
assert.equal(measurements.padding, measurements.tokenPadding);
await page.screenshot({ path: shot(`terminal-task-picker-${mode}-360.png`) });
}
await page.setViewportSize({ width: 1440, height: 1000 });
const taskQuery = page.getByRole("combobox", { name: "Run a task", exact: true });
await taskQuery.fill("no-such-task");
await page.getByText("No entries match the filter.", { exact: true }).waitFor();
assert.equal(await page.getByRole("option").count(), 0);
await taskQuery.fill("Smoke task");
const taskOption = page.getByRole("option", { name: "Smoke task echo task-ok" });
assert.equal(await taskQuery.getAttribute("aria-activedescendant"), await taskOption.getAttribute("id"));
await taskQuery.press("Enter");
await waitCount("pty_open", 6);
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("echo task-ok")));
// Run selected text and run the active file. The editor keeps its selection while the menu takes focus.
// The shell owns its control keys, so the test opens the file from a new tab.
await click("New tab (Ctrl+T)");
await page.getByRole("button", { name: /^Find file/ }).click();
await page.getByRole("textbox", { name: "Find a file" }).fill("hello.py");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "hello.py" }).first().click();
const editor = page.locator(".cm-content").first();
await editor.waitFor();
const editorFont = await editor.evaluate(element => ({ family: getComputedStyle(element).fontFamily, weight: getComputedStyle(element).fontWeight }));
assert.equal(editorFont.weight, terminalFont.weight, "The terminal uses the code font weight");
assert.ok(editorFont.family.startsWith(terminalFont.family.split(",")[0]), "The terminal uses the code font");
await editor.click();
await page.keyboard.press("Control+a");
await click("More terminal actions");
await menu("Run selected text");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("print('hello')")));
await click("More terminal actions");
await menu("Run the active file");
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && c.args.data.includes("python 'C:\\smoke-workspace\\src\\hello.py'")));
await click("Terminal profiles and tasks");
await menu("New terminal window Ctrl+Alt+Shift+`");
await waitCount("pty_new_window", 1);
await click("More terminal actions");
await menu("Start dictation");
await waitCount("pty_dictation", 1);
await click("More terminal actions");
await menu("Clear the terminal");
assert.equal(await count("pty_close"), 1);
// Kill down to one session and none, start again, the new and window shortcuts, then close and a fresh reopen.
await page.setViewportSize({ width: 880, height: 600 });
await page.screenshot({ path: shot("terminal-narrow.png") });
for (let remaining = 5; remaining > 1; remaining--) await click("Kill terminal");
await waitCount("pty_close", 5);
assert.equal(await page.getByRole("navigation", { name: "Terminal list" }).count(), 0);
await click("Kill terminal");
await waitCount("pty_close", 6);
await click("Start a terminal");
await waitCount("pty_open", 7);
await page.locator(".pane.shown .xterm-helper-textarea").focus();
await page.keyboard.press("Control+Shift+Backquote");
await waitCount("pty_open", 8);
await page.keyboard.press("Control+Shift+Alt+Backquote");
await waitCount("pty_new_window", 2);
const opens = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").map(c => c.args.id));
await click("Close terminal (end all sessions)");
await waitCount("pty_close", opens.length);
const closedIds = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").map(c => c.args.id));
assert.deepEqual([...closedIds].sort(), [...opens].sort());
await page.keyboard.press("Control+j");
await waitCount("pty_open", opens.length + 1);
const freshId = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").at(-1).args.id);
assert.equal(opens.includes(freshId), false);
// The new shell takes the focus when it starts. Wait for that before the focus moves to the close button.
await page.waitForFunction(id => window.__TEST__.calls.some(c => c.command === "pty_resize" && c.args.id === id), freshId);
await appearance(page, "light");
await settle(page);
await page.getByRole("button", { name: "Close terminal (end all sessions)", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close terminal (end all sessions)", exact: true }).waitFor();
await page.screenshot({ path: shot("terminal-close-light-narrow-focus.png") });
await page.keyboard.press("Enter");
await waitCount("pty_close", opens.length + 1);
await page.keyboard.press("Control+Shift+Backquote");
await waitCount("pty_open", opens.length + 2);
assert.equal(await page.locator(".pane.shown").count(), 1);
// Off asks first while a shell runs. Cancel keeps the shells. OK ends them and removes the controls.
await settings.bringToFront();
await dialog.getByRole("button", { name: "Features", exact: true }).click();
const terminalSwitch = dialog.getByRole("switch", { name: "Terminal", exact: true });
await terminalSwitch.click();
await settings.waitForFunction(() => window.__TEST__.state.prompts?.length === 1);
await settings.waitForFunction(() => document.querySelector("#feature-terminal").checked);
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), ["Terminal sessions will end.\nTurn off Terminal?"]);
assert.equal(await terminalSwitch.isChecked(), true, "Cancel keeps Terminal on");
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), true);
const closesBefore = await count("pty_close");
await settings.evaluate(() => { window.__TEST__.state.confirm = "Ok"; });
await terminalSwitch.click();
await page.waitForFunction(before => window.__TEST__.calls.filter(c => c.command === "pty_close").length > before, closesBefore);
assert.equal(await settings.evaluate(() => window.__TEST__.settings("features").terminal), false);
await page.getByRole("button", { name: "Terminal", exact: true }).waitFor({ state: "detached" });
assert.equal(await dialog.getByRole("button", { name: "Terminal", exact: true }).count(), 0, "Settings → Terminal hides while Terminal is off");
for (const mode of ["light", "dark"]) {
await appearance(settings, mode);
await settings.setViewportSize({ width: 360, height: 640 });
await settle(settings);
await settings.screenshot({ path: shot(`features-terminal-off-${mode}-360.png`) });
}
// Without prompts, an Off with no shell needs no question.
await terminalSwitch.check();
await page.getByRole("button", { name: "Terminal", exact: true }).first().waitFor();
await settings.evaluate(() => { window.__TEST__.state.prompts = []; });
await terminalSwitch.uncheck();
await settings.waitForFunction(() => window.__TEST__.settings("features").terminal === false);
assert.deepEqual(await settings.evaluate(() => window.__TEST__.state.prompts), []);
await terminalSwitch.check();
assert.deepEqual([...page.errors, ...settings.errors], []);
await settings.close();
// The terminal window: one session, no workspace open, the exit code from the channel, and close.
await page.goto(`${smokeUrl}/?terminalWindow=C%3A%5Csmoke-workspace`);
await page.locator(".xterm").waitFor();
await waitCount("pty_open", 1);
assert.equal(await count("workspace_open"), 0);
assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1);
assert.equal(await page.getByRole("button", { name: "Maximize panel", exact: true }).count(), 0);
await page.screenshot({ path: shot("terminal-window.png") });
await page.evaluate(() => window.__TEST__.pty.exit(window.__TEST__.calls.find(c => c.command === "pty_open").args.id, 3));
await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("[Process exited with code 3]"));
await click("Close terminal window");
await waitCount("plugin:window|destroy", 1);
assert.equal(await count("pty_close"), 0, "The host removed the exited shell, so the close needs no host call");
assert.deepEqual(page.errors, []);
console.log("PASS: terminal lazy load, copy, ANSI tokens, selection, splits, profiles, history, Settings → Terminal, tasks, run file, Off prompt, close and reopen, and the terminal window.");
}, { timeout: 30000 });
+147
View File
@@ -0,0 +1,147 @@
// One full-width document Find in Writer, table cells, Source source, and Reading: replacement, regex, CRLF, focus return, both themes, and narrow controls.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("find/documentFind", async ({ page }) => {
const output = await outputDir("find/documentFind");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"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",
},
});
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
});
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
async function onePanel() {
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await page.locator('.cm-search').count(), 0, 'No default CodeMirror search panel');
// Read both widths in one task. Two separate reads can cross a layout change.
const [bar, pane] = await page.locator('.rs-find-bar:visible').evaluate(node => [node, node.closest('.editor.pane-active')].map(element => element.getBoundingClientRect().width));
assert.ok(Math.abs(bar - pane) < 3, 'Find spans the document pane');
}
async function sourceEditor() {
await page.waitForFunction(() => !!document.querySelector('.source-editor .cm-content'));
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__SOURCE__ = EditorView.findFromDOM(document.querySelector('.source-editor .cm-content'));
window.__SOURCE__.focus();
});
}
await page.goto(smokeUrl);
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();
for (const theme of ['dark', 'light']) {
await page.evaluate(async theme => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode: theme });
}, theme);
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.evaluate(async sample => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.live-writer > .cm-editor .cm-content'));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: sample }, selection: { anchor: 0 } });
window.__CM__.focus();
}, sample);
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.screenshot({ path: `${output}/writer-${theme}.png` });
await page.keyboard.press('Escape');
await page.locator('.live-writer td').first().dblclick();
await page.locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Control+f');
await onePanel();
assert.equal(await find.evaluate(node => node === document.activeElement), true, 'Table focus opens the document find');
assert.equal(await page.locator('.writer-cell-editor .rs-find-bar').count(), 0);
await find.fill('Last Alpha');
await page.keyboard.press('Enter');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/);
await page.screenshot({ path: `${output}/table-focus-${theme}.png` });
await page.keyboard.press('Escape');
await chooseView(page, 'Source');
await sourceEditor();
await page.evaluate(() => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: 'Alpha alpha alphabet\r\nAlpha second\r\nAlpha third' }, selection: { anchor: 0 } }); });
await page.keyboard.press('Control+f');
await find.fill('Alpha');
await onePanel();
await page.keyboard.press('Enter');
const selection = () => page.evaluate(() => JSON.stringify(window.__SOURCE__.state.selection.main));
const first = await selection();
await page.keyboard.press('Enter');
assert.notEqual(await selection(), first);
await page.keyboard.press('Shift+Enter');
assert.equal(await selection(), first);
await page.getByRole('checkbox', { name: 'Match case' }).check();
await page.getByRole('checkbox', { name: 'Whole word' }).check();
await replace.fill('Gamma');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__SOURCE__.state.doc.toString()), 'Gamma alpha alphabet\nGamma second\nGamma third');
await page.getByRole('checkbox', { name: 'Regex' }).check();
await find.fill('[');
assert.equal(await find.getAttribute('aria-invalid'), 'true');
assert.equal(await page.getByRole('button', { name: 'Replace all', exact: true }).isDisabled(), true);
await find.fill('(?<=G)(amma)');
await page.getByRole('checkbox', { name: 'Whole word' }).uncheck();
await replace.fill('$1!');
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
assert.match(await page.evaluate(() => window.__SOURCE__.state.doc.toString()), /^Gamma! alpha/);
await page.getByRole('checkbox', { name: 'Regex' }).uncheck();
await find.fill('Gamma');
await page.getByRole('button', { name: 'Select all', exact: true }).click();
assert.equal(await page.evaluate(() => window.__SOURCE__.state.selection.ranges.length), 3);
await page.screenshot({ path: `${output}/source-${theme}.png` });
await find.focus(); await page.keyboard.press('Escape');
assert.equal(await find.count(), 0);
assert.equal(await page.evaluate(() => window.__SOURCE__.hasFocus), true);
await page.keyboard.press('Control+h');
assert.equal(await replace.evaluate(node => node === document.activeElement), true);
await find.fill('Gamma');
await page.keyboard.press('Enter');
await page.keyboard.press('F3');
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
await page.setViewportSize({ width: 800, height: 700 });
// The outline closes in the resize event, one frame after the viewport changes. The pane width changes again at that point.
await page.locator('.shell.right-open').waitFor({ state: 'detached' });
await onePanel();
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
await find.focus(); await page.keyboard.press('Escape');
await page.evaluate(sample => { const view = window.__SOURCE__; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: sample } }); }, sample);
await chooseView(page, 'Read');
await page.locator('.reading').focus();
await page.keyboard.press('Control+f');
await find.fill('Alpha'); await page.keyboard.press('Enter');
await onePanel();
assert.equal(await replace.count(), 0, 'Reading search does not offer replacement');
assert.equal(await page.evaluate(() => window.getSelection().toString()), 'Alpha');
const anchor = await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML);
await page.keyboard.press('Enter');
assert.notEqual(await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML), anchor);
await page.screenshot({ path: `${output}/reading-${theme}.png` });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true);
await chooseView(page, 'Write');
}
console.log('PASS: one full-width document Find in Writer, nested table focus, Source/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
});
+168
View File
@@ -0,0 +1,168 @@
// Find in plug-in views: privacy attributes, Project Management views, plug-in documents, custom find handlers, focus, both themes, and narrow layouts.
// Project Management is a native feature. Its board is in the hidden storage of the workspace (.runestone/pm/).
import assert from 'node:assert/strict';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
const board = {
schema: 1, kind: 'board', id: 'host-find-board',
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 },
],
defaults: { todo: 'todo', doing: 'doing', done: 'done' },
};
await runSmoke('find/pluginViews', async ({ page }) => {
const output = await outputDir('find/pluginViews');
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
state: { catalog: JSON.stringify({ schema: 1, boards: [{ name: 'Find board', value: board }] }, null, 2) + '\n' },
commands: test => {
const workspace = test.workspace({
root: 'C:/find-test',
files: {
'untitled.md': '# Existing note\n',
'sample.finddoc': 'Alpha alpha alphabet',
'.runestone/pm/.gitignore': '*\n',
'.runestone/pm/workspace.json': test.state.catalog,
},
});
test.files = workspace.files;
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
const code = `export function activate(api) {
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
root.innerHTML = '<section><h2>Test document</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) {
root.innerHTML = '<section><h2>' + name + '</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
}});
api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '<p>Native content</p>'; } });
}`;
return {
...workspace,
workspace_read: args => {
if (!workspace.files.has(args.rel) && args.missingOk) return null;
return workspace.workspace_read(args);
},
plugins_snapshot: () => ({ root: 'C:/test/plugins', plugins: [manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) }),
plugins_load: () => code,
plugins_data: () => 'null',
browser_connect: () => 'test',
};
},
});
await page.goto(smokeUrl);
await page.locator('.ws').getByText('find-test', { exact: true }).waitFor();
await page.getByRole('button', { name: 'Plug-in views', exact: true }).waitFor();
const note = page.locator('.tree-tools').getByRole('button', { name: 'New note', exact: true });
assert.equal(await page.locator('.tree-tools').getByRole('button', { name: 'New file', exact: true }).count(), 0);
await note.click();
await page.waitForFunction(() => window.__TEST__.files.has('untitled 2.md'));
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
await page.keyboard.press('Control+f');
for (const label of ['Find in document', 'Replace with']) {
assert.equal(await page.getByRole('textbox', { name: label, exact: true }).getAttribute('autocomplete'), 'off');
}
await page.keyboard.press('Escape');
await page.screenshot({ path: `${output}/new-note-dark.png` });
assert.equal(await page.getByRole('dialog').count(), 0, 'The note opens without a filename dialog');
await note.click();
await page.waitForFunction(() => window.__TEST__.files.has('untitled 3.md'));
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, theme);
await page.getByRole('tab', { name: 'untitled 3.md', exact: true }).click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
await page.keyboard.press('Control+f');
const writerFind = page.getByRole('textbox', { name: 'Find in document', exact: true });
await writerFind.fill('fift');
assert.equal(await writerFind.getAttribute('autocomplete'), 'off');
assert.equal(await page.getByRole('textbox', { name: 'Replace with', exact: true }).getAttribute('autocomplete'), 'off');
await page.screenshot({ path: `${output}/find-privacy-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.screenshot({ path: `${output}/find-privacy-${theme}-narrow.png` });
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1440, height: 1000 });
await page.mouse.move(900, 400);
await note.hover();
await page.getByRole('tooltip').filter({ hasText: /^New note$/ }).waitFor();
await page.screenshot({ path: `${output}/new-note-tooltip-${theme}.png` });
for (const name of ['Board', 'Changes']) {
await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name, exact: true }).click();
const pane = page.getByRole('tabpanel', { name, exact: true });
await pane.getByRole('button', { name: 'Details', exact: true }).focus();
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Non-document plugin views do not show document Find');
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
}
for (const surface of ['all-tasks', 'board']) {
// The ribbon button opens All tasks. The board scope opens the board in the same tab.
if (surface === 'all-tasks') await page.locator('.plugin-ribbon').getByRole('button', { name: 'Project Management', exact: true }).click();
else {
await page.locator('.plugin-editor-pane:visible').getByRole('button', { name: /^Board scope:/ }).click();
await page.getByRole('menuitemradio', { name: 'Find board', exact: true }).click();
await page.getByRole('tab', { name: 'Find board', exact: true }).waitFor();
}
const pane = page.locator('.plugin-editor-pane:visible');
await pane.locator('.pm-board').waitFor();
await pane.focus();
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Actual PM views do not show host Find');
await page.screenshot({ path: `${output}/pm-${surface}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.keyboard.press('Control+f');
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
await page.screenshot({ path: `${output}/pm-${surface}-${theme}-narrow.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
}
await page.getByRole('tree', { name: 'Workspace files' }).getByText('sample', { exact: true }).dblclick();
for (const name of ['sample']) {
const pane = page.getByRole('tabpanel', { name, exact: true });
const returnButton = pane.getByRole('button', { name: 'Details', exact: true });
await returnButton.focus();
await page.keyboard.press('Control+f');
const find = pane.getByRole('textbox', { name: 'Find in document', exact: true });
assert.equal(await find.getAttribute('autocomplete'), 'off');
await find.fill('Alpha');
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
assert.equal(await pane.getByRole('textbox', { name: 'Replace with' }).count(), 0);
await page.keyboard.press('Enter');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Alpha');
await page.keyboard.press('F3');
assert.equal(await page.evaluate(() => getSelection().toString()), 'alpha');
await pane.getByText('Whole word', { exact: true }).click();
await find.focus();
const matches = [];
for (let i = 0; i < 4; i++) {
await page.keyboard.press('Enter');
matches.push(await page.evaluate(() => ({ text: getSelection().toString(), button: !!getSelection().anchorNode?.parentElement?.closest('button') })));
}
assert.equal(matches.filter(match => match.button).length, 1, 'Rendered card buttons participate in search');
assert.ok(matches.every(match => /^alpha$/i.test(match.text)));
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
await page.setViewportSize({ width: 650, height: 800 });
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
const bar = await pane.locator('.rs-find-bar').boundingBox(), bounds = await pane.boundingBox();
assert.ok(bar.x >= bounds.x && bar.x + bar.width <= bounds.x + bounds.width + 1);
// The side panes give way in a narrow window and come back in a wide one (src/lib/layout/Workbench.svelte).
await page.screenshot({ path: `${output}/${name}-${theme}-narrow-focused.png` });
await find.focus();
await page.keyboard.press('Escape');
assert.equal(await returnButton.evaluate(node => node === document.activeElement), true);
await page.setViewportSize({ width: 1440, height: 1000 });
}
}
await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'Custom find', exact: true }).click();
await page.getByRole('tabpanel', { name: 'Custom find' }).focus();
await page.keyboard.press('Control+f');
assert.equal(await page.evaluate(() => window.customFindCalls), 1, 'Plugin find handlers retain ownership');
assert.equal(await page.locator('.rs-find-bar:visible').count(), 0);
console.log('PASS: Find privacy attributes, actual PM All Tasks and board scope, plugin document Find, custom handlers, focus, both themes, and narrow layouts');
});
+122
View File
@@ -0,0 +1,122 @@
// Writer find bar in the top editor panel: shortcuts, replacement, query sync, invalid regex, tooltip, outline filtering, focus return, and narrow layout.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("find/searchPanel", async ({ page }) => {
const output = await outputDir("find/searchPanel");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"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",
},
});
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
});
await page.goto(smokeUrl);
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();
const editor = page.getByRole("textbox", { name: "Writing editor", exact: true });
await editor.waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "# Alpha\n\nalpha Alpha alphabet\n\n## Beta\n\nBeta text\n" }, selection: { anchor: 0 } });
window.__CM__.focus();
});
await page.keyboard.press("Control+f");
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
await find.waitFor();
assert.equal(await find.evaluate(el => document.activeElement === el), true);
assert.equal(await page.locator(".cm-panels-top .rs-editor-search").count(), 1);
const panelBounds = await page.locator(".rs-editor-search").boundingBox();
const scrollBounds = await page.locator(".cm-scroller").boundingBox();
assert.ok(panelBounds.y + panelBounds.height <= scrollBounds.y + 1);
await find.fill("Alpha");
await page.keyboard.press("Enter");
const first = await page.evaluate(() => window.__CM__.state.selection.main.from);
await page.keyboard.press("Enter");
const second = await page.evaluate(() => window.__CM__.state.selection.main.from);
assert.notEqual(first, second);
await page.keyboard.press("Shift+Enter");
assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.from), first);
await page.getByRole("checkbox", { name: "Match case" }).check();
await page.getByRole("checkbox", { name: "Whole word" }).check();
await page.getByRole("textbox", { name: "Replace with" }).fill("Gamma");
await page.getByRole("button", { name: "Replace all", exact: true }).click();
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /# Gamma\n\nalpha Gamma alphabet/);
await page.getByRole("checkbox", { name: "Regex" }).check();
await find.fill("[");
assert.equal(await find.getAttribute("aria-invalid"), "true");
assert.equal(await page.getByRole("button", { name: "Replace all", exact: true }).isDisabled(), true);
await page.getByText("Invalid expression", { exact: true }).waitFor();
await find.fill("Gamma");
await page.getByRole("checkbox", { name: "Regex" }).uncheck();
await page.evaluate(async () => {
const moduleUrl = performance.getEntriesByType("resource").find(entry => entry.name.includes("/@codemirror_search.js"))?.name;
if (!moduleUrl) throw new Error("Search module was not loaded");
const { SearchQuery, setSearchQuery } = await import(moduleUrl);
window.__CM__.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: "Beta" })) });
});
await page.waitForFunction(() => document.querySelector('input[name="search"]').value === "Beta");
await find.focus();
await page.keyboard.press("Escape");
assert.equal(await find.count(), 0);
assert.equal(await editor.evaluate(el => document.activeElement === el), true);
await page.keyboard.press("Control+f");
await find.waitFor();
await page.getByRole("button", { name: "Next match (Enter)" }).focus();
await page.getByRole("tooltip", { name: "Next match (Enter)" }).waitFor({ state: "visible" });
await find.focus();
const outline = page.getByRole("region", { name: "Outline", exact: true });
if (!await outline.count()) await page.getByRole("button", { name: "Outline", exact: true }).click();
await outline.focus();
await page.keyboard.press("Control+f");
const outlineFind = page.getByRole("textbox", { name: "Find in outline", exact: true });
await outlineFind.fill("beta");
assert.equal(await outline.locator("li").count(), 1);
assert.equal(await outline.locator("li button").textContent(), "Beta");
await outlineFind.fill("missing");
await outline.getByText("No matching headings or symbols.").waitFor();
await outlineFind.fill("Gamma");
await page.screenshot({ path: path.join(output, "find-bars.png") });
await page.keyboard.press("Escape");
assert.equal(await outlineFind.count(), 0);
assert.equal(await outline.locator("li").count(), 2);
assert.equal(await outline.evaluate(el => document.activeElement === el), true);
await page.keyboard.press("Control+f");
await outlineFind.fill("Beta");
await page.keyboard.press("Enter");
await page.waitForFunction(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text === "## Beta");
assert.equal(await editor.evaluate(el => document.activeElement === el), true);
await page.setViewportSize({ width: 880, height: 760 });
// The outline gives way below 1100 pixels. The test opens it again to check its search field.
await page.getByRole("button", { name: "Show outline", exact: true }).click();
await outline.focus();
await page.keyboard.press("Control+f");
await outlineFind.waitFor();
await find.focus();
await page.screenshot({ path: path.join(output, "find-bars-narrow.png") });
for (const selector of [".rs-editor-search", ".outline-search"]) {
assert.equal(await page.locator(selector).evaluate(el => el.scrollWidth <= el.clientWidth), true, selector);
}
console.log("PASS: Top search panel, shortcuts, replacement, query sync, invalid regex, focus tooltip, outline filtering, focus return and narrow layout.");
});
+81
View File
@@ -0,0 +1,81 @@
// Find takes typed text key by key in Write, Source, Read, and both sides of Split, also after Enter finds a match.
import assert from "node:assert/strict";
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("find/typing", async ({ page }) => {
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
await mockTauri(page, {
state: { sample },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": test.state.sample } });
return { ...workspace, workspace_search: () => [], "plugin:dialog|message": () => "Cancel" };
},
});
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
const type = text => page.keyboard.type(text, { delay: 15 });
const focused = () => find.evaluate(node => node === document.activeElement);
const reading = { typed: "Alpha alp", removed: "Alpha aha" };
/**
* Open Find, then type, delete, and type again without another click in the field.
* After Enter, CodeMirror selects the text of the field in Write and Source, so the next key replaces it.
* In Read, the caret stays at the end of the text, so the next key adds to it.
*/
async function typing(label, open, afterEnter = { typed: "p", removed: "ha" }) {
await open();
await page.keyboard.press("Control+f");
await find.waitFor();
assert.equal(await focused(), true, `${label}: Find has focus`);
await type("Alpha");
assert.equal(await find.inputValue(), "Alpha", `${label}: each key reaches the field`);
await page.keyboard.press("Backspace");
await type("a al");
assert.equal(await find.inputValue(), "Alpha al", `${label}: Backspace and more keys reach the field`);
assert.equal(await focused(), true, `${label}: Find keeps focus`);
await page.keyboard.press("Enter");
assert.equal(await focused(), true, `${label}: Enter keeps focus in Find`);
await type("p");
assert.equal(await find.inputValue(), afterEnter.typed, `${label}: keys after Enter reach the field`);
await page.keyboard.press("Enter");
await page.keyboard.press("Backspace");
await page.keyboard.press("Backspace");
await type("ha");
assert.equal(await find.inputValue(), afterEnter.removed, `${label}: Backspace after Enter acts on the field`);
await page.keyboard.press("Escape");
await find.waitFor({ state: "detached" });
}
await page.goto(smokeUrl);
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.locator(".cm-content").waitFor();
await typing("Write", async () => { await page.locator(".cm-content").click(); });
await typing("Source", async () => {
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").click();
});
await typing("Read", async () => {
await chooseView(page, "Read");
await page.locator(".md-page > .reading").focus();
}, reading);
await chooseView(page, "Source");
await chooseView(page, "Read beside");
await typing("Split, the text side", async () => { await page.locator(".source-editor .cm-content").click(); });
await typing("Split, the reading side", async () => { await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } }); }, reading);
// A match stays selected until the search text changes, and the next search finds a match again.
await page.locator(".md-page > .reading").click({ position: { x: 40, y: 10 } });
await page.keyboard.press("Control+f");
await type("Alpha");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha", "Enter selects the match");
await type(" a");
assert.equal(await find.inputValue(), "Alpha a", "A key after Enter adds to the text");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "", "A new key removes the selected match");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.getSelection().toString()), "Alpha a", "Enter selects the match of the longer text");
await page.keyboard.press("Escape");
});
+73
View File
@@ -0,0 +1,73 @@
// The command palette (Ctrl+Shift+P), the side pane on Ctrl+\, the generated shortcut list in Help, and the Write formatting shortcuts.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "layout/commands";
await runSmoke(name, async ({ page }) => {
const output = await outputDir(name);
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({ root: "C:\\commands", files: { "a.md": "# Note\n\nalpha beta gamma delta epsilon\n" } });
test.files = workspace.files;
return { ...workspace, plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }), spelling_menu_install: () => null };
},
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator(".live-writer .cm-content").waitFor();
// The palette lists the app commands with their shortcuts and runs the chosen one.
await page.keyboard.press("Control+Shift+P");
const palette = page.getByRole("dialog", { name: "Commands", exact: true });
await palette.waitFor();
assert.equal(await palette.getByRole("button", { name: "Save the active file Ctrl+S", exact: true }).count(), 1);
assert.match(await palette.locator("footer").textContent(), /\d+ commands/);
await page.screenshot({ path: path.join(output, "palette.png") });
await page.getByRole("textbox", { name: "Find a command", exact: true }).fill("side pane");
assert.deepEqual((await palette.locator(".rs-picker-row").allTextContents()).map(text => text.replace(/\s+/g, " ").trim()), ["Show or hide the side pane Ctrl+\\"]);
assert.equal(await page.locator("aside.left").count(), 1);
await page.keyboard.press("Enter");
await palette.waitFor({ state: "detached" });
await page.locator("aside.left").waitFor({ state: "detached" });
// Ctrl+\ shows the side pane again. Ctrl+B no longer toggles it.
await page.keyboard.press("Control+Backslash");
await page.locator("aside.left").waitFor();
// Write formatting shortcuts make the same edits as the Format menu.
const select = word => page.evaluate(async word => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".live-writer .cm-content"));
const from = view.state.doc.toString().indexOf(word);
view.dispatch({ selection: { anchor: from, head: from + word.length } });
view.focus();
}, word);
for (const [word, keys] of [["beta", "Control+b"], ["gamma", "Control+i"], ["delta", "Control+Shift+X"], ["epsilon", "Control+Shift+H"], ["alpha", "Control+k"]]) {
await select(word);
await page.keyboard.press(keys);
}
assert.equal(await page.locator("aside.left").count(), 1, "Ctrl+B in Write does not hide the side pane");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("a.md").includes("==epsilon=="));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("a.md")), "# Note\n\n[alpha]() **beta** *gamma* ~~delta~~ ==epsilon==\n");
// The Format menu shows the shortcuts.
await page.locator(".live-writer .cm-line").filter({ hasText: "beta" }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Format", exact: true }).hover();
for (const label of ["Bold Ctrl+B", "Italic Ctrl+I", "Strikethrough Ctrl+Shift+X", "Highlight Ctrl+Shift+H"]) await page.getByRole("menuitem", { name: label, exact: true }).waitFor();
assert.equal(await page.getByRole("menuitem", { name: "Add external link Ctrl+K", exact: true }).count(), 1);
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
// Help lists every shortcut, open, in groups.
await page.keyboard.press("F1");
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
await help.waitFor();
const list = help.locator("details").filter({ hasText: "Keyboard shortcuts" });
assert.equal(await list.getAttribute("open"), "");
for (const heading of ["General", "Write", "Files"]) await list.getByRole("heading", { name: heading, exact: true }).waitFor();
const rows = await list.locator("dl div").allTextContents();
for (const row of ["Show all commandsCtrl+Shift+P", "Show or hide the side paneCtrl+\\", "BoldCtrl+B", "Delete permanentlyShift+Delete", "Help and aboutF1"]) assert(rows.includes(row), `Help lists ${row}`);
await page.screenshot({ path: path.join(output, "help-shortcuts.png") });
console.log("PASS: the command palette, Ctrl+\\ for the side pane, Write formatting shortcuts, menu shortcut labels, and the Help shortcut list");
});
+148
View File
@@ -0,0 +1,148 @@
// Keyboard and focus: radio check marks, menu focus rings, hover against active, readable disabled controls, the file tree keys, and splitters.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/keyboardFocus", async ({ page }) => {
const output = await outputDir("layout/keyboardFocus");
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\keyboard",
files: {
"alpha.md": "# Alpha\n",
"beta.md": "# Beta\n",
"notes/first.md": "# First\n",
"notes/second.md": "# Second\n",
"notes/deep/third.md": "# Third\n",
"zeta.txt": "Zeta\n",
},
}),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
}),
});
await page.setViewportSize({ width: 1280, height: 760 });
await page.goto(smokeUrl);
const tree = page.getByRole("tree", { name: "Workspace files" });
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const focused = () => page.evaluate(() => document.activeElement?.getAttribute("data-tree-rel") ?? document.activeElement?.getAttribute("aria-label"));
await row("alpha.md").waitFor();
// The tree has one Tab stop. Arrow keys move, Right opens or enters a folder, Left closes it or goes up.
assert.equal(await tree.locator('[role="treeitem"][tabindex="0"]').count(), 1);
await row("alpha.md").click();
await page.getByRole("tab", { name: "alpha.md", exact: true, selected: true }).waitFor();
await row("alpha.md").focus();
await page.keyboard.press("ArrowDown");
assert.equal(await focused(), "beta.md");
assert.equal(await row("beta.md").getAttribute("aria-selected"), "true");
// Folders come first: notes, alpha.md, beta.md, zeta.txt.
await page.keyboard.press("ArrowDown");
assert.equal(await focused(), "zeta.txt");
await page.keyboard.press("Home");
assert.equal(await focused(), "notes");
await page.keyboard.press("ArrowRight");
await row("notes/first.md").waitFor();
assert.equal(await row("notes").getAttribute("aria-expanded"), "true");
await page.keyboard.press("ArrowRight");
assert.equal(await focused(), "notes/deep");
await page.keyboard.press("ArrowLeft");
assert.equal(await focused(), "notes");
await page.keyboard.press("ArrowLeft");
assert.equal(await row("notes").getAttribute("aria-expanded"), "false");
await page.keyboard.press("End");
assert.equal(await focused(), "zeta.txt");
await page.keyboard.press("Home");
assert.equal(await focused(), "notes");
await page.keyboard.press("z");
assert.equal(await focused(), "zeta.txt");
await page.keyboard.press("Shift+ArrowUp");
assert.equal(await tree.locator('[aria-selected="true"]').count(), 2);
assert.equal(await tree.locator('[role="treeitem"][tabindex="0"]').count(), 1);
// Tab leaves the tree at once.
await page.keyboard.press("Tab");
assert.notEqual(await page.evaluate(() => !!document.activeElement?.closest('[role="tree"]')), true);
await page.keyboard.press("Shift+Tab");
assert.equal(await page.evaluate(() => !!document.activeElement?.closest('[role="tree"]')), true);
// A splitter takes focus. The arrow keys move it by 16 pixels, and Home and End go to its limits.
const splitter = page.getByRole("separator", { name: "Resize the side pane", exact: true });
const width = () => page.locator("aside.left").evaluate(node => Math.round(node.getBoundingClientRect().width));
const before = await width();
await splitter.focus();
await page.keyboard.press("ArrowRight");
assert.equal(await width(), before + 16);
assert.equal(await splitter.getAttribute("aria-valuenow"), String(before + 16));
await page.keyboard.press("Home");
assert.equal(await width(), 160);
await page.keyboard.press("End");
assert.equal(await width(), 480);
assert.equal(await splitter.evaluate(node => getComputedStyle(node).outlineWidth), "2px");
const outline = page.getByRole("separator", { name: "Resize the outline", exact: true });
await outline.focus();
const right = () => page.locator("aside.right").evaluate(node => Math.round(node.getBoundingClientRect().width));
const rightBefore = await right();
await page.keyboard.press("ArrowLeft");
assert.equal(await right(), rightBefore + 16);
await splitter.focus();
await page.keyboard.press("Home");
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
// An active toggle differs from a hovered button. A disabled button keeps full opacity and dim text.
const files = page.getByRole("button", { name: "Files", exact: true });
const search = page.getByRole("button", { name: "Search", exact: true });
await search.hover();
const look = locator => locator.evaluate(node => { const style = getComputedStyle(node); return { fill: style.backgroundColor, color: style.color, bar: style.boxShadow }; });
const [hovered, active] = [await look(search), await look(files)];
assert.equal(hovered.bar, "none");
assert.match(active.bar, /inset/);
assert.notEqual(hovered.color, active.color);
const save = page.getByRole("button", { name: "Save", exact: true });
assert.equal(await save.isDisabled(), true);
assert.equal(await save.evaluate(node => getComputedStyle(node).opacity), "1");
const dim = await page.evaluate(() => { const probe = document.createElement("span"); probe.style.color = "var(--rs-text-dim)"; document.body.append(probe); const color = getComputedStyle(probe).color; probe.remove(); return color; });
assert.equal(await save.evaluate(node => getComputedStyle(node).color), dim);
await page.locator("header.header").screenshot({ path: `${output}/header-states-${theme}.png` });
// The current radio row shows a check mark and no fill. Keyboard focus adds a ring that hover does not have.
await page.getByRole("tab", { name: "alpha.md", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "View", exact: true }).click();
const write = page.getByRole("menuitemradio", { name: "Write", exact: true });
const source = page.getByRole("menuitemradio", { name: "Source", exact: true });
assert.equal(await write.getAttribute("aria-checked"), "true");
assert.equal(await write.locator("svg").count(), 1);
assert.equal(await source.locator("svg").count(), 0);
await source.hover();
assert.equal(await source.evaluate(node => getComputedStyle(node).outlineStyle), "none");
await write.focus();
await page.keyboard.press("ArrowDown");
const keyed = page.locator('[role="menu"] button:focus-visible');
assert.equal(await keyed.getAttribute("aria-checked"), "false");
assert.equal(await keyed.evaluate(node => getComputedStyle(node).outlineWidth), "2px");
// With focus and the pointer on other rows, the checked row has no fill.
await page.mouse.move(0, 700);
assert.equal(await write.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
await page.screenshot({ path: `${output}/menu-check-${theme}.png` });
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
// Disabled menu rows keep full opacity and dim text.
await page.getByRole("tab", { name: "alpha.md", exact: true }).click({ button: "right" });
const disabled = page.getByRole("menuitem", { name: "Close tabs after", exact: true });
assert.equal(await disabled.isDisabled(), true);
assert.equal(await disabled.evaluate(node => getComputedStyle(node).opacity), "1");
assert.equal(await disabled.evaluate(node => getComputedStyle(node).color), dim);
await page.keyboard.press("Escape");
}
// Help names the key that leaves the text before Tab moves on.
await page.keyboard.press("F1");
await page.getByRole("dialog", { name: "Help and about" }).getByText("Leave the text, then press Tab", { exact: true }).waitFor();
await page.getByRole("button", { name: "Close help", exact: true }).click();
assert.deepEqual(page.errors, []);
console.log("PASS: one tree Tab stop, tree keys, type-ahead, range selection, keyboard splitters, radio check marks, menu focus ring, hover against active, readable disabled controls, Help, both themes.");
});
+202
View File
@@ -0,0 +1,202 @@
// Split view with different tabs: two documents side by side, a browser tab beside a document, a browser tab that covers
// the area and then moves into a pane, the close control of a plugin pane, and the Read beside toggle, in both themes.
// Also the divider that resizes two panes, a tab that the user drags into a pane, and the new browser tab beside a browser tab.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/mixedSplits", async ({ page }) => {
const output = await outputDir("layout/mixedSplits");
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\mixed-split-workspace",
files: { "a.md": "# Alpha\n\nAlpha text.\n", "b.md": "# Bravo\n\nBravo text.\n" },
});
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
let next = 0;
return {
...workspace,
browser_connect: () => "window-session",
browser_request: ({ command, args }) => {
if (command === "newTab") { globalThis.newTabUrls = [...(globalThis.newTabUrls || []), args.url ?? null]; const tabId = "native-" + (++next); snapshot.tabs.push({ id: tabId, profileId: "user", url: "about:blank", title: "Browser", loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === "closeTab") snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
return structuredClone(snapshot);
},
};
},
});
const pane = rel => page.locator(`[data-document-path="${rel}"]`);
const browserPane = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator('[data-browser-state="ready"]') });
const tab = name => page.getByRole("tab", { name: new RegExp(name) });
async function openToRight(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
}
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
// A native tab drag: dragstart on the tab button, dragover at a place of the target, then the drop and dragend.
async function dragOver(source, target, where) {
const point = await target.evaluate((node, where) => {
const r = node.getBoundingClientRect();
return where === "down" ? { x: r.left + r.width / 2, y: r.bottom - 12 } : where === "right" ? { x: r.right - 12, y: r.top + r.height / 2 } : { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}, where);
return source.evaluate((node, point) => {
const transfer = new DataTransfer();
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, cancelable: true, dataTransfer: transfer }));
const over = new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
document.elementFromPoint(point.x, point.y).dispatchEvent(over);
globalThis.tabDrag = { node, transfer, point };
return over.defaultPrevented;
}, point);
}
async function drop() {
return page.evaluate(() => {
const { node, transfer, point } = globalThis.tabDrag;
const event = new DragEvent("drop", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
document.elementFromPoint(point.x, point.y).dispatchEvent(event);
node.dispatchEvent(new DragEvent("dragend", { bubbles: true, clientX: point.x, clientY: point.y, dataTransfer: transfer }));
return event.defaultPrevented;
});
}
async function setMode(mode) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
}
async function newBrowserTab() {
await page.evaluate(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); await pluginHost.get("browser").newTab(); });
await page.locator('[data-browser-state="ready"]').last().waitFor();
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click(); await pane("a.md").locator(".cm-content").waitFor();
// A click in the file tree replaces the current tab, so the second file opens from a new tab.
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await page.locator('[data-tree-rel="b.md"]').click(); await pane("b.md").locator(".cm-content").waitFor();
assert.equal(await page.getByRole("tab").count(), 2);
await page.waitForFunction(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); return !!pluginHost.get("browser"); });
// Two different documents side by side.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".document-pane").count(), 2);
const left = await box(pane("b.md")), right = await box(pane("a.md"));
assert.ok(right.x >= left.x + left.width - 1 && Math.abs(left.y - right.y) < 2, "The documents show side by side");
assert.equal(await pane("a.md").locator(".breadcrumb").innerText(), "a.md", "A pane beside another pane names its file");
await tab("a.md").click({ button: "right" });
assert.equal(await page.getByRole("menuitem", { name: "Open to the right", exact: true }).isDisabled(), true, "A visible tab cannot open again");
await page.keyboard.press("Escape");
// A new browser tab opens in the focused pane. The document that it replaces stays open as a tab.
await newBrowserTab();
assert.equal(await pane("a.md").count(), 0);
assert.equal(await tab("a.md").count(), 1);
const documentBox = await box(pane("b.md")), webBox = await box(browserPane);
assert.ok(webBox.x >= documentBox.x + documentBox.width - 1, "The browser shows beside the document");
assert.ok(Math.abs(webBox.width - documentBox.width) < 4, "The panes share the area");
for (const theme of ["light", "dark"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await page.screenshot({ path: path.join(output, `document-and-browser-${theme}.png`) });
}
// A click in the document pane makes its tab active. The browser stays visible.
await pane("b.md").locator(".cm-content").click();
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("b.md"));
assert.equal(await browserPane.count(), 1);
// The document opens beside the browser, and the close control of the browser pane leaves the tab open.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".document-pane").count(), 3);
await browserPane.getByRole("button", { name: "Close split", exact: true }).click();
assert.equal(await page.locator(".document-pane").count(), 2);
assert.equal(await page.getByRole("tab", { name: /Browser/ }).count(), 1);
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
assert.equal(await page.locator(".document-pane").count(), 1);
// A browser tab that covers the whole area moves into the left pane when a document opens to the right.
await page.getByRole("tab", { name: /Browser/ }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The browser covers the area");
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
const coverLeft = await box(browserPane), coverRight = await box(pane("a.md"));
assert.ok(coverRight.x >= coverLeft.x + coverLeft.width - 1, "The browser keeps the left pane");
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > (await box(page.locator(".center"))).width - 4, "The last pane gives the browser the whole area");
// Read beside is the toggle for the Read view beside the editor.
await tab("b.md").click();
await pane("b.md").locator(".cm-content").waitFor();
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
await pane("b.md").locator(".md-page").waitFor();
await pane("b.md").getByRole("button", { name: "Read beside", exact: true }).click();
// The divider between two panes changes their sizes, with the pointer and with the keyboard.
await openToRight("a.md");
await pane("a.md").locator(".cm-content").waitFor();
const divider = page.getByRole("separator", { name: "Resize panes" });
assert.equal(await divider.count(), 1);
const area = await box(page.locator(".center"));
const handle = await box(divider);
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.2, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
const narrow = await box(pane("b.md")), wide = await box(pane("a.md"));
assert.ok(Math.abs(narrow.width - area.width * 0.3) < 4, `The left pane has 30% of the area: ${narrow.width} of ${area.width}`);
assert.ok(Math.abs(wide.x - (narrow.x + narrow.width)) < 2, "The right pane starts at the divider");
assert.equal(await divider.getAttribute("aria-valuenow"), "30");
await divider.focus(); await page.keyboard.press("ArrowRight");
assert.equal(await divider.getAttribute("aria-valuenow"), "35");
for (const mode of ["light", "dark"]) {
await setMode(mode);
await divider.hover();
await page.screenshot({ path: path.join(output, `divider-${mode}.png`) });
}
await divider.dblclick();
assert.equal(await divider.getAttribute("aria-valuenow"), "50");
// A new browser tab replaces the document in the focused pane. A document tab dragged to the bottom of the browser pane
// opens below it.
await newBrowserTab();
assert.equal(await pane("a.md").count(), 0);
assert.equal(await dragOver(tab("a.md"), browserPane, "down"), true, "The browser pane takes the tab");
await page.locator('.drop-hint[data-drop-zone="down"]').waitFor();
for (const mode of ["light", "dark"]) {
await setMode(mode);
await page.screenshot({ path: path.join(output, `tab-drop-${mode}.png`) });
}
assert.equal(await drop(), true);
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".drop-hint").count(), 0);
const web = await box(browserPane), below = await box(pane("a.md"));
assert.ok(below.y >= web.y + web.height - 1 && Math.abs(below.x - web.x) < 2, "The document shows below the browser");
assert.equal(await page.getByRole("separator", { name: "Resize panes" }).count(), 2);
// The browser tab dragged to the document pane replaces it there, and leaves its old pane. The first browser tab is not visible.
assert.equal(await dragOver(tab("Browser").last(), pane("b.md"), "center"), true);
assert.equal(await drop(), true);
await page.waitForFunction(() => document.querySelectorAll(".document-pane").length === 2);
assert.equal(await pane("b.md").count(), 0);
assert.equal(await tab("b.md").count(), 1, "The replaced document stays open as a tab");
const moved = await box(browserPane), rest = await box(pane("a.md"));
assert.ok(rest.x >= moved.x + moved.width - 1, "The browser shows left of the document");
// A drop on the pane that shows the tab changes nothing.
assert.equal(await dragOver(tab("Browser").last(), browserPane, "center"), false);
await drop();
// "New tab to the right" of a browser tab that covers the area opens a new browser tab beside it, not a copy of the page.
await pane("a.md").getByRole("button", { name: "Close split", exact: true }).click();
await browserPane.waitFor();
assert.ok((await box(browserPane)).width > area.width - 4, "The browser covers the area");
const before = await page.evaluate(() => globalThis.newTabUrls.length);
await tab("Browser").last().click({ button: "right" });
await page.getByRole("menuitem", { name: "New tab to the right", exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll(".plugin-pane.embedded:not(.inactive)").length === 2);
assert.deepEqual(await page.evaluate(start => globalThis.newTabUrls.slice(start), before), [null], "The new tab opens the home page");
const [first, second] = await page.locator(".plugin-pane.embedded:not(.inactive)").evaluateAll(nodes => nodes.map(node => { const r = node.getBoundingClientRect(); return { x: r.x, width: r.width }; }).sort((a, b) => a.x - b.x));
assert.ok(second.x >= first.x + first.width - 1 && first.width > area.width * 0.4, "The browser tabs show side by side");
await page.screenshot({ path: path.join(output, "browser-beside-browser.png") });
console.log(JSON.stringify({ passed: ["two documents side by side", "browser beside a document", "replaced document stays a tab", "focus by click", "plugin pane close control", "covering browser moves into a pane", "last pane releases the browser", "Read beside toggle", "divider by pointer, keyboard, and double-click", "tab drop below a pane", "tab drop replaces a pane", "new browser tab beside a browser tab", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
}, { timeout: 30000 });
+103
View File
@@ -0,0 +1,103 @@
// Sidebar layout persistence: the hidden outline, resized sidebars, the navigation view, and collapsed backlinks survive layout changes, tab changes, reloads, and reopened windows.
import assert from "node:assert/strict";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/outline", async ({ browser }) => {
const output = await outputDir("layout/outline");
// Pages share one context, so a reopened window keeps the saved layout.
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
// Unknown commands return null, as the original mock did.
await mockTauri(context, {
strict: false,
commands: test => ({
...test.workspace({ root: "D:\\LayoutTest", files: { "note.md": "# Layout test\n\nA note.\n", "data.txt": "Plain text.\n" } }),
plugins_snapshot: () => ({ root: "D:\\LayoutTest\\plugins", plugins: [] }),
}),
});
const errors = [];
let page;
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
if (page) { errors.push(...page.errors); await page.close(); }
page = await openPage(context, { timeout: 5000 });
await page.goto(smokeUrl);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).click();
await page.locator(`[role="tab"][data-path="${name}"][aria-selected="true"]`).waitFor();
}
await reopen();
await page.getByText("LayoutTest", { exact: true }).waitFor();
await quickOpen("note.md");
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".source-editor .cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
console.log("PASS: hidden outline stays hidden across Writer and Source changes");
await page.reload();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
assert.equal(await page.locator(".right").count(), 0);
await reopen();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
console.log("PASS: hidden outline survives reload and window reopen");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
// The left ribbon is 44 pixels wide, so the gutter at 374 gives a 330-pixel side pane.
await resize(0, 374);
await resize(1, 970);
const resized = await widths();
assert.deepEqual(resized, ["330px", "310px"]);
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await reopen();
assert.deepEqual(await widths(), resized);
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Hide outline", exact: true }).waitFor();
console.log("PASS: resized sidebars and chosen navigation view survive reopen");
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await reopen();
assert.equal(await page.locator(".left, .right").count(), 0);
await page.keyboard.press("Control+Backslash");
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
// Card e81770bc: collapsed backlinks stay collapsed while a tab without backlinks is active, and after a window reopen.
const backlinks = () => page.getByRole("button", { name: /^Backlinks \d+$/ });
await quickOpen("note.md");
await backlinks().click();
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await quickOpen("data.txt");
await backlinks().waitFor({ state: "detached" });
await quickOpen("note.md");
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await page.screenshot({ path: `${output}/backlinks-collapsed-after-tab-change.png` });
await reopen();
await quickOpen("note.md");
assert.equal(await backlinks().getAttribute("aria-expanded"), "false");
await backlinks().click();
assert.equal(await backlinks().getAttribute("aria-expanded"), "true");
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.workbenchLayout")).backlinksOpen), true);
console.log("PASS: collapsed backlinks survive a tab change and a window reopen");
errors.push(...page.errors);
assert.deepEqual(errors, []);
});
@@ -0,0 +1,112 @@
// Layout, icons, and Settings: side panes that give way, one file menu order with a danger Delete, tree chevrons,
// grouped search hits, readable bookmarks, 24-pixel targets, one switch design, and the first focus in Settings.
import assert from "node:assert/strict";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/panesAndSettings", async ({ browser }) => {
const output = await outputDir("layout/panesAndSettings");
const context = await browser.newContext({ viewport: { width: 1280, height: 760 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: "C:\\panes",
files: {
"alpha.md": "# Alpha\n\nThe river runs past the river mill.\n",
"notes/beta.md": "# Beta\n\nA river note.\n\nAnother river line.\n",
"notes/gamma.md": "# Gamma\n\nNo match here.\n",
".runestone/marks.json": JSON.stringify({ pins: [], bookmarks: ["notes/beta.md", "alpha.md"], order: {} }),
},
}),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
}),
});
const page = await openPage(context);
await page.goto(smokeUrl);
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
await row("alpha.md").waitFor();
await row("alpha.md").click();
await page.getByRole("tab", { name: "alpha.md", exact: true, selected: true }).waitFor();
// Side panes give way in narrow windows and come back when the window grows. The saved layout keeps the wide choice.
const panes = () => page.evaluate(() => ({ left: !!document.querySelector("aside.left"), right: !!document.querySelector("aside.right") }));
assert.deepEqual(await panes(), { left: true, right: true });
await page.setViewportSize({ width: 1000, height: 760 });
await page.waitForFunction(() => !document.querySelector("aside.right"));
assert.deepEqual(await panes(), { left: true, right: false });
await page.setViewportSize({ width: 760, height: 760 });
await page.waitForFunction(() => !document.querySelector("aside.left"));
const layout = () => page.evaluate(() => JSON.parse(localStorage.getItem("runestone.workbenchLayout") ?? "{}"));
assert.equal((await layout()).leftOpen, true);
assert.equal((await layout()).rightOpen, true);
// A pane that the user opens in a narrow window stays open.
await page.getByRole("button", { name: "Show outline", exact: true }).click();
await page.locator("aside.right").waitFor();
await page.screenshot({ path: `${output}/narrow-760.png` });
await page.setViewportSize({ width: 1280, height: 760 });
await page.waitForFunction(() => !!document.querySelector("aside.left") && !!document.querySelector("aside.right"));
// The file menu: open, clipboard, organize, show and copy path, history, then Delete in the error color.
await row("alpha.md").click({ button: "right" });
const menu = page.getByRole("menu", { name: "File actions", exact: true });
await menu.waitFor();
const labels = await menu.locator(":scope > button, :scope > hr").evaluateAll(nodes => nodes.map(node => node.tagName === "HR" ? "|" : node.querySelector(".action-label").textContent));
assert.deepEqual(labels, ["Open in new tab", "Open to the right", "Open in default app", "Open in terminal", "|", "Cut", "Copy", "Paste", "Make a copy", "|",
"Rename", "Remove bookmark", "Pin", "Save as template", "|", "Show in Explorer", "Copy path", "|", "Undo file move", "Redo file move", "|", "Delete", "Delete permanently"]);
const error = await page.evaluate(() => { const probe = document.createElement("span"); probe.style.color = "var(--rs-error)"; document.body.append(probe); const color = getComputedStyle(probe).color; probe.remove(); return color; });
assert.equal(await menu.getByRole("menuitem", { name: "Delete", exact: true }).evaluate(node => getComputedStyle(node).color), error);
// Each function has one icon: duplicate, template, and tab differ from copy.
const icon = name => menu.getByRole("menuitem", { name, exact: true }).locator("svg").first().evaluate(node => node.innerHTML);
const copy = await icon("Copy");
for (const name of ["Make a copy", "Save as template", "Open in new tab"]) assert.notEqual(await icon(name), copy, name);
await page.screenshot({ path: `${output}/file-menu.png` });
await page.keyboard.press("Escape");
// Folders use the shared chevron. It turns when the folder opens.
const chevron = row("notes").locator(".twist svg");
assert.equal(await chevron.count(), 1);
assert.equal(await chevron.evaluate(node => getComputedStyle(node).transform), "none");
await row("notes").click();
await page.waitForFunction(() => getComputedStyle(document.querySelector('[data-tree-rel="notes"] .twist svg')).transform !== "none");
// Search hits come in groups by file, with a count and marked matches.
await page.getByRole("button", { name: "Search", exact: true }).click();
await page.getByPlaceholder("Search files and notes").fill("river");
await page.keyboard.press("Enter");
await page.getByRole("status").filter({ hasText: "3 results in 2 files" }).waitFor();
const groups = await page.locator(".results > .file").evaluateAll(nodes => nodes.map(node => [node.querySelector(".name").textContent, node.querySelector(".count").textContent]));
assert.deepEqual(groups, [["alpha.md", "1"], ["beta.md", "2"]]);
assert.equal(await page.locator(".results > .file").first().locator("mark").count(), 2);
assert.equal(await page.locator(".results mark").first().textContent(), "river");
await page.screenshot({ path: `${output}/search.png` });
await page.locator(".results button").filter({ hasText: "Another river line." }).click();
await page.getByRole("tab", { name: "beta.md", exact: true, selected: true }).waitFor();
// Bookmarks show the file name, its folder, and a remove button.
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
const bookmark = page.locator(".pane li").filter({ hasText: "beta.md" });
assert.equal(await bookmark.locator(".folder").textContent(), "notes");
await page.screenshot({ path: `${output}/bookmarks.png` });
await bookmark.getByRole("button", { name: "Remove bookmark: beta.md", exact: true }).click();
await bookmark.waitFor({ state: "detached" });
// Targets are at least 24 pixels.
const close = await page.getByRole("button", { name: "Close beta.md", exact: true }).boundingBox();
assert.ok(close.width >= 24 && close.height >= 24, JSON.stringify(close));
const outlineRows = await page.locator("aside.right li button").evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().height));
assert.ok(outlineRows.length && outlineRows.every(height => height >= 24), JSON.stringify(outlineRows));
// Settings: the first focus is on the search, and every switch has one design.
const settings = await openPage(context);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("textbox", { name: "Search settings", exact: true }).waitFor();
await settings.waitForFunction(() => document.activeElement?.getAttribute("aria-label") === "Search settings");
await settings.getByRole("button", { name: "General", exact: true }).click();
const switches = await settings.getByRole("switch").evaluateAll(nodes => nodes.map(node => { const rect = node.getBoundingClientRect(); return `${node.className.split(" ")[0]} ${Math.round(rect.width)}x${Math.round(rect.height)}`; }));
assert.ok(switches.length >= 4 && switches.every(item => item === "rs-switch 40x24"), JSON.stringify(switches));
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
assert.equal(await settings.getByRole("switch", { name: "Transparent surfaces", exact: true }).evaluate(node => node.className.split(" ")[0]), "rs-switch");
await settings.screenshot({ path: `${output}/settings-appearance.png` });
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: panes give way, file menu order and icons, danger Delete, tree chevrons, grouped search, bookmarks, 24-pixel targets, one switch design, Settings first focus.");
});
@@ -0,0 +1,84 @@
// A PDF file beside a note: "Open to the right" in the file tree opens the PDF in a new pane beside the note.
// The user writes in the note and turns the pages of the PDF, and both panes stay visible. A drag of the divider resizes
// both panes. A PDF that covers the area moves into the left pane when a note opens to its right. Both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { samplePdf } from "../../fixtures/pdf/fixtures.mjs";
await runSmoke("layout/pdfBesideNote", async ({ page }) => {
const output = await outputDir("layout/pdfBesideNote");
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
state: { sample: [...samplePdf()] },
commands: test => ({
...test.workspace({ root: "C:\\pdf-beside-note", files: { "Sample.pdf": "", "note.md": "# Note\n\nReading notes.\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
workspace_read_bytes: () => new Uint8Array(test.state.sample).buffer,
}),
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
const note = page.locator('[data-document-path="note.md"]');
const pdf = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator(".pdf-viewer") });
const status = pdf.locator(".pdf-viewer .status");
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The pane is visible"); return value; }
async function besideEachOther(left, right, message) {
const a = await box(left), b = await box(right);
assert.ok(b.x >= a.x + a.width - 1 && Math.abs(a.y - b.y) < 2, message);
return [a, b];
}
await page.goto(smokeUrl);
await row("note.md").click();
await note.locator(".cm-content").waitFor();
// The file tree opens the PDF in a new pane to the right of the note.
await row("Sample.pdf").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
await status.filter({ hasText: /^Page 1 of 2$/ }).waitFor();
assert.equal(await page.locator(".document-pane").count(), 2);
await besideEachOther(note, pdf, "The PDF shows to the right of the note");
// Write in the note. The PDF stays visible.
await note.locator(".cm-content").click();
await page.keyboard.press("Control+End");
await page.keyboard.type("Typed beside the PDF.");
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
assert.equal(await pdf.count(), 1);
// Turn a page of the PDF. The note stays visible and keeps the text.
await pdf.getByRole("button", { name: "Next page", exact: true }).click();
await status.filter({ hasText: /^Page 2 of 2$/ }).waitFor();
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\./);
// Back to the note: the keyboard goes to the note.
await note.locator(".cm-content").click();
await page.keyboard.type(" More.");
assert.match(await note.locator(".cm-content").innerText(), /Typed beside the PDF\. More\./);
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("note.md"));
// The divider gives the PDF more space.
const divider = page.getByRole("separator", { name: "Resize panes" });
const handle = await box(divider), area = await box(page.locator(".center"));
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + handle.width / 2 - area.width * 0.15, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
const [left, right] = await besideEachOther(note, pdf, "The panes stay side by side after a resize");
assert.ok(right.width > left.width + area.width * 0.2, "The PDF pane is wider than the note pane");
for (const mode of ["light", "dark"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: path.join(output, `pdf-beside-note-${mode}.png`) });
}
// A PDF that covers the area moves into the left pane when a note opens to its right.
await pdf.getByRole("button", { name: "Close split", exact: true }).click();
await page.getByRole("tab", { name: /Sample/ }).click();
await status.waitFor();
assert.ok((await box(pdf)).width > area.width - 4, "The PDF covers the area");
await row("note.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Open to the right", exact: true }).click();
await note.locator(".cm-content").waitFor();
await besideEachOther(pdf, note, "The PDF keeps the left pane");
console.log(JSON.stringify({ passed: ["file tree opens a PDF to the right", "typing in the note beside the PDF", "page turn in the PDF beside the note", "divider resize", "covering PDF moves into a pane", "light/dark screenshots"], nativeDesktop: "not tested" }, null, 2));
}, { timeout: 30000 });
+125
View File
@@ -0,0 +1,125 @@
// Plain fixes: Save, Don't save, and Cancel when a changed tab closes, the conflict banner, the status bar facts,
// panes that follow the active tab, table hints and controls, and the line break setting.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/plainFixes", async ({ page }) => {
const output = await outputDir("layout/plainFixes");
await mockTauri(page, {
state: { answer: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\plain",
files: {
"a.md": "# Alpha\n\nFirst line\nsecond line of the same paragraph.\n",
"b.md": "# Beta\r\n\r\nWindows text.\r\n",
"c.md": "# Gamma\n\nThird note.\n",
"table.md": "| Name | Value |\n| --- | --- |\n| One | 1 |\n| Two | =B2*2 |\n",
},
});
Object.assign(test, { files: workspace.files });
return {
...workspace,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
"plugin:dialog|message": args => { (test.state.prompts ??= []).push(args); return test.state.answer; },
};
},
});
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto(smokeUrl);
await page.getByText("plain", { exact: true }).waitFor();
await page.evaluate(() => window.__TEST__.writeSettings("general", { autosaveEnabled: false, autosaveSeconds: 5 }));
const open = async name => {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { name, exact: true, selected: true }).waitFor();
};
const status = () => page.locator(".status").innerText();
const type = async text => { await page.locator(".cm-content").click(); await page.keyboard.press("Control+End"); await page.keyboard.type(text); };
const answer = value => page.evaluate(value => { window.__TEST__.state.answer = value; }, value);
const file = name => page.evaluate(name => window.__TEST__.files.get(name), name);
// The status bar shows the save state, the cursor, the words, the line endings, and the view. Native watching has no label.
await open("a.md");
await page.locator(".cm-content").click();
await page.keyboard.press("Control+Home");
await page.waitForFunction(() => /Ln 1, Col 1/.test(document.querySelector(".status").textContent));
assert.match(await status(), /Saved/);
assert.match(await status(), /10 words/);
assert.match(await status(), /LF/);
assert.doesNotMatch(await status(), /watch/i);
await open("b.md");
await page.waitForFunction(() => /CRLF/.test(document.querySelector(".status").textContent));
await page.locator(".status").screenshot({ path: `${output}/status.png` });
// Closing a changed tab asks Save, Don't save, or Cancel.
await type(" Edited");
await page.waitForFunction(() => /Unsaved/.test(document.querySelector(".status").textContent));
const prompts = () => page.evaluate(() => window.__TEST__.state.prompts ?? []);
await page.keyboard.press("Control+w");
await page.waitForFunction(() => (window.__TEST__.state.prompts ?? []).length === 1);
assert.deepEqual((await prompts())[0].buttons, { YesNoCancelCustom: ["Save", "Don't save", "Cancel"] });
assert.equal(await page.getByRole("tab", { name: /^b\.md/ }).count(), 1, "Cancel keeps the tab");
await answer("Save");
await page.keyboard.press("Control+w");
await page.getByRole("tab", { name: /^b\.md/ }).waitFor({ state: "detached" });
assert.match(await file("b.md"), /Edited/);
await open("c.md");
await type(" Dropped");
await answer("Don't save");
await page.keyboard.press("Control+w");
await page.getByRole("tab", { name: /^c\.md/ }).waitFor({ state: "detached" });
assert.doesNotMatch(await file("c.md"), /Dropped/);
// The conflict banner: the warning icon, the safe choice first, and the choice that discards edits last.
await open("a.md");
await type(" Mine");
await page.evaluate(() => {
window.__TEST__.files.set("a.md", "# Alpha\n\nChanged on disk.\n");
window.__TEST__.emit("workspace-event", { root: "C:\\plain", kind: "modify", paths: ["a.md"] });
});
const banner = page.locator(".conflict");
await banner.waitFor();
assert.equal(await banner.locator("svg").count(), 1);
assert.deepEqual(await banner.getByRole("button").allInnerTexts(), ["Keep my edits", "Save a copy", "Use disk version"]);
const color = token => page.evaluate(token => { const probe = document.createElement("span"); probe.style.color = `var(${token})`; document.body.append(probe); const value = getComputedStyle(probe).color; probe.remove(); return value; }, token);
assert.equal(await banner.getByRole("button", { name: "Use disk version" }).evaluate(node => getComputedStyle(node).color), await color("--rs-error"));
assert.equal(await banner.evaluate(node => getComputedStyle(node).borderBottomColor), await color("--rs-warn"));
await page.setViewportSize({ width: 880, height: 800 });
assert.ok(await banner.evaluate(node => node.scrollWidth <= node.clientWidth + 1), "The banner wraps in a narrow pane");
await page.screenshot({ path: `${output}/conflict-narrow.png` });
await page.setViewportSize({ width: 1280, height: 800 });
await banner.getByRole("button", { name: "Keep my edits" }).click();
await banner.waitFor({ state: "detached" });
// Read follows CommonMark soft breaks by default. The setting keeps each source line break.
await page.keyboard.press("Control+s");
await chooseView(page, "Read");
const paragraph = page.locator(".md-page .reading p").first();
assert.equal(await paragraph.evaluate(node => getComputedStyle(node).whiteSpace), "normal");
await page.evaluate(() => window.__TEST__.writeSettings("general", { ...window.__TEST__.settings("general"), keepLineBreaks: true }));
await page.waitForFunction(() => getComputedStyle(document.querySelector(".md-page .reading p")).whiteSpace === "pre-line");
await page.evaluate(() => window.__TEST__.writeSettings("general", { ...window.__TEST__.settings("general"), keepLineBreaks: false }));
await chooseView(page, "Write");
// A plain table cell has no hover hint, because the footer shows its address. The controls show while a cell has focus.
await open("table.md");
const table = page.locator(".live-writer .writer-table");
await table.waitFor();
await table.locator("td").first().hover();
await page.waitForTimeout(500);
assert.equal(await page.locator(".rs-tooltip:popover-open").count(), 0);
await table.locator("td").first().click();
await page.waitForFunction(() => getComputedStyle(document.querySelector(".writer-table .table-add")).opacity === "1");
await page.keyboard.press("Escape");
// The outline and the status bar follow the active tab: a tab without a document has no outline and no document facts.
await page.evaluate(() => window.__TEST__.emit("runestone-theme-editor-open", null));
await page.getByRole("tab", { name: "Theme editor", exact: true, selected: true }).waitFor();
await page.waitForFunction(() => !/Ln \d/.test(document.querySelector(".status").textContent));
assert.equal(await page.locator("aside.right li").count(), 0);
assert.deepEqual(page.errors, []);
console.log("PASS: status bar facts, Save, Don't save, and Cancel on close, conflict banner order and colors, line break setting, table hints and controls, panes that follow the active tab.");
});
+146
View File
@@ -0,0 +1,146 @@
// Document splits: independent modes, edits, saves, selections, and conflicts per pane; nested relative links; narrow stacking; and the close guard.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/splits", async ({ page }) => {
const output = await outputDir("layout/splits");
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) page.errors.push(message.text()); });
// The checks need edits to stay unsaved; autosave runs every 5 s by default (src/lib/workspace/settings.ts:12, src/lib/layout/Workbench.svelte:1165).
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
state: { answer: "Cancel" },
commands: test => {
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
files: {
"a.md": "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n",
"b.md": "# b.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"c.md": "# c.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"d.md": "# d.md\n\nOriginal text.\n\n```js\nconst answer = 42;\n```\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n",
"notes/b.md": "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n",
"notes/c.md": "# Charlie\n\nThird paragraph.\n",
"sample.txt": "const answer = 42;\n",
},
});
Object.assign(test, { files: workspace.files, writes: [], prompts: [] });
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("conflict");
workspace.files.set(args.rel, args.contents);
test.writes.push(args.rel);
},
spelling_menu_install: () => {},
"plugin:dialog|message": args => { test.prompts.push(args.message); return test.state.answer; },
};
},
});
const pane = path => page.locator(`[data-document-path="${path}"]`);
const item = name => page.getByRole('menuitem',{name,exact:true});
async function openRight(path,label) {
const current = pane(path);
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
await item('Open to the right').click();
}
async function append(path, text) {
const target=pane(path).locator('.cm-content');
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
}
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
async function focus(path) { await pane(path).locator('.cm-content').click(); }
async function changeOnDisk(path, text) {
await page.evaluate(([path, text]) => {
window.__TEST__.files.set(path, text);
window.__TEST__.emit("workspace-event", { root: "C:\\tab-menu-workspace", kind: "modify", paths: [path] });
}, [path, text]);
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click(); await pane('a.md').locator('.cm-content').waitFor();
await append('a.md','\nLeft unsaved.');
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),2);
assert.match(await text('a.md'),/Left unsaved/);
await append('notes/b.md','\nRight saved.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.writes.includes('notes/b.md'));
assert.equal(await page.evaluate(()=>window.__TEST__.writes.includes('a.md')),false,'Save uses the focused right pane');
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.writes.includes('a.md'));
await chooseView(pane('notes/b.md'), 'Source'); await pane('notes/b.md').locator('.source-editor .cm-content').waitFor();
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
await openRight('a.md','Right note');
assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>!!document.activeElement?.matches('[data-document-path="notes/b.md"] .source-editor .cm-content')); await page.keyboard.press('Control+End'); await page.keyboard.type('\nSource edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Source edit.'));
await chooseView(pane('notes/b.md'), 'Write'); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Source edit/);
await chooseView(pane('notes/b.md'), 'Read'); await pane('notes/b.md').locator('.reading').waitFor();
assert.equal(await pane('a.md').locator('.reading').count(),0,'Reading mode belongs to its pane');
await focus('a.md'); assert.equal(await pane('notes/b.md').locator('.reading').count(),1);
await chooseView(pane('notes/b.md'), 'Write'); await pane('notes/b.md').locator('.cm-content').waitFor();
for(const path of ['a.md','notes/b.md']) await pane(path).locator('.cm-content').evaluate(async node=> {
const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const v=EditorView.findFromDOM(node); const source=v.state.doc.toString(); const from=source.indexOf(source.includes('Alpha') ? 'Origin' : 'Second'); v.dispatch({selection:{anchor:from,head:from+6}});
});
// Read the selection of each pane editor. Each editor keeps its own selection.
const selections=(await Promise.all(['a.md','notes/b.md'].map(path=>pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const {state}=EditorView.findFromDOM(node); return state.sliceDoc(state.selection.main.from,state.selection.main.to); })))).filter(Boolean).sort();
assert.deepEqual(selections,['Origin','Second'],'Each pane retains its own selection');
await openRight('a.md','Right note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='notes/b.md');
await openRight('notes/b.md','Original note'); assert.equal(await page.locator('.document-pane').count(),2);
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='a.md');
await append('notes/b.md','\nRight still unsaved.');
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
await page.screenshot({path:`${output}/two-editors-${theme}.png`});
}
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),1); assert.equal(await pane('a.md').count(),1);
assert.match(await text('a.md'),/Left unsaved/);
assert.equal(await page.getByRole('tab').count(),2,'Closing a split preserves both tabs');
await page.getByRole('tab',{name:/b.md/}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
assert.match(await text('notes/b.md'),/Right still unsaved/,'The closed split retains its unsaved buffer');
await page.getByRole('tab',{name:/a.md/}).click(); await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await openRight('notes/b.md','Relative'); await pane('notes/c.md').locator('.cm-content').waitFor();
assert.equal(await page.locator('.document-pane').count(),3);
assert.match(await text('notes/c.md'),/Charlie/,'Relative links use the pane document folder');
await pane('notes/c.md').getByRole('button',{name:'Close split',exact:true}).click();
assert.equal(await page.locator('.document-pane').count(),2);
await changeOnDisk('notes/b.md','# Bravo disk\n\nExternal update.\n');
await pane('notes/b.md').getByRole('alert').waitFor();
assert.equal(await pane('a.md').getByRole('alert').count(),0);
assert.match(await text('notes/b.md'),/Right still unsaved/,'A disk conflict preserves the right pane edits');
await focus('a.md');
await pane('notes/b.md').getByRole('button',{name:'Use disk version',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-document-path="notes/b.md"] .cm-content')?.textContent.includes('External update.'));
assert.match(await text('a.md'),/Left unsaved/,'Resolving the other pane cannot replace the primary buffer');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:740});
for(const theme of ['light','dark']) {
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
const first=await pane('a.md').boundingBox(), second=await pane('notes/b.md').boundingBox();
assert.ok(first.width>500 && second.width>500 && second.y>=first.y+first.height-1,'Narrow panes stack with readable widths');
await page.screenshot({path:`${output}/stacked-${theme}.png`});
}
await append('notes/b.md','\nNarrow edit.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Narrow edit.'));
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
await append('a.md','\nAfter closing split.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('a.md').includes('After closing split.'));
await page.setViewportSize({width:1440,height:1000});
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
await append('notes/b.md','\nClose guard.');
await page.keyboard.press('Control+w');
await page.waitForFunction(()=>window.__TEST__.prompts.length>0);
assert.equal(await pane('notes/b.md').count(),1,'Cancel keeps the dirty split open');
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.__TEST__.files.get('notes/b.md').includes('Close guard.'));
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
await page.waitForFunction(()=>window.__TEST__.files.get('a.md').includes('Other tab closed.'));
// A closed tab releases its editor state. The reopened note has no undo history.
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
const reopened=await text('notes/b.md');
assert.match(reopened,/Close guard\./);
await focus('notes/b.md'); await page.keyboard.press('Control+z');
assert.equal(await text('notes/b.md'),reopened,'Closing the tab releases only its editor state');
console.log(JSON.stringify({passed:['independent Writer/Source/Reading modes','dirty close cancellation and editor state release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
}, { timeout: 15000 });
+144
View File
@@ -0,0 +1,144 @@
// The title bar and the side pane: the bottom bar with the workspace switcher, Help, and Settings, the ribbon fallback, readable tabs with a list of all tabs, the drag area, caption buttons, Snap Layouts, and the macOS layout.
import assert from "node:assert/strict";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const names = ["meeting-notes", "research-plan", "inbox", "field-notes", "weekly-review", "reading-list", "project-ideas", "travel", "budget", "journal", "recipes"];
await runSmoke("layout/titleBar", async ({ browser }) => {
const output = await outputDir("layout/titleBar");
const context = await browser.newContext({ viewport: { width: 1280, height: 720 } });
await mockTauri(context, {
state: { names },
commands: test => ({
...test.workspace({ root: "C:\\Users\\me\\Documents\\Field work", files: Object.fromEntries(test.state.names.map(name => [`notes/${name}.md`, `# ${name}\n\nText.\n`])) }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
window_snap_layouts: () => null,
}),
});
const page = await openPage(context);
async function open(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(`${name}.md`);
await page.getByRole("dialog").getByRole("button").filter({ hasText: `${name}.md` }).first().click();
await page.getByRole("tab", { name: `${name}.md`, exact: true, selected: true }).waitFor();
}
const box = locator => locator.evaluate(node => { const rect = node.getBoundingClientRect(); return { x: rect.x, right: rect.right, width: rect.width, height: rect.height, bottom: rect.bottom }; });
await page.goto(smokeUrl);
// The bar at the bottom of the side pane holds the workspace switcher, Help, and Settings, as in Obsidian.
// The switcher opens the workspace list above it.
const workspace = page.getByRole("button", { name: "Field work", exact: true });
await workspace.waitFor();
// Auto-save stays off, so the edited tab keeps its unsaved mark.
await page.evaluate(() => window.__TEST__.writeSettings("general", { autosaveEnabled: false, autosaveSeconds: 5 }));
const footer = page.locator("aside.left .left-footer");
assert.equal(await footer.locator(".workspace-button").count(), 1);
assert.equal(await footer.getByRole("button", { name: "Help and about (F1)", exact: true }).count(), 1);
assert.equal(await footer.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).count(), 1);
assert.equal(await page.locator("header.header .workspace-button").count(), 0);
// The header right keeps only Save, the outline toggle, and the window controls. The other tools are in the left ribbon.
assert.deepEqual(await page.locator(".header-right").getByRole("button").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))),
["Save", "Hide outline", "Minimize window", "Maximize window", "Close window"]);
const ribbon = page.locator(".plugin-ribbon");
assert.equal(await ribbon.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).count(), 0, "The ribbon has no second copy while the pane is open");
await workspace.click();
const picker = page.getByRole("dialog", { name: "Workspaces" });
await picker.waitFor();
assert.ok(await picker.evaluate((node, top) => node.getBoundingClientRect().bottom <= top, (await workspace.boundingBox()).y));
await page.screenshot({ path: `${output}/bottom-bar.png` });
await page.keyboard.press("Escape");
// While the side pane is closed, the workspace switcher, Help, and Settings move to the bottom of the ribbon.
await page.keyboard.press("Control+\\");
await page.locator("aside.left").waitFor({ state: "detached" });
const ribbonSwitcher = ribbon.getByRole("button", { name: "Open folder (Ctrl+O)", exact: true });
await ribbonSwitcher.click();
await picker.waitFor();
const switcherBox = await ribbonSwitcher.boundingBox(), pickerBox = await picker.boundingBox();
assert.ok(pickerBox.y + pickerBox.height <= switcherBox.y + 1 && pickerBox.x < 100, JSON.stringify({ switcherBox, pickerBox }));
await page.screenshot({ path: `${output}/ribbon-fallback.png` });
await page.keyboard.press("Escape");
await ribbon.getByRole("button", { name: "Help and about (F1)", exact: true }).click();
await page.getByRole("dialog", { name: "Help and about" }).waitFor();
await page.getByRole("button", { name: "Close help", exact: true }).click();
assert.equal(await ribbon.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).isVisible(), true);
assert.equal((await box(ribbon)).width, 44);
await page.keyboard.press("Control+\\");
await page.locator("aside.left").waitFor();
// With few tabs, the drag area fills the free space after the + button.
const drag = page.locator(".window-drag-space");
await open(names[0]);
const center = await box(page.locator(".header-center")), free = await box(drag);
assert.ok(free.width > 400 && Math.abs(free.right - center.right) <= 1, JSON.stringify({ center, free }));
// Tabs keep a readable width and scroll. Fades show hidden tabs, and the list names every tab.
for (const name of names.slice(1)) await open(name);
const widths = await page.locator("header .tab").evaluateAll(tabs => tabs.map(tab => tab.getBoundingClientRect().width));
assert.ok(widths.every(width => width >= 120), JSON.stringify(widths));
const strip = page.locator("header .tabs");
assert.equal(await strip.evaluate(node => node.classList.contains("fade-start")), true);
assert.equal(await strip.evaluate(node => node.classList.contains("fade-end")), false, "The active last tab is in view with its close button");
await page.locator(".cm-content").click();
await page.keyboard.type("Edit ");
// An unsaved tab adds " •" to its name.
await page.getByRole("tab", { name: /^recipes.md/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
await page.getByRole("button", { name: "All tabs", exact: true }).click();
const list = page.getByRole("menu", { name: "All tabs", exact: true });
await list.waitFor();
assert.equal(await list.getByRole("menuitemradio").count(), names.length);
const recipes = list.getByRole("menuitemradio", { name: /^recipes\.md/ });
assert.equal(await recipes.getAttribute("aria-checked"), "true");
assert.match(await recipes.innerText(), /Unsaved/);
assert.equal(await recipes.locator("svg").count(), 1, "The pinned tab shows the pin icon");
await page.screenshot({ path: `${output}/all-tabs.png` });
await list.getByRole("menuitemradio", { name: "inbox.md", exact: true }).click();
await page.getByRole("tab", { name: "inbox.md", exact: true, selected: true }).waitFor();
await list.waitFor({ state: "detached" });
assert.equal(await strip.evaluate(node => node.classList.contains("fade-end")), true);
// When the tabs scroll, they use all space up to a drag area of 48 pixels. Caption buttons are square and fill the title bar height.
assert.equal(Math.round((await box(drag)).width), 48);
assert.ok(Math.abs((await box(drag)).right - (await box(page.locator(".header-center"))).right) <= 1);
assert.equal(await drag.getAttribute("data-tauri-drag-region"), "");
const captions = await page.locator(".window-controls .icon-btn").evaluateAll(buttons => buttons.map(button => ({ width: button.getBoundingClientRect().width, height: button.getBoundingClientRect().height, radius: getComputedStyle(button).borderRadius })));
const height = (await box(page.locator("header.header"))).height;
assert.deepEqual(captions, Array(3).fill({ width: 46, height, radius: "0px" }));
// Resting on maximize asks the host for Snap Layouts. A short pass does not.
const calls = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "window_snap_layouts").length);
await page.getByRole("button", { name: "Maximize window", exact: true }).hover();
await page.mouse.move(600, 400);
await page.waitForTimeout(700);
assert.equal(await calls(), 0);
await page.getByRole("button", { name: "Maximize window", exact: true }).hover();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "window_snap_layouts"));
await page.mouse.move(600, 400);
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
await page.locator("header.header").screenshot({ path: `${output}/header-${theme}.png` });
}
await page.setViewportSize({ width: 880, height: 560 });
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert.ok((await box(page.locator(".window-controls"))).right <= 880);
await page.screenshot({ path: `${output}/narrow.png` });
// macOS keeps its native traffic lights: no caption buttons, and room at the start of the title bar.
const mac = await openPage(context);
await mac.addInitScript(() => {
Object.defineProperty(navigator, "platform", { get: () => "MacIntel" });
Object.defineProperty(navigator, "userAgentData", { get: () => ({ platform: "macOS" }) });
});
await mac.goto(smokeUrl);
await mac.getByRole("button", { name: "Field work", exact: true }).waitFor();
assert.equal(await mac.evaluate(() => document.documentElement.dataset.titleBar), "mac");
assert.equal(await mac.locator(".window-controls").count(), 0);
assert.equal(await mac.locator(".header-left").evaluate(node => getComputedStyle(node).paddingLeft), "82px");
assert.match(await mac.getByRole("button", { name: "Settings (⌘,)", exact: true }).getAttribute("aria-label"), /⌘/);
await mac.locator("header.header").screenshot({ path: `${output}/header-mac.png` });
assert.deepEqual([...page.errors, ...mac.errors], []);
console.log("PASS: bottom bar of the side pane, ribbon fallback, readable tabs with fades and a list, tabs that fill the header up to the drag area, square caption buttons, Snap Layouts request, macOS layout, both themes, narrow window.");
});
+149
View File
@@ -0,0 +1,149 @@
// The view control: Write, Source, and Read always visible, the Split toggle, keys, the status bar, the breadcrumb, the file title setting, narrow panes, and both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/viewModes", async ({ browser }) => {
const output = await outputDir("layout/viewModes");
const context = await browser.newContext({ viewport: { width: 1200, height: 760 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: "C:\\view-modes",
files: {
"notes/field-notes.md": "# Project field notes\n\nFirst paragraph with **bold** text.\n",
"top.md": "# Top\n\nRoot note.\n",
"src/hello.py": "print('hello')\n",
},
}),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
}),
});
const page = await openPage(context), settings = await openPage(context);
const group = page.getByRole("radiogroup", { name: "View", exact: true });
const radio = name => group.getByRole("radio", { name, exact: true });
const split = page.locator(".chrome-bar").getByRole("button", { name: "Read beside", exact: true });
const checked = () => group.getByRole("radio", { checked: true }).getAttribute("aria-label");
const status = () => page.locator(".status").innerText();
async function open(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("tab", { name, exact: true, selected: true }).waitFor();
}
await page.goto(smokeUrl);
await page.getByText("view-modes", { exact: true }).waitFor();
await open("field-notes.md");
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
// All choices stay visible, and the pointer does not move them.
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), ["Write", "Source", "Read"]);
assert.equal(await checked(), "Write");
assert.equal(await split.getAttribute("aria-pressed"), "false");
const boxes = () => group.getByRole("radio").evaluateAll(nodes => nodes.map(node => JSON.stringify(node.getBoundingClientRect())));
const before = await boxes();
await radio("Source").hover();
assert.deepEqual(await boxes(), before);
// Hover gets a fill. Only the current choice gets the accent bar.
const look = name => radio(name).evaluate(node => ({ fill: getComputedStyle(node).backgroundColor, bar: getComputedStyle(node).boxShadow }));
const [hovered, current] = [await look("Source"), await look("Write")];
assert.notEqual(hovered.fill, "rgba(0, 0, 0, 0)");
assert.equal(hovered.bar, "none");
assert.match(current.bar, /inset/);
assert.notEqual(hovered.fill, current.fill);
// The tab names the file, so the breadcrumb shows only its folder and the status bar shows only the view.
assert.equal(await page.locator(".breadcrumb").innerText(), "notes");
assert.equal(await page.locator(".breadcrumb").getAttribute("title"), "notes/field-notes.md");
assert.doesNotMatch(await status(), /field-notes/);
assert.match(await status(), /Write$/);
// The group has one Tab stop. Arrow keys, Home, and End move the choice.
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.tabIndex)), [0, -1, -1]);
await radio("Write").focus();
await page.keyboard.press("ArrowRight");
await page.locator(".source-editor .cm-gutters").waitFor();
assert.equal(await checked(), "Source");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Source");
assert.match(await status(), /Source$/);
await page.keyboard.press("End");
await page.locator(".md-page .reading").waitFor();
assert.equal(await checked(), "Read");
assert.match(await status(), /Read$/);
await page.keyboard.press("Home");
await page.locator(".live-writer").waitFor();
assert.equal(await checked(), "Write");
// Ctrl+Shift+E switches between Read and the editor. Ctrl+E switches between Write and Source.
await page.locator(".cm-content").click();
await page.keyboard.press("Control+Shift+E");
await page.locator(".md-page .reading").waitFor();
await page.keyboard.press("Control+Shift+E");
await page.locator(".live-writer").waitFor();
await page.keyboard.press("Control+e");
await page.locator(".source-editor").waitFor();
await page.keyboard.press("Control+e");
await page.locator(".live-writer").waitFor();
// Split shows Read beside the current editor. Write and Source keep it. Read ends it.
await chooseView(page, "Read beside");
assert.equal(await split.getAttribute("aria-pressed"), "true");
await page.locator(".body.split .live-writer").waitFor();
await page.locator(".body.split .md-page").waitFor();
await chooseView(page, "Source");
await page.locator(".body.split .source-editor").waitFor();
assert.equal(await split.getAttribute("aria-pressed"), "true");
await chooseView(page, "Read");
assert.equal(await split.getAttribute("aria-pressed"), "false");
assert.equal(await page.locator(".body.split").count(), 0);
assert.equal(await page.locator(".editor-wrap").isVisible(), false);
await chooseView(page, "Read beside");
await page.locator(".body.split .source-editor").waitFor();
assert.equal(await checked(), "Source");
await chooseView(page, "Read beside");
await chooseView(page, "Write");
// The file title shows by default. The General setting hides it in Write and Read.
assert.equal(await page.locator(".live-writer .document-title").count(), 1);
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "General", exact: true }).click();
const titleSwitch = settings.getByRole("switch", { name: "File name title", exact: true });
assert.equal(await titleSwitch.isChecked(), true);
await titleSwitch.uncheck();
await page.waitForFunction(() => !document.querySelector(".live-writer .document-title"));
await chooseView(page, "Read");
await page.locator(".md-page .reading").waitFor();
assert.equal(await page.locator(".md-page .document-title").count(), 0);
await titleSwitch.check();
await page.locator(".md-page .document-title").waitFor();
await chooseView(page, "Write");
await page.locator(".live-writer .document-title").waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); window.dispatchEvent(new Event("focus")); }, theme);
await page.waitForFunction(mode => document.documentElement.dataset.theme === mode, theme);
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-${theme}.png` });
await chooseView(page, "Read beside");
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-split-${theme}.png` });
await chooseView(page, "Read beside");
}
// The controls show icons only, at every width (UI-056). The names stay for assistive technology and tooltips.
assert.equal(await page.locator(".chrome-bar").evaluate(bar => [...bar.querySelectorAll(".view-modes button, button.split")].map(button => button.textContent.trim()).join("")), "");
// The side panes give way first in a narrow window.
await page.setViewportSize({ width: 520, height: 600 });
await page.locator("aside.left").waitFor({ state: "detached" });
assert.equal(await radio("Read").getAttribute("aria-label"), "Read");
assert.ok(await page.locator(".chrome-bar").evaluate(node => node.scrollWidth <= node.clientWidth + 1));
await page.locator(".chrome-bar").screenshot({ path: `${output}/bar-narrow.png` });
await page.setViewportSize({ width: 1200, height: 760 });
// Other text files have Write and Source only. A file at the workspace root has no folder in the breadcrumb.
await open("hello.py");
assert.deepEqual(await group.getByRole("radio").evaluateAll(nodes => nodes.map(node => node.getAttribute("aria-label"))), ["Write", "Source"]);
assert.equal(await split.count(), 0);
await open("top.md");
assert.equal(await page.locator(".breadcrumb").innerText(), "");
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: visible view choices, hover and current states, radio keys, Ctrl+E and Ctrl+Shift+E, Split, status bar, breadcrumb, file title setting, narrow panes, both themes.");
});
+171
View File
@@ -0,0 +1,171 @@
// A drag of the tab that a pane shows, with real mouse input: the tab moves to a new pane on the right or bottom side of
// its pane, and the pane shows the next tab. A browser tab that covers the area moves beside the document below it.
// With only one tab, the drag shows no hint.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/visibleTabDrag", async ({ page }) => {
const output = await outputDir("layout/visibleTabDrag");
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\visible-tab-drag-workspace",
files: { "a.md": "# Alpha\n\nAlpha text.\n", "b.md": "# Bravo\n\nBravo text.\n", "c.md": "# Charlie\n\nCharlie text.\n" },
});
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
let next = 0;
return {
...workspace,
browser_connect: () => "window-session",
browser_request: ({ command }) => {
if (command === "newTab") { const tabId = "native-" + (++next); snapshot.tabs.push({ id: tabId, profileId: "user", url: "about:blank", title: "Browser", loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
return structuredClone(snapshot);
},
};
},
});
const pane = rel => page.locator(`[data-document-path="${rel}"]`);
const browserPane = page.locator(".plugin-pane:not(.inactive)").filter({ has: page.locator('[data-browser-state="ready"]') });
const tab = name => page.getByRole("tab", { name: new RegExp(name) });
const hint = page.locator(".drop-hint");
async function box(locator) { const value = await locator.boundingBox(); assert.ok(value, "The element is visible"); return value; }
const shown = () => page.locator("[data-document-path]").evaluateAll(nodes => nodes.map(node => node.getAttribute("data-document-path")));
const activeTab = () => page.locator('[role="tab"][aria-selected="true"]').innerText();
/** Press the mouse button on a tab and move the pointer to a part of a target. The button stays down. */
async function dragTo(name, target, where) {
const from = await box(tab(name)), to = await box(target);
const point = where === "right" ? { x: to.x + to.width - 30, y: to.y + to.height / 2 }
: where === "left" ? { x: to.x + 30, y: to.y + to.height / 2 }
: where === "down" ? { x: to.x + to.width / 2, y: to.y + to.height - 30 }
: { x: to.x + to.width / 2, y: to.y + to.height / 2 };
await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(from.x + from.width / 2 + 8, from.y + from.height / 2 + 8, { steps: 3 });
await page.mouse.move(point.x, point.y, { steps: 10 });
// The browser fires dragover on the next move. A target that a step only enters gets no dragover.
await page.mouse.move(point.x + 2, point.y + 2, { steps: 2 });
}
async function open(name) {
await page.locator(`[data-tree-rel="${name}"]`).click();
await pane(name).locator(".cm-content").waitFor();
}
await page.goto(smokeUrl);
await open("a.md");
assert.equal(await page.getByRole("tab").count(), 1);
// The only tab has no other tab to leave in its pane. The drag shows no hint and changes nothing.
await dragTo("a.md", pane("a.md"), "right");
await page.waitForTimeout(200);
assert.equal(await hint.count(), 0, "The only tab cannot open a pane");
await page.mouse.up();
assert.deepEqual(await shown(), ["a.md"]);
// A click in the file tree replaces the current tab, so each more file opens from a new tab.
for (const name of ["b.md", "c.md"]) {
await page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true }).click();
await open(name);
}
assert.deepEqual(await shown(), ["c.md"]);
// The middle of the pane already shows the tab, so it is no drop target. The right part opens a new pane.
await dragTo("c.md", pane("c.md"), "center");
await page.waitForTimeout(200);
assert.equal(await hint.count(), 0, "The middle of the pane does not take its own tab");
const area = await box(page.locator("main.center"));
await page.mouse.move(area.x + area.width - 30, area.y + area.height / 2, { steps: 5 });
await page.locator('.drop-hint[data-drop-zone="right"]').waitFor();
await page.screenshot({ path: path.join(output, "visible-tab-hint.png") });
await page.mouse.up();
await pane("b.md").locator(".cm-content").waitFor();
assert.equal(await hint.count(), 0);
// c.md is the last tab, so its pane shows the tab before it.
assert.deepEqual(await shown(), ["b.md", "c.md"], "The tab moves to the right, and its pane shows the tab before it");
assert.match(await activeTab(), /c\.md/, "The moved tab stays the active tab");
const left = await box(pane("b.md")), right = await box(pane("c.md"));
assert.ok(right.x >= left.x + left.width - 1 && Math.abs(left.y - right.y) < 2, "The panes show side by side");
assert.equal(await page.getByRole("tab").count(), 3, "All tabs stay open");
// The tab of the left pane moves below it. The pane shows the only tab that no pane shows.
await dragTo("b.md", pane("b.md"), "down");
await page.locator('.drop-hint[data-drop-zone="down"]').waitFor();
await page.mouse.up();
await pane("a.md").locator(".cm-content").waitFor();
assert.equal(await page.locator(".document-pane").count(), 3);
const top = await box(pane("a.md")), bottom = await box(pane("b.md"));
assert.ok(bottom.y >= top.y + top.height - 1 && Math.abs(top.x - bottom.x) < 2, "The moved tab shows below its old pane");
assert.match(await activeTab(), /b\.md/);
// Each tab now shows in a pane, so a pane has no other tab to show. The drag shows no hint.
await dragTo("a.md", pane("a.md"), "right");
await page.waitForTimeout(200);
assert.equal(await hint.count(), 0, "No tab is free for the pane");
await page.mouse.up();
assert.equal(await page.locator(".document-pane").count(), 3);
// A browser tab that covers the area moves to a new pane on the right. The document below it shows on the left.
for (let panes = 3; panes > 1; panes--) await page.getByRole("button", { name: "Close split", exact: true }).first().click();
assert.equal(await page.locator(".document-pane").count(), 1);
const below = (await shown())[0];
await page.waitForFunction(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); return !!pluginHost.get("browser"); });
await page.evaluate(async () => { const { pluginHost } = await import("/src/lib/plugins/registry.ts"); await pluginHost.get("browser").newTab(); });
await page.locator('[data-browser-state="ready"]').waitFor();
assert.ok((await box(browserPane)).width > area.width - 4, "The browser covers the area");
await dragTo("Browser", page.locator("main.center"), "right");
await page.locator('.drop-hint[data-drop-zone="right"]').waitFor();
await page.mouse.up();
await pane(below).locator(".cm-content").waitFor();
const documentBox = await box(pane(below)), webBox = await box(browserPane);
assert.ok(webBox.x >= documentBox.x + documentBox.width - 1, "The browser shows to the right of the document");
assert.match(await activeTab(), /Browser/);
// A tab that no pane shows opens in a new pane on the left side of the browser pane (card 156758f1).
const free = ["a.md", "b.md", "c.md"].find(name => name !== below);
await dragTo(free, browserPane, "left");
await page.locator('.drop-hint[data-drop-zone="left"]').waitFor();
const leftHint = await box(hint), browserBefore = await box(browserPane);
assert.ok(Math.abs(leftHint.x - browserBefore.x) < 2 && leftHint.width < browserBefore.width * 0.6, "The hint covers the left half of the pane");
assert.equal((await hint.innerText()).trim(), "Open to the left");
await page.screenshot({ path: path.join(output, "left-drop-hint.png") });
await page.mouse.up();
await pane(free).locator(".cm-content").waitFor();
const first = await box(pane(below)), middle = await box(pane(free)), last = await box(browserPane);
assert.ok(first.x + first.width <= middle.x + 1 && middle.x + middle.width <= last.x + 1, "The new pane shows between the document and the browser");
assert.match(await activeTab(), new RegExp(free.replace(".", "\\.")));
// The tab menu closes the split of a tab. The tab stays open, and the other panes stay.
const tabCount = await page.getByRole("tab").count();
const closeButtons = page.getByRole("button", { name: "Close split", exact: true });
assert.equal(await closeButtons.count(), 3, "Each pane bar has a Close split button");
assert.equal((await closeButtons.first().innerText()).trim(), "Close split", "The button shows its name");
await closeButtons.first().screenshot({ path: path.join(output, "close-split-button.png") });
// Screenshots of the pane bars in both themes and in a narrow window.
const viewport = page.viewportSize();
for (const mode of ["light", "dark"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, mode);
await page.waitForTimeout(150);
await page.screenshot({ path: path.join(output, `close-split-${mode}.png`) });
}
await page.setViewportSize({ width: 760, height: viewport.height });
await page.waitForTimeout(200);
await page.screenshot({ path: path.join(output, "close-split-narrow.png") });
// A narrow pane shows only the icon of the button. The tooltip gives its name.
await closeButtons.last().hover();
await page.locator(".rs-tooltip:popover-open").filter({ hasText: "Close split" }).waitFor();
await page.mouse.move(0, 0);
await page.setViewportSize(viewport);
await tab(free).click({ button: "right" });
await page.getByRole("menuitem", { name: "Close split", exact: true }).click();
await page.waitForFunction(count => document.querySelectorAll(".document-pane").length + document.querySelectorAll(".plugin-pane:not(.inactive)").length <= count, 3);
assert.deepEqual((await shown()).filter(Boolean), [below], "The pane of the tab closes. The browser pane stays.");
assert.equal(await page.getByRole("tab").count(), tabCount, "The tab stays open");
// A tab that no pane shows has no Close split item.
await tab(free).click({ button: "right" });
assert.equal(await page.getByRole("menuitem", { name: "Close split", exact: true }).count(), 0);
await page.keyboard.press("Escape");
console.log(JSON.stringify({ passed: ["one tab shows no hint", "own pane middle is no target", "visible tab moves right", "visible tab moves below", "no free tab shows no hint", "covering browser tab moves right", "free tab opens left of a pane", "tab menu closes a split and keeps the tab"], nativeDesktop: "not tested" }, null, 2));
});
@@ -0,0 +1,65 @@
// Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/windowControls", async ({ page }) => {
const output = await outputDir("layout/windowControls");
await mockTauri(page, {
state: { maximized: false, confirm: "Cancel" },
commands: test => ({
workspace_last_path: () => null,
"plugin:window|is_maximized": () => test.state.maximized,
"plugin:window|toggle_maximize": () => { test.state.maximized = !test.state.maximized; test.emit("tauri://resize", { width: 1400, height: 900 }); },
"plugin:window|minimize": () => {},
"plugin:window|destroy": () => {},
"plugin:window|close": () => { test.emit("tauri://close-requested"); },
"plugin:dialog|message": () => test.state.confirm,
}),
});
// The Terminal button belongs to the Terminal feature, which is on by default (src/lib/features/catalog.ts).
const called = command => page.evaluate(command => window.__TEST__.calls.some(call => call.command === command), command);
const config = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/tauri.conf.json"), "utf8"));
assert.equal(config.app.windows[0].decorations, false);
const capability = JSON.parse(await readFile(path.join(repoRoot, "src-tauri/capabilities/default.json"), "utf8"));
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
}
await page.goto(smokeUrl);
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).click();
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
// Native maximize/restore (e.g. double-clicking the drag region) updates the button too.
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert.ok(await called("plugin:window|minimize"));
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:dialog|message"));
assert.equal(await called("plugin:window|destroy"), false);
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
await page.getByRole("button", { name: "Close window", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === "plugin:window|destroy"));
await page.getByRole("button", { name: "Terminal", exact: true }).click();
for (const width of [1400, 880]) {
await page.setViewportSize({ width, height: 900 });
const layout = await page.evaluate(() => {
const header = document.querySelector(".header").getBoundingClientRect();
const controls = [...document.querySelectorAll(".header button")].map(el => el.getBoundingClientRect());
return { height: header.height, top: header.top, fits: controls.every(rect => rect.x >= 0 && rect.right <= innerWidth && rect.y >= header.y && rect.bottom <= header.bottom), drag: document.querySelector(".window-drag-space").getBoundingClientRect().width };
});
assert.equal(layout.height, 36);
assert.equal(layout.top, 0);
assert.ok(layout.fits);
assert.ok(layout.drag >= 40);
await page.screenshot({ path: path.join(output, `window-controls-${width}.png`) });
}
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
}, { viewport: { width: 1400, height: 900 }, timeout: 30000 });
+770
View File
@@ -0,0 +1,770 @@
// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { chooseView, mockTauri, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("layout/workbench", async ({ page }) => {
const output = await outputDir("layout/workbench");
const showcase = await readFile(path.join(repoRoot, "fixtures/reader-showcase.md"), "utf8");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"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",
},
});
Object.assign(test, { files: workspace.files, root: workspace.root });
// The Terminal feature opens its shells through the default `pty_*` handlers of the harness.
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => "Cancel",
};
},
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
async function contents() {
return page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
return EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString();
});
}
async function waitForText(text) {
await page.evaluate(async () => { window.__EditorView = (await import("/node_modules/@codemirror/view/dist/index.js")).EditorView; });
await page.waitForFunction(expected => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() === expected, text);
}
async function focusEditor() {
await page.locator(".source-editor .cm-content").click({position:{x:120,y:12}});
}
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await quickOpen("welcome.md");
const original = await contents();
assert.ok(original.startsWith("---\ntitle:"));
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Added in source.");
await waitForText(original + "Added in source.");
await quickOpen("hello.py");
await page.getByRole("tab", { name: /welcome\.md/ }).click();
await focusEditor();
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.__EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"))?.state.doc.toString() !== expected, original + "Added in source.");
await page.keyboard.press("Control+y");
await waitForText(original + "Added in source.");
await page.keyboard.press("Control+s");
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
await chooseView(page, "Read beside");
await page.locator(".md-page h1").first().waitFor();
assert.ok(await page.locator(".source-editor").isVisible());
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await waitForText("# Agent update\n");
await focusEditor();
await page.keyboard.press("Control+End");
await page.keyboard.type("Local edit");
await page.evaluate(() => {
window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
});
await page.getByRole("button", { name: "Keep my edits" }).waitFor();
assert.equal(await contents(), "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Keep my edits" }).click();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit");
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
await page.screenshot({ path: path.join(output, "core-rebuild-terminal.png") });
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
await page.getByRole("button", { name: "Terminal", exact: true }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
await page.getByRole("button", { name: "New terminal", exact: true }).click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
await page.getByRole("button", { name: "Terminal", exact: true }).click();
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
// A new note starts in its filename field, which keeps its own keys (src/lib/editor/DocumentEditor.svelte:386-392, src/lib/editor/noteTitle.ts:80).
await page.getByRole("textbox", { name: "Note filename", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "core-rebuild.png") });
await page.keyboard.press("Escape");
await page.evaluate(text => {
window.__TEST__.files.set("reader-showcase.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
// Each view choice shows only an icon (UI-056). The accessible name and the tooltip give its name and shortcut (src/lib/layout/ViewModes.svelte).
const read = page.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name: "Read", exact: true });
const readTip = page.getByRole("tooltip").filter({ hasText: "Read (Ctrl+Shift+E)" });
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await readTip.waitFor({ state: "visible" });
const tip = await readTip.boundingBox();
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
await read.click();
assert.equal(await read.getAttribute("aria-checked"), "true");
await page.locator(".reading h1:not(.document-title)").waitFor();
assert.equal(await page.locator(".source-editor").isVisible(), false);
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
assert.equal(await page.locator(".reading ol > li").count(), 3);
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
assert.equal(await page.locator(".reading input:checked").count(), 2);
assert.equal(await page.locator(".md-properties").getAttribute("open"), null);
assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes"));
const surface = await page.locator(".reading").boundingBox();
assert.ok(surface.width <= 741);
await page.mouse.move(700, 980);
await page.screenshot({ path: path.join(output, "reader-mode.png") });
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
await page.getByRole("button", { name: "Copy code", exact: true }).click();
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
await page.screenshot({ path: path.join(output, "reader-details.png") });
// At the minimum window width of 880 pixels the outline gives way, and Split stacks in the remaining pane.
await page.setViewportSize({ width: 880, height: 900 });
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
await page.screenshot({ path: path.join(output, "reader-narrow.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await chooseView(page, "Read beside");
await page.waitForFunction(() => {
const host = document.querySelector(".source-editor");
const rendered = host?.querySelector(".cm-editor");
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
});
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
await page.screenshot({ path: path.join(output, "reader-split.png") });
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
await page.setViewportSize({ width: 1440, height: 1000 });
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
await page.screenshot({ path: path.join(output, "reader-split-wide.png") });
// A second press ends the Split view.
await chooseView(page, "Read beside");
await page.locator(".md-page").waitFor({ state: "detached" });
// The editor stores one line break character. The saved file keeps its own line breaks.
assert.equal(await contents(), showcase.replace(/\r\n/g, "\n"));
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
await read.focus();
await readTip.waitFor({ state: "visible" });
await page.keyboard.press("Escape");
await readTip.waitFor({ state: "hidden" });
// Continuous live Markdown: only active lines reveal source; checkboxes
// remain inline and update the original file without HTML serialization.
const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n';
await page.evaluate(text => {
window.__TEST__.files.set("writing.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
}, writingSource);
await quickOpen("writing.md");
await chooseView(page, "Write");
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.waitFor();
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0);
await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 });
await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor();
const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." });
await paragraph.click();
await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor();
await page.keyboard.press("Home");
await page.keyboard.type("New ");
await page.keyboard.press("Control+s");
const editedSource = writingSource.replace("A **formatted**", "New A **formatted**");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource);
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
await chooseView(page, "Source");
await waitForText(editedSource);
await focusEditor();
await page.keyboard.press("Control+z");
await waitForText(writingSource);
await chooseView(page, "Write");
await writer.waitFor();
// Write keeps the caret of the Source undo, so the paragraph can show its source.
await page.locator(".live-writer .cm-line").filter({ hasText: /A (\*\*)?formatted(\*\*)? paragraph\./ }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("First new paragraph.");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("**Second new paragraph.**");
await page.keyboard.press("Enter");
await page.keyboard.press("Enter");
await page.keyboard.type("Third new paragraph.");
assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1);
await page.keyboard.press("Home");
await page.keyboard.press("Shift+ArrowUp");
await page.keyboard.press("Shift+ArrowUp");
assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph."));
await page.keyboard.press("Backspace");
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph."));
assert.ok(await writer.evaluate(el => el.contains(document.activeElement)));
// Link syntax becomes editable on a normal click, without opening the link.
await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click();
await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor();
await page.keyboard.press("End");
await page.keyboard.press("Home");
await page.keyboard.press("Shift+End");
await page.keyboard.type("[Project link](https://example.com/new)");
await page.keyboard.press("ArrowDown");
await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor();
const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" });
const checkbox = task.getByRole("checkbox");
assert.ok(await task.evaluate(line => {
const box = line.querySelector('input').getBoundingClientRect();
const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft'));
const range = document.createRange(); range.selectNode(text);
const label = range.getBoundingClientRect();
return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left;
}));
await checkbox.click();
await task.locator('.writer-completed').waitFor();
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
// Task markers stay rendered until the cursor reaches them (src/lib/editor/liveMarkdown.ts:262-268).
await task.locator('.writer-completed').click();
await page.keyboard.press("Home");
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
await page.keyboard.press("Shift+End");
await page.keyboard.type('- [ ] Revised task');
await page.keyboard.press("ArrowUp");
await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor();
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
await page.locator(".live-writer .md-diagram svg").waitFor();
await page.screenshot({ path: path.join(output, "writing-continuous.png") });
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await page.evaluate(() => {
window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
});
await quickOpen("crlf.md");
await chooseView(page, "Write");
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
await page.keyboard.press("Home");
await page.keyboard.type("Changed ");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n");
await page.keyboard.press("Control+n");
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
await page.getByRole("button", { name: "Continue", exact: true }).click();
// Enter keeps the new note's filename and moves to its body (src/lib/editor/noteTitle.ts:57, 83).
await page.getByRole("textbox", { name: "Note filename", exact: true }).press("Enter");
await writer.waitFor();
await page.keyboard.type("One");
await page.keyboard.press("Enter");
await page.keyboard.type("Two");
await page.keyboard.press("Enter");
await page.keyboard.type("Three");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.getByRole("tab", { name: "crlf.md", exact: true }).click();
await page.getByRole("tab", { name: "blank.md", exact: true }).click();
await writer.waitFor();
await page.keyboard.press("Control+z");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree");
await page.keyboard.press("Control+y");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
await page.keyboard.press("Control+f");
// The find field is labelled "Find in document" (src/lib/editor/FindPanel.svelte:60).
await page.getByRole("textbox", { name: "Find in document", exact: true }).fill("Two");
await page.keyboard.press("Escape");
await page.keyboard.press("Control+a");
await page.keyboard.type("- [ ] First task");
await page.keyboard.press("Enter");
await page.keyboard.type("Second task");
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task");
await page.evaluate(() => {
window.__TEST__.files.set("blank.md", "Fresh disk version\r\n");
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] });
});
await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor();
await page.keyboard.press("Control+z");
assert.ok((await writer.innerText()).includes("Fresh disk version"));
const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.<br>Keep listings consistent.<br>Introduce automated investing.<br>Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;<br>- Trading |\n\nAfter the table.\n';
await page.evaluate(text => {
window.__TEST__.files.set("tables.md", text);
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["tables.md"] });
}, tableSource);
await page.setViewportSize({ width: 1440, height: 1000 });
await quickOpen("tables.md");
await chooseView(page, "Write");
const table = page.locator('.live-writer table');
await table.waitFor();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
const tableHeading = page.locator('.live-writer .writer-heading');
await tableHeading.click();
assert.equal(await tableHeading.innerText(), '# Table layout');
await table.locator('tbody tr').first().locator('td').first().click();
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
// The add controls show while a cell of the table has focus (src/lib/editor/DocumentEditor.svelte).
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '1'));
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
assert.equal(await table.locator('th').count(), 5);
assert.equal(await table.locator('tbody tr').count(), 2);
assert.equal(await table.locator('br').count(), 4);
assert.ok(!(await table.innerText()).includes('<br>'));
// Columns keep the 3rem minimum width (`.reading th, .reading td` in src/lib/layout/reading.css; reduced from 8rem in 909894b).
assert.ok(await table.locator('th').evaluateAll(cells => {
const minimum = 3 * parseFloat(getComputedStyle(document.documentElement).fontSize);
return cells.every(cell => cell.getBoundingClientRect().width >= minimum - 0.5);
}));
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
// The add controls show on hover, and also while a cell of the table has focus. This part checks hover alone.
await page.evaluate(() => document.activeElement?.blur());
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
await table.locator('td').first().hover();
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
await addColumn.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
await page.screenshot({ path: path.join(output, 'writing-table-column.png') });
await addColumn.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
await addRow.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
await page.screenshot({ path: path.join(output, 'writing-table-row.png') });
await addRow.click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |'));
assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2);
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource);
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+y');
await table.locator('th').last().click();
const cellEditor = page.locator('.writer-cell-editor');
await cellEditor.waitFor();
assert.equal(await table.locator('th').count(), 6);
assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0);
await page.keyboard.type('New column');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column'));
await page.keyboard.press('Tab');
assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count());
await page.keyboard.press('Shift+Tab');
assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count());
await table.locator('tbody tr').first().locator('td').nth(4).click();
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
await page.keyboard.press('Control+End');
// Shift+Enter adds a line break in a cell; Enter moves to the next row (src/lib/editor/tableControls.ts:278-286).
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('Plain | pipe and *stars*');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
assert.equal(await table.locator('th').count(), 6);
await page.screenshot({ path: path.join(output, 'writing-table-cell-edit.png') });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
await cellEditor.waitFor();
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain'));
await page.keyboard.press('Escape');
await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click();
const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md'));
await table.locator('tbody tr').first().locator('td').nth(4).click();
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit);
await table.locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Tab');
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4);
await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor();
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
await chooseView(page, 'Read');
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
assert.equal(await page.locator('.md-page table br').count(), 5);
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('selection-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
window.__TEST__.clipboard = '';
// Cell copies write plain text and HTML through clipboard.write (src/lib/editor/tableSelectionControls.ts:80-85).
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
write: async items => { window.__TEST__.clipboard = await (await items[0].getType('text/plain')).text(); },
writeText: async text => { window.__TEST__.clipboard = text; },
readText: async () => window.__TEST__.clipboard,
} });
}, selectionTable);
await quickOpen('selection-table.md');
await chooseView(page, 'Write');
const selectedTable = page.locator('.live-writer table');
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
await page.mouse.move(fromCell.x + 15, fromCell.y + 15);
await page.mouse.down();
await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 });
await page.mouse.up();
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
await page.screenshot({ path: path.join(output, 'table-cell-selection-menu.png') });
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
await page.keyboard.press('Control+i');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0);
assert.equal(await selectedTable.locator('strong').count(), 4);
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
async function cellAction(name, formatted = false) {
await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' });
if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
}
await cellAction('Clear formatting', true);
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
await cellAction('Copy Ctrl+C');
// clipboard.write resolves its items asynchronously.
await page.waitForFunction(expected => window.__TEST__.clipboard === expected, 'one\ttwo\nfour\tfive');
await cellAction('Cut Ctrl+X');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
await cellAction('Paste Ctrl+V');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await cellAction('Align centre');
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) {
await cellAction(name, true);
await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector);
await cellAction('Clear formatting', true);
}
// Native clipboard events must operate on the rectangle, including one-step undo.
await page.locator('.writer-table').evaluate(el => {
const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
});
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red');
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three');
assert.equal(await selectedTable.locator('th').count(), 3);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await page.keyboard.press('Control+a');
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9);
await cellAction('Delete cells');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0);
await page.keyboard.press('Control+z');
await selectedTable.waitFor();
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) {
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
await page.getByRole('menuitem', { name, exact: true }).click();
await selectedCell(1, 0).click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Escape');
assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`);
await selectedCell(1, 0).click();
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
await selectedCell(1, 0).click({ button: 'right' });
await cellAction('Clear formatting', true);
}
const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('table-actions.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
}, actionsSource);
await quickOpen('table-actions.md');
await chooseView(page, 'Write');
const actionTable = page.locator('.live-writer table');
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
async function actionItem(label, group, r = 1, c = 0) {
await actionCell(r, c).click({ button: 'right' });
if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover();
await page.getByRole('menuitem', { name: label, exact: true }).click();
}
async function saveActionSource() {
await page.keyboard.press('Control+s');
return page.evaluate(() => window.__TEST__.files.get('table-actions.md'));
}
async function undoAction() {
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource);
}
for (const [label, group, r, c, rows, columns] of [
['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2],
['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1],
]) {
await actionItem(label, group, r, c);
assert.equal(await actionTable.locator('tr').count(), rows, label);
assert.equal(await actionTable.locator('th').count(), columns, label);
await undoAction();
}
await actionItem('Move row down', 'Row');
assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group');
await undoAction();
await actionItem('Move row up', 'Row', 2);
assert.equal(await actionCell(1, 0).innerText(), 'Apple');
await undoAction();
await actionItem('Move column right', 'Column');
assert.equal(await actionCell(0, 0).innerText(), 'Value');
assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right');
await undoAction();
await actionItem('Move column left', 'Column', 1, 1);
assert.equal(await actionCell(0, 0).innerText(), 'Value');
await undoAction();
await actionItem('Sort by column (A to Z)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']);
await undoAction();
await actionItem('Sort by column (Z to A)', undefined, 1, 1);
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']);
await undoAction();
await actionCell(0, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled());
assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled());
await page.keyboard.press('Escape');
async function selectBrokers() {
await actionCell(1, 0).click();
await page.keyboard.press('Control+Home');
for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight');
for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers');
}
await selectBrokers();
await actionCell(1, 0).click({ button: 'right' });
assert.equal(await page.getByRole('menuitem', { name: 'Copy Ctrl+C', exact: true }).isDisabled(), false);
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
await page.screenshot({ path: path.join(output, 'table-text-row-menu.png') });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
await page.screenshot({ path: path.join(output, 'table-text-column-menu.png') });
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
await page.keyboard.press('ArrowRight');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
await page.keyboard.press('ArrowLeft');
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column');
await page.keyboard.press('Escape');
await actionItem('Bold', 'Format');
assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers');
assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group'));
await actionItem('Add external link');
await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1');
assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Add link');
await page.getByRole('dialog').locator('input').fill('notes/second');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki');
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Search for “Brokers”');
await page.getByPlaceholder('Search files and notes').waitFor();
assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers');
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers'));
await selectBrokers();
await actionItem('Extract current selection…');
await page.getByRole('dialog').locator('input').fill('extracted-brokers.md');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n');
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md');
await page.keyboard.press('Control+z');
await selectBrokers();
await page.evaluate(() => { window.__TEST__.clipboard = '<b>literal</b>\nnext'; });
await actionItem('Paste as plain text');
assert.ok((await saveActionSource()).includes('Interactive &lt;') || (await saveActionSource()).includes('Interactive \\<b\\>literal\\</b\\><br>next'));
assert.equal(await actionCell(1, 0).locator('b').count(), 0);
await page.keyboard.press('Control+z');
await selectBrokers();
await page.evaluate(() => {
navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? '<em>Rich paste</em>' : 'Rich paste'], { type }) }];
});
await actionItem('Paste Ctrl+V');
await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste');
await page.keyboard.press('Control+z');
await page.evaluate(() => { delete navigator.clipboard.read; });
await selectBrokers();
await actionItem('Copy Ctrl+C');
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
await actionItem('Cut Ctrl+X');
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
await page.keyboard.press('Control+z');
await selectBrokers();
await actionItem('Select all Ctrl+A');
assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group');
await page.setViewportSize({ width: 800, height: 600 });
await actionCell(1, 0).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
assert.ok(await page.locator('.table-cell-menu, .table-cell-submenu:popover-open').evaluateAll(panels => panels.every(panel => {
const rect = panel.getBoundingClientRect(); return rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight;
})));
await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1000, height: 900 });
const richTable = '| Name | Notes |\r\n| :--- | ---: |\r\n| Untouched | ~~Old~~ **bold** [link](https://example.com) ![attachment](missing.png)<br />Next |\r\n| Short |\r\n';
await page.evaluate(text => {
window.__TEST__.files.set('rich-table.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
}, richTable);
await quickOpen('rich-table.md');
await chooseView(page, 'Write');
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
await richCell.click();
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable);
await page.keyboard.press('Control+End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited'));
const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md'));
assert.ok(richSaved.includes('| Untouched |'));
assert.ok(richSaved.includes('~~Old~~'));
assert.ok(richSaved.includes('**bold**'));
assert.ok(richSaved.includes('https://example.com'));
assert.ok(richSaved.includes('![attachment](<missing.png>)'));
assert.ok(richSaved.includes('<br>Next edited'));
assert.ok(!/(?<!\r)\n/.test(richSaved));
await page.keyboard.press('Escape');
await richCell.click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' again');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Next edited again'));
const shortCell = page.locator('.live-writer tbody tr').last().locator('td').last();
await shortCell.click();
await cellEditor.evaluate(el => {
const data = new DataTransfer(); data.setData('text/plain', 'Pasted | text\nSecond line');
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
});
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Pasted \\| text<br>Second line'));
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+b');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('**Pasted \\| text**'));
assert.equal(await page.locator('.live-writer th').count(), 2);
// Physical mouse coordinates below tall block widgets must resolve to the
// visible line, including immediately adjacent heading/body lines.
const longTable = '| Ticker | Name | Notes |\n| --- | --- | --- |\n' +
Array.from({ length: 14 }, (_, index) => `| STOCK${index} | Company ${index} | First note<br>Second note<br>Third note |`).join('\n');
const hitTestSource = `# Listed\n\n${longTable}\n\n# Tier 1\nTier one body directly below heading.\n\n${longTable}\n\n## Tier 2\nTier two body directly below heading.\n`;
await page.evaluate(text => {
window.__TEST__.files.set('table-hit-testing.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
}, hitTestSource);
await quickOpen('table-hit-testing.md');
await chooseView(page, 'Write');
async function clickRenderedLine(locator, expected) {
await locator.scrollIntoViewIfNeeded();
const rect = await locator.boundingBox();
assert.ok(rect);
await page.mouse.click(rect.x + 45, rect.y + rect.height * .7);
const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent);
assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`);
}
async function checkLinesAfterTables() {
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
for (const [heading, body] of [
['# Tier 1', 'Tier one body directly below heading.'],
['## Tier 2', 'Tier two body directly below heading.'],
]) {
const tables = page.locator('.live-writer .writer-table');
await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded();
await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading);
await page.keyboard.press('End');
await page.keyboard.type(' edited');
await page.keyboard.press('Control+s');
await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading);
await page.keyboard.press('Control+z');
await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body);
}
}
await page.setViewportSize({ width: 1440, height: 1000 });
await checkLinesAfterTables();
await page.locator('.cm-scroller').evaluate(async el => {
el.scrollTop = 0;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
});
await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click();
await page.keyboard.press('Control+End');
for (let line = 0; line < 4; line++) {
await page.keyboard.press('Enter');
await page.keyboard.type('A newly added line changes the table height.');
}
await checkLinesAfterTables();
await page.setViewportSize({ width: 1000, height: 900 });
await checkLinesAfterTables();
await page.screenshot({ path: path.join(output, 'table-cursor-position.png') });
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
});
+83
View File
@@ -0,0 +1,83 @@
// Backlinks panel in isolation: both themes, narrow panels, long lists, keyboard use, empty, busy, and error states, and text contrast.
import { writeFile } from "node:fs/promises";
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/backlinks", async ({ page }) => {
const output = await outputDir("links/backlinks");
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
<aside id="fixture" style="width:320px;height:500px;display:flex;flex-direction:column;background:var(--rs-bg-elevated);margin:24px"></aside>
<script type="module">
import '/src/app.css';
import {mount,unmount} from '/node_modules/.vite/deps/svelte.js';
import Backlinks from '/src/lib/layout/Backlinks.svelte';
import {applyAppearance} from '/src/lib/theme/appearance.ts';
let component;
window.renderBacklinks = async ({mode='dark',width=320,entries=[],busy=false,error=null}={}) => {
if(component) await unmount(component);
applyAppearance({theme:'default',mode});
document.querySelector('#fixture').style.width=width+'px';
component=mount(Backlinks,{target:document.querySelector('#fixture'),props:{entries,busy,error,onOpen:entry=>window.openedBacklink=entry,onRebuild:()=>window.rebuildCount=(window.rebuildCount||0)+1}});
};
await window.renderBacklinks();
window.backlinksReady=true;
</script></body></html>` }));
const entries = Array.from({ length: 28 }, (_, index) => ({
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
line: index + 3, from: index * 100, to: index * 100 + 10,
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
kind: "wiki", target: "Target",
}));
const measurements = [];
await page.goto(`${smokeUrl}/__backlinks__`);
await page.waitForFunction(() => window.backlinksReady);
const panel = page.getByRole("region", { name: "Backlinks", exact: true });
await panel.getByText("No other notes link to this file.").waitFor();
await page.screenshot({ path: `${output}/empty-dark.png` });
for (const mode of ["light", "dark"]) {
for (const width of [320, 180]) {
await page.evaluate(args => window.renderBacklinks(args), { mode, width, entries });
const toggle = panel.getByRole("button", { name: "Backlinks 28", exact: true });
await toggle.focus();
await page.keyboard.press("Enter");
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
assert.equal(await panel.locator(".source").first().isVisible(), false);
await page.keyboard.press("Space");
assert.equal(await toggle.getAttribute("aria-expanded"), "true");
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.ok(await page.evaluate(() => window.rebuildCount > 0));
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.openedBacklink.sourcePath), entries[0].sourcePath);
const metrics = await panel.evaluate(node => {
const source = node.querySelector(".source"), title = node.querySelector(".source-title"), content = node.querySelector(".content");
const style = getComputedStyle(source);
const color = value => value.match(/[\d.]+/g).slice(0, 3).map(Number);
const luminance = rgb => rgb.map(value => value / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126,.7152,.0722][index], 0);
const contrast = (a,b) => { const l1=luminance(color(a)),l2=luminance(color(b));return (Math.max(l1,l2)+.05)/(Math.min(l1,l2)+.05); };
const background = getComputedStyle(document.querySelector("#fixture")).backgroundColor;
return { text: style.color, accent: getComputedStyle(title).color, background,
textContrast: contrast(style.color,background), linkContrast:contrast(getComputedStyle(title).color,background),
width:node.clientWidth,scrollWidth:node.scrollWidth,scrollable:content.scrollHeight>content.clientHeight,
focusStyle:style.outlineStyle,focusColor:style.outlineColor,opacity:style.opacity };
});
assert.ok(metrics.textContrast >= 4.5, `Text contrast: ${mode} ${width}`);
assert.ok(metrics.linkContrast >= 4.5, `Link contrast: ${mode} ${width}`);
assert.ok(metrics.scrollWidth <= metrics.width, "The panel must not scroll horizontally");
assert.ok(metrics.scrollable, "Long lists must scroll inside the panel");
assert.equal(metrics.focusStyle, "solid");
assert.equal(metrics.opacity, "1");
measurements.push({ mode, width, ...metrics });
await page.screenshot({ path: `${output}/${mode}-${width}-focus.png` });
}
}
await page.evaluate(() => window.renderBacklinks({ busy:true, error:"Could not read one note. Rebuild the index to try again." }));
assert.equal(await panel.getByRole("button", { name:"Rebuild note index", exact:true }).isDisabled(), true);
await panel.getByText("Reading workspace links…").waitFor();
await page.screenshot({ path:`${output}/busy-error-dark.png` });
await writeFile(path.join(output, "measurements.json"), JSON.stringify(measurements,null,2));
console.log("Backlinks smoke passed: themes, narrow panels, long lists, keyboard, empty, busy, error, and contrast.");
}, { viewport: { width: 720, height: 640 }, timeout: 30000 });
+81
View File
@@ -0,0 +1,81 @@
// File tree drags into Writer and the Source: documents become escaped links, images embed, and undo restores the source.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/fileDragLinks", async ({ page }) => {
await page.addInitScript(() => localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false })));
await mockTauri(page, {
commands: test => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
const workspace = test.workspace({
root: "C:\\file-drag-links",
files: { "notes/draft.md": "Before.\n\nAfter.\n", "files/report [Q1] (#1).pdf": "PDF fixture", "images/diagram (#1).svg": btoa(svg) },
});
return {
...workspace,
workspace_read_data_url: ({ rel }) => "data:image/svg+xml;base64," + workspace.files.get(rel),
plugins_snapshot: () => ({ plugins: [], issues: [] }),
spelling_menu_install: () => null,
};
},
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
async function drag(path, target) {
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
assert.ok(from && to, "The file and editor must be visible");
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
await page.locator(".image-drop-target").waitFor();
await page.mouse.up();
}
const writerSource = () => page.evaluate(() => window.dragWriter.state.doc.toString());
const ideSource = () => page.evaluate(() => window.dragSource.state.doc.toString());
await page.goto(smokeUrl);
await row("notes").click();
await row("notes/draft.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.dragWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await row("files").click();
const original = await writerSource();
await drag("files/report [Q1] (#1).pdf", ".cm-content");
await page.waitForFunction(() => window.dragWriter.state.doc.toString().includes(".pdf)"));
const linked = await writerSource();
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
assert.ok(!linked.includes("!["), "A document must be a link, not an image");
await page.evaluate(() => window.dragWriter.focus());
await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original, "Writer undo restores the exact source");
await row("images").click();
await drag("images/diagram (#1).svg", ".cm-content");
await page.locator(".md-image-frame img").waitFor();
assert.ok((await writerSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
await page.evaluate(() => window.dragWriter.focus());
await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original);
console.log("PASS: Writer drags insert escaped document links and image embeds, and undo restores the source");
await page.keyboard.press("Control+e");
await page.locator(".source-editor .cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.dragSource = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
});
const originalIde = await ideSource();
await drag("files/report [Q1] (#1).pdf", ".source-editor .cm-content");
await page.waitForFunction(() => window.dragSource.state.doc.toString().includes(".pdf)"));
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
await page.evaluate(() => window.dragSource.focus());
assert.equal(await page.evaluate(() => window.dragSource.hasFocus), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.dragSource.state.doc.toString() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "Source undo restores the exact source");
await drag("images/diagram (#1).svg", ".source-editor .cm-content");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: Source drags insert escaped document links and image embeds, undo restores the source, and no file moves");
}, { timeout: 15000 });
+100
View File
@@ -0,0 +1,100 @@
// Link editing in the Writer: link tooltips and source colors, Edit link in prose, table, and wiki cells with undo, multiple links in a cell, and table tooltips at narrow widths.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/linkEditing", async ({ page }) => {
const output = await outputDir("links/linkEditing");
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal [guide](docs/guide.md) text.\n\n| Name | Value |\n| --- | --- |\n| [Roadmap](docs/roadmap.md) | [[guide\\|Guide]] |\n| [One](same.md) + [Two](same.md) | Empty |\n`;
return {
...test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, note(name)])) }),
spelling_menu_install: () => {},
};
},
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}), theme);
const prose = page.locator('.writer-link').filter({hasText:'guide'}).first();
await prose.hover();
// A focused table cell can keep its own tooltip open (src/lib/ui/tooltip.ts:32), so wait for the link's tooltip.
await page.getByRole('tooltip',{name:'Ctrl+click to open link',exact:true}).waitFor();
assert.equal(await prose.getAttribute('title'),null);
await page.screenshot({path:path.join(output, 'editor-link-tooltip-'+theme+'.png')});
await page.keyboard.press('Escape');
await prose.click();
assert.equal(await page.locator('.writer-link-source').count(),1);
const colored = await page.locator('.writer-link-source').evaluate(el => ({color:getComputedStyle(el).color, parent:getComputedStyle(el.parentElement).color}));
assert.notEqual(colored.color,colored.parent);
await page.screenshot({path:path.join(output, 'editor-link-source-'+theme+'.png')});
const cell=page.locator('.writer-table td').first();
await cell.locator('a').click({position:{x:22,y:8}});
assert.ok(await page.evaluate(()=>getSelection().anchorOffset > 0));
await cell.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(await page.evaluate(()=>getSelection().toString()),theme === 'dark' ? 'docs/roadmap.md' : 'docs/new-roadmap.md');
await page.screenshot({path:path.join(output, 'editor-table-source-'+theme+'.png')});
await page.keyboard.type('docs/new-roadmap.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
if(theme === 'dark') {
await page.locator('.cm-line').filter({hasText:'Original'}).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/roadmap.md');
await page.keyboard.press('Control+Shift+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
}
await cell.locator('a').click({position:{x:22,y:8}});
const selection=await page.evaluate(()=>{const s=getSelection();return {offset:s.anchorOffset,length:s.anchorNode.textContent.length};});
assert.ok(selection.offset>0 && selection.offset<selection.length,JSON.stringify(selection));
await page.keyboard.type('X');
assert.ok((await cell.innerText()).includes('X'));
await page.keyboard.press('Escape');
const wiki=page.locator('.writer-table td').nth(1);
await wiki.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),theme==='dark'?'guide':'new-guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'),'new-guide');
}
const multi=page.locator('.writer-table td').nth(2);
await multi.locator('a').nth(1).click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await multi.locator('a').first().getAttribute('href'),'same.md');
assert.equal(await multi.locator('a').nth(1).getAttribute('href'),'second.md');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.getByRole('button',{name:'Files',exact:true}).click();
await page.setViewportSize({width:620,height:700});
await page.waitForTimeout(250);
await page.locator('.table-add-row').scrollIntoViewIfNeeded();
await page.waitForTimeout(100);
await page.locator('.table-add-row').focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
const rect=await page.locator('.rs-tooltip:popover-open').boundingBox();
assert.ok(rect.x>=0 && rect.x+rect.width<=620);
await page.screenshot({path:path.join(output, 'editor-tooltip-narrow-focus.png')});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(),0);
assert.equal(await page.locator('.table-edit-help:visible').count(),0);
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
// Only a formula cell has a hover hint. The footer shows the address of the cell with focus (src/lib/editor/tableControls.ts).
await page.waitForTimeout(500);
assert.ok((await page.locator('.rs-tooltip:popover-open').allInnerTexts()).every(text => !/^[A-Z]+\d+/.test(text)));
await page.screenshot({path:path.join(output, 'editor-cell-tooltip-narrow-'+mode+'.png')});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
}
console.log('Editor link and tooltip checks passed');
}, { timeout: 15000 });
+185
View File
@@ -0,0 +1,185 @@
// Link context menus in the Writer, Reading, Source, and table cells: browser and workspace actions, Edit link with undo, keyboard use, narrow windows, bookmarks, rename, and move.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/linkMenus", async ({ page }) => {
const output = await outputDir("links/linkMenus");
await mockTauri(page, {
commands: test => {
const note = name => `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`;
const files = Object.fromEntries(["b.md", "c.md", "d.md"].map(name => [name, note(name)]));
// Enter in a table cell moves to the next row, and adds one after the last row (src/lib/editor/tableControls.ts:278-285).
// The second row keeps each link edit a single undo step.
files["a.md"] = "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n\n| Link | Note |\n| --- | --- |\n| [Cell web](https://example.com/cell) | [[b.md\\|Cell note]] |\n| Plain | Row |\n";
files["sample.txt"] = "const answer = 42;\n";
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files });
Object.assign(test, { files: workspace.files, clipboard: null, opened: null, app: null, revealed: null, searched: null, windows: [] });
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { test.clipboard = text; } } });
return {
...workspace,
workspace_search: args => { test.searched = args.query; return []; },
workspace_rename: args => { workspace.files.set(args.to, workspace.files.get(args.from)); workspace.files.delete(args.from); },
workspace_reveal: args => { test.revealed = args.rel; },
workspace_open_default: args => { test.app = args.rel; },
workspace_open_window: args => { test.windows.push(args); },
"plugin:opener|open_url": args => { test.opened = args.url; },
spelling_menu_install: () => {},
};
},
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const report = [];
async function writerMenu(target='Web label') {
await page.locator('.cm-content').getByText('Selected reading text.', { exact: true }).click();
await page.locator('.cm-content').getByText(target, { exact: true }).click({ button: 'right' });
await menu('Markdown text actions').waitFor();
}
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async () => {
const { pluginHost } = await import('/src/lib/plugins/registry.ts');
// "Open link in app browser" opens a new browser tab with the link (newTab). A link click uses open.
pluginHost.register('link-smoke', 'browser', { newTab: async target => { window.__TEST__.browser = target; }, open: async target => { window.__TEST__.browser = target; return true; }, mountSettings: () => () => {}, mountBookmarks: () => () => {} });
});
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default', mode}); }, theme);
await writerMenu();
for (const label of ['Open link in app browser', 'Open link in default browser', 'Copy URL', 'Edit link']) assert.equal(await item(label).count(), 1);
await page.screenshot({ path: `${output}/writer-link-${theme}.png` });
await item('Copy URL').click();
await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/path');
await writerMenu(); await item('Open link in default browser').click();
await page.waitForFunction(() => window.__TEST__.opened === 'https://example.com/path');
await writerMenu(); await item('Open link in app browser').click();
await page.waitForFunction(() => window.__TEST__.browser === 'https://example.com/path');
await writerMenu(); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); const v = EditorView.findFromDOM(document.querySelector('.cm-content')); return v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/edit-url-${theme}.png` });
await page.keyboard.type('https://changed.example');
await page.keyboard.press('Control+z');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await writerMenu('Workspace note');
for (const label of ['Open in new tab', 'Open in new window', 'Copy path', 'Bookmark', 'Show in Explorer', 'Reveal file in navigation', 'Edit link']) assert.equal(await item(label).count(), 1);
for (const label of ['Rename…', 'Move file to…', 'Open in default app']) assert.equal(await item(label).count(), 0);
await page.screenshot({ path: `${output}/workspace-link-${theme}.png` });
await dismiss();
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await writerMenu('Workspace note'); await page.keyboard.press('End');
assert.match(await page.evaluate(() => document.activeElement.textContent), /Select all/);
await page.screenshot({path:`${output}/workspace-narrow-${theme}.png`});
await dismiss(); await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await writerMenu('Workspace note');
await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('Workspace path').click();
await page.waitForFunction(() => window.__TEST__.clipboard === 'b.md');
await writerMenu('Workspace note'); await item('Show in Explorer').click(); await page.waitForFunction(() => window.__TEST__.revealed === 'b.md');
await writerMenu('Workspace note'); await item('Reveal file in navigation').click();
await page.waitForFunction(() => document.activeElement?.getAttribute('data-tree-rel') === 'b.md');
await chooseView(page, 'Read');
const reading = page.locator('.reading');
await reading.getByText('Selected reading text.',{exact:true}).evaluate(node => { const range = document.createRange(); range.selectNodeContents(node); const s = getSelection(); s.removeAllRanges(); s.addRange(range); node.closest('.reading').focus(); });
await page.keyboard.press('Shift+F10');
await menu('Reading actions').waitFor();
await page.keyboard.press('End'); assert.match(await page.evaluate(() => document.activeElement.textContent), /^Search for/);
await page.screenshot({ path: `${output}/reading-selection-${theme}.png` });
await page.keyboard.press('Home'); await page.keyboard.press('Enter');
await page.waitForFunction(() => window.__TEST__.clipboard === 'Selected reading text.');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', {name:/^Search for/}).click();
await page.waitForFunction(() => window.__TEST__.searched === 'Selected reading text.');
await page.evaluate(() => getSelection().removeAllRanges());
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
await item('Copy URL').click(); await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/path');
await page.getByRole('button', { name: 'Search', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
const rect=await menu('Reading actions').boundingBox(); assert.ok(rect.x>=0 && rect.x+rect.width<=560 && rect.y+rect.height<=620);
await page.screenshot({ path: `${output}/reading-narrow-${theme}.png` });
await dismiss();
assert.equal(await reading.evaluate(node => node.contains(document.activeElement)), true);
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); view.dispatch({selection:{anchor:view.state.doc.toString().indexOf('Web label')+2}}); view.focus(); });
await page.keyboard.press('Shift+F10'); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const {state}=EditorView.findFromDOM(document.querySelector('.source-editor .cm-content')); return state.sliceDoc(state.selection.main.from,state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/ide-edit-url-${theme}.png` });
await chooseView(page, 'Write');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
const cellLink = page.locator('.writer-table a').filter({hasText:'Cell web'});
await cellLink.click({button:'right'});
await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-link-${theme}.png`});
await item('Copy URL').click();
await page.waitForFunction(() => window.__TEST__.clipboard === 'https://example.com/cell');
await cellLink.click({button:'right'}); await item('Edit link').click();
const sourceCell = page.locator('.writer-table .is-source-editing .writer-cell-editor');
await sourceCell.waitFor();
assert.equal(await page.getByLabel('Edit link target').count(), 0);
assert.equal(await page.evaluate(() => getSelection().toString()), 'https://example.com/cell');
assert.equal(await sourceCell.locator('.writer-link-target').innerText(), 'https://example.com/cell');
await page.screenshot({path:`${output}/table-edit-${theme}.png`});
await page.keyboard.type('https://changed.example/cell'); await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://changed.example/cell');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
const cellNote = page.locator('.writer-table a').filter({hasText:'Cell note'});
await cellNote.click({button:'right'}); await item('Edit link').click();
assert.equal(await page.evaluate(() => getSelection().toString()), 'b.md');
await page.keyboard.type('c.md'); await page.keyboard.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'c.md'));
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'b.md'));
await cellLink.click({button:'right'}); await item('Edit link').click();
await page.keyboard.type('https://escape.example'); await page.keyboard.press('Escape');
assert.equal(await sourceCell.count(), 0);
assert.equal(await cellLink.getAttribute('href'), 'https://escape.example');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await cellLink.click(); await page.keyboard.press('Shift+F10'); await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-narrow-${theme}.png`});
await dismiss();
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
report.push({theme,passed:['Writer and Source edit URL selection','browser destinations','workspace file actions','Reader copy/search/link actions','inline table web/wiki link edits and undo','table source Escape and keyboard menu','keyboard focus return','narrow viewport'],nativeDesktop:'not tested'});
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.__TEST__.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.__TEST__.windows[0]; window.__TEST__.emit('tab-transfer-accepted',{id:transfer}); });
assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab');
await page.locator('[data-tree-rel="a.md"]').click();
await writerMenu('Workspace note'); await item('Bookmark').click();
await page.waitForFunction(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json') || '{}').bookmarks?.includes('b.md'));
await writerMenu('Workspace note'); await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('System path').click();
await page.waitForFunction(() => window.__TEST__.clipboard.endsWith('\\b.md'));
await chooseView(page, 'Read');
const readerWorkspaceMenu = async () => { await page.locator('.reading').getByRole('link',{name:'Workspace note'}).click({button:'right'}); };
await readerWorkspaceMenu(); await item('Open in default app').click();
await page.waitForFunction(() => window.__TEST__.app === 'b.md');
await readerWorkspaceMenu(); await item('Rename…').click();
await page.getByLabel('New file name').fill('renamed.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.__TEST__.files.has('renamed.md') && !window.__TEST__.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json')).bookmarks.includes('renamed.md')),true);
await chooseView(page, 'Write');
await page.locator('.cm-content').evaluate(async node => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(node); const from=view.state.doc.toString().indexOf('b.md'); view.dispatch({changes:{from,to:from+4,insert:'renamed.md'}}); });
await chooseView(page, 'Read');
await readerWorkspaceMenu(); await item('Move file to…').click();
await page.getByLabel('Move file to (workspace path, including filename)').fill('notes/moved.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.__TEST__.files.has('notes/moved.md') && !window.__TEST__.files.has('renamed.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.__TEST__.files.get('.runestone/marks.json')).bookmarks.includes('notes/moved.md')),true);
console.log(JSON.stringify(report,null,2));
}, { timeout: 15000 });
+91
View File
@@ -0,0 +1,91 @@
// Writer previews: ordered-list spacing around fenced code, and local, wiki, and table-source links that open document tabs, in both themes at wide and narrow widths.
import assert from "node:assert/strict";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/previewLinks", async ({ browser, page }) => {
const output = await outputDir("links/previewLinks");
// Every load starts without saved tabs or settings.
await page.addInitScript(() => localStorage.clear());
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
commands: test => {
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: { "a.md": "# Links\n\nOriginal text.\n" } });
test.files = workspace.files;
return {
...workspace,
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_suggestions: () => ({ language: "en-US", words: [], misspelled: false }),
"plugin:dialog|message": () => "Cancel",
};
},
});
// The app stays at its own root URL; compare with the normalized form.
const appUrl = new URL(smokeUrl).href;
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
async function resetFile(text) {
await page.locator('.cm-content').evaluate(async (node, text) => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
}, text);
}
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
await resetFile(installation);
const preview = page.locator('.writer-preview').filter({ has: page.locator('ol') });
await preview.waitFor();
if (theme === 'dark' && width === 1440) {
await preview.evaluate(element => { element.style.whiteSpace = 'pre-wrap'; });
const gap = await preview.locator('li').first().evaluate(item => item.querySelector('p').getBoundingClientRect().top - item.getBoundingClientRect().top);
assert.ok(gap > 15, 'Inherited editor whitespace reproduces the reported blank line');
await page.screenshot({ path:`${output}/ordered-list-before-dark-1440.png` });
await preview.evaluate(element => { element.style.removeProperty('white-space'); });
}
const metrics = await preview.evaluate(element => {
const item = element.querySelector('li'), paragraph = item.querySelector('p');
return { whiteSpace: getComputedStyle(element).whiteSpace, itemTop: item.getBoundingClientRect().top, paragraphTop: paragraph.getBoundingClientRect().top, firstHeight: item.getBoundingClientRect().height, lineHeight: parseFloat(getComputedStyle(paragraph).lineHeight) };
});
assert.equal(metrics.whiteSpace, 'normal');
assert.ok(Math.abs(metrics.paragraphTop - metrics.itemTop) < 2, 'Number and first paragraph share one line');
assert.ok(metrics.firstHeight < metrics.lineHeight * 3, 'Short list item has no blank formatting lines');
assert.equal(await preview.locator('li').count(), 5);
assert.match(await preview.locator('code').last().innerText(), /sha256sum --check SHA256SUMS\n/);
await page.screenshot({ path:`${output}/ordered-list-${theme}-${width}.png` });
const fixture = '# Links\n\nOutside.\n\n| Task | Link |\n| --- | --- |\n| Plugin setup | [Plugin installation](<docs/plugins.md#install-a-plugin>) |\n| Wiki | [[docs/plugins.md\\|Plugin guide]] |\n';
await resetFile(fixture);
await page.evaluate(() => window.__TEST__.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
const localLink = page.locator('.writer-table a').filter({ hasText:'Plugin installation' });
await localLink.click({ modifiers:[width === 620 ? 'Meta' : 'Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
assert.equal(page.url(), appUrl);
assert.equal(browser.contexts().flatMap(context => context.pages()).length, 1, 'Local link cannot open a browser tab');
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
await page.screenshot({ path:`${output}/local-link-tab-${theme}-${width}.png` });
await page.getByRole('tab', { name:'a.md', exact:true }).click();
const wiki = page.locator('.writer-table a').filter({ hasText:'Plugin guide' });
await wiki.click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.equal(await page.getByRole('tab', { name:'plugins.md', exact:true }).count(), 1, 'Duplicate link focuses its existing document');
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await page.locator('.writer-table a').filter({ hasText:'Plugin installation' }).click();
const source = page.locator('.is-source-editing .writer-cell-editor');
await source.waitFor();
await page.screenshot({ path:`${output}/source-link-${theme}-${width}.png` });
await source.locator('.writer-link-target').click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
}
console.log('PASS: nested fenced-code list spacing, preserved code newlines, rendered/table-source/wiki local links open document tabs, duplicate target focus, both themes, narrow and wide windows. Native WebView acceptance remains open.');
}, { timeout: 15000 });
+157
View File
@@ -0,0 +1,157 @@
// Section links: heading anchors in the Writer, Reading, Split, and Source views, an encoded duplicate heading in another file, a missing section, and folded headings, in both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/sectionLinks", async ({ page }) => {
const output = await outputDir("links/sectionLinks");
// Every load starts without saved tabs or settings.
await page.addInitScript(() => localStorage.clear());
// Unknown commands return null, as the original mock did.
await mockTauri(page, {
strict: false,
commands: test => {
const workspace = test.workspace({ root: "C:\\tab-menu-workspace", folders: ["notes"], files: { "a.md": "# Links\n\nOriginal text.\n" } });
test.files = workspace.files;
return {
...workspace,
"plugin:window|is_maximized": () => false,
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_suggestions: () => ({ language: "en-US", words: [], misspelled: false }),
"plugin:dialog|message": () => "Cancel",
};
},
});
// The app stays at its own root URL; use the normalized form.
const url = new URL(smokeUrl).href;
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n\n' + filler;
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
// A heading link puts the heading at the top of the view, below a gap of about 24 pixels.
// The last heading of a short document cannot reach the top, so the checks use headings with text below them.
async function headingAtTop(selector, text, scroller) {
await page.waitForFunction(({ selector, text, scroller }) => [...document.querySelectorAll(selector)].some(node => {
const offset = node.textContent.includes(text) ? node.getBoundingClientRect().top - node.closest(scroller).getBoundingClientRect().top : -1;
return offset >= 0 && offset <= 60;
}), { selector, text, scroller });
}
const writerHeadingAtTop = text => headingAtTop('.cm-line.writer-heading', text, '.cm-scroller');
const readerHeadingAtTop = text => headingAtTop('.reading h2', text, '.md-page');
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 });
await page.goto(url);
await page.evaluate(({ source, other }) => {
window.__TEST__.files.set('a.md', source);
window.__TEST__.files.set('other.md', other);
}, { source, other });
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await writerHeadingAtTop('Windows installer');
await top();
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('macOS setup', await jumpLine('## macOS installer'));
await writerHeadingAtTop('macOS installer (Apple Silicon)');
await top();
await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
await top();
await page.locator('.writer-link').filter({ hasText:'Missing section' }).click({ modifiers:['Control'] });
await page.getByText('Could not open #no-such-section', { exact:true }).waitFor();
await top();
await page.locator('.writer-link').filter({ hasText:'Other document' }).click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'other.md', exact:true }).waitFor();
await page.waitForFunction(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
});
// The card case: a link to a heading in another file.
await writerHeadingAtTop('Café setup');
await page.screenshot({ path:`${output}/other-file-${theme}-${width}.png` });
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top();
await chooseView(page, 'Read');
await readerJump('Windows setup', 'Windows installer');
await readerHeadingAtTop('Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await readerHeadingAtTop('macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await chooseView(page, 'Read beside');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await chooseView(page, 'Read beside');
await chooseView(page, 'Source');
await page.locator('.source-editor .cm-content').waitFor();
await chooseView(page, 'Read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await chooseView(page, 'Source');
await page.waitForFunction(() => {
const node = document.querySelector('.source-editor .cm-content');
return node?.textContent.includes('Linux');
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
assert.equal(page.url(), url);
assert.equal(await page.evaluate(() => window.__TEST__.files.get('a.md')), source);
}
await page.goto(url);
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
await page.evaluate(text => window.__TEST__.files.set('a.md', text), folded);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await top();
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await chooseView(page, 'Read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
await readerJump('Jump to nested', 'Nested');
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
}, { timeout: 15000 });
@@ -0,0 +1,99 @@
// Workspace links: wiki resolution across folders, backlink navigation, live edits, discarded drafts, created, moved, and deleted notes, and the duplicate-name guard.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("links/workspaceLinks", async ({ page }) => {
const output = await outputDir("links/workspaceLinks");
await mockTauri(page, {
commands: test => {
const workspace = test.workspace({
root: "C:\\smoke-workspace",
writeEvents: true,
files: {
"projects/source.md": "# Source\n\n[[Target]]\n",
"archive/deep/Target.md": "# Target\n",
"other.md": "# Other\n\n[Target](archive/deep/Target.md)\n",
},
});
const { files } = workspace;
Object.assign(test, { files, root: workspace.root });
return {
...workspace,
workspace_write: args => {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
return workspace.workspace_write(args);
},
workspace_search: () => [],
"plugin:dialog|message": () => test.answer ?? "Cancel",
};
},
});
await page.addInitScript(() => localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false})));
async function openNote(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox',{name:'Find a file'}).fill(name);
await page.getByRole('dialog').getByRole('button').filter({hasText:name}).first().click();
await page.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
}
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
await page.goto(smokeUrl);
await page.getByText('smoke-workspace',{exact:true}).waitFor();
await openNote('projects/source.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.getByRole('tab',{name:'Target.md',exact:true}).waitFor();
await backlink('projects/source.md').waitFor();
await backlink('other.md').waitFor();
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
await page.screenshot({path:path.join(output, 'workspace-links-dark.png')});
await backlink('projects/source.md').click();
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='projects/source.md');
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
await writer.focus(); await page.keyboard.press('Control+Home'); await page.keyboard.press('Control+a'); await page.keyboard.type('# Source\n\nNo links now.');
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.waitForFunction(()=>!document.querySelector('button[aria-label="Open projects/source.md, line 3"]'));
await backlink('other.md').waitFor();
await page.evaluate(()=>{
window.__TEST__.files.set('duplicates/Target.md','# Another target');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await openNote('other.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='archive/deep/Target.md');
await page.evaluate(()=>{
window.__TEST__.files.set('wiki.md','# Wiki\n\n[[Target]]\n');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['wiki.md']});
});
await openNote('wiki.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.locator('.status').filter({hasText:'More than one note matches Target'}).waitFor();
assert.equal(await page.locator('.breadcrumb').getAttribute('title'),'wiki.md');
await page.evaluate(()=>{
window.__TEST__.files.delete('duplicates/Target.md');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'remove',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.title==='archive/deep/Target.md');
await backlink('wiki.md').waitFor();
await page.evaluate(()=>{
const {files,emit,root}=window.__TEST__;
files.set('moved/wiki.md',files.get('wiki.md')); files.delete('wiki.md');
emit('workspace-event',{root,kind:'rename',paths:['wiki.md','moved/wiki.md']});
});
await backlink('moved/wiki.md').waitFor();
assert.equal(await backlink('wiki.md').count(),0);
// A changed tab asks Save, Don't save, or Cancel (src/lib/layout/Workbench.svelte).
await page.evaluate(()=>{window.__TEST__.answer="Don't save";});
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).click();
await page.keyboard.press('Control+w');
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).waitFor({state:'detached'});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await backlink('projects/source.md').waitFor();
await page.setViewportSize({width:620,height:850});
await page.evaluate(()=>{document.documentElement.dataset.theme='light';});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.screenshot({path:path.join(output, 'workspace-links-narrow.png')});
console.log('Workspace link integration passed: workspace wiki resolution, new tabs, backlinks navigation, live edits, discarded drafts, creation, move, deletion and duplicate guard.');
});
+325
View File
@@ -0,0 +1,325 @@
// Shared menu design: styles, themes, icons, disabled rows, focus return, submenus, spelling menus, scrolling, and viewport edges.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("menus/consistency", async ({ page }) => {
const output = await outputDir("menus/consistency");
await mockTauri(page, {
commands: test => {
window.tabMenuTest = { revealed: null };
window.spellingTest = { commands: [], emit: payload => test.emit("spelling-menu", payload) };
const spellingMenu = method => args => { window.spellingTest.commands.push({ method, ...args }); };
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
folders: ["notes"],
files: Object.fromEntries(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`])),
});
return {
...workspace,
workspace_reveal: ({ rel }) => { window.tabMenuTest.revealed = rel; },
spelling_menu_install: spellingMenu("spelling_menu_install"),
spelling_menu_select: spellingMenu("spelling_menu_select"),
spelling_suggestions: () => {
if (window.spellingTest.delay) return new Promise(resolve => { window.spellingTest.resolve = resolve; });
return { language: "en-US", words: [], misspelled: false };
},
};
},
});
const menu = name => page.getByRole("menu", { name, exact: true });
const item = name => page.getByRole("menuitem", { name, exact: true });
async function metrics(panel) {
return panel.evaluate(node => {
const row = node.querySelector(":scope > button");
const icon = row.querySelector(".action-icon");
const label = row.querySelector(".action-label");
const css = getComputedStyle(node), button = getComputedStyle(row);
return {
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font, css.backdropFilter],
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
iconWidth: icon.getBoundingClientRect().width,
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
};
});
}
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
await page.goto(smokeUrl);
const row = page.locator('[data-tree-rel="a.md"]');
await row.waitFor();
await row.click();
const tab = page.getByRole("tab", { name: "a.md", exact: true });
await tab.waitFor();
await page.locator(".cm-content").waitFor();
// Without a background image, menus are opaque and do not blur (UI-043).
await row.click({ button: "right" });
const opaque = await metrics(menu("File actions"));
assert.match(opaque.panel[2], /^rgb\(/, "Menus are opaque without a background image");
assert.equal(opaque.panel[6], "none");
await dismiss();
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
const canvas = document.createElement('canvas');
canvas.width = 800; canvas.height = 600;
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 800, 600);
gradient.addColorStop(0, '#628ba8'); gradient.addColorStop(1, '#b47796');
context.fillStyle = gradient; context.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: 0.15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
await file.waitFor();
const reference = await metrics(file);
assert.equal(reference.row[1], "24px", "Menus use compact shared rows");
assert.equal(reference.row[0], "2px 10px");
const compactHeight = await file.evaluate(node => node.getBoundingClientRect().height);
await page.evaluate(() => {
document.documentElement.style.setProperty('--rs-menu-row-height', '30px');
document.documentElement.style.setProperty('--rs-menu-row-padding', '4px 10px');
});
const previousHeight = await file.evaluate(node => node.getBoundingClientRect().height);
await page.screenshot({ path: path.join(output, `menu-spacing-before-${theme}.png`) });
await page.evaluate(() => {
document.documentElement.style.removeProperty('--rs-menu-row-height');
document.documentElement.style.removeProperty('--rs-menu-row-padding');
});
assert.ok(compactHeight < previousHeight * .85, 'The same actions use at least 15% less vertical space');
console.log(JSON.stringify({ theme, compactHeight, previousHeight }));
await page.screenshot({ path: path.join(output, `menu-spacing-after-${theme}.png`) });
// With a background image, menus use the surface transparency (82% by default), and the hovered row is a thin veil (UI-061).
assert.ok(reference.panel[2].includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(reference.panel[2]), "With a background image, menus use the surface transparency");
assert.match(reference.panel[6], /blur\(18px\)/, "With a background image, menus blur it");
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
await item("Pin").hover();
assert.match(await item("Pin").evaluate(node => getComputedStyle(node).backgroundColor), /(\/ 0\.06\)|, 0\.06\))$/, "With a background image, the hovered row is a thin veil");
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
assert.equal(new Set(offsets).size, 1, "All file labels align");
await page.screenshot({ path: path.join(output, `menu-file-${theme}.png`) });
await dismiss();
assert.equal(await row.evaluate(node => node === document.activeElement), true);
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
await file.waitFor();
assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles");
assert.equal(await item("Show in Explorer").locator("svg.action-icon").count(), 1);
await page.keyboard.press("End");
assert.equal(await item("Show in Explorer").evaluate(node => node === document.activeElement), true);
await page.keyboard.press("Enter");
await file.waitFor({ state: "detached" });
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "", "Pane action opens the workspace root");
await row.click({ button: "right" });
await item("Show in Explorer").click();
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "a.md", "File action reveals the selected file");
await page.locator('[data-tree-rel="notes"]').click({ button: "right" });
assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles");
await dismiss();
await tab.click({ button: "right" });
const tabs = menu("Tab actions");
assert.deepEqual(await metrics(tabs), reference, "Tab and file menus share styles");
await item("Close tabs after").hover();
assert.equal(await item("Close tabs after").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
await item("Move tab").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Move tab")), reference, "Submenus share styles");
await page.screenshot({ path: path.join(output, `menu-tab-${theme}.png`) });
await page.keyboard.press("ArrowLeft");
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.getByText("Original text.", { exact: true }).click();
await page.keyboard.press("Shift+F10");
const editor = menu("Markdown text actions");
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
await item("Paragraph").focus();
await page.keyboard.press("ArrowRight");
assert.deepEqual(await metrics(menu("Paragraph")), reference);
await page.screenshot({ path: path.join(output, `menu-editor-${theme}.png`) });
await dismiss();
await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
await dismiss();
const wordPoint = await page.getByText("Original text.", { exact: true }).evaluate(element => {
const node = element.firstChild;
const range = document.createRange();
range.setStart(node, 0); range.setEnd(node, "Original".length);
const bounds = range.getBoundingClientRect();
return { x: bounds.left + bounds.width / 2, y: bounds.top + bounds.height / 2 };
});
await page.mouse.click(wordPoint.x, wordPoint.y, { button: "right" });
await editor.waitFor();
assert.deepEqual(await metrics(editor), reference, "Word and blank-space menus share styles");
assert.equal(await item("Format").count(), 1, "Words retain the Markdown actions");
await dismiss();
await page.evaluate(() => {
const input = document.createElement("input");
input.id = "native-spelling-test";
input.spellcheck = true;
input.value = "Original";
Object.assign(input.style, { position: "fixed", left: "500px", top: "100px" });
document.body.append(input);
input.focus();
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
});
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 0, name: "", label: "", shortcut: "", kind: 3, enabled: false, checked: false, children: [] },
{ id: 73, name: "cut", label: "Cu&t", shortcut: "Ctrl+X", kind: 0, enabled: false, checked: false, children: [] },
{ id: 74, name: "copy", label: "&Copy", shortcut: "Ctrl+C", kind: 0, enabled: true, checked: false, children: [] },
{ id: 75, name: "spellCheck", label: "Spell check", shortcut: "", kind: 1, enabled: true, checked: true, children: [] },
] }));
const spelling = menu("Spelling actions");
await spelling.waitFor();
assert.deepEqual(await metrics(spelling), reference, "Spelling and file menus share styles");
assert.equal(await item("Add to dictionary").locator("svg.action-icon").count(), 1);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "Spell check" }).getAttribute("aria-checked"), "true");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("Copy Ctrl+C").evaluate(node => node === document.activeElement), true, "Spelling keyboard navigation skips disabled commands");
await page.screenshot({ path: path.join(output, `menu-spelling-${theme}.png`) });
await page.keyboard.press("Home");
await page.keyboard.press("Enter");
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "spelling-1", command: 71 });
assert.equal(await page.locator("#native-spelling-test").evaluate(node => node === document.activeElement), true);
async function emitSpelling(request) {
await page.evaluate(request => window.spellingTest.emit({ request, items: [
{ id: 81, name: "suggestion", label: "Replacement", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
] }), request);
await spelling.waitFor();
}
await emitSpelling("cancel");
await dismiss();
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "cancel", command: null });
await emitSpelling("outside");
await row.click();
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "outside", command: null });
await emitSpelling("old");
await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss();
await page.evaluate(() => {
window.spellingTest.delay = true;
const input = document.querySelector('#native-spelling-test');
input.value = 'recieved'; input.focus(); input.setSelectionRange(3, 3);
input.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
window.spellingTest.emit({ request: 'delayed-spelling', fallback_spelling: true, items: [
{ id: 90, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
] });
});
await spelling.waitFor();
assert.equal(await item('Copy').count(), 1, 'Editing actions appear before the spelling service resolves');
await page.evaluate(() => { window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); window.spellingTest.delay = false; });
await item('received').waitFor();
await page.screenshot({ path: path.join(output, `menu-spelling-async-${theme}.png`) });
await dismiss();
await page.evaluate(() => {
window.spellingTest.delay = true;
document.querySelector('#native-spelling-test').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
window.spellingTest.emit({ request: 'dismissed-spelling', fallback_spelling: true, items: [
{ id: 91, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
] });
});
await spelling.waitFor();
await dismiss();
await page.evaluate(async () => {
window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true });
window.spellingTest.delay = false;
await new Promise(resolve => requestAnimationFrame(resolve));
});
assert.equal(await spelling.count(), 0, 'Late spelling results cannot reopen a dismissed menu');
await page.evaluate(() => { document.querySelector('#native-spelling-test').value = 'Original'; });
await page.locator("#native-spelling-test").evaluate(node => node.remove());
await page.evaluate(() => {
const input = document.createElement("input");
input.spellcheck = false;
document.body.append(input);
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
window.spellingTest.emit({ request: "ordinary-input", items: [] });
input.remove();
});
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true });
}
await page.setViewportSize({ width: 420, height: 320 });
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [{ label: "Modifier toutes les occurrences dans le document", icon: "select", shortcut: "Ctrl+F2" }], () => root.remove(), "Long translated label");
});
const translated = menu("Long translated label");
assert(await translated.locator('.action-label').evaluate(node => {
const css = getComputedStyle(node);
return css.whiteSpace === 'normal' && css.textOverflow !== 'ellipsis' && node.scrollWidth <= node.clientWidth;
}), 'Long translated actions wrap without truncation');
await page.screenshot({ path: path.join(output, "menu-translated-long-label.png") });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [
{ label: "Without icon", run: () => {} },
{ label: "With icon", icon: "copy", run: () => {} },
{ label: "Unavailable", icon: "trash", disabled: true },
{ label: "More", icon: "plus", children: [
{ label: "Languages", children: [{ label: "English", checked: true, run: () => {} }] },
...Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })),
] },
], () => root.remove(), "Edge test");
});
const edge = menu("Edge test");
const offsets = await edge.locator(":scope > button").evaluateAll(nodes => nodes.map(node => node.querySelector(".action-label").getBoundingClientRect().left));
assert.equal(new Set(offsets).size, 1, "Iconless labels keep the icon column");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
await page.keyboard.press("ArrowRight");
const sub = menu("More");
await page.keyboard.press("ArrowRight");
assert.equal(await sub.isVisible(), true, "Nested submenus keep the parent visible");
assert.equal(await menu("Languages").isVisible(), true);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "English" }).evaluate(node => node === document.activeElement), true);
await page.keyboard.press("ArrowLeft");
assert.equal(await menu("Languages").isVisible(), false);
assert.equal(await item("Languages").evaluate(node => node === document.activeElement), true);
for (const panel of [edge, sub]) {
const bounds = await panel.boundingBox();
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
}
await page.keyboard.press("End");
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: path.join(output, "menu-edge.png") });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const dialog = document.createElement("dialog");
dialog.id = "menu-modal-test";
dialog.style.cssText = "height:220px;width:320px;overflow:auto";
const content = document.createElement("div");
content.style.height = "600px";
dialog.append(content);
document.body.append(dialog);
dialog.showModal();
dialog.scrollTop = 160;
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
window.menuModalScroll = dialog.scrollTop;
const root = actionMenu(180, 280, Array.from({ length: 30 }, (_, index) => ({ label: `Modal action ${index}`, icon: "copy" })), () => root.remove(), "Modal scrolling test", dialog);
const dismissOnAncestorScroll = event => { if (!root.contains(event.target)) root.remove(); };
dialog.addEventListener("scroll", dismissOnAncestorScroll, true);
});
await page.keyboard.press("End");
const modalMenu = menu("Modal scrolling test");
await modalMenu.waitFor();
assert.equal(await item("Modal action 29").evaluate(node => node === document.activeElement), true);
assert.equal(await page.locator("#menu-modal-test").evaluate(dialog => dialog.scrollTop), await page.evaluate(() => window.menuModalScroll), "Keyboard traversal scrolls only the menu panel");
const modalBounds = await modalMenu.boundingBox(), lastBounds = await item("Modal action 29").boundingBox();
assert.ok(lastBounds.y >= modalBounds.y && lastBounds.y + lastBounds.height <= modalBounds.y + modalBounds.height + 1, "End keeps the last row visible inside a short modal");
await page.screenshot({ path: path.join(output, "menu-modal-end.png") });
await page.keyboard.press("Home");
assert.equal(await item("Modal action 0").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.locator("#menu-modal-test").evaluate(dialog => { dialog.close(); dialog.remove(); });
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
}, { timeout: 15000 });
+115
View File
@@ -0,0 +1,115 @@
// Full-app plug-ins: compact header, navigation, dynamic and restored tabs, dialogs, settings forms across windows, and disable cleanup.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("plugins/access", async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
await mockTauri(context, {
commands: test => {
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
api.settings.subscribe?.(() => { window.accessTest.settings++; });
api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) {
window.accessTest.mounts++;
container.innerHTML = '<h2>Local Autocomplete</h2><label>Model<input aria-label="Model"></label><button>Save model</button><p class="mount-context"></p>';
container.querySelector('p').textContent = context?.surface;
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"org.example.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
"org.example.tasks": `export function activate(api) {
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', launch() { api.openView('default-board'); }, mount(container) { container.textContent = 'Task content'; } });
api.registerView({ id: 'default-board', title: 'Default board', launcher: false, placement: 'editor', mount(container) { container.textContent = 'Default board content'; } });
window.taskTestApi = api;
api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } });
}`,
};
// Settings and the enabled state live in localStorage, so both windows of the context share them.
window.addEventListener("storage", event => {
if (event.key?.startsWith("settings:")) test.emit("plugin-settings-changed", event.key.slice(9));
if (event.key === "disabled") test.emit("plugins-changed", {});
});
return {
browser_connect: () => "test-session",
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: "C:/test/plugins", plugins: plugins.map(manifest => ({ manifest, hash: "test", enabled: !(manifest.id === "runestone.local-autocomplete" && localStorage.getItem("disabled")), installedAt: 1, path: "C:/test/plugins/" + manifest.id, error: null, removal: false })) }),
plugins_load: ({ id }) => modules[id],
plugins_data: ({ id, value }) => {
if (value !== null) { localStorage.setItem("settings:" + id, value); test.emit("plugin-settings-changed", id); }
return localStorage.getItem("settings:" + id) || "null";
},
plugins_set_enabled: ({ enabled }) => { if (!enabled) localStorage.setItem("disabled", "true"); test.emit("plugins-changed", {}); },
plugins_release: () => null,
"plugin:window|is_maximized": () => false,
};
},
});
const output = await outputDir("plugins/access");
const main = await openPage(context), settings = await openPage(context);
const external = page => page.evaluate(() => performance.getEntriesByType("resource").find(entry => new URL(entry.name).pathname === "/src/lib/plugins/external.ts").name);
try {
await main.goto(smokeUrl);
await main.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "All tasks", exact: true }).waitFor();
assert.equal(await main.getByRole("button", { name: "Open tab or view", exact: true }).count(), 0);
assert.equal(await main.getByRole("button", { name: "Commands", exact: true }).count(), 1);
await main.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "All tasks", exact: true }).click();
await main.getByText("Default board content", { exact: true }).waitFor();
await main.evaluate(() => window.taskTestApi.openView("tasks"));
await main.getByText("Task content", { exact: true }).waitFor();
const module = await external(main);
await main.evaluate(async module => {
const { closePluginEditor, pluginTabState, pluginView, restorePluginTab } = await import(module);
let view;
const off = pluginView.subscribe(value => { view = value; }); off();
const transfer = pluginTabState(view);
closePluginEditor(view.key);
if (!await restorePluginTab(transfer)) throw Error("Tab restore failed");
}, module);
await main.getByText("Task content", { exact: true }).waitFor();
await main.evaluate(async module => { await (await import(module)).runPluginCommand("org.example.browser", "new-tab"); }, module);
await main.getByText("Browser content", { exact: true }).waitFor();
await main.evaluate(async module => { (await import(module)).openPluginView("org.example.tasks", "dialog"); }, module);
await main.getByRole("dialog", { name: "Task summary" }).waitFor();
await main.keyboard.press("Escape");
for (const theme of ["dark", "light"]) {
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await main.screenshot({ path: path.join(output, `plugin-access-${theme}.png`) });
}
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Local Autocomplete", exact: true }).click();
await settings.getByRole("textbox", { name: "Model", exact: true }).fill("unsaved-model");
assert.equal(await settings.locator(".mount-context").innerText(), "settings");
await settings.waitForTimeout(5500);
assert.equal(await settings.getByRole("textbox", { name: "Model", exact: true }).inputValue(), "unsaved-model");
assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1);
await settings.getByRole("button", { name: "Save model", exact: true }).click();
await main.waitForFunction(() => window.accessTest.settings === 1);
await settings.screenshot({ path: path.join(output, "plugin-access-settings.png") });
await settings.getByRole("button", { name: "General", exact: true }).click();
await settings.waitForFunction(() => window.accessTest.disposed === 1);
await settings.getByRole("textbox", { name: "Search settings" }).fill("Local");
await settings.getByRole("textbox", { name: "Model", exact: true }).waitFor();
await settings.getByRole("textbox", { name: "Search settings" }).fill("");
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("switch", { name: "Local Autocomplete", exact: true }).uncheck();
await settings.getByRole("button", { name: "Local Autocomplete", exact: true }).waitFor({ state: "detached" });
await main.getByRole("button", { name: "Commands", exact: true }).waitFor({ state: "detached" });
assert.deepEqual([...main.errors, ...settings.errors], []);
} catch (error) {
await settings.screenshot({ path: path.join(output, "plugin-access-failure.png") });
console.log(await settings.locator("body").innerText(), await settings.evaluate(() => window.accessTest), [...main.errors, ...settings.errors]);
throw error;
}
console.log("Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.");
});
+50
View File
@@ -0,0 +1,50 @@
// Local Autocomplete settings choices use the shared action menu in a modal: keyboard choice, saving, focus return, and cleanup.
// @requires repo:RuneStone_Local_Autocomplete/src
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { outputDir, pluginRepo, runSmoke, smokeUrl } from '../_harness/index.mjs';
const autocompleteSource = path.join(pluginRepo('RuneStone_Local_Autocomplete'), 'src');
await runSmoke('plugins/choiceMenus', async ({ page }) => {
const output = await outputDir('plugins/choiceMenus');
await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 'text/html', body: '<link rel="stylesheet" href="/src/lib/theme/tokens.css"><link rel="stylesheet" href="/src/lib/ui/menu.css"><style>dialog{inset:0;margin:0;max-width:none;max-height:none;width:100%;height:100%;box-sizing:border-box;background:var(--rs-bg);color:var(--rs-text);padding:0;border:0}</style><dialog><main></main></dialog>' }));
await page.route('**/__autocomplete__/*.mjs', async route => {
const name = new URL(route.request().url()).pathname.split('/').pop();
assert.ok(['main.mjs', 'engine.mjs'].includes(name));
await route.fulfill({ contentType: 'application/javascript', body: await readFile(path.join(autocompleteSource, name), 'utf8') });
});
for (const theme of ['light', 'dark']) for (const width of [1100, 390]) {
await page.setViewportSize({ width, height: 850 });
await page.goto(smokeUrl + '/__choice-audit__');
await page.evaluate(async theme => {
document.documentElement.dataset.theme = theme;
const { showActionMenu } = await import('/src/lib/ui/managedActionMenu.ts');
const { activate } = await import('/__autocomplete__/main.mjs');
let view;
window.choiceAudit = { saved: null };
await activate({ ui: { showActionMenu }, completion: { version: 1, transport() {}, invalidate() {}, registerProvider() { return () => {}; }, registerInput() { return { dispose() {}, request() {} }; } },
settings: { read: async () => ({}), write: async value => { window.choiceAudit.saved = value; } },
onDispose() {}, registerCommand() {}, registerView(value) { view = value; } });
document.querySelector('dialog').showModal();
window.choiceAudit.dispose = view.mount(document.querySelector('main'), { surface: 'settings' });
}, theme);
const trigger = page.getByRole('button', { name: 'Server type', exact: true });
await trigger.click();
const menu = page.getByRole('menu', { name: 'Server type', exact: true });
assert.equal(await menu.evaluate(node => !!node.closest('dialog[open]')), true);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitemradio', { name: 'Ollama', exact: true }).evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: path.join(output, `autocomplete-${theme}-${width}.png`) });
await page.keyboard.press('Enter');
assert.match(await trigger.innerText(), /Ollama/);
await page.getByRole('button', { name: 'Save settings', exact: true }).click();
await page.waitForFunction(() => window.choiceAudit.saved?.adapter === 'ollama');
await trigger.click(); await page.keyboard.press('Escape');
assert.equal(await trigger.evaluate(node => node === document.activeElement), true);
await trigger.click(); await page.evaluate(() => window.choiceAudit.dispose());
assert.equal(await page.locator('.rs-menu').count(), 0);
}
console.log('PASS: Local Autocomplete shared choices, modal input, saved adapter, focus return, and cleanup in both themes at 1100/390px.');
}, { timeout: 30000 });
+189
View File
@@ -0,0 +1,189 @@
// Plug-in installation: ZIP and Git-link review, download errors, token clearing, updates, disabled installs, cleanup, and uninstall.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const fixture = path.join(repoRoot, "fixtures", "plugins", "workspace-overview");
const manifest = JSON.parse(readFileSync(path.join(fixture, "plugin.json"), "utf8"));
const pluginCode = readFileSync(path.join(fixture, "main.js"), "utf8") + "\n// Browser cleanup probe\n";
await runSmoke("plugins/install", async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: "en-US", timezoneId: "America/Vancouver" });
const page = await openPage(context);
const settingsPage = await openPage(context);
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
// The settings window forwards plug-in commands to the main window, which owns the installed state.
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
await mockTauri(context, {
state: { manifest, pluginCode },
commands: test => {
const { manifest, pluginCode } = test.state;
const isMaximized = () => false;
if (location.search.includes("settingsWindow")) {
return new Proxy({}, { get: (_table, command) => command === "plugin:window|is_maximized" ? isMaximized : args => window.settingsHostInvoke(command, args) });
}
let installed = [];
let removalPrepared = false;
const data = { preserved: true };
const pluginPath = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id;
const changed = () => test.emit("plugins-changed", null);
Object.assign(test, { data, cleaned: false, released: false });
const ws = test.workspace({
root: "C:\\smoke-workspace",
files: {
"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",
},
writeEvents: true,
});
return {
...ws,
"plugin:window|is_maximized": isMaximized,
settings_open_window: () => null,
plugins_snapshot: () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed }),
plugins_choose: () => [{ token: "candidate", source: "C:/Downloads/overview.zip", manifest, error: null }],
plugins_from_git: ({ url, tag }) => {
if (tag === "missing") throw new Error("Release not found. Publish a release with one plugin ZIP.");
return [{ token: "git-candidate", source: url + " @ " + (tag || "v1.0.0"), manifest, error: null }];
},
plugins_cancel: () => { removalPrepared = false; },
plugins_install: ({ enabled }) => {
const previous = installed[0];
installed = [{ manifest, hash: "reviewed-hash", enabled: previous ? previous.enabled : enabled, installedAt: Date.parse("2026-10-05T18:24:36Z"), path: pluginPath, error: null, removal: false }];
changed();
return [{ name: manifest.name, error: null }];
},
plugins_load: () => {
test.cleaned = false; test.released = false;
return pluginCode.replace("export function activate(api) {", "export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });");
},
plugins_release: () => { test.released = true; },
plugins_prepare_remove: () => { removalPrepared = true; return { token: "remove-plan", plugin: installed[0] }; },
plugins_remove: async () => {
if (!removalPrepared) throw Error("Missing removal plan");
removalPrepared = false;
installed[0].enabled = false; changed();
for (let i = 0; i < 100 && !test.released; i++) await new Promise(resolve => setTimeout(resolve, 50));
if (!test.cleaned || !test.released) throw Error("Cleanup was not acknowledged");
installed = []; changed();
},
};
},
});
const output = await outputDir("plugins/install");
const shot = name => settingsPage.screenshot({ path: path.join(output, name) });
const settingsDialog = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function settings() {
await page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
await settingsPage.goto(smokeUrl + "/?settingsWindow=true");
await settingsDialog.getByRole("button", { name: "Plug-ins", exact: true }).click();
}
async function uninstall() { await settingsDialog.locator(".card").filter({ hasText: "Workspace overview" }).getByRole("button", { name: "Uninstall", exact: true }).click(); }
try {
await page.goto(smokeUrl);
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await settings();
assert.equal(await settingsDialog.getByRole("button", { name: "Install from folder", exact: true }).count(), 0);
assert.equal(await settingsDialog.getByRole("button", { name: "Install from file", exact: true }).count(), 0);
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
const review = settingsPage.getByRole("dialog", { name: "Review plugin installation", exact: true });
await review.getByText("Source: C:/Downloads/overview.zip", { exact: true }).waitFor();
await review.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_install"), 0);
const gitButton = settingsDialog.getByRole("button", { name: "Install from Git link", exact: true });
await gitButton.click();
const gitDialog = settingsPage.getByRole("dialog", { name: "Install from Git link", exact: true });
await gitDialog.getByLabel("Repository link", { exact: true }).fill("https://git.example/owner/plugin.git");
await gitDialog.getByLabel("Release tag (optional)", { exact: true }).fill("missing");
await gitDialog.getByLabel("Access token (optional)", { exact: true }).fill("test-token");
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await gitDialog.getByRole("alert").getByText(/Release not found/).waitFor();
assert.equal(await gitDialog.getByLabel("Access token (optional)", { exact: true }).inputValue(), "");
await gitDialog.getByLabel("Release tag (optional)", { exact: true }).fill("v1.0.0");
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await review.getByText("Source: https://git.example/owner/plugin.git @ v1.0.0", { exact: true }).waitFor();
await review.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_install"), 0);
assert(await gitButton.evaluate(element => element === document.activeElement));
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
await review.getByRole("button", { name: "Install and enable", exact: true }).click();
await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).waitFor();
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await settingsDialog.locator("time").getAttribute("datetime"), "2026-10-05T18:24:36.000Z");
assert.match(await settingsDialog.locator("time").innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await shot("plugin-manager-installed.png");
await settingsPage.keyboard.press("Escape");
await page.getByRole("button", { name: "Commands", exact: true }).click();
await page.getByRole("menuitem", { name: /Show workspace overview/ }).click();
const view = page.getByRole("dialog", { name: "Workspace overview", exact: true });
await view.getByText(/files and folders in this workspace/).waitFor();
await view.getByRole("button", { name: "Close plugin view", exact: true }).click();
await settings();
await settingsDialog.getByRole("button", { name: "Install plugin ZIP", exact: true }).click();
await review.getByText(/Update .* → .*Settings and enabled state stay the same/).waitFor();
assert.equal(await review.getByRole("button", { name: "Install and enable", exact: true }).count(), 0);
for (const mode of ["dark", "light"]) {
await settingsPage.evaluate(async mode => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode });
}, mode);
for (const width of [1440, 590]) {
await settingsPage.setViewportSize({ width, height: width === 590 ? 820 : 1000 });
await shot(`plugin-update-review-${mode}-${width}.png`);
assert.equal(await review.evaluate(element => element.scrollWidth > element.clientWidth), false);
}
}
await review.getByRole("button", { name: "Apply packages", exact: true }).click();
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
assert.equal(await count("plugins_remove"), 0);
await settingsPage.setViewportSize({ width: 1440, height: 1000 });
await uninstall();
const confirmation = settingsPage.getByRole("dialog", { name: "Uninstall Workspace overview?", exact: true });
assert(await confirmation.getByRole("button", { name: "Cancel", exact: true }).evaluate(el => el === document.activeElement));
assert.equal(await confirmation.getByRole("button", { name: "Continue", exact: true }).count(), 0);
await confirmation.getByRole("button", { name: "Cancel", exact: true }).click();
assert.equal(await count("plugins_remove"), 0);
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
await uninstall();
await confirmation.waitFor();
await settingsPage.keyboard.press("Escape");
assert(await settingsDialog.isVisible());
assert(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked());
assert.equal(await count("plugins_remove"), 0);
await uninstall();
await confirmation.waitFor();
await shot("plugin-uninstall-confirmation.png");
await confirmation.getByRole("button", { name: "Uninstall and delete files", exact: true }).click();
await settingsDialog.getByText("No plugins installed.", { exact: true }).waitFor();
assert.equal(await count("plugins_remove"), 1);
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
await settingsPage.keyboard.press("Escape");
assert.equal(await page.getByRole("button", { name: "Plugin commands and views", exact: true }).count(), 0);
await settingsPage.setViewportSize({ width: 590, height: 820 });
await settings();
await shot("plugin-manager-narrow.png");
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitButton.click();
await gitDialog.getByLabel("Repository link", { exact: true }).fill("https://git.example/owner/plugin.git");
await shot("plugin-git-narrow.png");
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole("button", { name: "Review release", exact: true }).click();
await review.getByRole("button", { name: "Install, keep disabled", exact: true }).click();
await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).waitFor();
assert.equal(await settingsDialog.getByRole("switch", { name: "Workspace overview", exact: true }).isChecked(), false);
assert.equal(await count("plugins_from_git"), 3);
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
} catch (error) {
console.log("Main page:", await page.locator("body").innerText());
console.log("Page errors:", [...page.errors, ...settingsPage.errors]);
throw error;
}
console.log("External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.");
});
+179
View File
@@ -0,0 +1,179 @@
// Feature lifecycle: the built-in Table formulas setting and the native Terminal feature turn off, persist, and turn on again across windows.
// Terminal off asks first while a shell runs, and then ends the shells of each window.
// An old Table Formulas package stays inactive, shows that the feature is built in, and uninstalls without restoration.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { mockInstalledPlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs';
await runSmoke('plugins/lifecycle', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Closed settings</title>' }));
const page = await openPage(context);
const settingsPage = await openPage(context);
page.on('console', message => { if (message.type() === 'error' || message.type() === 'warning') console.log(message.type(), message.text()); });
await mockTauri(context, {
commands: test => {
const ws = test.workspace({
root: 'C:\\smoke-workspace',
files: {
'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 files = ws.files;
test.files = files;
return {
...ws,
workspace_write: ({ rel, contents, expected }) => {
if (expected !== undefined && files.get(rel) !== expected) throw new Error('Save blocked: file changed on disk');
files.set(rel, contents);
test.emit('workspace-event', { root: ws.root, kind: 'modify', paths: [rel] });
},
settings_open_window: () => null,
// Terminal off asks first while a shell runs (src/lib/layout/SettingsDialog.svelte).
'plugin:dialog|message': args => { test.state.prompts = [...test.state.prompts ?? [], args.message]; return 'Ok'; },
};
},
});
await mockInstalledPlugins(context, [oldTableFormulasRow]);
const output = await outputDir('plugins/lifecycle');
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const switchFor = name => dialog.getByRole('switch', { name, exact: true });
const ptyCalled = command => window.__TEST__.calls.some(call => call.command === command);
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function quickOpen(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill(name);
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
}
async function settings(category = 'Plug-ins') {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto(smokeUrl + '/?settingsWindow=true');
await dialog.getByRole('button', { name: category, exact: true }).click();
}
// The switch of an old package of a built-in feature stays disabled.
const idle = () => settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled || input.id === 'external-runestone.table-formulas'));
async function closeSettings() {
await idle();
await settingsPage.goto(smokeUrl + '/__settings-closed');
await page.bringToFront();
}
try {
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source);
await quickOpen('formulas.md');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
assert(!await page.evaluate(() => window.__TEST__.calls.some(call => call.command === 'plugins_load' && call.args.id === 'runestone.table-formulas')), 'The old Table Formulas package does not load');
await settings('General');
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
assert.equal(await page.evaluate(() => window.__TEST__.settings('general').tableFormulas), false, 'The settings file stores the choice');
assert.match(await table.innerText(), /=A2\*3/);
assert.equal(await page.locator('.table-formula-tools').count(), 0);
await table.locator('td').last().click();
await page.locator('.writer-cell-editor').fill('=A2*4');
await page.keyboard.press('Enter');
await settings('General');
await switchFor('Table formulas').check();
await closeSettings();
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
await page.getByRole('radiogroup', { name: 'View', exact: true }).getByRole('radio', { checked: true }).press('End');
const preview = page.locator('.md-page table').first();
await preview.locator('.md-table-formula').waitFor();
await settings('General');
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
assert.match(await preview.innerText(), /=A2\*4/);
await settings('General');
await switchFor('Table formulas').check();
await closeSettings();
await preview.locator('.md-table-formula').waitFor();
assert.equal(await preview.locator('.md-table-formula').innerText(), '8');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4'));
assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<')));
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.waitForFunction(ptyCalled, 'pty_open');
await settings();
const oldPackage = dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name: 'Table Formulas', exact: true }) });
await oldPackage.getByText('Included with RuneStone', { exact: true }).waitFor();
await oldPackage.getByText(/Table Formulas is now built in\. You can remove this old package\./).waitFor();
assert(await oldPackage.getByRole('switch').isDisabled(), 'The old package cannot be enabled');
assert.equal(await switchFor('Terminal').count(), 0, 'Terminal is a feature, not a plugin');
await dialog.getByRole('button', { name: 'Features', exact: true }).click();
await switchFor('Terminal').uncheck();
await page.waitForFunction(ptyCalled, 'pty_close');
const prompts = await settingsPage.evaluate(() => window.__TEST__.state.prompts);
assert.deepEqual(prompts, ['Terminal sessions will end.\nTurn off Terminal?'], 'Terminal off asks first while a shell runs');
assert.equal(await settingsPage.evaluate(() => window.__TEST__.settings('features').terminal), false);
await settingsPage.screenshot({ path: path.join(output, 'features-terminal-off.png') });
await closeSettings();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
const opened = await count('pty_open');
await page.keyboard.press('Control+j');
await page.keyboard.press('Control+Shift+Backquote');
assert.equal(await count('pty_open'), opened);
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
await settings('Features');
assert(!await switchFor('Terminal').isChecked());
assert.equal(await dialog.getByRole('button', { name: 'Terminal', exact: true }).count(), 0, 'Settings → Terminal shows only while Terminal is on');
const standalone = await openPage(context);
await standalone.goto(smokeUrl + '?terminalWindow=C%3A%5Csmoke-workspace');
await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
await switchFor('Terminal').check();
await standalone.locator('.xterm').waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_open');
await dialog.getByRole('button', { name: 'Terminal', exact: true }).waitFor();
await switchFor('Terminal').uncheck();
await standalone.getByText('Terminal is off. Turn it on in Settings → Features.', { exact: true }).waitFor();
await standalone.waitForFunction(ptyCalled, 'pty_close');
assert.equal((await settingsPage.evaluate(() => window.__TEST__.state.prompts)).length, 1, 'The shell of the terminal window gives a prompt too');
page.errors.push(...standalone.errors);
await standalone.close();
await switchFor('Terminal').check();
await closeSettings();
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.locator('.xterm').waitFor();
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source);
await page.getByRole('button', { name: 'Terminal', exact: true }).focus();
await quickOpen('formulas.md');
await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
await idle();
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name: 'Table Formulas', exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Table Formulas?', exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await confirmation.waitFor({ state: 'hidden' });
await switchFor('Table Formulas').waitFor({ state: 'detached' });
await closeSettings();
assert.equal(await page.locator('.xterm').count(), 1, 'The package removal does not touch the Terminal feature');
assert.equal(await table.locator('.md-table-formula').innerText(), '8', 'Removing the old package keeps the built-in formulas');
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
await dialog.getByText('No plugins installed.', { exact: true }).waitFor();
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
} catch (error) {
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings-failure.png') });
console.log('Settings page:', settingsPage.url(), await settingsPage.locator('body').innerText());
await page.screenshot({ path: path.join(output, 'plugins-failure.png') });
console.log(await page.locator('.md-page').allTextContents());
console.log([...page.errors, ...settingsPage.errors]);
throw error;
}
console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, Terminal off with a prompt, persistence, shortcuts, the terminal window, removal, and no automatic restoration.');
});
+92
View File
@@ -0,0 +1,92 @@
// Settings density: title bars and window controls match the main window, compact plugin rows, narrow layouts, Git dialog focus, many categories.
// @known-issue The settings window controls are 35px high and the main window's are 36px: the settings header draws its divider as a border inside the shared title bar height.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/density", async ({ browser }) => {
const output = await outputDir("settings/density");
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
await mockTauri(context, {
commands: () => ({
plugins_snapshot: () => ({ root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
})) }),
workspace_last_path: () => null,
"plugin:window|is_maximized": () => false,
}),
});
const main = await openPage(context, { timeout: 7000 });
const settings = await openPage(context, { timeout: 7000 });
await main.goto(smokeUrl);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
const header = settings.locator("dialog > header");
const mainHeader = main.locator(".header");
assert.equal((await header.boundingBox()).height, (await mainHeader.boundingBox()).height, "Settings and main title bars share their height");
for (const name of ["Minimize window", "Maximize window", "Close window"]) {
const a = await main.getByRole("button", { name, exact: true }).boundingBox();
const b = await settings.getByRole("button", { name, exact: true }).boundingBox();
assert.equal(a.width, b.width);
assert.equal(a.height, b.height, `${name} has the same dimensions in both windows`);
}
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("switch", { name: "Example plugin 1", exact: true }).waitFor();
const content = settings.locator(".content");
const pluginRows = content.locator(".row");
assert.equal(await pluginRows.count(), 7);
for (const theme of ["dark", "light"]) {
await settings.evaluate(value => { document.documentElement.dataset.theme = value; }, theme);
for (const width of [1152, 540, 360]) {
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 420 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert(await content.evaluate(element => element.scrollWidth <= element.clientWidth), "The plugin content does not scroll horizontally");
const rows = await pluginRows.evaluateAll(elements => elements.map(element => element.getBoundingClientRect().height));
if (width === 1152) {
assert(rows.every(height => height <= 100), `Desktop plugin rows stay compact: ${rows}`);
const count = await pluginRows.evaluateAll(elements => {
const container = elements[0].closest(".content").getBoundingClientRect();
return elements.filter(element => element.getBoundingClientRect().bottom <= container.bottom).length;
});
assert(count >= 5, `At least five complete plugin rows fit at the screenshot size, got ${count}`);
}
const copy = pluginRows.first().locator(".plugin-copy");
const controls = pluginRows.first().locator(".controls");
const a = await copy.boundingBox(), b = await controls.boundingBox();
assert(a.x + a.width <= b.x + 1 || a.y + a.height <= b.y + 1, "Plugin text does not overlap its actions");
for (const button of await controls.getByRole("button").all()) {
const bounds = await button.boundingBox();
assert(bounds.width >= 28 && bounds.height >= 28);
assert(await button.getAttribute("aria-label"));
}
await settings.screenshot({ path: path.join(output, `${theme}-${width}.png`) });
}
}
await settings.setViewportSize({ width: 540, height: 420 });
await settings.getByRole("button", { name: "Install from Git link", exact: true }).click();
const install = settings.getByRole("dialog", { name: "Install from Git link", exact: true });
await install.waitFor();
assert(await install.getByRole("textbox", { name: "Repository link", exact: true }).isVisible());
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Cancel");
await settings.keyboard.press("Escape");
await install.waitFor({ state: "detached" });
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Install from Git link");
await settings.getByRole("button", { name: "General", exact: true }).click();
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
await settings.evaluate(async () => {
const { pluginTools } = await import("/src/lib/plugins/external.ts");
pluginTools.set(Array.from({ length: 12 }, (_, index) => ({ owner: "org.example.plugin-0", id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: "settings" })));
});
await settings.setViewportSize({ width: 360, height: 420 });
const sidebar = settings.locator("dialog aside");
assert((await sidebar.boundingBox()).height <= 154, "Many plugin categories leave space for setting controls");
assert(await sidebar.evaluate(element => element.scrollWidth <= element.clientWidth));
await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).scrollIntoViewIfNeeded();
const category = await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).boundingBox();
const navigation = await sidebar.boundingBox();
assert(category.y >= navigation.y && category.y + category.height <= navigation.y + navigation.height, "Every plugin category remains reachable");
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
assert.deepEqual([...main.errors, ...settings.errors], []);
console.log("Settings density smoke passed: matching title bars and window controls, seven plugin rows, compact layout, readable text, accessible actions, both themes, narrow layouts, Git dialog focus, and many plugin categories.");
});
@@ -0,0 +1,114 @@
// Display language: four locales, persistence, cross-window updates, menu keyboard focus, translated editor menus, and transparency settings.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('settings/displayLanguage', async ({ browser }) => {
const output = await outputDir('settings/displayLanguage');
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await mockTauri(context, {
commands: test => ({
...test.workspace({
root: 'C:\\appearance-smoke',
files: Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`])),
}),
plugins_snapshot: () => ({ root: 'C:/appearance-smoke-plugins', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const settings = await openPage(context, { timeout: 15000 });
const main = await openPage(context, { timeout: 15000 });
const languagePicker = settings.locator('#language-picker');
const surfaceOpacity = () => settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim());
await main.goto(smokeUrl);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await languagePicker.waitFor();
for (const [language, name, heading, appearance, enabled, files] of [
['fr', 'Français', 'Paramètres', 'Apparence', 'Surfaces transparentes', 'Fichiers'],
['ja', '日本語', '設定', '外観', '背景を透過', 'ファイル'],
['zh-CN', '简体中文', '设置', '外观', '透明界面', '文件'],
['en', 'English', 'Settings', 'Appearance', 'Transparent surfaces', 'Files'],
]) {
await languagePicker.click();
await settings.getByRole('menuitemradio', { name, exact: true }).click();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
await main.getByRole('button', { name: files, exact: true }).waitFor();
assert.equal(await settings.locator('html').getAttribute('lang'), language);
assert.equal(await main.locator('html').getAttribute('lang'), language);
assert.equal(await settings.evaluate(() => window.__TEST__.settings('language')), language);
await settings.reload();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
// Arrow keys and Escape retain shared menu focus behavior.
await languagePicker.focus();
await settings.keyboard.press('Enter');
await settings.keyboard.press('End');
await settings.keyboard.press('Home');
await settings.keyboard.press('Escape');
assert(await languagePicker.evaluate(node => node === document.activeElement));
assert(await main.evaluate(async () => {
const { imageControls } = await import('/src/lib/editor/imageControls.ts');
const root = document.createElement('div'); root.innerHTML = '<img data-md-src="sample.png" alt="sample">'; document.body.append(root);
let removed = false;
const cleanup = imageControls(root, { remove: () => { removed = true; } });
root.querySelector('.md-image-frame').dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
cleanup(); root.remove(); return removed;
}), `${language}: Delete image keyboard action`);
assert(await main.evaluate(async () => {
const { tableSelectionControls } = await import('/src/lib/editor/tableSelectionControls.ts');
const root = document.createElement('div'); root.innerHTML = '<div><table><tr><th>A</th><th>B</th></tr><tr><td>one</td><td>two</td></tr></table></div>'; document.body.append(root);
const wrapper = root.firstElementChild, table = root.querySelector('table');
let text = '| A | B |\n| --- | --- |\n| one | two |';
const view = { posAtDOM: () => 0, dom: root, focus() {} };
const controls = tableSelectionControls(root, wrapper, table, view, () => text, () => {}, next => { text = next; }, { get: () => undefined, activate() {}, editSource() {} }, {});
controls.select({ anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } });
wrapper.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
controls.destroy(); root.remove(); return !text.includes('one') && text.includes('two');
}), `${language}: Delete selected table cell keyboard action`);
await settings.screenshot({ path: path.join(output, `${language}-general.png`) });
await main.locator('[data-tree-rel="theme-0.py"]').click();
await main.locator('.source-editor .cm-content').waitFor();
await main.locator('.source-editor .cm-content').click({ button: 'right' });
await main.locator('.rs-menu').waitFor();
const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' };
await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor();
await main.screenshot({ path: path.join(output, `${language}-workbench-editor-menu.png`) });
await main.keyboard.press('Escape');
await settings.getByRole('button', { name: appearance, exact: true }).click();
for (const mode of ['dark', 'light']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 18 } });
window.dispatchEvent(new Event('focus'));
}, mode);
const toggle = settings.getByRole('switch', { name: enabled, exact: true });
await toggle.uncheck();
assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off');
await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off');
assert.equal(await surfaceOpacity(), '100%');
// Without a background image, menus are opaque at every transparency amount (UI-043).
const menuBackground = async () => {
await main.locator('.source-editor .cm-content').click({ button: 'right' });
const bg = await main.locator('.rs-menu').first().evaluate(node => getComputedStyle(node).backgroundColor);
await main.keyboard.press('Escape');
return bg;
};
let bg = await menuBackground();
assert(bg.startsWith('rgb('), `Opaque menu: ${bg}`);
await toggle.check();
await settings.locator('#surface-transparency').fill('30');
assert.equal(await surfaceOpacity(), '70%');
await main.waitForFunction(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim() === '70%');
bg = await menuBackground();
assert(bg.startsWith('rgb('), `Opaque menu at 30% transparency: ${bg}`);
await main.screenshot({ path: path.join(output, `${language}-${mode}-opaque-menu.png`) });
await settings.setViewportSize({ width: 360, height: 640 });
await settings.locator('#surface-transparency').scrollIntoViewIfNeeded();
assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`);
await settings.screenshot({ path: path.join(output, `${language}-${mode}-narrow.png`) });
await settings.setViewportSize({ width: 1100, height: 800 });
}
await settings.reload();
}
assert.deepEqual([...settings.errors, ...main.errors], []);
console.log('PASS: 4 locales, persistence, cross-window updates, keyboard menu focus, both themes, opaque menus, transparency levels, narrow layout.');
});
+165
View File
@@ -0,0 +1,165 @@
// General settings: auto-save timers, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, narrow layout.
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const { version } = JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"));
await runSmoke("settings/general", async ({ browser }) => {
const output = await outputDir("settings/general");
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await mockTauri(context, {
state: { writes: [] },
commands: test => {
const workspace = test.workspace({ root: "D:\\Notes", files: { "note.txt": "Original note" } });
return {
...workspace,
workspace_write: args => { workspace.workspace_write(args); test.state.writes.push(args); },
plugins_snapshot: () => ({ root: "D:\\AppData\\RuneStone\\plugins", plugins: [] }),
settings_open_window: () => null,
};
},
});
const page = await openPage(context);
const settingsPage = await openPage(context);
const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
async function showSettings(shortcut = false) {
if (shortcut) await page.keyboard.press("Control+,");
else await trigger.click();
await settingsPage.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.waitFor();
}
async function closeSettings() {
await settingsPage.goto("about:blank");
await page.bringToFront();
}
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
async function changeSeconds(value) {
await interval.fill(String(value));
await interval.press("Tab");
}
async function edit(value) {
await page.evaluate(async text => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } });
}, value);
}
const writes = () => page.evaluate(() => window.__TEST__.state.writes.length);
await page.clock.install();
await page.goto(smokeUrl);
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
await showSettings();
assert.equal(await interval.inputValue(), "5");
assert(await enabled.isChecked());
await changeSeconds(2);
await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor();
await closeSettings();
await page.reload();
await showSettings();
assert.equal(await interval.inputValue(), "2", "Interval survives reload");
await changeSeconds(0);
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.settings("general").autosaveSeconds), 2);
await changeSeconds(2);
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
assert(await settings.getByRole("button", { name: "Install plugin ZIP", exact: true }).isEnabled());
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
await settings.getByText("No settings found", { exact: true }).waitFor();
await settings.getByRole("button", { name: "Clear search" }).click();
await settingsPage.screenshot({ path: path.join(output, "general.png") });
await closeSettings();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".source-editor .cm-content").waitFor();
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
await showSettings();
await changeSeconds(3);
await closeSettings();
await edit("Saved at three seconds");
const before = await writes();
await page.clock.runFor(2100);
assert.equal(await writes(), before, "Old two-second timer is removed");
await page.clock.runFor(1000);
assert.equal(await writes(), before + 1, "New interval saves the dirty buffer");
await page.clock.runFor(3100);
assert.equal(await writes(), before + 1, "Clean files are not rewritten");
await showSettings();
await enabled.uncheck();
assert(await interval.isDisabled());
await closeSettings();
await edit("Manual save while auto-save is disabled");
await page.clock.runFor(10000);
assert.equal(await writes(), before + 1);
await page.keyboard.press("Control+s");
await page.waitForFunction(count => window.__TEST__.state.writes.length === count, before + 2);
await page.locator(".source-editor .cm-content").focus();
await showSettings(true);
await settings.waitFor();
await closeSettings();
await page.locator(".source-editor .cm-content").focus();
await page.keyboard.press("F1");
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
await page.keyboard.press("Escape");
const other = await openPage(context);
await other.goto(`${smokeUrl}/?settingsWindow=true`);
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
await other.getByRole("button", { name: "Restore defaults" }).click();
await page.waitForFunction(() => window.__TEST__.settings("general").autosaveEnabled);
await showSettings();
await enabled.waitFor();
assert(await enabled.isChecked(), "Other windows receive changes");
assert.equal(await interval.inputValue(), "5");
await closeSettings();
await edit("Auto-save enabled from another window");
await page.clock.runFor(5100);
assert.equal(await writes(), before + 3);
await other.close();
await showSettings();
await settingsPage.evaluate(() => {
window.__SET_ITEM__ = Storage.prototype.setItem;
Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); };
});
await changeSeconds(7);
await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor();
await settingsPage.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; });
await closeSettings();
await showSettings();
assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings");
await closeSettings();
await page.getByRole("button", { name: "Help and about (F1)" }).click();
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
await help.getByRole("heading", { name: "RuneStone", exact: true }).waitFor();
await help.getByText(`Version ${version}`, { exact: false }).waitFor();
await page.screenshot({ path: path.join(output, "help.png") });
await page.keyboard.press("Escape");
await page.keyboard.press("Control+Backslash");
await showSettings(true);
await settings.waitFor();
await closeSettings();
await page.keyboard.press("F1");
await help.waitFor();
await page.keyboard.press("Escape");
await settingsPage.setViewportSize({ width: 540, height: 420 });
await showSettings(true);
await settings.waitFor();
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
await settingsPage.screenshot({ path: path.join(output, "narrow.png") });
for (let i = 0; i < 12; i++) {
await settingsPage.keyboard.press("Tab");
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
}
assert.deepEqual([...page.errors, ...settingsPage.errors], []);
console.log("Settings smoke passed: timer changes, disabled auto-save, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, shortcuts, and narrow layout.");
});
+86
View File
@@ -0,0 +1,86 @@
// Settings window title bar: scoped permissions, drag regions, minimize, maximize, restore, close, Escape, focus, errors, themes, and the browser fallback.
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/titlebar", async ({ browser }) => {
const settingsCapability = JSON.parse(readFileSync(path.join(repoRoot, "src-tauri/capabilities/settings.json"), "utf8"));
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
}
const output = await outputDir("settings/titlebar");
const context = await browser.newContext({ viewport: { width: 920, height: 650 } });
await mockTauri(context, {
label: "settings-main",
state: { maximized: false, failMinimize: false },
commands: test => ({
plugins_snapshot: () => ({ root: "D:\\SettingsTest\\plugins", plugins: [] }),
"plugin:window|is_maximized": () => test.state.maximized,
"plugin:window|toggle_maximize": () => { test.state.maximized = !test.state.maximized; },
"plugin:window|minimize": () => { if (test.state.failMinimize) throw new Error("Window action failed"); },
"plugin:window|close": () => null,
}),
});
const page = await openPage(context, { timeout: 5000 });
await page.goto(`${smokeUrl}/?settingsWindow=true`);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.waitFor();
assert.equal(await dialog.getByRole("button", { name: /^Close/ }).count(), 1);
assert(await dialog.locator("header[data-tauri-drag-region] h1[data-tauri-drag-region]").isVisible());
assert.equal(await dialog.locator(".window-controls [data-tauri-drag-region]").count(), 0);
const calls = () => page.evaluate(() => window.__TEST__.calls.map(call => call.command));
const closes = async () => (await calls()).filter(command => command === "plugin:window|close").length;
const button = name => page.getByRole("button", { name, exact: true });
await button("Minimize window").click();
assert((await calls()).includes("plugin:window|minimize"));
await button("Maximize window").click();
await button("Restore window").waitFor();
await button("Restore window").focus();
await page.keyboard.press("Enter");
await button("Maximize window").waitFor();
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", {}); });
await button("Restore window").waitFor();
await button("Close window").focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
await page.keyboard.press("Space");
const beforeEscape = await closes();
assert.equal(beforeEscape, 1);
await page.getByRole("textbox", { name: "Search settings" }).focus();
await page.keyboard.press("Escape");
assert.equal(await closes(), beforeEscape + 1);
await page.mouse.move(400, 180);
for (const theme of ["dark", "light"]) {
await page.evaluate(value => document.documentElement.setAttribute("data-theme", value), theme);
for (const size of [{ width: 920, height: 650 }, { width: 540, height: 420 }]) {
await page.setViewportSize(size);
assert(await dialog.evaluate(element => element.scrollWidth === element.clientWidth));
for (const label of ["Minimize window", "Restore window", "Close window"]) {
const control = dialog.getByRole("button", { name: label, exact: true });
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= size.width && bounds.height >= 28);
// Caption buttons are square (src/lib/ui/WindowControls.svelte).
assert.equal(await control.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
}
await page.screenshot({ path: path.join(output, `${theme}-${size.width}.png`) });
}
}
await page.evaluate(() => { window.__TEST__.state.failMinimize = true; });
await button("Minimize window").click();
await dialog.getByRole("alert").filter({ hasText: "Window action failed" }).waitFor();
await page.evaluate(() => { window.__TEST__.state.failMinimize = false; });
await button("Minimize window").focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Restore defaults");
await page.keyboard.press("Tab");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Minimize window");
// Without the Tauri mock, the page is a plain browser preview.
const web = await openPage(browser);
await web.goto(`${smokeUrl}/?settingsWindow=true`);
await web.getByRole("button", { name: "Close settings", exact: true }).waitFor();
assert.equal(await web.getByRole("group", { name: "Window controls" }).count(), 0);
assert.deepEqual(page.errors, []);
console.log("Settings window smoke passed: scoped permissions, drag regions, minimize, maximize, restore, resize, close, Escape, keyboard focus, tooltips, errors, both themes, narrow layout, and browser fallback.");
});
+79
View File
@@ -0,0 +1,79 @@
// Settings window: browser preview fallback, standalone layout, two-way save sync, failed saves, native open requests, and close. The OS title bar is not tested.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("settings/window", async ({ browser }) => {
const output = await outputDir("settings/window");
const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
const autosaveSeconds = page => page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds);
// The main window and settings run as browser previews, without the Tauri mock.
const main = await openPage(context);
await main.goto(smokeUrl);
await main.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
assert.equal(await main.locator("dialog:modal").count(), 1, "Browser preview retains the settings dialog");
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
assert.equal(await settings.locator(".workbench").count(), 0);
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
await interval.fill("17"); await interval.press("Tab");
await main.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "17");
await main.getByRole("spinbutton", { name: "Auto-save interval" }).fill("29");
await main.getByRole("spinbutton", { name: "Auto-save interval" }).press("Tab");
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
await settings.reload();
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
await interval.fill("301"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Choose a whole number" }).waitFor();
assert.equal(await autosaveSeconds(settings), 29);
await settings.evaluate(() => { Storage.prototype.setItem = () => { throw new Error("Storage full"); }; });
await interval.fill("40"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Could not save these settings" }).waitFor();
assert.equal(await autosaveSeconds(settings), 29);
await settings.reload();
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("heading", { name: "Plug-ins", exact: true }).waitFor();
await settings.getByRole("button", { name: "General", exact: true }).click();
await settings.screenshot({ path: path.join(output, "settings-window.png") });
await settings.setViewportSize({ width: 540, height: 420 });
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await settings.keyboard.press("Escape");
await settings.waitForURL(`${smokeUrl}/`);
// A desktop window with the Tauri mock opens settings in a native window.
const desktop = await openPage(context);
await mockTauri(desktop, {
state: { opens: 0, fail: false, closes: 0 },
commands: test => ({
settings_open_window: async () => {
test.state.opens++;
if (test.state.fail) throw new Error("Native window creation failed");
await new Promise(resolve => setTimeout(resolve, 150));
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
workspace_last_path: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|close": () => { test.state.closes++; },
}),
});
const desktopState = () => desktop.evaluate(() => window.__TEST__.state);
await desktop.goto(smokeUrl);
await desktop.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).dblclick();
assert.equal((await desktopState()).opens, 1, "Rapid requests share the pending native open");
assert.equal(await desktop.locator("dialog:modal").count(), 0, "Native open does not block the workbench");
await desktop.waitForTimeout(180);
await desktop.keyboard.press("Control+,");
await desktop.waitForFunction(() => window.__TEST__.state.opens === 2);
await desktop.waitForTimeout(180);
await desktop.evaluate(() => { window.__TEST__.state.fail = true; });
await desktop.keyboard.press("Control+,");
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
await desktop.goto(`${smokeUrl}/?settingsWindow=true`);
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
await desktop.getByRole("button", { name: "Close window", exact: true }).click();
assert.equal((await desktopState()).closes, 1);
assert.deepEqual([main, settings, desktop].flatMap(page => page.errors), []);
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
});
+168
View File
@@ -0,0 +1,168 @@
// Table drag handles: hover and focus grips, previews, row and column moves, undo, cancellation, keyboard moves, and auto-scroll.
import assert from "node:assert/strict";
import path from "node:path";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
const long = '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n';
await runSmoke("tables/drag", async ({ page }) => {
const output = await outputDir("tables/drag");
await mockTauri(page, {
state: { files: { 'drag.md': source, 'long.md': long } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
const headers = () => table.locator('th').allTextContents();
async function grip(axis, index) {
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
await handle.scrollIntoViewIfNeeded();
const rect = await handle.boundingBox();
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
await page.mouse.down();
}
async function target(axis, index, after = false) {
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
}
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await quickOpen('drag.md');
await chooseView(page, "Write");
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
const firstGrip = page.locator('.table-drag-row[data-index="1"]');
await firstGrip.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '1');
assert.equal(await page.locator('.table-drag-row[data-index="2"]').evaluate(el => getComputedStyle(el).opacity), '0');
await page.mouse.move(5, 5);
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '0');
await grip('row', 1);
assert.equal(await page.locator('.table-drag-preview').count(), 0);
await target('row', 2, true);
const preview = page.locator('.table-drag-preview');
await preview.waitFor();
assert.match(await preview.innerText(), /Alpha/);
assert.equal(await preview.getAttribute('aria-hidden'), 'true');
assert.equal(await preview.evaluate(el => getComputedStyle(el).pointerEvents), 'none');
const initialPreview = await preview.boundingBox();
await target('row', 4, true);
assert.ok((await preview.boundingBox()).y > initialPreview.y + 20);
assert.equal(await preview.locator('.table-drag-preview-label').innerText(), 'Row 2 → 5');
assert.equal(await table.locator('.is-cell-selected').count(), 3);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: path.join(output, 'row.png') });
await page.mouse.up();
assert.equal(await preview.count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| Delta | 40 | Four |\n| Alpha'));
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await page.keyboard.press('Control+y');
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await grip('row', 4); await target('row', 1); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await target('column', 2, true);
assert.deepEqual(await preview.locator('tr').allTextContents(), ['Name', 'Alpha', 'Beta', 'Gamma', 'Delta']);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: path.join(output, 'column.png') });
await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| ---: | :---: | :--- |'));
await grip('column', 2); await target('column', 0); await page.mouse.up();
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Cancel, out-of-table drop, and click without a drag must not change source.
await grip('row', 1); await target('row', 4, true); await page.keyboard.press('Escape'); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('row', 1); await page.mouse.move(5, 5, { steps: 5 }); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// The focused grip offers the same operation to keyboard users.
// Tab into the handle, rather than leaving mouse focus on it.
await page.locator('.table-add-row').focus();
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 1');
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-column[data-index="0"]')).opacity === '1');
await page.keyboard.press('ArrowRight');
assert.deepEqual(await headers(), ['Value', 'Name', 'Notes']);
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 2');
await page.keyboard.press('ArrowLeft');
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Editing a cell before dragging must commit its latest contents.
await table.locator('tbody tr').first().locator('td').first().click();
await page.keyboard.press('Control+End'); await page.keyboard.type(' edited');
await grip('row', 1); await target('row', 4, true); await page.mouse.up();
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha edited']);
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha edited', 'Beta', 'Gamma', 'Delta']);
// Keep column handles aligned when a narrow table viewport scrolls.
// At 760 pixels the side panes give way. The test opens both again, so the table pane stays narrow.
await page.setViewportSize({ width: 760, height: 700 });
await page.locator('aside.left').waitFor({ state: 'detached' });
await page.keyboard.press('Control+Backslash');
await page.locator('aside.left').waitFor();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('aside.right').waitFor();
await table.locator('th').first().scrollIntoViewIfNeeded();
await grip('column', 0);
const viewport = await page.locator('.writer-table .md-table-scroll').boundingBox();
await page.mouse.move(viewport.x + viewport.width - 2, viewport.y + 15, { steps: 8 });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft > 0; });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft + el.clientWidth >= el.scrollWidth - 2; });
await target('column', 2, true); await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await page.screenshot({ path: path.join(output, 'narrow.png') });
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await quickOpen('long.md');
await chooseView(page, "Write");
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
const first = await table.locator('tr').nth(1).boundingBox();
await page.mouse.move(first.x + 20, scroller.y + scroller.height - 5, { steps: 8 });
await page.waitForFunction(() => {
const last = document.querySelector('.live-writer table tbody tr:last-child').getBoundingClientRect();
const viewport = document.querySelector('.live-writer .cm-scroller').getBoundingClientRect();
return last.bottom < viewport.bottom - 20;
});
await target('row', 30, true);
await page.mouse.up();
assert.equal((await rows()).at(-1), 'Item 1');
assert.equal((await rows())[0], 'Item 2');
await page.keyboard.press('Control+z');
assert.equal((await rows())[0], 'Item 1');
await grip('row', 2); await target('row', 3, true);
await page.locator('.table-drag-row[data-index="2"]').dispatchEvent('pointercancel');
await page.mouse.up();
assert.equal((await rows())[1], 'Item 2');
assert.equal(await page.locator('.is-table-dragging').count(), 0);
assert.equal(await preview.count(), 0);
});
+92
View File
@@ -0,0 +1,92 @@
// Table Enter and Shift+Enter, table clipboard with line breaks, task marker editing, and title Tab, in both themes and a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/enterKey", async ({ page }) => {
const output = await outputDir("tables/enterKey");
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n" }, writeEvents: true }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
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 source = '# Example\n\n| Name | Notes |\n| --- | --- |\n| Alpha | First<br>Second |\n| Beta | Last |\n\nAfter.\n\n- [ ] A task\n';
const reset = async () => {
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
await page.locator('.live-writer table').waitFor();
};
const cell = (r, c) => page.locator('.live-writer table tr').nth(r).locator('th,td').nth(c);
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
await reset();
await cell(1, 1).click();
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 2);
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 3);
assert.equal(await page.locator('.live-writer table tr').count(), 4);
await page.keyboard.type('New');
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('Line');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /New<br>Line/);
await shot(`${mode}-table-enter`);
await reset();
await cell(0, 0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name: 'Select cell', exact: true }).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
const copied = await page.locator('.writer-table').evaluate(node => {
const data = new DataTransfer();
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true }));
return { html: data.getData('text/html'), text: data.getData('text/plain') };
});
assert.match(copied.html, /<table>/);
assert.match(copied.text, /Name\tNotes/);
await page.evaluate(() => {
const view = window.__CM__;
const anchor = view.state.sliceDoc().indexOf('After.');
view.dispatch({ selection: { anchor } }); view.focus();
});
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, copied) => {
const data = new DataTransfer(); data.setData('text/html', copied.html); data.setData('text/plain', copied.text);
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}, copied);
assert.equal(await page.locator('.live-writer table').count(), 2);
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /First<br>Second/);
await shot(`${mode}-table-paste`);
await reset();
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('A task') + 3 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 1);
await shot(`${mode}-checklist-text`);
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('[ ]') + 1 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 0);
await shot(`${mode}-checklist-source`);
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
await page.getByRole('textbox', { name: 'Note filename', exact: true }).press('Tab');
await page.waitForFunction(() => document.activeElement?.classList.contains('cm-content'));
await shot(`${mode}-title-tab`);
await page.setViewportSize({ width: 600, height: 760 });
await reset();
await shot(`${mode}-narrow`);
await page.setViewportSize({ width: 1440, height: 1000 });
}
});
+160
View File
@@ -0,0 +1,160 @@
// Built-in table formulas: live recalculation, raw formula editing, Enter and Tab, undo, cycles, saving, the footer layout, the Read and Split views,
// and the general setting that turns formulas off and on.
import assert from "node:assert/strict";
import path from "node:path";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
await runSmoke("tables/formulas", async ({ page }) => {
const output = await outputDir("tables/formulas");
await mockTauri(page, {
state: { files: { 'formulas.md': source } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".source-editor .cm-content").waitFor();
}
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
const result = (r, c) => cell(r, c).locator('.md-table-formula');
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
}
// Footer controls share one normal-flow block aligned to the table at any width.
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), helpHidden: document.querySelector('.table-edit-help').hidden, summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.footer.x - geometry.tools.x) < 2);
if (!geometry.helpHidden) assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
if (!geometry.helpHidden) {
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
}
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await quickOpen('formulas.md');
await page.keyboard.press('Control+e');
await table.waitFor();
assert.equal(await result(1, 3).innerText(), '9.5');
assert.equal(await result(3, 3).innerText(), '17.5');
await cell(1, 3).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await cell(1, 3).getAttribute('title'), null);
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /D2.*AVERAGE/);
await shot('cell-hint');
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await cell(1, 3).click();
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
await edit.fill('=AVERAGE(B2+C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 19');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2,C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2:C2)');
await page.keyboard.press('Enter');
await cell(1, 1).click();
await edit.fill('5');
assert.equal(await result(1, 3).innerText(), '7.5');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Tab');
await cell(1, 3).click();
assert.equal(await edit.innerText(), '=AVERAGE(B2:C2)');
assert.match(await page.locator('.table-formula-status').innerText(), /D2/);
await edit.fill('=B2*C2');
await page.keyboard.press('Enter');
assert.equal(await result(1, 3).innerText(), '50');
assert.equal(await result(3, 3).innerText(), '58');
assert.match(await save(), /\| =B2\*C2 \|/);
await cell(1, 3).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=AVERAGE(B2:C2)');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Control+y');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=B2*C2');
assert.equal(await result(3, 3).innerText(), '58');
await cell(2, 3).click();
await edit.fill('=D3');
// Enter would start editing D4 below (src/lib/editor/tableControls.ts:283), so leave the table to render both results.
await page.keyboard.press('Control+Enter');
// The table renders again after it loses focus. Wait for that before the check.
for (const [r, c] of [[2, 3], [3, 3]]) await result(r, c).filter({ hasText: /^#CYCLE!$/ }).waitFor();
assert.equal(await result(2, 3).innerText(), '#CYCLE!');
assert.equal(await result(3, 3).innerText(), '#CYCLE!');
await cell(2, 3).click();
await edit.fill('=AVERAGE(B3:C3)');
await page.keyboard.press('Tab');
await cell(3, 1).click();
await edit.fill('=SUM(B2:B3)');
await page.keyboard.press('Enter');
assert.equal(await result(3, 1).innerText(), '12');
const saved = await save();
assert.match(saved, /=SUM\(B2:B3\)/);
assert.doesNotMatch(saved, /\\=/);
await cell(3, 1).click();
await checkFooter();
await shot('footer');
await page.setViewportSize({ width: 850, height: 1000 });
await checkFooter();
await shot('footer-narrow');
await page.locator('.table-formula-help summary').click();
assert.equal(await page.locator('.table-formula-help').getAttribute('open'), '');
await checkFooter();
await page.setViewportSize({ width: 1440, height: 1000 });
await shot('formulas');
await page.keyboard.press('Control+e');
await page.keyboard.press('Control+e');
assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Read beside']) {
await chooseView(page, mode);
const preview = page.locator('.md-page table').first();
await preview.waitFor();
// Enter in the last row added an empty row below Total (src/lib/editor/tableControls.ts:285).
const total = preview.locator('tbody tr').filter({ hasText: 'Total' });
assert.equal(await total.locator('.md-table-formula').last().innerText(), '58', `${mode} view`);
}
// The general setting turns formulas off in all views. The source text shows and the file stays the same.
const file = await page.evaluate(() => window.__TEST__.files.get('formulas.md'));
const general = await page.evaluate(() => window.__TEST__.settings('general') ?? {});
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: false });
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
const total = page.locator('.md-page table').first().locator('tbody tr').filter({ hasText: 'Total' });
assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
await shot('formulas-off-split');
await chooseView(page, 'Read beside');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').count(), 0);
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
assert.equal(await page.locator('.table-formula-tools').count(), 0, 'Writer shows no formula help');
await shot('formulas-off-writer');
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: true });
await result(3, 3).waitFor();
assert.equal(await result(3, 3).innerText(), '58');
await page.locator('.table-formula-tools').first().waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.files.get('formulas.md')), file);
});
+127
View File
@@ -0,0 +1,127 @@
// Links in table cells: clicks keep the caret in place, keyboard entry, inline Edit link, wiki aliases, repeated targets, save, and undo, in both themes and a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/linkCaret", async ({ page }) => {
const output = await outputDir("tables/linkCaret");
await mockTauri(page, {
commands: test => {
localStorage.clear();
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
folders: ["notes"],
files: { "a.md": '# Links\n\nOutside table.\n\n| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Text |\n| Three | Text |\n| Four | Text |\n| Five | [Roadmp](docs/roadmap.md) |\n| Keyboard | Before [Guide](docs/guide.md) after |\n| Wiki | [[guide\\|Guide]] |\n| Repeated | **Prefix** [One](same.md) + [Sec**ond**](same.md "Title") |\n' },
});
test.files = workspace.files;
test.prompts = [];
return {
...workspace,
spelling_menu_install: () => null,
"plugin:dialog|message": ({ message }) => { test.prompts.push(message); return "Cancel"; },
};
},
});
page.setDefaultTimeout(15000);
const sourceCell = () => page.locator('.is-source-editing .writer-cell-editor');
async function clickTextAt(locator, offset, button = 'left') {
const point = await locator.evaluate((element, offset) => {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (offset > node.textContent.length) { offset -= node.textContent.length; continue; }
const range = document.createRange();
range.setStart(node, offset); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
}
throw new Error('No text position');
}, offset);
await page.mouse.click(point.x, point.y, { button });
}
const selected = () => page.evaluate(() => getSelection().toString());
const caretPrefix = () => page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
const documentText = () => page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
return EditorView.findFromDOM(node).state.doc.toString();
});
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
const cell = page.getByRole('cell', { name:'B6 · Row 6, column 2', exact:true });
await clickTextAt(cell.locator('a'), 5);
await sourceCell().waitFor();
assert.equal(await cell.locator('.writer-link-target').innerText(), 'docs/roadmap.md', 'Ordinary click reveals the URL');
assert.equal(await caretPrefix(), '[Roadm', 'The caret stays at the clicked label character');
await page.keyboard.type('a');
assert.equal(await sourceCell().innerText(), '[Roadmap](docs/roadmap.md)');
await shot(`click-label-${theme}-${width}`);
await page.keyboard.press('Escape');
assert.equal(await cell.locator('a').innerText(), 'Roadmap');
await clickTextAt(cell.locator('a'), 3);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'docs/roadmap.md');
assert.equal(await page.getByRole('dialog').count(), 0);
await shot(`edit-target-${theme}-${width}`);
await page.keyboard.type('docs/changed.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.locator('.cm-line').filter({ hasText:'Outside table.' }).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/roadmap.md');
await page.keyboard.press('Control+y');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.keyboard.press('Control+s');
assert.match(await page.evaluate(() => window.__TEST__.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'B7 · Row 7, column 2', exact:true });
await clickTextAt(keyboard, 7);
assert.equal(await sourceCell().count(), 0, 'Plain cell text remains rendered');
await page.keyboard.press('ArrowRight');
await sourceCell().waitFor();
assert.equal(await keyboard.locator('.writer-link-target').innerText(), 'docs/guide.md');
assert.equal(await caretPrefix(), 'Before [G');
await shot(`keyboard-${theme}-${width}`);
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'B8 · Row 8, column 2', exact:true });
await clickTextAt(wiki.locator('a'), 3);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '[[guide\\|Gui');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'), 'new-guide');
const repeated = page.getByRole('cell', { name:'B9 · Row 9, column 2', exact:true });
await clickTextAt(repeated.locator('a').nth(1), 4);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '**Prefix** [One](same.md) + [Sec**o');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await repeated.locator('a').first().getAttribute('href'), 'same.md');
assert.equal(await repeated.locator('a').nth(1).getAttribute('href'), 'second.md');
assert.match(await documentText(), /\[Sec\*\*ond\*\*\]\(second.md "Title"\)/);
assert.deepEqual(await page.evaluate(() => window.__TEST__.prompts), []);
}
});

Some files were not shown because too many files have changed in this diff Show More