Файли
openidea/e2e/customEditorToolbar.spec.ts
T
LU XIANGRUIтаwildcatDownstairs c13cb2bf27 feat(plugins): add customEditor.toolbar menu above split/preview text editors (#8164)
Adds the `customEditor.toolbar` menu location (plugin API 1.21). A `[[contributes.menus]]` entry with `view` naming one of the plugin's own split or preview custom editors puts its command as an icon button in a thin strip above the text half of that editor; `when` works as for other menus. The host rejects a missing or unknown `view`, a tab-layout editor, unknown commands and submenus at install time. Buttons use the command's icon (else the plugin icon), the command title as tooltip and aria-label, and run with the same editor context as editor.title; the strip is hidden in preview-only mode and when nothing applies.

Closes #7796

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-05 14:05:54 +08:00

280 рядки
11 KiB
TypeScript

import { expect, stubDesktop, test } from "./fixtures";
const EVIDENCE = process.env.CUSTOM_EDITOR_TOOLBAR_EVIDENCE;
test("customEditor.toolbar renders SVG commands above split text half and hides in preview-only", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1200, height: 760 });
await stubDesktop(page);
await page.evaluate(async () => {
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const pluginsBackendPath = "/src/features/plugins/backend.ts";
const pluginsStorePath = "/src/features/plugins/store.ts";
const projectionPath = "/src/features/plugins/projection.ts";
const bridgeRawPath = "/src/features/plugins/views/frame-bridge.js?raw";
const { docBackend } = await import(/* @vite-ignore */ backendPath);
const { editorService } = await import(/* @vite-ignore */ contributionsPath);
const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ pluginsBackendPath);
const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath);
const { syncUiContributions } = await import(/* @vite-ignore */ projectionPath);
const { default: bridgeSource } = await import(/* @vite-ignore */ bridgeRawPath);
const bridgeFn = bridgeSource.trim().replace(/;\s*$/, "");
const source = "/dev/acme-api/two_sum.problem.py";
const code = [
"from typing import List",
"",
"",
"class Solution:",
" def twoSum(self, nums: List[int], target: int) -> List[int]:",
" seen: dict[int, int] = {}",
" for index, value in enumerate(nums):",
" complement = target - value",
" if complement in seen:",
" return [seen[complement], index]",
" seen[value] = index",
" return []",
"",
].join("\n");
docBackend().files.set(source, code);
window.__ipc.handlers.fs_read_text = (args) => docBackend().files.get(String(args.path)) ?? "";
window.__ipc.handlers.fs_probe = () => ({ size: code.length, binary: false, tooLarge: false });
window.__ipc.handlers.window_is_fullscreen = () => false;
const runSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">' +
'<path data-run-svg="1" d="M4.5 3.2L12.5 8L4.5 12.8V3.2Z" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round" fill="currentColor" fill-opacity="0.18"/>' +
"</svg>";
const pluginSvg =
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">' +
'<rect data-plugin-svg="1" x="2.5" y="2.5" width="11" height="11" rx="2.5" stroke="currentColor" stroke-width="1.4"/>' +
'<path d="M5.5 6.5L7.5 8L5.5 9.5M8.5 9.5H10.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>' +
"</svg>";
const statementHtml = `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<script>(${bridgeFn})(null);</script>
<style>
html, body {
margin: 0;
height: 100%;
background: var(--openidea-bg-editor, var(--openidea-bg));
color: var(--openidea-fg);
font: 13px/1.6 var(--openidea-font-ui, system-ui, sans-serif);
}
main { padding: 18px 22px; }
h1 { margin: 0 0 6px; font-size: 16px; font-weight: 600; }
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
border: 1px solid var(--openidea-border);
color: var(--openidea-fg-muted);
margin-bottom: 12px;
}
p { margin: 0 0 12px; }
pre {
margin: 0;
padding: 10px 12px;
border-radius: 6px;
border: 1px solid var(--openidea-border);
background: var(--openidea-bg-elevated, transparent);
font: 12px/1.5 var(--openidea-font-mono, monospace);
}
</style>
</head>
<body>
<main>
<h1>1. Two Sum</h1>
<span class="badge">Easy · Array · Hash Table</span>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return indices of the two numbers such that they add up to <code>target</code>.</p>
<pre>Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]</pre>
</main>
</body>
</html>`;
const pageUrl = URL.createObjectURL(new Blob([statementHtml], { type: "text/html" }));
const base = createMemoryPluginsBackend();
const template = (await base.list()).plugins[0]!;
const plugin = {
...template,
id: "leetcode",
name: "LeetCode Runner",
status: "active" as const,
enabled: true,
icon: { light: pluginSvg, dark: null },
};
const calls: unknown[] = [];
Object.assign(window, { __customToolbarCalls: calls });
setPluginsBackend({
...base,
webPageUrl: async (pluginId: string) => (pluginId === "leetcode" ? pageUrl : base.webPageUrl(pluginId, "v")),
assets: async (pluginId: string, prefix: string) =>
pluginId === "leetcode" && prefix === "commandIcon/run" ? [["commandIcon/run", runSvg]] : [],
runCommand: async (pluginId: string, command: string, arg: string | null, editor: unknown, paths: string[]) => {
calls.push({ pluginId, command, arg, editor, paths });
return null;
},
});
const baseUi = [
{
pluginId: "leetcode",
point: "commands",
key: "run",
decl: { id: "run", title: "Run Solution", icon: "icons/run.svg" },
},
{
pluginId: "leetcode",
point: "commands",
key: "submit",
decl: { id: "submit", title: "Submit Solution", icon: "check" },
},
{
pluginId: "leetcode",
point: "commands",
key: "testcase",
decl: { id: "testcase", title: "Edit Testcases" },
},
{
pluginId: "leetcode",
point: "customEditors",
key: "statement",
decl: {
id: "statement",
title: "Statement",
patterns: ["*.problem.py"],
priority: "default",
layout: "split",
web: "web/index.html",
},
},
];
Object.assign(window, { __customToolbarPlugin: plugin, __customToolbarBaseUi: baseUi });
usePlugins.setState({ plugins: [plugin], ui: baseUi });
syncUiContributions(baseUi, [plugin]);
await editorService().openFile(source);
});
await expect(page.frameLocator('iframe[data-plugin-webview="leetcode"]').locator("h1")).toHaveText("1. Two Sum");
await expect(page.getByRole("toolbar", { name: "Statement actions" })).toHaveCount(0);
if (EVIDENCE) {
await page.screenshot({ path: `${EVIDENCE}/7796-before-light.png`, animations: "disabled" });
await page.evaluate(async () => {
const themePath = "/src/workbench/theme.ts";
await (await import(/* @vite-ignore */ themePath)).setTheme("dark");
});
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await page.screenshot({ path: `${EVIDENCE}/7796-before-dark.png`, animations: "disabled" });
await page.evaluate(async () => {
const themePath = "/src/workbench/theme.ts";
await (await import(/* @vite-ignore */ themePath)).setTheme("light");
});
await expect(page.locator("html")).toHaveAttribute("data-theme", "light");
}
// Now contribute `customEditor.toolbar` entries for `statement`.
await page.evaluate(async () => {
const pluginsStorePath = "/src/features/plugins/store.ts";
const projectionPath = "/src/features/plugins/projection.ts";
const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath);
const { syncUiContributions } = await import(/* @vite-ignore */ projectionPath);
const w = window as unknown as { __customToolbarPlugin: unknown; __customToolbarBaseUi: unknown[] };
const ui = [
...w.__customToolbarBaseUi,
{
pluginId: "leetcode",
point: "menus",
key: "customEditor.toolbar/statement/run",
decl: { menu: "customEditor.toolbar", view: "statement", command: "run" },
},
{
pluginId: "leetcode",
point: "menus",
key: "customEditor.toolbar/statement/submit",
decl: { menu: "customEditor.toolbar", view: "statement", command: "submit" },
},
{
pluginId: "leetcode",
point: "menus",
key: "customEditor.toolbar/statement/testcase",
decl: { menu: "customEditor.toolbar", view: "statement", command: "testcase" },
},
];
usePlugins.setState({ plugins: [w.__customToolbarPlugin as never], ui: ui as never });
syncUiContributions(ui as never, [w.__customToolbarPlugin as never]);
});
const toolbar = page.getByRole("toolbar", { name: "Statement actions" });
await expect(toolbar).toBeVisible();
const runBtn = toolbar.getByRole("button", { name: "Run Solution" });
const submitBtn = toolbar.getByRole("button", { name: "Submit Solution" });
const testcaseBtn = toolbar.getByRole("button", { name: "Edit Testcases" });
await expect(runBtn.locator('[data-run-svg="1"]')).toBeVisible();
await expect(submitBtn).toBeVisible();
await expect(testcaseBtn.locator('[data-plugin-svg="1"]')).toBeVisible();
// Verify the strip sits directly above the text editor (not in the tab strip).
const geometry = await page.evaluate(() => {
const strip = document.querySelector('[role="toolbar"][aria-label="Statement actions"]')!.getBoundingClientRect();
const cm = document.querySelector(".cm-editor")!.getBoundingClientRect();
return {
stripTop: strip.top,
stripBottom: strip.bottom,
stripLeft: strip.left,
stripRight: strip.right,
cmTop: cm.top,
cmLeft: cm.left,
cmRight: cm.right,
};
});
expect(geometry.stripBottom).toBeLessThanOrEqual(geometry.cmTop + 1);
expect(Math.abs(geometry.stripLeft - geometry.cmLeft)).toBeLessThanOrEqual(2);
expect(Math.abs(geometry.stripRight - geometry.cmRight)).toBeLessThanOrEqual(2);
if (EVIDENCE) {
await page.screenshot({ path: `${EVIDENCE}/7796-after-light.png`, animations: "disabled" });
await page.evaluate(async () => {
const themePath = "/src/workbench/theme.ts";
await (await import(/* @vite-ignore */ themePath)).setTheme("dark");
});
await expect(page.locator("html")).toHaveAttribute("data-theme", "dark");
await page.screenshot({ path: `${EVIDENCE}/7796-after-dark.png`, animations: "disabled" });
}
// Clicking runs the command with the active editor context.
await runBtn.click();
await expect
.poll(() =>
page.evaluate(() => (window as unknown as { __customToolbarCalls: { command: string }[] }).__customToolbarCalls),
)
.toEqual([
expect.objectContaining({
pluginId: "leetcode",
command: "run",
arg: null,
editor: expect.objectContaining({ path: "/dev/acme-api/two_sum.problem.py" }),
paths: [],
}),
]);
// Switching to preview-only hides the toolbar strip.
await page.getByRole("button", { name: "Statement Only" }).click();
await expect(toolbar).toHaveCount(0);
// Switching back to split restores it.
await page.getByRole("button", { name: "Editor and Statement" }).click();
await expect(toolbar).toBeVisible();
});