A local-first multi-agent app development platform, built on PenguinHarness
fix(web): trap and restore focus in the Modal primitive (#602)
Yaowei Zhengb4656e0037ff
diff --git a/changelog/unreleased/2026-09-03-modal-focus-trap.md b/changelog/unreleased/2026-09-03-modal-focus-trap.mdnew file mode 100644index 00000000..d35271f1--- /dev/null+++ b/changelog/unreleased/2026-09-03-modal-focus-trap.md@@ -0,0 +1,27 @@+# Dialogs hold on to keyboard focus, and hand it back++- **Date:** 2026-09-03+- **Type:** fix+- **Scope:** `web`+- **PR:** [#602](https://github.com/Prism-Shadow/penguin-harness/pull/602)++[中文版](2026-09-03-modal-focus-trap.zh.md)++The Web App's `Modal` primitive, which every dialog in the app is built on, now contains+keyboard focus for as long as it is open and returns it when it closes.++## Details++- Opening a dialog moves focus to its first focusable control, or to the dialog itself when+ it has none. A dialog whose content sets `autoFocus` keeps that choice.+- Tab and Shift+Tab cycle within the dialog, wrapping at both ends, rather than walking out+ into the page behind the overlay.+- Closing returns focus to the element that held it before, on every path: Escape, the close+ button, a click on the overlay, the `open` prop going false, and the dialog unmounting.+- `role="dialog"` and `aria-modal="true"` now sit on every dialog. They had been set only on+ the headerless variant — confirmations and `PagedDialog` — so a titled dialog was announced+ as a plain container with no name.+- A titled dialog is named by its own heading through `aria-labelledby`, not by a second copy+ of the title string.+- A menu or popover opened from inside a dialog still owns its own focus and its own Escape,+ and Escape still closes one layer at a time.diff --git a/changelog/unreleased/2026-09-03-modal-focus-trap.zh.md b/changelog/unreleased/2026-09-03-modal-focus-trap.zh.mdnew file mode 100644index 00000000..44609735--- /dev/null+++ b/changelog/unreleased/2026-09-03-modal-focus-trap.zh.md@@ -0,0 +1,23 @@+# 对话框接住键盘焦点,关闭时再交还++- **Date:** 2026-09-03+- **Type:** fix+- **Scope:** `web`+- **PR:** [#602](https://github.com/Prism-Shadow/penguin-harness/pull/602)++[English](2026-09-03-modal-focus-trap.md)++Web App 的 `Modal` 基础组件——应用里每一个对话框都建立在它之上——现在会在打开期间把键盘焦点+留在框内,关闭时再交还回去。++## 细节++- 打开对话框时,焦点移到框内第一个可聚焦控件;框内没有可聚焦控件时则落在对话框本身。内容自带+ `autoFocus` 的对话框保持它自己的选择。+- Tab 与 Shift+Tab 在框内循环、两端回绕,不再走出遮罩、落到背后的页面上。+- 关闭时焦点回到打开前持有它的元素,所有关闭路径一致:Escape、关闭按钮、点击遮罩、`open`+ 变为 false,以及对话框直接卸载。+- `role="dialog"` 与 `aria-modal="true"` 现在出现在每一个对话框上。此前只设在无标题栏的变体+ (确认框与 `PagedDialog`)上,因此带标题的对话框在辅助技术里只是一个没有名字的普通容器。+- 带标题的对话框通过 `aria-labelledby` 由自己的标题命名,而不是再复制一份标题字符串。+- 从对话框内部打开的菜单或浮层仍然自己掌管焦点与 Escape,Escape 也仍然一次只关闭一层。diff --git a/packages/web/src/components/ui/dropdown.tsx b/packages/web/src/components/ui/dropdown.tsxindex 9b3945e1..327a5003 100644--- a/packages/web/src/components/ui/dropdown.tsx+++ b/packages/web/src/components/ui/dropdown.tsx@@ -36,7 +36,7 @@import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { createPortal } from "react-dom";import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";-import { isTopEscLayer, popEscLayer, pushEscLayer } from "./modal";+import { FOCUSABLE_SELECTOR, isTopEscLayer, popEscLayer, pushEscLayer } from "./modal";import { scrollMovesAnchor } from "../../lib/context-menu";/** Gap between the trigger and the portaled panel, and the panel's minimum distance from the viewport edge (px). */@@ -133,11 +133,7 @@ export function Dropdown({const panelItems = useCallback(() =>panelRef.current- ? [- ...panelRef.current.querySelectorAll<HTMLElement>(- 'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',- ),- ]+ ? [...panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)]: [],[],);diff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsxindex 7414daa6..b7d3a0a0 100644--- a/packages/web/src/components/ui/modal.tsx+++ b/packages/web/src/components/ui/modal.tsx@@ -10,15 +10,20 @@* rectangle, leaving a misaligned edge (a white sliver showing through). After* portaling, every modal is a sibling child of body and stacks naturally in DOM* order.+ *+ * **Focus is contained**: opening moves focus into the panel, Tab and Shift+Tab cycle+ * inside it, and closing returns focus to whatever held it before. `role="dialog"` plus+ * `aria-modal` announce the page behind as out of scope, but neither moves focus — without+ * the trap, Tab walks straight out of the overlay into content the dialog sits on top of.*/-import { useEffect, useRef } from "react";+import { useEffect, useId, useRef } from "react";import { createPortal } from "react-dom";-import type { ReactNode } from "react";+import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";import { CloseButton } from "./icons";export interface ModalProps {open: boolean;- /** Dialog name: rendered as the header bar, or (headerless) exposed as the panel's aria-label only. */+ /** Dialog name: rendered as the header bar and used to name the dialog, or (headerless) exposed as the panel's aria-label only. */title: string;onClose: () => void;children: ReactNode;@@ -61,6 +66,26 @@ export function isTopEscLayer(id: symbol): boolean {return escLayers[escLayers.length - 1] === id;}+/**+ * The elements an overlay hands focus to, in DOM order. Shared with Dropdown so a dialog and+ * a menu agree on what "focusable" means. Visually hidden controls stay in the set on+ * purpose: the app's file pickers are hidden the `sr-only` way rather than with `display:+ * none` precisely so they keep their place in the Tab order (hidden-file-input.tsx).+ */+export const FOCUSABLE_SELECTOR =+ 'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';++/**+ * Index that Tab — or Shift+Tab, `backward` — moves to within a ring of `count` focusables,+ * wrapping at both ends so focus cannot walk out of the dialog. `at` is -1 when focus sits on+ * the panel container itself rather than on one of the ring's elements, which enters the ring+ * at whichever end the direction implies.+ */+export function nextFocusIndex(count: number, at: number, backward: boolean): number {+ if (at < 0) return backward ? count - 1 : 0;+ return (at + (backward ? -1 : 1) + count) % count;+}+export function Modal({open,title,@@ -79,6 +104,24 @@ export function Modal({const onCloseRef = useRef(onClose);onCloseRef.current = onClose;+ const titleId = useId();+ const panelRef = useRef<HTMLDivElement>(null);++ // Where focus goes when the dialog closes, read during render rather than in the effect+ // below: a child with `autoFocus` is focused during the same commit, before any effect+ // runs, so by effect time document.activeElement already points inside the dialog and the+ // element to return to is gone. Written only on the closed->open edge, so reopening from a+ // different trigger returns to that trigger, and a StrictMode double-mount — whose extra+ // cleanup restores focus once before the real one — does not drop the target.+ const restoreFocusRef = useRef<HTMLElement | null>(null);+ const wasOpenRef = useRef(false);+ if (open !== wasOpenRef.current) {+ wasOpenRef.current = open;+ if (open)+ restoreFocusRef.current =+ document.activeElement instanceof HTMLElement ? document.activeElement : null;+ }+useEffect(() => {if (!open) return;const id = pushEscLayer();@@ -92,6 +135,47 @@ export function Modal({};}, [open]);+ // Opening moves focus into the panel, closing hands it back. `aria-modal` tells assistive+ // tech the page behind is out of scope but moves nothing, so without this a keyboard user+ // stays parked on the trigger with the dialog's own controls several Tabs away.+ useEffect(() => {+ if (!open) return;+ const panel = panelRef.current;+ // A child with autoFocus already claimed focus during the commit — leave it there.+ if (panel && !panel.contains(document.activeElement))+ (panel.querySelector<HTMLElement>(FOCUSABLE_SELECTOR) ?? panel).focus();+ // Every close path lands in this cleanup: Escape, the close button, the overlay+ // mousedown, `open` going false, and the dialog unmounting outright.+ return () => restoreFocusRef.current?.focus();+ }, [open]);++ /**+ * Tab and Shift+Tab cycle inside the panel instead of walking out into the page behind the+ * overlay.+ *+ * Two things this must not take over. A control that owns Tab for its own model (the+ * composer's slash picker accepts a completion with it) marks the event handled, and this+ * yields to that the way Dropdown's arrow keys do. And a menu or popover opened from inside+ * the dialog is portaled to body — outside this panel's DOM subtree, yet still a React+ * child, so its keydown bubbles through here; the containment check leaves that panel's own+ * focus alone.+ */+ const onPanelKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {+ if (e.key !== "Tab" || e.defaultPrevented) return;+ const panel = panelRef.current;+ if (!panel?.contains(document.activeElement)) return;+ e.preventDefault();+ const items = [...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)];+ // A dialog with nothing focusable in it keeps focus on the container, which is what the+ // panel's tabIndex={-1} is for.+ if (items.length === 0) {+ panel.focus();+ return;+ }+ const at = items.indexOf(document.activeElement as HTMLElement);+ items[nextFocusIndex(items.length, at, e.shiftKey)]?.focus();+ };+if (!open) return null;return createPortal(<div@@ -101,12 +185,21 @@ export function Modal({}}><div- {...(headerless ? { role: "dialog", "aria-label": title } : {})}+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ // The titled branch is named by its own heading rather than a second copy of the+ // string, so a renamed dialog cannot end up announcing the old name.+ {...(headerless ? { "aria-label": title } : { "aria-labelledby": titleId })}+ tabIndex={-1}+ onKeyDown={onPanelKeyDown}className={`anim-pop w-full ${widthClass ?? "sm:max-w-md"} rounded-t-lg border border-gray-200 bg-white pb-[env(safe-area-inset-bottom)] shadow-xl sm:rounded-lg sm:pb-0 dark:border-gray-800 dark:bg-gray-900`}>{!headerless && (<div className="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-800">- <h2 className="text-base font-semibold">{title}</h2>+ <h2 id={titleId} className="text-base font-semibold">+ {title}+ </h2><CloseButton onClose={onClose} /></div>)}diff --git a/packages/web/test/modal-focus.test.ts b/packages/web/test/modal-focus.test.tsnew file mode 100644index 00000000..b79ce02f--- /dev/null+++ b/packages/web/test/modal-focus.test.ts@@ -0,0 +1,155 @@+/**+ * Focus behaviour of the Modal primitive (src/components/ui/modal.tsx), which every dialog in+ * the app inherits: focus enters the panel on open, Tab and Shift+Tab cycle inside it, and+ * focus returns to the trigger on close.+ *+ * `nextFocusIndex` is the arithmetic and is exercised directly. The wiring around it cannot+ * be: this suite is `environment: "node"` with no jsdom, and Modal renders through+ * `createPortal(…, document.body)`, so it cannot even be handed to `renderToStaticMarkup` the+ * way info-popover.test.ts renders Field. So the wiring is asserted against the source, the+ * way portal-panel-dismiss.test.ts asserts its hook's listeners — thin, but it pins the parts+ * that are silent when they break: an aria attribute that reappears inside the `headerless`+ * branch names only half the dialogs, and a restore target read one commit too late is a+ * dialog that hands focus back to itself.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { nextFocusIndex } from "../src/components/ui/modal";++const modal = readFileSync(+ fileURLToPath(new URL("../src/components/ui/modal.tsx", import.meta.url)),+ "utf8",+);+const dropdown = readFileSync(+ fileURLToPath(new URL("../src/components/ui/dropdown.tsx", import.meta.url)),+ "utf8",+);++/** The panel div's opening tag — the element carrying the dialog's role and its focus wiring. */+function panelTag(): string {+ const tag = /<div\n\s+ref=\{panelRef\}[\s\S]*?\n {6}>/.exec(modal);+ expect(tag, "the panel div should carry ref={panelRef}").not.toBeNull();+ return tag![0];+}++/** The `useEffect(...)` block containing `marker`, up to and including its dependency array. */+function effectWith(marker: string): string {+ const at = modal.indexOf(marker);+ expect(at, `expected ${marker} in modal.tsx`).toBeGreaterThan(-1);+ const start = modal.lastIndexOf("useEffect(", at);+ expect(start, `${marker} should sit inside a useEffect`).toBeGreaterThan(-1);+ const deps = modal.indexOf("}, [", at);+ return modal.slice(start, modal.indexOf(");", deps) + 2);+}++describe("nextFocusIndex", () => {+ it("steps forward and wraps past the last element", () => {+ expect(nextFocusIndex(3, 0, false)).toBe(1);+ expect(nextFocusIndex(3, 2, false)).toBe(0);+ });++ it("steps backward and wraps past the first element", () => {+ expect(nextFocusIndex(3, 2, true)).toBe(1);+ expect(nextFocusIndex(3, 0, true)).toBe(2);+ });++ it("enters the ring at the end the direction implies when focus is on the panel itself", () => {+ // -1 is focus sitting on the container: a dialog whose focusable content mounted after+ // open, or one whose only control was just disabled. Shift+Tab must reach the last+ // element, not the second-to-last — the plain modulo gets this wrong.+ expect(nextFocusIndex(4, -1, false)).toBe(0);+ expect(nextFocusIndex(4, -1, true)).toBe(3);+ });++ it("holds a single-element ring in place rather than escaping it", () => {+ expect(nextFocusIndex(1, 0, false)).toBe(0);+ expect(nextFocusIndex(1, 0, true)).toBe(0);+ });+});++describe("Modal dialog semantics", () => {+ it("is a modal dialog on both branches, not only the headerless one", () => {+ const tag = panelTag();+ expect(tag).toContain('role="dialog"');+ expect(tag).toContain('aria-modal="true"');+ // The branch may only choose HOW the dialog is named. A role that moved back inside it+ // would leave every titled dialog — the majority — as an unannounced div.+ const branch = /\{\.\.\.\(headerless[\s\S]*?\)\}/.exec(tag);+ expect(branch, "the headerless branch should be a spread on the panel").not.toBeNull();+ expect(branch![0]).not.toContain("role");+ expect(branch![0]).not.toContain("aria-modal");+ });++ it("names the titled branch from its own heading instead of a second copy of the string", () => {+ expect(panelTag()).toContain('"aria-labelledby": titleId');+ expect(modal).toContain("<h2 id={titleId}");+ // The headerless branch has no heading to point at, so it keeps the string itself.+ expect(panelTag()).toContain('"aria-label": title');+ });++ it("keeps the container focusable so a dialog with no controls can still hold focus", () => {+ expect(panelTag()).toContain("tabIndex={-1}");+ });+});++describe("Modal focus containment", () => {+ it("moves focus into the panel on open, yielding to a child that autofocused", () => {+ const effect = effectWith("FOCUSABLE_SELECTOR) ?? panel");+ // A child with autoFocus is focused during the commit, before this effect runs; stealing+ // focus back to the close button would undo it at every call site that uses autoFocus.+ expect(effect).toContain("!panel.contains(document.activeElement)");+ expect(effect).toContain("[open]");+ });++ it("returns focus on every close path", () => {+ // Keyed on `open` alone, so the cleanup runs for Escape, the close button, the overlay+ // mousedown, the prop going false, and an outright unmount alike.+ const effect = effectWith("restoreFocusRef.current?.focus()");+ expect(effect).toContain("return () => restoreFocusRef.current?.focus();");+ expect(effect).toContain("[open]");+ });++ it("reads the element to return to during render, before any effect can run", () => {+ // autoFocus fires in the same commit, so an effect-time read would capture a node inside+ // the dialog and hand focus back to the dialog that just closed.+ const capture = modal.indexOf("restoreFocusRef.current =");+ expect(capture).toBeGreaterThan(-1);+ expect(capture).toBeLessThan(modal.indexOf("useEffect("));+ });++ it("cycles Tab within the panel, and yields to the two things that own it first", () => {+ const handler = /const onPanelKeyDown = [\s\S]*?\n {2}\};/.exec(modal);+ expect(handler, "onPanelKeyDown should be declared in modal.tsx").not.toBeNull();+ const body = handler![0];+ expect(body).toContain("nextFocusIndex(");+ expect(body).toContain("e.shiftKey");+ expect(body).toContain("e.preventDefault()");+ // A control that drives Tab itself (the composer's slash picker accepts a completion with+ // it) marks the event handled.+ expect(body).toContain("e.defaultPrevented");+ // A menu or popover opened inside the dialog is portaled out of this subtree but still+ // bubbles here as a React child; it owns its own focus while it is open.+ expect(body).toContain("panel?.contains(document.activeElement)");+ });++ it("leaves Escape on the layer stack, so only the topmost dialog closes", () => {+ expect(effectWith("const id = pushEscLayer();")).toContain("isTopEscLayer(id)");+ });+});++describe("focusable selector", () => {+ it("is shared with Dropdown rather than copied into it", () => {+ expect(modal).toContain("export const FOCUSABLE_SELECTOR =");+ expect(dropdown).toContain("querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)");+ expect(dropdown).not.toContain("a[href]");+ });++ it("keeps visually hidden controls in the ring", () => {+ // The app's file pickers are hidden the `sr-only` way — position/clip, not `display:+ // none` — specifically so they stay Tab-reachable (hidden-file-input.tsx). A selector+ // narrowed to visible boxes would drop every "upload" and "import" control in a dialog.+ expect(modal).toContain("input:not([disabled])");+ expect(modal).not.toContain("offsetParent");+ });+});