diff --git a/e2e/toolbarCustomization.spec.ts b/e2e/toolbarCustomization.spec.ts
index 725f497bfc..748b54a8f6 100644
--- a/e2e/toolbarCustomization.spec.ts
+++ b/e2e/toolbarCustomization.spec.ts
@@ -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");
+});
diff --git a/src/workbench/ContributedToolbar.test.tsx b/src/workbench/ContributedToolbar.test.tsx
index 9a7fe97858..795a36a6c3 100644
--- a/src/workbench/ContributedToolbar.test.tsx
+++ b/src/workbench/ContributedToolbar.test.tsx
@@ -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();
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(
+ <>
+
+
+ >,
+ );
+ 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();
+});
diff --git a/src/workbench/ContributedToolbar.tsx b/src/workbench/ContributedToolbar.tsx
index 77cc0f64c2..59ae9748b0 100644
--- a/src/workbench/ContributedToolbar.tsx
+++ b/src/workbench/ContributedToolbar.tsx
@@ -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}
/>
))}
>
diff --git a/src/workbench/TitleBar.test.tsx b/src/workbench/TitleBar.test.tsx
index 5138014604..7ef55fc6e4 100644
--- a/src/workbench/TitleBar.test.tsx
+++ b/src/workbench/TitleBar.test.tsx
@@ -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(
+ <>
+
+
+ >,
+ );
+ 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);
+ }
+ });
+});
diff --git a/src/workbench/TitleBar.tsx b/src/workbench/TitleBar.tsx
index 445f30760a..37f4d43916 100644
--- a/src/workbench/TitleBar.tsx
+++ b/src/workbench/TitleBar.tsx
@@ -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
);
diff --git a/src/workbench/focus.ts b/src/workbench/focus.ts
index 28e47410f1..3323243cc6 100644
--- a/src/workbench/focus.ts
+++ b/src/workbench/focus.ts
@@ -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.