Files
RuneStone/tests/smoke/tabs/lastTabAndSiteIcons.smoke.mjs
2026-11-16 04:21:21 -07:00

336 lines
19 KiB
JavaScript

// The last tab becomes a new tab, compact tab widths, site icons, mixed file and plugin tabs, close actions, plugin disable, and secondary windows.
// @known-issue Without a workspace, plugin tabs cannot be dragged to reorder: they are native-draggable but get no drag data (Workbench.svelte workingTabDragData).
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, settle as settleFrames, smokeUrl } from "../_harness/index.mjs";
const pluginCode = `export function activate(api) {
window.tabTest.api = api;
const mount = (id, container) => {
window.tabTest.mounts[id] = (window.tabTest.mounts[id] || 0) + 1;
const input = document.createElement("input");
input.setAttribute("aria-label", id + " state");
container.append(input);
return () => {
window.tabTest.disposals[id] = (window.tabTest.disposals[id] || 0) + 1;
input.remove();
};
};
for (const [id, title, icon] of [["overview", "Overview", "puzzle"], ["browser", "Browser", "globe"]]) {
api.registerView({ id, title, icon, placement: "editor", navigation: true, mount: container => mount(id, container) });
}
api.registerDocumentType({
id: "board", title: "Board", icon: "kanban", extensions: ["board"],
identify: (path, source) => ({ id: source }),
mount: (container, document) => mount(document.id, container),
});
}`;
// `?secondary` loads a secondary window. `?settingsWindow` loads the settings window, which sends its commands to the main page.
function windowRoles(context) {
return context.addInitScript(() => {
const internals = window.__TAURI_INTERNALS__;
if (location.search.includes("secondary")) internals.metadata = { currentWindow: { label: "workspace-2" }, currentWebview: { label: "workspace-2" } };
if (!location.search.includes("settingsWindow")) return;
const { invoke } = internals;
internals.invoke = (command, args = {}) => command.startsWith("plugin:event|") || command.startsWith("plugin:window|")
? invoke(command, args)
: window.settingsHostInvoke(command, args);
});
}
await runSmoke("tabs/lastTabAndSiteIcons", async ({ browser }) => {
const output = await outputDir("tabs/lastTabAndSiteIcons");
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await mockTauri(context, {
state: { pluginCode },
commands: test => {
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 }));
const root = "C:\\plugin-tab-workspace";
const files = Object.fromEntries(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
files["project.board"] = "project-board";
const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
let enabled = true;
window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, closeRequests: 0, destroys: 0 };
const workspace = test.workspace({ root, files });
return {
...workspace,
workspace_last_path: () => location.search.includes("no-workspace") ? null : root,
settings_open_window: () => null,
"plugin:window|is_maximized": () => false,
"plugin:window|close": () => { window.tabTest.closeRequests++; test.emit("tauri://close-requested"); },
"plugin:window|destroy": () => { window.tabTest.destroys++; },
"plugin:dialog|message": () => { window.tabTest.prompts++; return window.tabTest.answer; },
plugins_snapshot: () => ({ root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] }),
plugins_load: () => test.state.pluginCode,
plugins_release: () => null,
plugins_set_enabled: args => { enabled = args.enabled; test.emit("plugins-changed"); },
};
},
});
await windowRoles(context);
const page = await openPage(context);
const pages = [page];
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
const tab = name => page.getByRole("tab", { name, exact: true });
const bar = page.getByRole("tablist", { name: "Working tabs" });
const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
const settle = () => settleFrames(page);
async function openFile(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 settle();
}
async function openView(name) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click();
await tab(name).waitFor();
}
async function drag(from, to, side = "before", cancel) {
const source = await tab(from).boundingBox(), target = await tab(to).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
if (cancel === "escape") await page.keyboard.press("Escape");
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
await page.mouse.up();
await settle();
}
async function menu(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menu", { name: "Tab actions" }).waitFor();
}
await page.goto(smokeUrl);
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
await tab("New tab").waitFor();
for (const close of ["button", "middle", "shortcut", "all"]) {
const before = await tab("New tab").getAttribute("data-path");
if (close === "button") await page.getByRole("button", { name: "Close New tab", exact: true }).click();
if (close === "middle") await tab("New tab").click({ button: "middle" });
if (close === "shortcut") await page.keyboard.press("Control+w");
if (close === "all") {
await menu("New tab");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
}
await page.waitForFunction(before => {
const tabs = document.querySelectorAll('.header [role="tab"]');
return tabs.length === 1 && tabs[0].getAttribute("data-path") !== before;
}, before);
assert.equal(await tab("New tab").getAttribute("aria-selected"), "true");
}
for (const name of ["a.md", "b.md", "c.md", "note-0.md"]) await openFile(name);
await page.getByRole("textbox", { name: "Writing editor", exact: true }).filter({ hasText: "# note-0.md" }).waitFor();
for (const width of [880, 1280, 1440]) {
await page.setViewportSize({ width, height: 1000 });
await settle();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
const dimensions = await page.locator(".header").evaluate(header => {
const bar = header.querySelector('[role="tablist"]');
const rows = [...bar.querySelectorAll(".tab")];
const plus = header.querySelector('[aria-label="New tab (Ctrl+T)"]');
const bounds = bar.getBoundingClientRect();
return {
overflow: bar.scrollWidth - bar.clientWidth,
left: bounds.left,
navigationRight: header.querySelector(".header-left").getBoundingClientRect().right,
tabWidth: Math.min(...rows.map(row => row.getBoundingClientRect().width)),
gap: plus.getBoundingClientRect().left - Math.min(bounds.right, rows.at(-1).getBoundingClientRect().right),
fits: header.scrollWidth <= header.clientWidth,
};
});
if (width >= 1280) assert.ok(dimensions.overflow <= 1, JSON.stringify(dimensions));
assert.ok(Math.abs(dimensions.left - dimensions.navigationRight) <= 2, JSON.stringify(dimensions));
assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions));
assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions));
assert.ok(dimensions.fits);
const plus = page.getByRole("button", { name: "New tab (Ctrl+T)", exact: true });
await plus.evaluate(button => button.blur());
await plus.focus();
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl+T)" }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".header").screenshot({ path: path.join(output, `compact-tabs-${width}-${theme}.png`) });
}
}
await menu("note-0.md");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
console.log("PASS: the last tab becomes a new tab, tabs retain usable widths, and the adjacent plus button has a focus tooltip");
await openFile("a.md");
await openFile("b.md");
await openView("Overview");
await page.getByRole("textbox", { name: "overview state" }).fill("Keep this state");
await openView("Browser");
const siteIcon = "data:image/svg+xml;base64," + Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="3" fill="#e35336"/></svg>').toString('base64');
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
await tab("Browser").locator("img.tab-icon").waitFor();
await page.waitForFunction(() => document.querySelector('.header img.tab-icon')?.naturalWidth === 16);
assert.equal(await tab("Browser").locator("img").getAttribute("alt"), "");
assert.equal(await tab("Browser").locator("img").getAttribute("draggable"), "false");
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.locator(".header").screenshot({ path: path.join(output, `site-icon-${theme}.png`) });
}
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", "data:image/png;base64,aW1hZ2U="));
await tab("Browser").locator("img").waitFor({ state: "detached" });
assert.equal(await tab("Browser").locator("svg").count(), 1);
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
await tab("Browser").locator("img").waitFor();
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", null));
await tab("Browser").locator("img").waitFor({ state: "detached" });
assert.equal(await tab("Browser").locator("svg").count(), 1);
console.log("PASS: site icons appear in both themes and missing or broken icons use the fallback");
await openFile("project.board");
await tab("project").waitFor();
assert.equal(await page.locator(".header").getByRole("tablist").count(), 1);
assert.deepEqual(await order(), ["a.md", "b.md", "Overview", "Browser", "project"]);
await drag("Overview", "a.md");
await drag("project", "b.md");
await drag("a.md", "Browser", "after");
const mixed = ["Overview", "project", "b.md", "Browser", "a.md"];
assert.deepEqual(await order(), mixed);
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
for (const cancel of ["escape", "outside"]) {
await drag("Browser", "Overview", "before", cancel);
assert.deepEqual(await order(), mixed);
}
await tab("Browser").press("Alt+Shift+Home");
assert.equal((await order())[0], "Browser");
await tab("Browser").press("ArrowRight");
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
assert.equal(await page.getByRole("textbox", { name: "overview state" }).inputValue(), "Keep this state");
await tab("Overview").press("ArrowRight");
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
await page.evaluate(() => window.tabTest.api.updateViewTitle("browser", "Browser page"));
await tab("Browser page").waitFor();
assert.equal((await order())[0], "Browser page");
assert.deepEqual(await page.evaluate(() => window.tabTest.mounts), { overview: 1, browser: 1, "project-board": 1 });
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), {});
assert.equal(await tab("project").getAttribute("aria-controls"), await page.getByRole("tabpanel", { name: "project" }).getAttribute("id"));
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await menu("Browser page");
assert.equal(await page.getByRole("menuitem", { name: "Pin", exact: true }).count(), 1);
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
await page.getByRole("menuitem", { name: "Move tab right", exact: true }).click();
}
console.log("PASS: mixed file, feature, and plugin document tabs move without remounting or changing selection");
await tab("Browser page").press("Alt+Shift+End");
await tab("project").press("Alt+Shift+End");
await tab("a.md").press("Alt+Shift+Home");
await tab("Overview").press("Alt+Shift+Home");
await tab("b.md").press("Alt+Shift+Home");
await menu("b.md");
await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
await tab("a.md").click();
await page.locator(".cm-content").fill("Unsaved text");
await tab("a.md •").waitFor();
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
await menu("Overview");
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
await page.waitForFunction(() => window.tabTest.prompts === 1);
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
await page.evaluate(() => window.tabTest.answer = "Ok");
await menu("Overview");
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
await tab("project").waitFor({ state: "detached" });
assert.deepEqual(await order(), ["b.md", "Overview"]);
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
await menu("Overview");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
await tab("Overview").waitFor({ state: "detached" });
assert.deepEqual(await order(), ["b.md"]);
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), { browser: 1, "project-board": 1, overview: 1 });
console.log("PASS: mixed close actions follow visual order, preserve pins, and respect cancelled discards");
await openView("Overview");
for (let index = 0; index < 14; index++) await openFile(`note-${index}.md`);
await tab("Overview").press("Alt+Shift+Home");
const source = await tab("Overview").boundingBox(), bounds = await bar.boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 });
await page.waitForFunction(() => {
const bar = document.querySelector('[aria-label="Working tabs"]');
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
});
// Native drag needs a fresh pointer event after the strip scrolls beneath it, as in tabs/order.
await page.mouse.move(bounds.x + bounds.width - 4, source.y + source.height / 2);
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2);
await page.mouse.up();
await settle();
assert.equal((await order()).at(-1), "Overview");
await page.keyboard.press("Control+t");
await tab("New tab").press("Alt+Shift+Home");
await openFile("c.md");
assert.equal((await order())[0], "c.md");
const fileOrder = (await order()).filter(name => name !== "Overview");
await page.keyboard.press("Control+,");
const settingsPage = await openPage(context);
pages.push(settingsPage);
await settingsPage.goto(smokeUrl + '/?settingsWindow=true');
await settingsPage.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settingsPage.getByRole("switch", { name: "Tab fixtures", exact: true }).click();
await settingsPage.waitForFunction(() => document.getElementById("external-test.tabs")?.checked === false);
await tab("Overview").waitFor({ state: "detached" });
assert.deepEqual(await order(), fileOrder);
console.log("PASS: plugin drag auto-scroll, empty-tab replacement, and plugin disable preserve the mixed order");
await settingsPage.close();
await page.goto(`${smokeUrl}?no-workspace`);
await tab("New tab").waitFor();
await openView("Overview");
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
await openView("Browser");
await drag("Browser", "Overview");
assert.deepEqual(await order(), ["Browser", "Overview"]);
await page.setViewportSize({ width: 880, height: 700 });
await page.screenshot({ path: path.join(output, "plugin-tab-order.png") });
await tab("Browser").click({ button: "middle" });
assert.deepEqual(await order(), ["Overview"]);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
assert.deepEqual(pages.flatMap(page => page.errors), []);
console.log("PASS: plugin tabs reorder and close without an open workspace");
for (const close of ["button", "middle", "shortcut", "all", "plugin", "dirty"]) {
await page.goto(`${smokeUrl}?secondary`);
await tab("New tab").waitFor();
if (close === "plugin") {
await openView("Overview");
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
assert.equal(await page.evaluate(() => window.tabTest.closeRequests), 0);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
} else if (close === "dirty") {
await openFile("a.md");
await page.locator(".cm-content").fill("Keep these unsaved edits");
await page.keyboard.press("Control+w");
await page.waitForFunction(() => window.tabTest.prompts === 1);
assert.equal(await page.evaluate(() => window.tabTest.destroys), 0);
assert.match(await page.locator(".cm-content").innerText(), /Keep these unsaved edits/);
await page.screenshot({ path: path.join(output, "secondary-last-tab-cancel.png") });
await page.evaluate(() => window.tabTest.answer = "Ok");
await page.keyboard.press("Control+w");
} else if (close === "button") {
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
} else if (close === "middle") {
await tab("New tab").click({ button: "middle" });
} else if (close === "shortcut") {
await page.keyboard.press("Control+w");
} else {
await openFile("a.md");
await openFile("b.md");
await menu("b.md");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
}
await page.waitForFunction(() => window.tabTest.destroys === 1);
assert.equal(await page.evaluate(() => window.tabTest.closeRequests), close === "dirty" ? 2 : 1);
}
assert.deepEqual(pages.flatMap(page => page.errors), []);
console.log("PASS: secondary windows close through the window guard for the last empty, document, or plugin tab; Cancel preserves unsaved edits");
});