import { createRequire } from "node:module"; import assert from "node:assert/strict"; import { mkdir } from "node:fs/promises"; const require = createRequire(import.meta.url); const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); const page = await context.newPage(); await context.exposeBinding("settingsHostInvoke", (_source, command, args) => page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args })); page.setDefaultTimeout(10000); const errors = []; page.on("pageerror", error => errors.push(error.message)); 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), }); }`; await context.addInitScript(({ pluginCode }) => { window.isTauri = true; localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 })); const root = "C:\\plugin-tab-workspace"; const files = new Map(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`])); files.set("project.board", "project-board"); const callbacks = new Map(), listeners = new Map(); let sequence = 0, enabled = true; 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" }; const emit = async (event, payload) => { await Promise.all((listeners.get(event) || []).map(id => callbacks.get(id)?.({ event, id, payload }))); }; window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, closeRequests: 0, destroys: 0, files }; const label = location.search.includes("secondary") ? "workspace-2" : "main"; window.__TAURI_INTERNALS__ = { metadata: { currentWindow: { label }, currentWebview: { label } }, transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, unregisterCallback: id => callbacks.delete(id), invoke: async (command, args = {}) => { if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|")) return window.settingsHostInvoke(command, args); if (command === "settings_open_window") return; if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; } if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } if (command === "plugin:window|is_maximized") return false; if (command === "plugin:window|close") { window.tabTest.closeRequests++; await emit("tauri://close-requested"); return; } if (command === "plugin:window|destroy") { window.tabTest.destroys++; return; } if (command.startsWith("plugin:window|")) return; if (command === "plugins_snapshot") return { root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] }; if (command === "plugins_load") return pluginCode; if (command === "plugins_data") return "null"; if (command === "plugins_release") return; if (command === "plugins_set_enabled") { enabled = args.enabled; emit("plugins-changed"); return; } if (command === "workspace_last_path") return location.search.includes("no-workspace") ? null : root; if (command === "workspace_open") return { root, name: "plugin-tab-workspace", watch_mode: "native" }; if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } if (command === "workspace_write") { files.set(args.rel, args.contents); return; } if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" })); if (command === "workspace_search") return []; if (command === "plugin:dialog|message") { window.tabTest.prompts++; return window.tabTest.answer; } throw new Error(`Unhandled IPC: ${command}`); }, }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; }, { pluginCode }); 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 = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); 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(); } try { const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; await page.goto(url); 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 mkdir(".audit", { recursive: true }); await page.locator(".header").screenshot({ path: `.audit/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('').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 mkdir("output", { recursive: true }); await page.locator(".header").screenshot({ path: `output/tab-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; }); 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 context.newPage(); settingsPage.on("pageerror", error => errors.push(error.message)); await settingsPage.goto(url + '/?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(`${url}?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 mkdir(".audit", { recursive: true }); await page.screenshot({ path: ".audit/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(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(`${url}?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 mkdir(".audit", { recursive: true }); await page.screenshot({ path: ".audit/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(errors, []); console.log("PASS: secondary windows close through the window guard for the last empty, document, or plugin tab; Cancel preserves unsaved edits"); } catch (error) { await mkdir(".audit", { recursive: true }); await page.screenshot({ path: ".audit/plugin-tab-order-failure.png" }); console.error("Browser errors:", errors); throw error; } finally { await browser.close(); }