Move the tests from scripts/ to tests/ by feature
Unit tests go to tests/unit/<area>/, browser smoke tests to tests/smoke/<area>/, and tests against a running desktop app to tests/native/. Files named after dates, work passes, or Kanban cards get feature names, for example editorOctober12 -> editor/footnotes. scripts/ keeps the build, release, and package tools. Plugin repositories import scripts/packagePlugin.mjs, and the Terminal smoke test imports scripts/pluginMocks.mjs, which now re-exports the harness copy. The unit tests get their own type check (tests/tsconfig.json) with Node types. pnpm check runs it after the app check. Add @types/node and fix the three test mocks that it reported.
This commit is contained in:
@@ -0,0 +1,357 @@
|
||||
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('<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 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();
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
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: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
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") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const dragSources = new Map();
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
dragSources.set(data, { page, name });
|
||||
return data;
|
||||
}
|
||||
async function drop(page, data) {
|
||||
await bar(page).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
|
||||
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
|
||||
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
|
||||
}, data);
|
||||
const source = dragSources.get(data);
|
||||
if (source) {
|
||||
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
}
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-lifecycle", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
try {
|
||||
const page = await create();
|
||||
for (const name of ["a.md", "b.md", "c.md"]) await open(page, name);
|
||||
await tab(page, "c.md").focus(); await page.keyboard.press("Alt+Shift+ArrowLeft"); await page.keyboard.press("Alt+Shift+ArrowLeft");
|
||||
await pin(page, "b.md"); await tab(page, "b.md").click();
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
const session = await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`)));
|
||||
assert.deepEqual(session.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
|
||||
assert.equal(session.activePath, "b.md"); assert.equal(session.documents[2].pinned, true);
|
||||
assert.ok(!JSON.stringify(session).includes("Saved text"));
|
||||
await page.goto(url + "?missing"); await tab(page, "b.md").waitFor();
|
||||
assert.deepEqual(await bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["c.md", "b.md"]);
|
||||
assert.equal(await tab(page, "b.md").getAttribute("aria-selected"), "true");
|
||||
await tab(page, "b.md").click({ button: "right" }); await page.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await page.keyboard.press("Escape");
|
||||
await screenshots(page, "restored-documents");
|
||||
await page.locator(".cm-content").fill("Unsaved draft");
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`))), session);
|
||||
await page.evaluate(() => { window.lifecycle.answer = "Ok"; return window.lifecycle.close(); });
|
||||
page.on("dialog", dialog => dialog.accept());
|
||||
await page.reload(); await tab(page, "b.md").waitFor();
|
||||
assert.match(await page.locator(".cm-content").innerText(), /Saved text/);
|
||||
await open(page, "saved.board"); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
await page.evaluate(() => window.lifecycle.close()); await page.reload();
|
||||
await tab(page, "saved").waitFor(); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
const source = await create("?plugins"), target = await create("?plugins"), other = await create("?other"), disabled = await create("?plugins&disabled");
|
||||
assert.equal(await tab(other, "New tab").count(), 1);
|
||||
await openBoard(source); await source.getByRole("textbox", { name: "Board state" }).fill("Transferred board state"); await pin(source, "Board");
|
||||
let data = await start(source, "Board"); assert.ok(JSON.parse(data).tabTransfer);
|
||||
await drop(other, data); await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
|
||||
await drop(disabled, data); await disabled.getByText("Enable this tab's plugin before moving it to this window.").waitFor();
|
||||
assert.equal(await tab(source, "Board").count(), 1);
|
||||
await drop(target, data); await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
await tab(target, "Board").click({ button: "right" }); await target.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await target.keyboard.press("Escape");
|
||||
await screenshots(target, "joined-plugin");
|
||||
data = await start(target, "Board"); await drop(source, data); await tab(target, "Board").waitFor({ state: "detached" });
|
||||
await openBoard(target); await target.getByRole("textbox", { name: "Board state" }).fill("Destination state");
|
||||
data = await start(source, "Board"); await drop(target, data);
|
||||
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Destination state"); assert.equal(await tab(source, "Board").count(), 1);
|
||||
await tab(source, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
await tab(source, "Board").click({ button: "right" }); await source.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
|
||||
const token = await source.evaluate(() => window.lifecycle.transfer); assert.ok(token);
|
||||
const detached = await create(`?plugins&tabTransfer=${token}`); await detached.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
await tab(source, "Board").waitFor({ state: "detached" });
|
||||
data = await start(detached, "Board"); await drop(source, data); await tab(detached, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await source.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: normal-close restore, order, active tab, pins, missing files, workspace isolation, canceled close, disk-only restore, plugin documents, plugin join, duplicate protection, disabled plugin, and tear-out return");
|
||||
} catch (reason) {
|
||||
for (const page of context.pages()) console.error(page.url(), (await page.locator("body").innerText()).slice(-1000));
|
||||
throw reason;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,139 @@
|
||||
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tab-menu-workspace";
|
||||
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
|
||||
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
|
||||
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
|
||||
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
|
||||
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
|
||||
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const tab = name => page.getByRole("tab", { name, exact: true });
|
||||
const menu = () => page.getByRole("menu", { name: "Tab actions", exact: true });
|
||||
const item = name => page.getByRole("menuitem", { name, exact: true });
|
||||
const order = () => page.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
|
||||
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 tab(name).waitFor();
|
||||
}
|
||||
async function show(name) { await tab(name).click({ button: "right" }); await menu().waitFor(); }
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("tab-menu-workspace", { exact: true }).waitFor();
|
||||
for (const name of ["a.md", "b.md", "c.md", "d.md"]) await open(name);
|
||||
await page.locator(".cm-content").filter({ hasText: "Original text." }).waitFor();
|
||||
await show("b.md");
|
||||
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
|
||||
assert.equal(await item("Rename…").count(), 0);
|
||||
assert.equal(await item("Reading view").count(), 0);
|
||||
assert.doesNotMatch(await menu().innerText(), /Alt|Shift|Ctrl/);
|
||||
await page.screenshot({ path: ".audit/tab-menu-inactive.png" });
|
||||
await item("Pin").click();
|
||||
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
|
||||
assert.ok(await tab("b.md").getAttribute("aria-describedby"));
|
||||
await show("d.md");
|
||||
assert.equal(await item("Close tabs after").isDisabled(), true);
|
||||
await page.screenshot({ path: ".audit/tab-menu-active.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await tab("d.md").evaluate(node => node === document.activeElement), true);
|
||||
await tab("d.md").press("Shift+F10");
|
||||
assert.equal(await item("Close").evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await item("Move tab left").evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await page.keyboard.press("Escape");
|
||||
await show("d.md");
|
||||
await item("Reading view").click();
|
||||
await page.locator(".md-page").waitFor();
|
||||
await show("d.md");
|
||||
await item("Editing view").click();
|
||||
await page.locator(".cm-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Source mode").click();
|
||||
await page.locator(".monaco-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Writing mode").click();
|
||||
await page.locator(".cm-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Copy path").click();
|
||||
await item("Workspace path").click();
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.clipboard), "d.md");
|
||||
await show("d.md");
|
||||
await item("Show in system explorer").click();
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "d.md");
|
||||
await show("d.md");
|
||||
await item("Rename…").click();
|
||||
await page.getByRole("dialog").getByRole("textbox").fill("renamed.md");
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await tab("renamed.md").waitFor();
|
||||
await show("a.md");
|
||||
await item("Close tabs after").click();
|
||||
await tab("renamed.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["a.md", "b.md"]);
|
||||
await open("c.md");
|
||||
await show("c.md");
|
||||
await item("Close others").click();
|
||||
await tab("a.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md", "c.md"]);
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Unsaved text");
|
||||
await tab("c.md •").waitFor();
|
||||
await show("c.md •");
|
||||
await item("Close all").click();
|
||||
await page.waitForFunction(() => window.tabMenuTest.prompts.length === 1);
|
||||
assert.deepEqual(await order(), ["b.md", "c.md"]);
|
||||
await page.evaluate(() => { window.tabMenuTest.answer = "Ok"; });
|
||||
await show("c.md •");
|
||||
await item("Close all").click();
|
||||
await tab("c.md •").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md"]);
|
||||
await show("b.md");
|
||||
assert.equal(await item("Close all").isDisabled(), true);
|
||||
await item("Unpin").click();
|
||||
await show("b.md");
|
||||
await item("Close").click();
|
||||
await tab("b.md").waitFor({ state: "detached" });
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await show("New tab");
|
||||
assert.equal(await item("Rename…").count(), 0);
|
||||
assert.equal(await item("Reading view").count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: active/inactive menus, keyboard focus, pinning, view modes, file actions, ordered closes, cancelled discard, and empty tabs");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/tab-menu-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,128 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE set if Playwright is shared.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tab-order-workspace";
|
||||
const files = new Map(Array.from({ length: 16 }, (_, i) => [`note-${String(i).padStart(2, "0")}.md`, `# Note ${i}\n\nKeep this text.\n`]));
|
||||
files.set("note-00.md", Array.from({ length: 200 }, (_, i) => `Paragraph ${i}.\n\n`).join(""));
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence,
|
||||
unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tab-order-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") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const tab = name => page.getByRole("tab", { name, exact: true });
|
||||
const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
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 tab(name).waitFor();
|
||||
}
|
||||
async function drag(from, to, side, cancel) {
|
||||
const source = await tab(from).boundingBox();
|
||||
const 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();
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("tab-order-workspace", { exact: true }).waitFor();
|
||||
for (const name of ["note-00.md", "note-01.md", "note-02.md"]) await open(name);
|
||||
await drag("note-00.md", "note-02.md", "after");
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]);
|
||||
assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true");
|
||||
await drag("note-00.md", "note-01.md", "before");
|
||||
assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]);
|
||||
for (const cancel of ["escape", "outside"]) {
|
||||
await drag("note-00.md", "note-02.md", "after", cancel);
|
||||
assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]);
|
||||
}
|
||||
await tab("note-00.md").click();
|
||||
assert.equal(await tab("note-00.md").getAttribute("aria-selected"), "true");
|
||||
await page.locator(".cm-scroller").evaluate(node => { node.scrollTop = 1200; });
|
||||
await settle();
|
||||
const scrollTop = await page.locator(".cm-scroller").evaluate(node => node.scrollTop);
|
||||
assert.ok(scrollTop > 1000);
|
||||
await tab("note-00.md").press("Alt+Shift+ArrowRight");
|
||||
await settle();
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-00.md", "note-02.md"]);
|
||||
assert.ok(Math.abs(await page.locator(".cm-scroller").evaluate(node => node.scrollTop) - scrollTop) < 5);
|
||||
assert.equal(await tab("note-00.md").evaluate(node => document.activeElement === node), true);
|
||||
await tab("note-00.md").press("ArrowRight");
|
||||
assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true");
|
||||
await tab("note-02.md").press("Shift+F10");
|
||||
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
|
||||
assert.equal(await page.getByRole("menuitem", { name: /Move tab right/ }).isDisabled(), true);
|
||||
await page.getByRole("menuitem", { name: /Move tab left/ }).click();
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]);
|
||||
await tab("note-01.md").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
|
||||
assert.equal(await page.getByRole("menuitem", { name: /Move tab left/ }).isDisabled(), true);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.getByRole("menu", { name: "Tab actions" }).count(), 0);
|
||||
console.log("PASS: pointer moves, cancellation, keyboard moves, and tab menus");
|
||||
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await tab("New tab").press("Alt+Shift+Home");
|
||||
assert.match((await order())[0], /^empty:/);
|
||||
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
await tab("note-01.md").click({ button: "middle" });
|
||||
assert.deepEqual(await order(), ["note-02.md", "note-00.md"]);
|
||||
console.log("PASS: empty tabs and middle-click close after reorder");
|
||||
|
||||
for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`);
|
||||
const bar = page.getByRole("tablist", { name: "Working tabs" });
|
||||
assert.ok(await bar.evaluate(node => node.scrollLeft > 0));
|
||||
await tab("note-15.md").press("Alt+Shift+Home");
|
||||
assert.equal((await order())[0], "note-15.md");
|
||||
assert.equal(await bar.evaluate(node => node.scrollLeft), 0);
|
||||
const source = await tab("note-15.md").boundingBox();
|
||||
const 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.
|
||||
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), "note-15.md");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: automatic scrolling and drag to the end of an overflowing tab bar");
|
||||
if (process.env.SCREENSHOT_PATH) await page.screenshot({ path: process.env.SCREENSHOT_PATH });
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
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") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
return data;
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
|
||||
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
|
||||
return page.evaluate(({ data, point, type, mime }) => {
|
||||
const transfer = new DataTransfer(); transfer.setData(mime, data);
|
||||
const node = document.elementFromPoint(point.x, point.y) || document.body;
|
||||
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
|
||||
node.dispatchEvent(event);
|
||||
return event.defaultPrevented;
|
||||
}, { data, point, type, mime });
|
||||
}
|
||||
async function receive(page, data, point) {
|
||||
assert.equal(await eventAt(page, data, point), true);
|
||||
assert.equal(await eventAt(page, data, point, "drop"), true);
|
||||
}
|
||||
async function point(page, kind) {
|
||||
return page.locator(".header").evaluate((header, kind) => {
|
||||
const bounds = header.getBoundingClientRect();
|
||||
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
|
||||
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
|
||||
const first = header.querySelector('.tab').getBoundingClientRect();
|
||||
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
|
||||
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
|
||||
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
|
||||
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
|
||||
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
|
||||
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
|
||||
}, kind);
|
||||
}
|
||||
try {
|
||||
const source = await create("?plugins"), target = await create("?plugins");
|
||||
await open(target, "b.md");
|
||||
await open(source, "a.md"); await pin(source, "a.md");
|
||||
await source.locator(".cm-content").fill("Unsaved ribbon transfer");
|
||||
let data = await start(source, "a.md •");
|
||||
const broad = await point(target, "blank");
|
||||
assert.equal(await eventAt(target, data, broad), true, "Blank titlebar space accepts transferred tabs");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), true);
|
||||
assert.equal(await eventAt(target, data, await point(target, "outside")), false, "The document body stays outside the drop target");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), false);
|
||||
assert.equal(await eventAt(target, data, await point(target, "controls")), false, "Window controls stay outside the drop target");
|
||||
assert.equal(await eventAt(target, data, broad, "dragover", "text/plain"), false, "Ordinary file and text drags retain their behavior");
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await target.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await eventAt(target, data, broad);
|
||||
await target.screenshot({ path: `output/tab-ribbon-drop/${mode}-blank-receiving.png` });
|
||||
}
|
||||
await receive(target, data, broad);
|
||||
await tab(target, "a.md •").waitFor(); await tab(source, "a.md •").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["b.md", "a.md •"]);
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved ribbon transfer/);
|
||||
assert.ok(await tab(target, "a.md •").getAttribute("aria-describedby"));
|
||||
await open(source, "c.md"); data = await start(source, "c.md");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
await tab(target, "c.md").waitFor(); await tab(source, "c.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •"]);
|
||||
await openBoard(source); await pin(source, "Board"); await source.getByRole("textbox", { name: "Board state" }).fill("Plugin ribbon state");
|
||||
data = await start(source, "Board");
|
||||
await target.setViewportSize({ width: 700, height: 700 });
|
||||
const nearby = await point(target, "near");
|
||||
await eventAt(target, data, nearby);
|
||||
await bar(target).and(target.locator('.receiving')).waitFor();
|
||||
await target.screenshot({ path: "output/tab-ribbon-drop/narrow-near-receiving.png" });
|
||||
await receive(target, data, nearby);
|
||||
await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •", "Board"]);
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Plugin ribbon state");
|
||||
assert.ok(await tab(target, "Board").getAttribute("aria-describedby"));
|
||||
await screenshots(target, "ribbon-plugin-pinned");
|
||||
data = await start(target, "Board");
|
||||
assert.equal(await eventAt(target, data, await point(target, "near")), false, "Same-window reordering stays precise");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
assert.deepEqual(await order(target), ["Board", "c.md", "b.md", "a.md •"]);
|
||||
await tab(target, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: broad titlebar and nearby ribbon drops, exact tab ordering, rejection outside the ribbon and over window controls, ordinary drag isolation, pinned unsaved documents, narrow plugin transfers, and source acknowledgement");
|
||||
} catch (error) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `output/tab-ribbon-drop/failure-${index}.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["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 callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
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; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-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") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
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 settle() {
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function roundTrip(selector, label) {
|
||||
const scroller = page.locator(selector);
|
||||
const position = async (top) => label === 'IDE'
|
||||
? page.evaluate(async top => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
|
||||
if (top !== undefined) editor.setScrollTop(top, 1);
|
||||
return editor.getScrollTop();
|
||||
}, top)
|
||||
: scroller.evaluate((el, top) => {
|
||||
if (top !== undefined) el.scrollTop = top;
|
||||
return el.scrollTop;
|
||||
}, top);
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(1800);
|
||||
await settle();
|
||||
const first = await position();
|
||||
assert.ok(first > 1000, `${label}: first document is scrollable`);
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(650);
|
||||
await settle();
|
||||
const second = await position();
|
||||
for (let repeat = 0; repeat < 2; repeat++) {
|
||||
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
|
||||
await page.getByRole('tab', { name, exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
const actual = await position();
|
||||
assert.ok(Math.abs(actual - expected) < 5, `${label}: ${name} expected ${expected}, got ${actual}`);
|
||||
}
|
||||
}
|
||||
console.log(`PASS: ${label} retains independent tab scroll positions`);
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(() => {
|
||||
for (const name of ['scroll-a.md', 'scroll-b.md']) {
|
||||
window.__TEST__.files.set(name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join(''));
|
||||
}
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['scroll-a.md', 'scroll-b.md'] });
|
||||
});
|
||||
await open('scroll-b.md');
|
||||
await open('scroll-a.md');
|
||||
if (await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).count()) {
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
}
|
||||
await roundTrip('.cm-scroller', 'Writing');
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Reading');
|
||||
await page.getByRole('button', { name: 'Split', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Split preview');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
await roundTrip('.monaco-scrollable-element', 'IDE');
|
||||
assert.deepEqual(errors, []);
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
console.error((await page.locator('body').innerText()).slice(-2000));
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,129 @@
|
||||
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: 900 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const root = location.search.includes("other") ? "C:\\other" : "C:\\transfer";
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten" || command.startsWith("plugin:window|")) return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "transfer", watch_mode: "native" };
|
||||
if (command === "workspace_read") return "# " + args.rel + "\n\nOriginal text.\n";
|
||||
if (command === "workspace_list") return args.rel ? [] : ["a.md", "b.md"].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: [] };
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const source = await context.newPage(), target = await context.newPage(), other = await context.newPage();
|
||||
for (const page of [source, target, other]) page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
for (const page of [source, target, other]) page.on("pageerror", error => errors.push(error.message));
|
||||
const tab = (page, name) => page.locator('[role="tab"]').filter({ hasText: name });
|
||||
async function open(page, name) {
|
||||
await page.bringToFront();
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).waitFor();
|
||||
await page.getByRole("tab").first().waitFor();
|
||||
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 tab(page, name).waitFor();
|
||||
}
|
||||
async function start(page, name) {
|
||||
return tab(page, name).evaluate(node => {
|
||||
const transfer = new DataTransfer();
|
||||
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
}
|
||||
async function drop(page, data) {
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.setData("application/x-runestone-tab", data);
|
||||
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
node.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
}, data);
|
||||
}
|
||||
async function captureTransfer(page, data) {
|
||||
await mkdir("output/tab-transfer", { recursive: true });
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
await applyAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.setData("application/x-runestone-tab", data);
|
||||
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
}, data);
|
||||
await page.screenshot({ path: `output/tab-transfer/${theme}-receiving.png` });
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.all([source.goto(url), target.goto(url), other.goto(url + "/?other")]);
|
||||
await open(source, "a.md");
|
||||
await open(target, "b.md");
|
||||
await tab(source, "a.md").click({ button: "right" });
|
||||
await source.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
await source.locator(".cm-content").fill("Unsaved transfer text");
|
||||
let data = await start(source, "a.md");
|
||||
assert.ok(JSON.parse(data).tabTransfer);
|
||||
await drop(other, data);
|
||||
await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
await captureTransfer(target, data);
|
||||
await drop(target, data);
|
||||
console.log("Dropped into matching workspace");
|
||||
await tab(target, "a.md").waitFor();
|
||||
await tab(source, "a.md").waitFor({ state: "detached" });
|
||||
console.log("Source acknowledged transfer");
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
|
||||
const changedTarget = await context.newPage();
|
||||
changedTarget.on("pageerror", error => errors.push(error.message));
|
||||
await changedTarget.goto(url);
|
||||
await changedTarget.getByRole("tab").first().waitFor();
|
||||
await open(source, "a.md");
|
||||
data = await start(source, "a.md");
|
||||
await source.locator(".cm-content").fill("Changed during transfer");
|
||||
await drop(changedTarget, data);
|
||||
await tab(changedTarget, "a.md").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
assert.match(await source.locator(".cm-content").innerText(), /Changed during transfer/);
|
||||
assert.ok(await tab(target, "a.md").getAttribute("aria-describedby"));
|
||||
assert.deepEqual(await target.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["a.md", "b.md"]);
|
||||
await open(source, "a.md");
|
||||
data = await start(source, "a.md");
|
||||
await drop(target, data);
|
||||
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
|
||||
await mkdir("output/tab-transfer", { recursive: true });
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await target.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
await applyAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
await target.screenshot({ path: `output/tab-transfer/${theme}.png` });
|
||||
}
|
||||
await target.setViewportSize({ width: 700, height: 700 });
|
||||
await target.screenshot({ path: "output/tab-transfer/narrow.png" });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: same-workspace transfer, unsaved text, pinned state, insertion order, other-workspace rejection, duplicate protection, and source edits during transfer");
|
||||
} catch (reason) {
|
||||
console.log(await other.locator("body").innerText());
|
||||
console.log(await target.locator("body").innerText());
|
||||
throw reason;
|
||||
} finally { await browser.close(); }
|
||||
Reference in New Issue
Block a user