fix(ui): a dialog keeps the focus it was given, and hands it back where it took it from

Round 5 extracted `ui/dialogFocus` so no shell would hand-roll the focus
contract, then introduced four ways to lose the focus anyway — all four measured
in jsdom against the real components.

**Ownership was narrower than the trap.** `ui/Modal` traps Tab over the whole
dialog on purpose, so a toast's Undo or ✕ stays reachable; ownership was tracked
over the panel alone. Tabbing to that ✕ therefore read as "the user left the
dialog", and since removing a toast fires no `focusin` to re-arm, closing
afterwards skipped the restore and left the focus on <body>. Before this hook
existed the restore was unconditional, so it was a regression.

**A dialog stacked above us is still ours.** A nested `ui/Modal` portals into its
own host, so it is outside the outer dialog's root however wide that scope is
drawn — widening alone could not fix it. Both closing in one commit left the
focus on <body>: the outer skipped its restore, and the child's own target (a
control inside the outer panel) was already detached, because passive cleanups
run parent-first. Ownership now means "inside my dialog, or inside a modal layer
above it", which is what the rule always intended.

**The wizard disagreed with `ui/Modal` on its first line.** `trapTab(e, panel)`,
with neither the dialog-root scope (so its own toast host was outside the cycle
— the connection notice never auto-dismisses, and its ✕ was unreachable from the
keyboard) nor the `container` argument the JSDoc exists for: `panel.contains(
panel)` is true, so focus sitting ON the tabIndex=-1 panel matched no branch and
a Shift+Tab walked into the app behind the scrim. Both call sites now pass the
same three arguments.

**The toast handover was a render-phase read-modify-write.** A `useMemo` read a
module global that the next line overwrote; React re-invokes a component body
and every `useMemo` factory in it on a StrictMode double render, and the LAST
invocation commits — so the second pass re-read what the first had just written,
the takeover host classified its OWN new toast as inherited, and the dev build
behaved exactly like the code round 5 replaced. Snapshotted through a ref keyed
on `isTop`, so a repeated invocation of one render is a no-op.

And the fourth `aria-modal` shell, `Welcome`'s screenshot lightbox, is finally
swept into the same contract: it declared itself a modal dialog while leaving
the focus on the thumbnail behind an 80%-black scrim and letting Tab walk the
landing page underneath.

The headline fix of the previous commit — StrictMode's re-mount taking the focus
off an `autoFocus` field — had no test at all; deleting it left all 1009 green.
It has one now.

