diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index ca90e8f57e..6d7634dd13 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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_state.disabled_by_window.lock().remove(window.label()); + } #[cfg(target_os = "macos")] { page_swipe::forget(window.label()); diff --git a/src/auxiliaryBoot.ts b/src/auxiliaryBoot.ts index b9b14ba561..867d065d63 100644 --- a/src/auxiliaryBoot.ts +++ b/src/auxiliaryBoot.ts @@ -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 { 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"); diff --git a/src/features/vcs/ComparisonTree.tsx b/src/features/vcs/ComparisonTree.tsx index 3e882dcb55..17bbf717f4 100644 --- a/src/features/vcs/ComparisonTree.tsx +++ b/src/features/vcs/ComparisonTree.tsx @@ -34,6 +34,7 @@ export function ComparisonTree({ renderFileIcon, renderDetails, ariaLabel, + autoFocus, openOnActivate = false, getColor, onOpen, @@ -48,6 +49,8 @@ export function ComparisonTree({ renderFileIcon?: (file: F) => ReactNode; renderDetails: (node: FileTreeNode) => 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({ } }} aria-label={ariaLabel} + autoFocus={autoFocus} className={styles.comparisonTree} renderNode={(n) => ( diff --git a/src/features/vcs/DiffWindow.tsx b/src/features/vcs/DiffWindow.tsx index 8c8f71e1c8..5707dd0bdb 100644 --- a/src/features/vcs/DiffWindow.tsx +++ b/src/features/vcs/DiffWindow.tsx @@ -351,7 +351,15 @@ export function DiffWindow() { Loading… ) : ( -
+
)} diff --git a/src/features/vcs/__tests__/diffToolbar.test.tsx b/src/features/vcs/__tests__/diffToolbar.test.tsx index c3260009a5..f092a47094 100644 --- a/src/features/vcs/__tests__/diffToolbar.test.tsx +++ b/src/features/vcs/__tests__/diffToolbar.test.tsx @@ -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( +
+ +
, + ); + try { + await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(2)); + const view = () => EditorView.findFromDOM([...document.querySelectorAll(".cm-editor")][1]!)!; + const host = document.querySelector("[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); + } + }); }); diff --git a/src/features/vcs/__tests__/diffWindowFocus.test.tsx b/src/features/vcs/__tests__/diffWindowFocus.test.tsx new file mode 100644 index 0000000000..8d697e7fad --- /dev/null +++ b/src/features/vcs/__tests__/diffWindowFocus.test.tsx @@ -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 } } }) => ( +
+
+
+ ), +})); +vi.mock("../store", async (original) => ({ + ...(await original()), + 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("[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(); + + 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(); + 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(); +}); diff --git a/src/features/vcs/operations.tsx b/src/features/vcs/operations.tsx index 496b58ef37..f50300db53 100644 --- a/src/features/vcs/operations.tsx +++ b/src/features/vcs/operations.tsx @@ -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} diff --git a/src/platform/initialFocus.test.ts b/src/platform/initialFocus.test.ts new file mode 100644 index 0000000000..e975632eac --- /dev/null +++ b/src/platform/initialFocus.test.ts @@ -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('
Loading…
'); + await settle(); + expect(document.activeElement).toBe(document.body); + + add('
'); + 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('
'); + add(''); + install(); + expect(document.activeElement?.id).toBe("search"); +}); + +it("falls back to a tree, then to editor text, when the window marks nothing", () => { + add('
'); + expect(initialFocusTarget(document)?.id).toBe("tree"); + document.getElementById("tree")!.remove(); + expect(initialFocusTarget(document)?.id).toBe("text"); +}); + +it("skips hidden and inert content", () => { + add( + '
', + ); + add('
'); + expect(initialFocusTarget(document)?.id).toBe("list"); +}); + +it("keeps focus restoration pending until a delayed replacement accepts it", async () => { + const host = add( + '
', + ); + install(); + (host.querySelector("#old") as HTMLElement).focus(); + host.innerHTML = ""; + await settle(); + expect(document.activeElement).toBe(document.body); + + host.innerHTML = '
'; + await settle(); + expect(document.activeElement?.id).toBe("replacement"); +}); + +it("tries fallback candidates when the first is disabled or CSS-hidden", async () => { + install(); + add( + '
', + ); + await settle(); + expect(document.activeElement?.id).toBe("tree"); +}); + +it("never takes focus from what has it", async () => { + const holder = add(''); + (holder.querySelector("#typed") as HTMLInputElement).focus(); + install(); + add('
'); + 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( + '
', + ); + 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('
'); + install(); + expect(document.activeElement?.id).toBe("host"); + document.getElementById("gap")!.dispatchEvent(new Event("pointerdown", { bubbles: true })); + (document.activeElement as HTMLElement).blur(); + add("later content"); + 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('
'); + 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("

nothing focusable

"); + vi.advanceTimersByTime(15_000); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("data-autofocus")); +}); diff --git a/src/platform/initialFocus.ts b/src/platform/initialFocus.ts new file mode 100644 index 0000000000..5fd9f55323 --- /dev/null +++ b/src/platform/initialFocus.ts @@ -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 { + for (const selector of TARGETS) + for (const el of root.querySelectorAll(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); + }; +} diff --git a/src/ui/Tree.test.tsx b/src/ui/Tree.test.tsx index a148e6cfc6..7d85501d34 100644 --- a/src/ui/Tree.test.tsx +++ b/src/ui/Tree.test.tsx @@ -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); + }); +}); diff --git a/src/ui/Tree.tsx b/src/ui/Tree.tsx index 582aa563b3..c3d4851cdf 100644 --- a/src/ui/Tree.tsx +++ b/src/ui/Tree.tsx @@ -164,6 +164,8 @@ export interface TreeProps { /** 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; /** Context key set while the tree itself has keyboard focus. */ focusContext?: string; @@ -869,6 +871,7 @@ export function Tree(props: TreeProps) { 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)