π OpenHands: AI-Driven Development
fix(modals): move focus into ModalBackdrop dialogs and keep it there (#18400)
Engel Nyst3e686de2610e
diff --git a/__tests__/components/features/skills/skill-detail-modal.test.tsx b/__tests__/components/features/skills/skill-detail-modal.test.tsxindex 58c232b504..09b54040e1 100644--- a/__tests__/components/features/skills/skill-detail-modal.test.tsx+++ b/__tests__/components/features/skills/skill-detail-modal.test.tsx@@ -1,3 +1,4 @@+import { useState } from "react";import { render, screen, within, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { beforeEach, describe, expect, it, vi } from "vitest";@@ -178,18 +179,26 @@ describe("SkillDetailModal", () => {sessionStorage.setItem(HOME_PROMPT_DRAFT_KEY, "earlier home draft");useConversationStore.getState().setMessageToSend("for a conversation");const skill = buildSkill({ name: "docker" });-- renderWithProviders(- <>- <CustomChatInput onSubmit={vi.fn()} />- <SkillDetailModal- skill={skill}- enabled- onToggle={vi.fn()}- onClose={vi.fn()}- />- </>,- );+ // The modal really closes, as on the Skills page; an open modal would keep+ // focus inside itself rather than let the composer behind it take it.+ function SkillsPageWithComposer() {+ const [isOpen, setIsOpen] = useState(true);+ return (+ <>+ <CustomChatInput onSubmit={vi.fn()} />+ {isOpen ? (+ <SkillDetailModal+ skill={skill}+ enabled+ onToggle={vi.fn()}+ onClose={() => setIsOpen(false)}+ />+ ) : null}+ </>+ );+ }++ renderWithProviders(<SkillsPageWithComposer />);const composer = screen.getByTestId("chat-input");expect(composer).toHaveTextContent("earlier home draft");diff --git a/__tests__/components/shared/modals/modal-backdrop.test.tsx b/__tests__/components/shared/modals/modal-backdrop.test.tsxindex 672c50aadd..3698a0d906 100644--- a/__tests__/components/shared/modals/modal-backdrop.test.tsx+++ b/__tests__/components/shared/modals/modal-backdrop.test.tsx@@ -1,7 +1,10 @@+import React from "react";+import { createPortal } from "react-dom";import { describe, expect, it, vi } from "vitest";import { render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";+import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";describe("ModalBackdrop", () => {@@ -10,7 +13,10 @@ describe("ModalBackdrop", () => {// containing block for `position: fixed` descendants and trap the// modal inside it (the OnboardingModal / InstallServerModal bug).render(- <div data-testid="transformed-ancestor" style={{ transform: "translateX(0)" }}>+ <div+ data-testid="transformed-ancestor"+ style={{ transform: "translateX(0)" }}+ ><ModalBackdrop onClose={vi.fn()}><p>modal content</p></ModalBackdrop>@@ -111,3 +117,223 @@ describe("ModalBackdrop", () => {expect(layerOf("elevated-modal")).toBeGreaterThan(layerOf("default-modal"));});});++describe("ModalBackdrop focus management", () => {+ function PageWithModal({+ renderModalContent,+ }: {+ renderModalContent: (close: () => void) => React.ReactNode;+ }) {+ const [isOpen, setIsOpen] = React.useState(false);+ const close = () => setIsOpen(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ open+ </button>+ <input aria-label="page composer" />+ {isOpen ? (+ <ModalBackdrop onClose={close} aria-label="test dialog">+ {renderModalContent(close)}+ </ModalBackdrop>+ ) : null}+ </>+ );+ }++ const threeButtons = (close: () => void) => (+ <>+ <button type="button" onClick={close}>+ first+ </button>+ <button type="button">middle</button>+ <button type="button">last</button>+ </>+ );++ it("moves focus to the first tabbable control inside the dialog when it opens", async () => {+ const user = userEvent.setup();+ render(<PageWithModal renderModalContent={threeButtons} />);++ await user.click(screen.getByRole("button", { name: "open" }));++ expect(screen.getByRole("button", { name: "first" })).toHaveFocus();+ });++ it("keeps focus on a control the dialog content focuses itself", async () => {+ const user = userEvent.setup();+ render(+ <PageWithModal+ renderModalContent={() => (+ <>+ <button type="button">first</button>+ {/* eslint-disable-next-line jsx-a11y/no-autofocus */}+ <input aria-label="name" autoFocus />+ </>+ )}+ />,+ );++ await user.click(screen.getByRole("button", { name: "open" }));++ expect(screen.getByRole("textbox", { name: "name" })).toHaveFocus();+ });++ it("keeps the content's own focus and restores the opener under StrictMode", async () => {+ const user = userEvent.setup();+ render(+ <React.StrictMode>+ <PageWithModal+ renderModalContent={(close) => (+ <>+ <button type="button" onClick={close}>+ first+ </button>+ {/* eslint-disable-next-line jsx-a11y/no-autofocus */}+ <input aria-label="name" autoFocus />+ </>+ )}+ />+ </React.StrictMode>,+ );+ const opener = screen.getByRole("button", { name: "open" });++ await user.click(opener);+ expect(screen.getByRole("textbox", { name: "name" })).toHaveFocus();++ await user.click(screen.getByRole("button", { name: "first" }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(opener).toHaveFocus();+ });++ it("wraps Tab and Shift+Tab inside the dialog and skips inert controls", async () => {+ const user = userEvent.setup();+ render(+ <PageWithModal+ renderModalContent={(close) => (+ <>+ {threeButtons(close)}+ <div inert>+ <button type="button">hidden panel</button>+ </div>+ </>+ )}+ />,+ );+ await user.click(screen.getByRole("button", { name: "open" }));+ const first = screen.getByRole("button", { name: "first" });+ const last = screen.getByRole("button", { name: "last" });++ await user.tab({ shift: true });+ expect(last).toHaveFocus();++ await user.tab();+ expect(first).toHaveFocus();+ });++ it("pulls focus back when something behind the dialog takes it", async () => {+ const user = userEvent.setup();+ render(<PageWithModal renderModalContent={threeButtons} />);+ await user.click(screen.getByRole("button", { name: "open" }));++ screen.getByRole("textbox", { name: "page composer" }).focus();++ expect(screen.getByRole("button", { name: "first" })).toHaveFocus();+ });++ it("lets a popover the dialog content portals elsewhere keep focus", async () => {+ const user = userEvent.setup();+ render(+ <PageWithModal+ renderModalContent={() =>+ createPortal(<input aria-label="popover search" />, document.body)+ }+ />,+ );+ await user.click(screen.getByRole("button", { name: "open" }));+ const popoverInput = screen.getByRole("textbox", {+ name: "popover search",+ });++ popoverInput.focus();++ expect(popoverInput).toHaveFocus();+ });++ it("restores focus to the opener when the dialog closes", async () => {+ const user = userEvent.setup();+ render(<PageWithModal renderModalContent={threeButtons} />);+ const opener = screen.getByRole("button", { name: "open" });+ await user.click(opener);++ await user.click(screen.getByRole("button", { name: "first" }));++ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(opener).toHaveFocus();+ });++ function OuterWithRemoval({ removesRow }: { removesRow: boolean }) {+ const [removed, setRemoved] = React.useState(false);+ const [confirming, setConfirming] = React.useState(false);+ return (+ <>+ <button type="button">outer first</button>+ {removed ? null : (+ <button type="button" onClick={() => setConfirming(true)}>+ remove+ </button>+ )}+ {confirming ? (+ <ConfirmationModal+ text="Remove it?"+ onConfirm={() => {+ setRemoved(removesRow);+ setConfirming(false);+ }}+ onCancel={() => setConfirming(false)}+ />+ ) : null}+ </>+ );+ }++ it("gives focus to the topmost of nested dialogs and hands it back on close", async () => {+ const user = userEvent.setup();+ render(+ <PageWithModal+ renderModalContent={() => <OuterWithRemoval removesRow={false} />}+ />,+ );+ await user.click(screen.getByRole("button", { name: "open" }));+ const removeButton = screen.getByRole("button", { name: "remove" });++ await user.click(removeButton);+ const cancel = screen.getByTestId("cancel-button");+ const confirm = screen.getByTestId("confirm-button");+ expect(cancel).toHaveFocus();+ await user.tab();+ expect(confirm).toHaveFocus();+ await user.tab();+ expect(cancel).toHaveFocus();+ await user.tab({ shift: true });+ expect(confirm).toHaveFocus();++ await user.click(cancel);+ expect(removeButton).toHaveFocus();+ });++ it("moves focus into the dialog below when the nested dialog's opener is gone", async () => {+ const user = userEvent.setup();+ render(+ <PageWithModal+ renderModalContent={() => <OuterWithRemoval removesRow />}+ />,+ );+ await user.click(screen.getByRole("button", { name: "open" }));+ await user.click(screen.getByRole("button", { name: "remove" }));++ await user.click(screen.getByTestId("confirm-button"));++ expect(screen.getByRole("button", { name: "outer first" })).toHaveFocus();+ });+});diff --git a/src/components/shared/modals/modal-backdrop.tsx b/src/components/shared/modals/modal-backdrop.tsxindex 24229f9f61..d2b671eed0 100644--- a/src/components/shared/modals/modal-backdrop.tsx+++ b/src/components/shared/modals/modal-backdrop.tsx@@ -1,5 +1,6 @@import React from "react";import { createPortal } from "react-dom";+import { useModalFocus } from "./use-modal-focus";interface ModalBackdropProps {children: React.ReactNode;@@ -23,6 +24,8 @@ export function ModalBackdrop({elevated = false,"aria-label": ariaLabel,}: ModalBackdropProps) {+ const focus = useModalFocus({ elevated });+React.useEffect(() => {if (!closeOnEscape) return undefined;const handleEscape = (e: KeyboardEvent) => {@@ -46,11 +49,18 @@ export function ModalBackdrop({// modal would render trapped inside it instead of overlapping its// parent modal.return createPortal(+ // Focus and key events from the content (including popovers it portals+ // elsewhere) bubble here through the React tree; see useModalFocus.+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions<div+ ref={focus.rootRef}role="dialog"aria-modal="true"aria-label={ariaLabel}- className={`fixed inset-0 flex items-center justify-center ${+ tabIndex={-1}+ onFocus={focus.onFocus}+ onKeyDown={focus.onKeyDown}+ className={`fixed inset-0 flex items-center justify-center outline-none ${elevated ? "z-[70]" : "z-60"}`}>diff --git a/src/components/shared/modals/use-modal-focus.ts b/src/components/shared/modals/use-modal-focus.tsnew file mode 100644index 0000000000..414b48aa47--- /dev/null+++ b/src/components/shared/modals/use-modal-focus.ts@@ -0,0 +1,177 @@+import React from "react";++const TABBABLE_CANDIDATES = [+ "a[href]",+ "area[href]",+ "button",+ "input:not([type='hidden'])",+ "select",+ "textarea",+ "iframe",+ "summary",+ "audio[controls]",+ "video[controls]",+ "[contenteditable]:not([contenteditable='false'])",+ "[tabindex]",+].join(",");++interface OpenModal {+ root: HTMLElement;+ elevated: React.RefObject<boolean>;+}++// Every mounted ModalBackdrop, in mount order. Only the topmost one owns focus.+const openModals: OpenModal[] = [];++function topmostModalRoot(): HTMLElement | null {+ // Elevated modals (the telemetry consent banner) paint above every default+ // modal regardless of mount order, so they own focus the same way.+ const topmost =+ [...openModals].reverse().find((modal) => modal.elevated.current) ??+ openModals.at(-1);+ return topmost?.root ?? null;+}++function isVisible(element: HTMLElement): boolean {+ return typeof element.checkVisibility === "function"+ ? element.checkVisibility({ visibilityProperty: true })+ : true;+}++function isRadioInput(element: Element): element is HTMLInputElement {+ return element instanceof HTMLInputElement && element.type === "radio";+}++/** Controls a user reaches with Tab inside `root`, in DOM order. */+function getTabbableElements(root: HTMLElement): HTMLElement[] {+ const tabbable = Array.from(+ root.querySelectorAll<HTMLElement>(TABBABLE_CANDIDATES),+ ).filter(+ (element) =>+ element.tabIndex >= 0 &&+ !element.matches(":disabled") &&+ !element.closest("[inert]") &&+ isVisible(element),+ );++ // A named radio group is a single Tab stop: its checked radio, else its first.+ return tabbable.filter((element) => {+ if (!isRadioInput(element) || !element.name) return true;+ const group = tabbable.filter(+ (other) => isRadioInput(other) && other.name === element.name,+ ) as HTMLInputElement[];+ return element === (group.find((radio) => radio.checked) ?? group[0]);+ });+}++function focusFirstTabbable(root: HTMLElement) {+ (getTabbableElements(root)[0] ?? root).focus();+}++/**+ * Modal focus contract for `ModalBackdrop`:+ * - on open, focus moves to the first tabbable control unless the content+ * already focused something inside the dialog (autoFocus or its own effect);+ * - Tab / Shift+Tab wrap inside the dialog, and focus that lands behind it+ * (programmatic focus, Tab from a non-tabbable element) is pulled back in;+ * - on close, focus returns to the element that was focused when it opened,+ * or into the dialog below when that element is gone.+ *+ * With nested modals only the topmost one acts. Popovers the dialog content+ * portals elsewhere stay usable because their focus and key events still+ * bubble through the dialog in the React tree.+ */+export function useModalFocus({ elevated }: { elevated: boolean }) {+ const rootRef = React.useRef<HTMLDivElement>(null);+ const elevatedRef = React.useRef(elevated);+ elevatedRef.current = elevated;+ // Read during the first render: children's autoFocus and mount effects run+ // before this component's effects and would already have moved focus.+ const [opener] = React.useState(() =>+ typeof document === "undefined" ? null : document.activeElement,+ );+ const focusEventFromDialogTree = React.useRef<Event | null>(null);++ React.useEffect(() => {+ const root = rootRef.current;+ if (!root) return undefined;+ const modal: OpenModal = { root, elevated: elevatedRef };+ openModals.push(modal);++ if (topmostModalRoot() === root && !root.contains(document.activeElement)) {+ focusFirstTabbable(root);+ }++ // Runs after React dispatched the same focusin through the dialog's+ // onFocus, so an unmarked event means focus landed outside the dialog.+ const handleFocusIn = (event: FocusEvent) => {+ // A closing dialog is already detached here; let the new focus stand.+ if (!root.isConnected || topmostModalRoot() !== root) return;+ if (event === focusEventFromDialogTree.current) return;+ focusFirstTabbable(root);+ };+ window.addEventListener("focusin", handleFocusIn);++ return () => {+ window.removeEventListener("focusin", handleFocusIn);+ openModals.splice(openModals.indexOf(modal), 1);++ // A real close detaches the dialog before this runs. StrictMode's+ // simulated unmount keeps it attached; restoring focus then would+ // override the content's own autoFocus when the effect re-runs.+ if (root.isConnected) return;++ // Leave focus alone if something outside the dialog deliberately took it.+ const active = document.activeElement;+ const focusWasInDialog =+ !active || active === document.body || root.contains(active);+ if (!focusWasInDialog) return;+ if (+ opener instanceof HTMLElement &&+ opener !== document.body &&+ opener.isConnected+ ) {+ opener.focus();+ return;+ }+ const below = topmostModalRoot();+ if (below?.isConnected) focusFirstTabbable(below);+ };+ }, []);++ const onFocus = React.useCallback((event: React.FocusEvent) => {+ focusEventFromDialogTree.current = event.nativeEvent;+ }, []);++ const onKeyDown = React.useCallback((event: React.KeyboardEvent) => {+ const root = rootRef.current;+ if (+ event.key !== "Tab" ||+ event.defaultPrevented ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey ||+ !root ||+ topmostModalRoot() !== root ||+ !root.contains(event.target as Node)+ ) {+ return;+ }+ const tabbable = getTabbableElements(root);+ const first = tabbable[0];+ const last = tabbable.at(-1);+ const active = document.activeElement;+ if (!first || !last) {+ event.preventDefault();+ root.focus();+ } else if (event.shiftKey && (active === first || active === root)) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && (active === last || active === root)) {+ event.preventDefault();+ first.focus();+ }+ }, []);++ return { rootRef, onFocus, onKeyDown };+}