fix(plugins): give the keyboard to a plugin dialog's or tool window's page (#8003)

A plugin dialog focused its Close button while its page loaded, and a plugin web tool window left the focus on its body when activated, so typing went nowhere until the user clicked into the page. WebKit doesn't let a sandboxed frame focus a field before the user acts on it, so the page's autofocus or focus() could not help.

The dialog and the tool window now focus the plugin frame, and the frame bridge sends a key typed while nothing in the page has the focus to the page's autofocus field. Shortcuts, Tab and Escape keep their meaning.

Fixes #7973
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-04 17:31:55 +08:00
1 джерело 8e36365bc4
коміт b4c8a6708c
5 files changed
+71 -6

No files matched your search

+3
Переглянути файл
@@ -2748,6 +2748,9 @@ fn handle(view: &str, event: ViewEvent) {
The page talks to the plugin's code as any web view does (`openidea.postMessage`
/ `onMessage`, `views::post_message("preview", …)`), and sees nothing else of the
IDE, so a dialog needs no capability. Only a dialog's page has `openidea.dialog`.
The dialog gives its page the keyboard when it opens, as a tool window does when
activated. The engine doesn't let a sandboxed page focus a field before the user
types or clicks, so mark the field with `autofocus`: the first key typed goes to it.
For something that stays open beside the editor without taking the keyboard,
use an [overlay](#overlays) or a tool window.
+37 -6
Переглянути файл
@@ -13,22 +13,24 @@ afterEach(() => {
localStorage.clear();
});
/** Runs the bridge in a fake frame window at `search`; what it posts up and its keydown handler. */
function bridgeAt(search: string) {
/** Runs the bridge in a fake frame window at `search`; what it posts up and its keydown handlers. */
function bridgeAt(search: string, doc: Record<string, unknown> = {}) {
const script = /<script>([\s\S]*)<\/script>/.exec(frameDocument("", { dark: true, vars: {} }))![1]!;
const sent: Array<Record<string, unknown>> = [];
const parent = { postMessage: (m: Record<string, unknown>) => void sent.push(m) };
const listeners: Record<string, (e: unknown) => void> = {};
const listeners: Record<string, Array<(e: unknown) => void>> = {};
const frameWindow: Record<string, unknown> = {
parent,
addEventListener: (type: string, fn: (e: unknown) => void) => void (listeners[type] = fn),
addEventListener: (type: string, fn: (e: unknown) => void) => void (listeners[type] ??= []).push(fn),
};
const html = document.createElement("html");
new Function("window", "document", "location", script)(
frameWindow,
{ documentElement: document.createElement("html") },
{ documentElement: html, activeElement: html, querySelector: () => null, ...doc },
{ search },
);
return { api: frameWindow.openidea as Record<string, unknown>, sent, keydown: listeners.keydown! };
const keydown = (e: unknown) => listeners.keydown!.forEach((fn) => fn(e));
return { api: frameWindow.openidea as Record<string, unknown>, sent, keydown };
}
const decl: DialogDecl = { id: "preview", title: "SQL Preview", web: "web/preview.html", width: 900, height: 600 };
@@ -57,6 +59,29 @@ describe("frame bridge: openidea.dialog", () => {
});
});
describe("frame bridge: autofocus", () => {
it("sends a key typed while nothing has the focus to the page's autofocus field", () => {
const body = document.createElement("body");
const field = { focus: vi.fn() };
const press = (init: Record<string, unknown>, activeElement: unknown = body) => {
const { keydown } = bridgeAt("?openidea=dialog", {
body,
activeElement,
querySelector: (sel: string) => (sel === "[autofocus]" ? field : null),
});
keydown({ key: "x", code: "KeyX", isComposing: false, ...init });
};
press({});
expect(field.focus).toHaveBeenCalledTimes(1);
// Shortcuts, Tab and Escape keep their meaning; a focused element keeps the focus.
press({ metaKey: true });
press({ key: "Tab" });
press({ key: "Escape" });
press({}, document.createElement("input"));
expect(field.focus).toHaveBeenCalledTimes(1);
});
});
describe("plugin dialogs", () => {
async function opened() {
const events: ViewEvent[] = [];
@@ -79,6 +104,12 @@ describe("plugin dialogs", () => {
return { events, frame, dispose, result };
}
it("gives the keyboard focus to its page", async () => {
const { frame, dispose } = await opened();
await waitFor(() => expect(document.activeElement).toBe(frame));
dispose();
});
it("opens on views.reveal with its title and page, and tells the plugin when it closes", async () => {
const { events, frame, dispose } = await opened();
expect(screen.getByRole("dialog", { name: "SQL Preview" })).toBeInTheDocument();
+4
Переглянути файл
@@ -228,6 +228,8 @@ describe("WebView", () => {
expect(frame.getAttribute("sandbox")).toBe("allow-scripts");
expect(frame.getAttribute("src")).toBe("about:blank");
expect(frame.getAttribute("allow")).toBeNull();
// A custom editor's page is not the tool window or dialog focus target.
expect(frame.hasAttribute("data-autofocus")).toBe(false);
});
it("uses the binary editor's own path for messages to plugin code", async () => {
@@ -320,6 +322,8 @@ describe("WebView", () => {
const view = render(<WebView pluginId="acme.draw" view="draw" label="Draw" />);
const { frame } = await frameOf(view.container);
expect(frame.getAttribute("src")).toContain("/r1/");
// A tool window's page is its content: activating the tool window focuses it.
expect(frame.hasAttribute("data-autofocus")).toBe(true);
// Plugins refreshed, same package: the same frame, not reloaded.
usePlugins.setState({ plugins: [info("1.0.0")] });
+12
Переглянути файл
@@ -632,6 +632,16 @@ export function WebView({
};
}, [pluginId, view, document, doc, eventEditor, editor, overlay, pluginDialog, runConfig, hasCode, post, page]);
// A dialog's page is all its content: the frame takes the focus the dialog gave its buttons while
// the page loaded, so typing reaches the page (and the field it focuses) without a click.
const framed = page !== null && "url" in page;
useEffect(() => {
const f = frame.current;
if (!pluginDialog || !framed || !f) return;
const body = f.closest<HTMLElement>("[data-dialog-body]");
if (body && !body.contains(f.ownerDocument.activeElement)) f.focus({ preventScroll: true });
}, [pluginDialog, framed]);
// An overlay floats over the workbench: no spinner or error card in its place.
if (overlay && (!page || "error" in page)) return null;
if (!page)
@@ -665,6 +675,8 @@ export function WebView({
sandbox="allow-scripts"
allow={clipboard ? "clipboard-read; clipboard-write" : undefined}
tabIndex={overlay ? -1 : undefined}
// A tool window or dialog page is that surface's content: activating it focuses the page.
data-autofocus={pluginDialog || !(document || editor || overlay || runConfig || binaryPath) ? "" : undefined}
src={frameQuery ? `${page.url}${page.url.includes("?") ? "&" : "?"}${frameQuery}` : page.url}
onLoad={() => {
postTheme();
+15
Переглянути файл
@@ -97,6 +97,21 @@
window.addEventListener("focus", notifyFocus);
window.addEventListener("pointerdown", notifyFocus, true);
// A sandboxed page can't focus a field before the user acts on it (WebKit ignores `autofocus`
// and `focus()` there), so a key typed while nothing in the page has the focus goes to the
// page's `autofocus` field, as it would have had the field kept the focus.
window.addEventListener(
"keydown",
(e) => {
if (e.metaKey || e.ctrlKey || e.altKey || e.key === "Tab" || e.key === "Escape") return;
const active = document.activeElement;
if (active && active !== document.body && active !== document.documentElement) return;
const field = document.querySelector("[autofocus]");
if (field && typeof field.focus === "function") field.focus();
},
true,
);
// IDE shortcuts (Save, Close, Find Action…) pressed while the page has focus:
// the ones the page left alone go to the workbench. Editing keys stay here.
const EDITING_KEYS = new Set(["a", "c", "v", "x", "z", "y"]);