fix(toolbar): keep editor focus when clicking toolbar action buttons (#7792)

Editor actions on the main toolbar (Collapse All, Expand All) and plugin toolbar slots did nothing when clicked: the button took focus on mousedown, so editorFocus was false by the time the click dispatched and the action's when clause rejected it. A press on a toolbar action now leaves focus where it is, except while a tool window has focus, where actions gated on !toolWindowFocus (Reformat Code, Select Next Tab) still need the click to leave the tool window. Covers the main toolbar and contributed toolbars.

Closes #7758

Co-authored-by: swift98 <[email protected]>
Co-authored-by: og-orca <[email protected]>
Цей коміт міститься в:
SwiftChenтаog-orca authored and GitHub committed 2026-12-03 19:30:00 +08:00
1 джерело 0bda7b194b
коміт 9e7f842caf
6 files changed
+143 -2

No files matched your search

+56 -1
Переглянути файл
@@ -1,4 +1,4 @@
import { expect, test } from "./fixtures";
import { expect, openFromTree, test } from "./fixtures";
test("Customize Main Toolbar keeps layout actions above the groups and stacks them in a narrow window", async ({
workbench: page,
@@ -136,3 +136,58 @@ test("the project colour gradient follows the Project widget", async ({ workbenc
await expect(icon).toHaveCount(0);
await expect.poll(anchor).toBe("");
});
test("main toolbar editor actions keep editor focus and run Collapse All / Expand All", async ({ workbench: page }) => {
const editor = await openFromTree(page, "App.tsx");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(
[
"export function formatOrder(total: number) {",
' const currency = "USD";',
" return currency + total.toFixed(2);",
"}",
].join("\n"),
);
await expect(content).toBeFocused();
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
appearance: {
...settings?.appearance,
mainToolbar: {
left: ["project"],
center: ["action:code.foldAll", "action:code.unfoldAll", "action:editor.nextTab"],
right: ["action:navigate.searchEverywhere"],
hidden: [],
},
},
},
});
});
const bar = page.locator("header").first();
await bar.getByRole("button", { name: "Collapse All", exact: true }).click({ delay: 80 });
await expect(editor.locator(".cm-foldPlaceholder")).toHaveCount(1);
await expect(content).toBeFocused();
await bar.getByRole("button", { name: "Expand All", exact: true }).click({ delay: 80 });
await expect(editor.locator(".cm-foldPlaceholder")).toHaveCount(0);
await expect(content).toBeFocused();
// With focus in a tool window, a toolbar click still leaves it so `!toolWindowFocus` actions run.
await openFromTree(page, "README.md");
const activeTab = page.locator("[role=tab][aria-selected=true]");
await expect(activeTab).toContainText("README.md");
const projectTree = page.getByRole("tree", { name: "Project" });
await projectTree.click();
await expect(projectTree).toBeFocused();
await bar.getByRole("button", { name: "Select Next Tab", exact: true }).click({ delay: 80 });
await expect(activeTab).toContainText("App.tsx");
});
+25
Переглянути файл
@@ -1,5 +1,6 @@
import { afterEach, expect, it, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { ContributedToolbar } from "./ContributedToolbar";
import { registerMenuSlotItem } from "./contributions";
import { registerAction } from "@/platform/actions";
@@ -31,3 +32,27 @@ it("renders toolbar slots with command icons and honors when clauses", () => {
render(<ContributedToolbar slot="editor.title" />);
expect(screen.queryByRole("button")).toBeNull();
});
it("takes focus on a click from a tool window only", async () => {
const focused: (Element | null)[] = [];
offs.push(
registerAction({ id: "test.focus", title: "Act", run: () => void focused.push(document.activeElement) }),
registerMenuSlotItem("editor.title", { action: "test.focus", label: "Act", icon: "run" }),
);
render(
<>
<textarea aria-label="Editor" />
<ContributedToolbar slot="editor.title" />
</>,
);
const editor = screen.getByRole("textbox", { name: "Editor" });
const button = screen.getByRole("button", { name: "Act" });
editor.focus();
await userEvent.click(button);
expect(focused).toEqual([editor]);
expect(editor).toHaveFocus();
// Editor actions are off while a tool window has focus, so there the button takes it.
setContext("toolWindowFocus", true);
offs.push(() => setContext("toolWindowFocus", false));
await userEvent.click(button);
expect(button).toHaveFocus();
});
+2
Переглянути файл
@@ -3,6 +3,7 @@ import { useActions } from "@/platform/actions";
import { useContextKeys, evaluateWhen } from "@/platform/context";
import { IconButton } from "@/ui";
import { useMenuSlotItems } from "./contributions";
import { keepFocusOnPress } from "./focus";
export function ContributedToolbar({ slot }: { slot: string }) {
const actions = useActions((s) => s.actions);
const items = useMenuSlotItems((s) => s.slots[slot]);
@@ -19,6 +20,7 @@ export function ContributedToolbar({ slot }: { slot: string }) {
actionArg={i.arg}
title={i.label}
size="small"
onMouseDown={keepFocusOnPress}
/>
))}
</>
+49
Переглянути файл
@@ -6,7 +6,9 @@ vi.mock("./WindowControls", () => ({
),
}));
import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { registerActions } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { commands, type Settings } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { usePlatform } from "@/platform/platformInfo";
@@ -252,3 +254,50 @@ describe("compact window header", () => {
expect(document.querySelector("header[data-titlebar='compact']")!.textContent).toBe("notes.txt");
});
});
describe("main toolbar action buttons", () => {
it("keeps editor focus on click, and takes focus when a tool window has it", async () => {
const savedProject = useProject.getState();
const focused: (Element | null)[] = [];
disposers.push(
registerActions([
{
id: "code.foldAll",
title: "Collapse All",
category: "Folding",
icon: "collapse-all",
run: () => void focused.push(document.activeElement),
},
]),
);
useProject.setState({
settings: {
appearance: {
mainToolbar: { left: [], center: ["action:code.foldAll"], right: [], hidden: [] },
},
} as Settings,
});
try {
render(
<>
<TitleBar />
<textarea aria-label="Editor" />
</>,
);
const editor = screen.getByRole("textbox", { name: "Editor" });
const button = screen.getByRole("button", { name: "Collapse All" });
editor.focus();
await userEvent.click(button);
expect(focused).toEqual([editor]);
expect(editor).toHaveFocus();
// Actions gated on `!toolWindowFocus` need the click to leave the tool window.
setContext("toolWindowFocus", true);
disposers.push(() => setContext("toolWindowFocus", false));
await userEvent.click(button);
expect(button).toHaveFocus();
} finally {
useProject.setState(savedProject);
}
});
});
+2
Переглянути файл
@@ -33,6 +33,7 @@ import { currentThemeChoice, useThemeOverride } from "./theme";
import styles from "./TitleBar.module.css";
import { useNativeTitlebar } from "./nativeTitlebar";
import { useDocumentTitle } from "./documentTitle";
import { keepFocusOnPress } from "./focus";
import { windowDragRegion } from "./window-drag";
import { useToolbarCenter } from "./toolbarCenter";
import { useProjectGradientAnchor } from "./projectGradient";
@@ -291,6 +292,7 @@ function ToolbarEntry({ id, items }: { id: string; items: ReadonlyMap<string, Ti
shortcut={shortcutLabel(action.id) ?? (action.id === "navigate.searchEverywhere" ? "⇧⇧" : undefined)}
iconSize={iconSize}
className={styles.tool}
onMouseDown={keepFocusOnPress}
/>
</div>
);
+9 -1
Переглянути файл
@@ -1,5 +1,5 @@
/** Focus routing between tool windows and the editor area. */
import { setContext, useContextKeys } from "@/platform/context";
import { getContext, setContext, useContextKeys } from "@/platform/context";
import { syncFocusScope } from "@/ui/focusScope";
import { maybeEditorService } from "./contributions";
@@ -55,6 +55,14 @@ function dropEditorCaret(e: FocusEvent) {
if (selection?.anchorNode && editor.contains(selection.anchorNode)) selection.removeAllRanges();
}
/**
* A press on a toolbar action leaves focus where it is, so editor actions find the editor focused.
* From a tool window it does take focus, because editor actions are off while a tool window has it.
*/
export function keepFocusOnPress(e: { preventDefault(): void }): void {
if (!getContext().toolWindowFocus) e.preventDefault();
}
/**
* Tracks which workbench part holds focus and publishes `toolWindowFocus`,
* `activeToolWindow` and `editorAreaFocus`. Returns an uninstaller.