fix(windows): open every auxiliary window with keyboard focus in its content (#8113)

A diff opened with Show Diff in New Window came up with nothing focused, so the first F7 / Shift+F7 did nothing until a click; the comparison window's file tree took no keys either. installInitialFocus now runs for every auxiliary window: it tries focus candidates ([data-autofocus], editor hosts, trees, grids, lists, editor text) until one accepts focus, restores focus when the focused content is replaced (the next diff), skips disabled, hidden and inert content, and stops once the user acts. The diff window's body forwards focus to the diff editor and the comparison tree is marked as its window's focus target.

Also forgets a closed window's cached menu state.

Refs #7250. Supersedes #7282.

Co-authored-by: albince-mi <[email protected]>
Co-authored-by: arookieofc-ai <[email protected]>
Цей коміт міститься в:
authored and GitHub committed 2026-12-05 02:39:21 +08:00
1 джерело f49302d365
коміт 84ae5bb179
11 files changed
+406 -2

No files matched your search

+3
Переглянути файл
@@ -330,6 +330,9 @@ pub fn run() {
project.agents.unsubscribe(window.label());
}
window_zoom::forget(window.label());
if let Some(menu_state) = window.try_state::<menu::MenuState>() {
menu_state.disabled_by_window.lock().remove(window.label());
}
#[cfg(target_os = "macos")]
{
page_swipe::forget(window.label());
+4 -1
Переглянути файл
@@ -1,13 +1,16 @@
import { registerLocalizedActions } from "./features/app/locale";
import { sharedWindowActions } from "./features/app/sharedWindowActions";
import type { AuxKind } from "./platform/auxWindow";
import { installInitialFocus } from "./platform/initialFocus";
import { mountWindowRoot } from "./windowBoot";
import { activateSecondaryWindow } from "./workbench/activateSecondary";
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
activateSecondaryWindow();
// Every auxiliary window, whatever its kind, can reach the other windows and go full screen.
// Every auxiliary window, whatever its kind, can reach the other windows, go full screen,
// and opens with keyboard focus in its content.
registerLocalizedActions(sharedWindowActions);
installInitialFocus();
switch (aux.kind) {
case "settings": {
const { bootSettingsWindow } = await import("./settingsWindowBoot");
+4
Переглянути файл
@@ -34,6 +34,7 @@ export function ComparisonTree<F>({
renderFileIcon,
renderDetails,
ariaLabel,
autoFocus,
openOnActivate = false,
getColor,
onOpen,
@@ -48,6 +49,8 @@ export function ComparisonTree<F>({
renderFileIcon?: (file: F) => ReactNode;
renderDetails: (node: FileTreeNode<F>) => ReactNode;
ariaLabel: string;
/** The comparison window's initial focus. */
autoFocus?: boolean;
openOnActivate?: boolean;
getColor?: (entry: F) => string | undefined;
onOpen?: () => void;
@@ -113,6 +116,7 @@ export function ComparisonTree<F>({
}
}}
aria-label={ariaLabel}
autoFocus={autoFocus}
className={styles.comparisonTree}
renderNode={(n) => (
<span className={styles.fileRow} style={{ flex: 1, padding: 0 }}>
+9 -1
Переглянути файл
@@ -351,7 +351,15 @@ export function DiffWindow() {
<T>Loading…</T>
</div>
) : (
<div className={styles.comparisonWindowBody} inert={closing}>
<div
className={styles.comparisonWindowBody}
inert={closing}
// The window's focus target (`installInitialFocus`), also for each next diff: like an editor
// tab's host, it hands focus on to the diff's text, so F7 and the other diff keys work at once.
data-autofocus=""
data-editor-focus=""
tabIndex={-1}
>
<DiffEditor key={diffInput(data).key} input={diffInput(data)} />
</div>
)}
+30
Переглянути файл
@@ -888,4 +888,34 @@ describe("Diff navigation caret", () => {
useKeymap.setState(keymap);
}
});
it("runs the first F7 in the real diff editor when its host receives the window's initial focus", async () => {
const keymap = useKeymap.getState();
applyKeymapSettings("intellij-macos", {});
const unregister = registerCompareActions();
const uninstall = installKeyboardDispatcher(window);
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "split" }));
texts.HEAD = "a\nb\nc\n";
texts.abc123 = "a\nB\nc\n";
const mounted = render(
<div data-editor-focus="" tabIndex={-1}>
<DiffEditor input={input} />
</div>,
);
try {
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(2));
const view = () => EditorView.findFromDOM([...document.querySelectorAll<HTMLElement>(".cm-editor")][1]!)!;
const host = document.querySelector<HTMLElement>("[data-editor-focus]")!;
host.focus();
await waitFor(() => expect(view().hasFocus).toBe(true));
view().dispatch({ selection: { anchor: 0 } });
fireEvent.keyDown(view().contentDOM, { key: "F7", code: "F7" });
await waitFor(() => expect(view().state.doc.lineAt(view().state.selection.main.head).number).toBe(2));
} finally {
mounted.unmount();
uninstall();
unregister();
useKeymap.setState(keymap);
}
});
});
+87
Переглянути файл
@@ -0,0 +1,87 @@
import { act, render, screen, waitFor } from "@testing-library/react";
import { emit } from "@tauri-apps/api/event";
import { clearMocks, mockIPC, mockWindows } from "@tauri-apps/api/mocks";
import { afterEach, expect, it, vi } from "vitest";
import { installInitialFocus } from "@/platform/initialFocus";
vi.mock("../DiffEditor", () => ({
DiffEditor: (props: { input: { data: { path: string } } }) => (
<div data-testid="diff-view" data-path={props.input.data.path}>
<div data-testid="diff-text" tabIndex={-1} />
</div>
),
}));
vi.mock("../store", async (original) => ({
...(await original<typeof import("../store")>()),
refreshNow: async () => {},
}));
vi.mock("@/editor/core/embeddedDocuments", () => ({
activateEmbeddedDocuments: () => ({ dirty: () => false, save: async () => {}, dispose: async () => {} }),
}));
import { activateDiffWindow, DiffWindow } from "../DiffWindow";
import { workingDiffData, type DiffData } from "../diffInput";
let uninstallFocus: (() => void) | undefined;
afterEach(() => {
uninstallFocus?.();
clearMocks();
});
/** Answers the diff window's start-up requests; each `openidea://launch` takes the next of `launches`. */
function mockDiffWindowHost(launches: DiffData[]) {
mockWindows("diff-main-1");
mockIPC(
(command) => {
switch (command) {
case "window_take_launch": {
const pending = launches.shift();
return pending ? { diffWindow: pending } : null;
}
case "project_current":
return { name: "repo", root: "/repo", settings: { files: { autoSave: false } } };
case "vcs_roots":
return [{ root: "/repo" }];
}
return null;
},
{ shouldMockEvents: true },
);
}
/** The element the diff's text takes focus from: DiffEditor hands a focused host on to its text. */
const host = (view: HTMLElement) => view.closest<HTMLElement>("[data-editor-focus]");
/** Boots the window as `bootAuxiliaryWindow` does: the shared focus rule, then the diff window. */
function bootDiffWindow() {
uninstallFocus = installInitialFocus(window, () => {});
return activateDiffWindow("main");
}
it("focuses the diff as soon as it shows, so the first F7 goes to it (#7250's separate window)", async () => {
mockDiffWindowHost([workingDiffData("/repo/a.ts")]);
const stop = bootDiffWindow();
render(<DiffWindow />);
const view = await screen.findByTestId("diff-view");
expect(host(view)).not.toBeNull();
await waitFor(() => expect(document.activeElement).toBe(host(view)));
stop();
});
it("focuses the next diff the window is handed in place of the one that had focus", async () => {
const launches = [workingDiffData("/repo/a.ts")];
mockDiffWindowHost(launches);
const stop = bootDiffWindow();
render(<DiffWindow />);
await waitFor(() => expect(document.activeElement).toBe(host(screen.getByTestId("diff-view"))));
// As after F7 or a click: focus in the first diff's text.
act(() => screen.getByTestId("diff-text").focus());
launches.push(workingDiffData("/repo/b.ts"));
await act(() => emit("openidea://launch"));
await waitFor(() => expect(screen.getByTestId("diff-view").dataset.path).toBe("/repo/b.ts"));
await waitFor(() => expect(document.activeElement).toBe(host(screen.getByTestId("diff-view"))));
stop();
});
+2
Переглянути файл
@@ -1357,6 +1357,8 @@ export function ChangesBetweenDialog({
renderFileIcon={listOnly && !to ? renderWorktreeFileIcon : undefined}
getColor={(f) => KIND_COLOR[f.kind === "untracked" ? "added" : f.kind]}
ariaLabel="Changed files"
// In its own window the tree is where keyboard focus starts.
autoFocus={native}
inlineDiff={!listOnly}
openOnActivate={listOnly}
onShowDiff={showFileDiff}
+131
Переглянути файл
@@ -0,0 +1,131 @@
import { afterEach, expect, it, vi } from "vitest";
import { initialFocusTarget, installInitialFocus } from "./initialFocus";
let uninstall: (() => void) | undefined;
afterEach(() => {
uninstall?.();
uninstall = undefined;
document.body.innerHTML = "";
vi.useRealTimers();
});
const install = (warn = vi.fn()) => {
uninstall = installInitialFocus(window, warn);
return warn;
};
/** Lets the mutation observer and microtasks run. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
function add(html: string): HTMLElement {
const holder = document.createElement("div");
holder.innerHTML = html;
document.body.append(holder);
return holder;
}
it("focuses the window's content once it has loaded, not before", async () => {
install();
expect(document.activeElement).toBe(document.body);
add('<div role="status">Loading…</div>');
await settle();
expect(document.activeElement).toBe(document.body);
add('<div data-autofocus tabindex="-1" id="target"></div>');
await settle();
expect(document.activeElement?.id).toBe("target");
});
it("prefers the window's data-autofocus target over a tree or an editor before it", () => {
add('<div class="cm-content" contenteditable="true"></div><div role="tree" tabindex="0"></div>');
add('<input data-autofocus id="search">');
install();
expect(document.activeElement?.id).toBe("search");
});
it("falls back to a tree, then to editor text, when the window marks nothing", () => {
add('<div class="cm-content" contenteditable="true" id="text"></div><div role="tree" tabindex="0" id="tree"></div>');
expect(initialFocusTarget(document)?.id).toBe("tree");
document.getElementById("tree")!.remove();
expect(initialFocusTarget(document)?.id).toBe("text");
});
it("skips hidden and inert content", () => {
add(
'<div hidden><div data-autofocus tabindex="-1"></div></div><div inert><div role="tree" tabindex="0"></div></div>',
);
add('<div role="listbox" tabindex="0" id="list"></div>');
expect(initialFocusTarget(document)?.id).toBe("list");
});
it("keeps focus restoration pending until a delayed replacement accepts it", async () => {
const host = add(
'<div data-autofocus tabindex="-1" id="host"><div class="cm-content" contenteditable="true" id="old"></div></div>',
);
install();
(host.querySelector("#old") as HTMLElement).focus();
host.innerHTML = "";
await settle();
expect(document.activeElement).toBe(document.body);
host.innerHTML = '<div class="cm-content" contenteditable="true" id="replacement"></div>';
await settle();
expect(document.activeElement?.id).toBe("replacement");
});
it("tries fallback candidates when the first is disabled or CSS-hidden", async () => {
install();
add(
'<button data-autofocus disabled id="disabled"></button><div data-autofocus tabindex="-1" id="css-hidden" style="display:none"></div><div role="tree" tabindex="0" id="tree"></div>',
);
await settle();
expect(document.activeElement?.id).toBe("tree");
});
it("never takes focus from what has it", async () => {
const holder = add('<input id="typed">');
(holder.querySelector("#typed") as HTMLInputElement).focus();
install();
add('<div data-autofocus tabindex="-1"></div>');
await settle();
expect(document.activeElement?.id).toBe("typed");
});
it("focuses the replacement when the focused content is removed (the window's next diff)", async () => {
const host = add(
'<div data-autofocus tabindex="-1" id="host"><div class="cm-content" contenteditable="true" id="old"></div></div>',
);
install();
(host.querySelector("#old") as HTMLElement).focus();
host.querySelector("#old")!.remove();
await settle();
await settle();
expect(document.activeElement?.id).toBe("host");
});
it("leaves focus alone after a click on empty space", async () => {
add('<div data-autofocus tabindex="-1" id="host"></div><div id="gap"></div>');
install();
expect(document.activeElement?.id).toBe("host");
document.getElementById("gap")!.dispatchEvent(new Event("pointerdown", { bubbles: true }));
(document.activeElement as HTMLElement).blur();
add("<span>later content</span>");
await settle();
await settle();
expect(document.activeElement).toBe(document.body);
});
it("stops waiting once the user does something", async () => {
install();
document.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
add('<div data-autofocus tabindex="-1"></div>');
await settle();
expect(document.activeElement).toBe(document.body);
});
it("warns about a window that never offers anything to focus", () => {
vi.useFakeTimers();
const warn = install();
add("<p>nothing focusable</p>");
vi.advanceTimersByTime(15_000);
expect(warn).toHaveBeenCalledWith(expect.stringContaining("data-autofocus"));
});
+124
Переглянути файл
@@ -0,0 +1,124 @@
/**
* Keyboard focus for a window that has none. A new window's page starts with nothing focused, and
* keys that need a focused element (F7 in a diff, arrows in a tree) do nothing until a click.
* Every window used to place focus itself, and the ones that didn't shipped without it (the diff
* window, the comparison window). This places it for them:
*
* - while the window opens, as soon as its content can take focus;
* - when the focused element is removed (the content replaced, such as the next diff).
*
* A window marks where its focus belongs with `[data-autofocus]` (Settings and the dialog windows
* already do). Without one, the first editor host, tree, grid, list or editor text gets it.
* Focus the user moved stays where it is: a click on empty space leaves nothing focused on purpose.
*/
/** In order of preference; within each, the first in document order. */
const TARGETS = [
"[data-autofocus]",
"[data-editor-focus]",
'[role="tree"]',
'[role="treegrid"]',
'[role="grid"]',
'[role="listbox"]',
".cm-content",
];
/** How long a window may take to show content that can take focus. */
const OPENING_MS = 15_000;
const nothingFocused = (doc: Document) => !doc.activeElement || doc.activeElement === doc.body;
function usable(el: HTMLElement): boolean {
if (!el.isConnected || el.closest("[hidden], [inert], [aria-hidden='true']")) return false;
if (el.matches(":disabled")) return false;
for (let node: HTMLElement | null = el; node; node = node.parentElement) {
const style = el.ownerDocument.defaultView?.getComputedStyle(node);
if (!style) continue;
if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
}
const editable = el.isContentEditable || el.getAttribute("contenteditable") === "true";
return editable || el.hasAttribute("tabindex") || el.tabIndex >= 0;
}
function* focusTargets(root: ParentNode): Generator<HTMLElement> {
for (const selector of TARGETS)
for (const el of root.querySelectorAll<HTMLElement>(selector)) if (usable(el)) yield el;
}
/** Where focus goes in `root` when nothing has it, or null when nothing there can take it. */
export function initialFocusTarget(root: ParentNode): HTMLElement | null {
return focusTargets(root).next().value ?? null;
}
/** Tries candidates in order until one accepts focus; disabled or CSS-hidden ones don't block fallbacks. */
function focusInitialTarget(root: ParentNode, doc: Document): boolean {
for (const el of focusTargets(root)) {
el.focus({ preventScroll: true });
if (!nothingFocused(doc)) return true;
}
return false;
}
/**
* Installs the rule on `win`'s document. `warn` reports a window whose content never offered a
* focus target while opening (development builds), so a new kind of window can't ship without one.
*/
export function installInitialFocus(
win: Window = window,
warn: (message: string) => void = import.meta.env.DEV ? (m) => console.warn(m) : () => {},
): () => void {
const doc = win.document;
/** Until something has focus, the user acts, or the window gives up waiting. */
let opening = true;
/** The element that last had focus: once it is gone with nothing focused, the content was replaced. */
let last: Element | null = null;
/** A replacement is still awaited: keep trying until one actually accepts focus. */
let restoring = false;
const place = () => !nothingFocused(doc) || focusInitialTarget(doc, doc);
const endOpening = () => {
opening = false;
clearTimeout(deadline);
};
const deadline = setTimeout(() => {
if (!opening) return;
endOpening();
warn("This window opened with nothing to focus: mark its focus target with data-autofocus.");
}, OPENING_MS);
const observer = new MutationObserver(() => {
if (opening) {
if (place()) endOpening();
} else if (restoring) {
if (place()) restoring = false;
} else if (last && !last.isConnected && nothingFocused(doc)) {
restoring = !place();
}
});
const onFocusIn = (e: FocusEvent) => {
last = e.target as Element;
};
// The user took over: leave focus where they put it.
const onInput = () => {
if (opening) endOpening();
restoring = false;
};
doc.addEventListener("focusin", onFocusIn, true);
doc.addEventListener("pointerdown", onInput, true);
doc.addEventListener("keydown", onInput, true);
observer.observe(doc.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["hidden", "inert"],
});
if (place()) endOpening();
return () => {
endOpening();
observer.disconnect();
doc.removeEventListener("focusin", onFocusIn, true);
doc.removeEventListener("pointerdown", onInput, true);
doc.removeEventListener("keydown", onInput, true);
};
}
+9
Переглянути файл
@@ -775,3 +775,12 @@ describe("Tree double-click", () => {
expect(labels(tree)).toEqual(["src", "main", "util.ts", "README.md"]);
});
});
describe("Tree autoFocus", () => {
it("marks the tree as its window's focus target only when asked", () => {
const { tree, unmount } = setup({ autoFocus: true });
expect(tree.hasAttribute("data-autofocus")).toBe(true);
unmount();
expect(setup().tree.hasAttribute("data-autofocus")).toBe(false);
});
});
+3
Переглянути файл
@@ -164,6 +164,8 @@ export interface TreeProps<T> {
/** CSS colour the row background is tinted with (File Colors). */
rowTint?: (node: T) => string | undefined;
"aria-label"?: string;
/** The window's or dialog's initial focus (`[data-autofocus]`). */
autoFocus?: boolean;
handleRef?: Ref<TreeHandle>;
/** Context key set while the tree itself has keyboard focus. */
focusContext?: string;
@@ -869,6 +871,7 @@ export function Tree<T>(props: TreeProps<T>) {
ref={scrollRef}
role="tree"
aria-label={given(props["aria-label"])}
data-autofocus={props.autoFocus ? "" : undefined}
aria-multiselectable={multiSelect || undefined}
aria-activedescendant={
leadRow && !leadRow.loading && virtualizer.getVirtualItems().some((v) => v.index === leadIndex)