Files
RuneStone/tests/smoke/menus/consistency.smoke.mjs
T
2026-11-03 00:23:07 -07:00

326 lines
20 KiB
JavaScript

// 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 });