9 tests, mutation-checked against 8 mutations, each red on the test that names it.
This commit is contained in:
2026-09-12 05:49:58 +02:00
parent 7f17b17c13
commit f8a31d48cf
10 changed files with 378 additions and 24 deletions
@@ -10,6 +10,7 @@
// The overlay/history machinery (useBackToClose) is exercised in history.dom.test.ts, so it's mocked
// out here to isolate the focus-trap behaviour from its module-global history side-effects.
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { useState } from "react";
import { render, screen, act, cleanup } from "@testing-library/react";
vi.mock("react-i18next", async (importOriginal) => {
@@ -199,6 +200,78 @@ describe("Modal focus trap (offsetParent stubbed 'visible')", () => {
expect(document.activeElement).toBe(trigger);
document.body.removeChild(trigger);
});
it("still restores the trigger after the focus visited the dialog's own toast", () => {
// The Tab trap deliberately spans the dialog ROOT so a toast's Undo/✕ is reachable; ownership
// was tracked over the PANEL, so touching that ✕ read as "the user left the dialog" and the
// restore was skipped — and removing the toast fires no focusin to re-arm it. Measured landing
// on <body> (deep-review round 6).
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
const { unmount } = render(
<Modal title="t" onClose={() => {}}>
<Body />
</Modal>,
);
act(() => void notify({ level: "error", message: "Nope" }));
const dismissToast = screen.getByTitle("notifications.dismiss");
dismissToast.focus();
expect(document.activeElement).toBe(dismissToast); // the scenario is actually being driven
act(() => clearAll()); // the toast goes away under the focus — no focusin follows
expect(document.activeElement).toBe(document.body);
unmount();
expect(document.activeElement).toBe(trigger);
document.body.removeChild(trigger);
});
it("restores the trigger when a dialog and the dialog stacked on it close together", () => {
// A nested Modal portals into its OWN host, so it is outside the outer dialog's root however
// wide that scope is drawn — reading that as "the user walked away" left the focus on <body>.
// The child cannot cover for it: passive cleanups run parent-first, and by then its own restore
// target (a control INSIDE the outer panel, captured when it opened) is already detached.
const trigger = document.createElement("button");
document.body.appendChild(trigger);
trigger.focus();
function Nested() {
const [open, setOpen] = useState(false);
return (
<Modal title="outer" onClose={() => {}}>
<button onClick={() => setOpen(true)}>open inner</button>
{open && (
<Modal title="inner" onClose={() => {}}>
<button>inner-body</button>
</Modal>
)}
</Modal>
);
}
const { unmount } = render(<Nested />);
act(() => void screen.getByText("open inner").click());
screen.getByText("inner-body").focus();
unmount();
expect(document.activeElement).toBe(trigger);
document.body.removeChild(trigger);
});
it("leaves the focus alone when the user moved it out of the dialog themselves", () => {
// The other half of the same rule, and the branch nothing drove: taking focus back from where
// the user deliberately put it is the rudest thing a closing dialog can do.
const trigger = document.createElement("button");
const elsewhere = document.createElement("button");
document.body.append(trigger, elsewhere);
trigger.focus();
const { unmount } = render(
<Modal title="t" onClose={() => {}}>
<Body />
</Modal>,
);
elsewhere.focus();
unmount();
expect(document.activeElement).toBe(elsewhere);
document.body.removeChild(trigger);
document.body.removeChild(elsewhere);
});
});
describe("Modal focus trap (raw jsdom — every offsetParent null)", () => {
@@ -0,0 +1,54 @@
// @vitest-environment jsdom
//
// The dialog's focus behaviour under React 18 StrictMode — its own file because StrictMode's
// mount→cleanup→mount is what the code under test reacts to, and the module-level layer stack in
// ui/Modal (and the overlay-host registry in ui/Toaster) leaks between tests in one file.
//
// Round 5 fixed this in Chrome and shipped it with NO test: the second mount found the focus
// outside the dialog (its own cleanup had just handed it back to the trigger) and moved it to the
// first focusable — taking it off an `autoFocus` field a beat after the browser had put it there.
// The command palette opened focused on its ✕ in dev and on its search field in prod, from the same
// code. Round 6 measured that deleting the fix left all 1009 tests green, which is why this exists.
//
// Same offsetParent stub as Modal.dom.test.tsx: jsdom never lays out, so every element reports
// offsetParent null and `focusablesIn` would see nothing.
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { StrictMode } from "react";
import { render, screen, cleanup } from "@testing-library/react";
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return { ...actual, useTranslation: () => ({ t: (key: string) => key }) };
});
vi.mock("../../lib/history", () => ({ useBackToClose: () => {} }));
import Modal from "./Modal";
describe("Modal focus under StrictMode", () => {
let origDesc: PropertyDescriptor | undefined;
beforeEach(() => {
origDesc = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetParent");
Object.defineProperty(HTMLElement.prototype, "offsetParent", {
configurable: true,
get(this: HTMLElement) {
return this.isConnected ? document.body : null;
},
});
});
afterEach(() => {
cleanup();
if (origDesc) Object.defineProperty(HTMLElement.prototype, "offsetParent", origDesc);
});
it("keeps the focus its autoFocus child asked for across the double mount", () => {
render(
<StrictMode>
<Modal title="t" onClose={() => {}}>
<input aria-label="field" autoFocus />
</Modal>
</StrictMode>,
);
// Without the remembered focus the second mount lands on the first focusable — the header ✕.
expect(document.activeElement).toBe(screen.getByLabelText("field"));
});
});
+5 -2
View File
@@ -42,15 +42,18 @@ export default function Modal({
// still gets the focus (round 5). Both rules live in the hook; `ui/AnchoredPopover` shares it.
const host = useFullscreenPortalHost();
const panelRef = useRef<HTMLDivElement>(null);
const rootRef = useRef<HTMLDivElement>(null);
const titleId = useId();
useDialogChrome(panelRef);
// Focus lands in the panel; OWNERSHIP is the whole dialog — the same element the Tab trap below
// is scoped to, toast host included. Tracking ownership over the panel alone meant tabbing to an
// in-dialog toast counted as leaving, and the close-time restore was then skipped (round 6).
useDialogChrome(panelRef, rootRef);
const overlayOrder = useOverlayOrder();
// Backdrop-click close must only fire when the press STARTED on the backdrop too. Otherwise a
// drag that begins inside the dialog (e.g. selecting text in an input) and is released out on
// the backdrop wrongly dismisses — the click event bubbles to the common ancestor (the backdrop).
const pressedOnBackdrop = useRef(false);
const rootRef = useRef<HTMLDivElement>(null);
// Keep a stable handler across renders so the stack id is assigned once per mount.
const onCloseRef = useRef(onClose);
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
//
// The toast handover under React 18 StrictMode — its own file, because `lastTopIds` is module-level
// state that leaks between tests.
//
// Round 5 made a taking-over host inherit "what the PREVIOUS top host last had on screen" by reading
// a module global in a `useMemo` and overwriting it in the same render pass. React re-invokes a
// component body — and every `useMemo` factory in it — on a StrictMode double render, and the LAST
// invocation is what commits: so the second pass re-read what the first had just written, the host
// classified its OWN new toast as inherited, and the dev build behaved exactly like the code round 5
// replaced. Measured in Chrome and in jsdom: role "status" without StrictMode, null with it.
//
// The named case is UploadDialog's — notify and close the overlay in ONE handler, so the toast is
// raised in the very commit that hands the app's host the top spot.
import { describe, it, expect, afterEach, vi } from "vitest";
import { StrictMode, useState } from "react";
import { render, screen, cleanup, fireEvent } from "@testing-library/react";
vi.mock("react-i18next", async (importOriginal) => {
const actual = await importOriginal<typeof import("react-i18next")>();
return { ...actual, useTranslation: () => ({ t: (key: string) => key }) };
});
import Toaster, { useOverlayOrder } from "./Toaster";
import { clearAll, notify } from "../../lib/notifications";
afterEach(() => {
cleanup();
clearAll();
});
/** An overlay with its own toast host, plus the app's — the shape every dialog produces. */
function Harness() {
const [open, setOpen] = useState(true);
return (
<>
<button
onClick={() => {
notify({ level: "success", message: "Uploaded" });
setOpen(false); // …in the SAME handler: one batch, one commit
}}
>
finish
</button>
{open && <Overlay />}
<Toaster />
</>
);
}
function Overlay() {
const order = useOverlayOrder();
return <Toaster overlay order={order} />;
}
describe("the toast handover", () => {
it("announces a toast raised in the takeover commit, even under StrictMode", () => {
render(
<StrictMode>
<Harness />
</StrictMode>,
);
fireEvent.click(screen.getByText("finish"));
// Not inherited → it carries its own role, because the live region is not armed yet.
expect(screen.getByText("Uploaded").closest("[role]")?.getAttribute("role")).toBe("status");
});
});
+20 -4
View File
@@ -1,4 +1,4 @@
import { useEffect, useId, useMemo, useState, useSyncExternalStore } from "react";
import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
import { useTranslation } from "react-i18next";
import { AlertCircle, AlertTriangle, CheckCircle2, Info, X, XCircle } from "lucide-react";
import { dismiss, getActiveToasts, subscribe, type NotifLevel } from "../../lib/notifications";
@@ -43,6 +43,7 @@ const topHost = () => {
// What the host that is currently top last rendered, for the next host to inherit. See `inherited`.
let lastTopIds: number[] = [];
const EMPTY_IDS: ReadonlySet<number> = new Set<number>();
export default function Toaster({
overlay = false,
@@ -81,9 +82,24 @@ export default function Toaster({
// — the handover must be readable by the taking-over host in the SAME commit, and an effect
// cleanup runs one phase too late; only the host that IS top writes, so the value is the losing
// host's last screen either way.
const inherited = useMemo(() => new Set(isTop ? lastTopIds : []), [isTop]);
// AFTER the memo above has read the outgoing host's screen — this host's own first render as top
// would otherwise overwrite the handover with the toasts it is about to classify.
//
// Snapshotted through a ref keyed on `isTop`, not a `useMemo`: React re-invokes a component body
// — and every `useMemo` factory in it — on a StrictMode double render and on a restarted one, and
// the LAST invocation is what commits. With a memo the second pass re-read `lastTopIds` after the
// first pass had already overwritten it on the line below, so the takeover host classified its
// OWN new toast as inherited and the dev build behaved exactly like the code this replaced
// (measured in jsdom: role "status" without StrictMode, null with it — round 6). The ref only
// recomputes when `isTop` actually flips, so a repeated invocation of one render is a no-op.
const handover = useRef<{ top: boolean; ids: ReadonlySet<number> }>({
top: false,
ids: EMPTY_IDS,
});
if (handover.current.top !== isTop)
handover.current = { top: isTop, ids: new Set(isTop ? lastTopIds : []) };
const inherited = handover.current.ids;
// AFTER the snapshot above has read the outgoing host's screen — this host's own first render as
// top would otherwise overwrite the handover with the toasts it is about to classify. Writing the
// same value twice is harmless; that is the point of the ref.
if (isTop) lastTopIds = toasts.map((n) => n.id);
const [armed, setArmed] = useState(false);
useEffect(() => {
+30 -6
View File
@@ -47,8 +47,13 @@ export function trapTab(
}
/** The rest of the contract: lock the page behind, open focused, hand the focus back on close.
* `scopeRef` is the panel the focus should land in. */
export function useDialogChrome(scopeRef: RefObject<HTMLElement | null>): void {
* `scopeRef` is the panel the focus should land in; `ownerRef`, when the dialog is bigger than its
* panel, is that whole dialog — it must be the SAME element `trapTab` is scoped to, or the two
* disagree about what counts as "inside" (see `heldRef`). */
export function useDialogChrome(
scopeRef: RefObject<HTMLElement | null>,
ownerRef?: RefObject<HTMLElement | null>,
): void {
// Capture the trigger to restore focus to, during THIS render — i.e. before commit runs the
// dialog's autoFocus (or our own initial focus) and moves activeElement into the dialog. Reading it
// later (in the effect) would capture a now-inside element that unmounts on close, stranding focus
@@ -65,6 +70,13 @@ export function useDialogChrome(scopeRef: RefObject<HTMLElement | null>): void {
// time a passive cleanup runs on a real unmount the panel is already out of the document and the
// focus has fallen to <body>, so "does the panel contain activeElement" answers false for both a
// close and a user who clicked away — and those two want opposite things.
//
// Measured against the DIALOG, not the panel. The two scopes must be the same one the Tab trap
// uses, and `ui/Modal`'s trap deliberately spans the dialog root so an in-dialog toast's Undo/✕
// stays reachable — so tabbing to that ✕ read as "the user left the dialog", and since removing
// the toast fires no `focusin` to re-arm, closing the dialog afterwards stranded the focus on
// <body> instead of handing it back to the trigger. Measured in jsdom, and a regression: before
// this hook existed the restore was unconditional (deep-review round 6).
const heldRef = useRef(true);
useEffect(() => {
const prev = document.body.style.overflow;
@@ -82,9 +94,21 @@ export function useDialogChrome(scopeRef: RefObject<HTMLElement | null>): void {
target.focus();
}
const onFocusIn = () => {
const inside = scopeRef.current?.contains(document.activeElement) ?? false;
heldRef.current = inside;
if (inside) focusedRef.current = document.activeElement as HTMLElement;
const owner = ownerRef?.current ?? scopeRef.current;
const active = document.activeElement;
// "Still ours" also means a dialog stacked ABOVE us. A nested `ui/Modal` portals into its own
// host on <body>, so it is outside our root BY CONSTRUCTION — widening the scope cannot see
// it — and while it held the focus we read that as the user walking away. Then both closing
// together left the focus on <body>: ours skipped the restore, and the child's own
// `restoreTo` was already detached (passive cleanups run parent-first). Measured in jsdom,
// and it is the ordinary case — an error dialog raised over a dialog (round 6).
heldRef.current =
(owner?.contains(active) ?? false) ||
(active instanceof Element && active.closest('[aria-modal="true"]') != null);
// Where to put the focus back on a re-mount, though: the PANEL's own last focus. A toast is
// gone by then, so restoring onto it would strand the focus exactly as before.
if (scopeRef.current?.contains(document.activeElement))
focusedRef.current = document.activeElement as HTMLElement;
};
onFocusIn();
document.addEventListener("focusin", onFocusIn);
@@ -96,5 +120,5 @@ export function useDialogChrome(scopeRef: RefObject<HTMLElement | null>): void {
// rudest thing a closing dialog can do.
if (heldRef.current && restoreTo && restoreTo.isConnected) restoreTo.focus();
};
}, [restoreTo, scopeRef]);
}, [restoreTo, scopeRef, ownerRef]);
}