Skip to content

Commit 34d4562

Browse files
committed
fix(ui): action dialogs return focus to a button the browser blurred as it turned disabled
A browser blurs a focused button when it becomes disabled, so an action button that disables itself while its action runs leaves focus on body by the time its dialog opens. The dialog now takes the control the user last pressed or clicked as its opener in that case. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibyekmZuiE5TVrwDWqH
1 parent 6a715ca commit 34d4562

2 files changed

Lines changed: 74 additions & 11 deletions

File tree

‎ui/packages/app-shell/src/views/actionDialogFocus-27521.test.tsx‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,27 @@ const INVITE_PARAMS: ActionParamDef[] = [
5252
* its action runs, which includes the time its dialog is open, and enabled
5353
* again a moment after the dialog closes, when the run settles.
5454
*/
55-
function InviteButtonWithDialog({ params = INVITE_PARAMS }: { params?: ActionParamDef[] }) {
55+
function InviteButtonWithDialog({
56+
params = INVITE_PARAMS,
57+
blurWhenDisabled = false,
58+
}: {
59+
params?: ActionParamDef[];
60+
/** A browser blurs a focused button that turns disabled; jsdom does not. */
61+
blurWhenDisabled?: boolean;
62+
}) {
5663
const [running, setRunning] = React.useState(false);
5764
const [open, setOpen] = React.useState(false);
5865
return (
5966
<>
60-
<button type="button" disabled={running} onClick={() => { setRunning(true); setOpen(true); }}>
67+
<button
68+
type="button"
69+
disabled={running}
70+
onClick={(event) => {
71+
if (blurWhenDisabled) event.currentTarget.blur();
72+
setRunning(true);
73+
setOpen(true);
74+
}}
75+
>
6176
Invite User
6277
</button>
6378
<ActionParamDialog
@@ -103,6 +118,17 @@ describe('row 23 — closing returns focus to the opener (objectstack#27521)', (
103118
await waitFor(() => expect(opener).toHaveFocus());
104119
});
105120

121+
it('…and when the browser blurred that button as it turned disabled, so the dialog opened with focus on body', async () => {
122+
const user = userEvent.setup();
123+
render(<InviteButtonWithDialog blurWhenDisabled />);
124+
const opener = screen.getByRole('button', { name: 'Invite User' });
125+
await user.click(opener);
126+
await waitFor(() => expect(screen.getByLabelText(/Email/)).toHaveFocus());
127+
await user.keyboard('{Escape}');
128+
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
129+
await waitFor(() => expect(opener).toHaveFocus());
130+
});
131+
106132
it('a user who moved focus meanwhile keeps it', async () => {
107133
const user = userEvent.setup();
108134
render(

‎ui/packages/app-shell/src/views/actionDialogReturnFocus.ts‎

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,30 @@
99
* - A row menu item. The menu closes as the action starts, so the item is
1010
* gone by the time the dialog closes. The opener is the menu's trigger,
1111
* which the menu names in `aria-labelledby`.
12-
* - An action button. It stays disabled while its action runs, and the
13-
* dialog closes before the run settles, so it refuses focus at that moment.
14-
* Focus waits for it to come back, as long as the user has not put focus
15-
* somewhere else in the meantime.
12+
* - An action button. It is disabled while its action runs, so a browser
13+
* blurs it before the dialog opens (focus is on `body` then), and it still
14+
* refuses focus when the dialog closes, before the run settles. The opener
15+
* is then the control the user last activated, and focus waits for it to
16+
* come back, as long as the user has not put focus somewhere else meanwhile.
1617
* - A dialog that hands over to the next one (a param dialog whose run ends
1718
* in a result dialog). The next dialog returns to the first one's opener.
1819
*
1920
* The hook is the `onCloseAutoFocus` half only; when it has no opener, or the
2021
* opener is gone, Radix's default stays.
2122
*/
2223

23-
import { useCallback, useLayoutEffect, useRef } from 'react';
24+
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
2425

2526
const DIALOG_SELECTOR = '[role="dialog"], [role="alertdialog"]';
2627

2728
/** How long a closed dialog waits for a disabled opener to come back. */
2829
const RETURN_FOCUS_WAIT_MS = 10_000;
2930

31+
/** How recent an activation must be to count as the opener of a dialog opening on `body`. */
32+
const ACTIVATION_WINDOW_MS = 10_000;
33+
34+
const CONTROL_SELECTOR = 'button, a[href], input, select, textarea, [role="button"], [role="menuitem"], [tabindex]';
35+
3036
/** The opener each open action dialog returns to, by its content element. */
3137
const openers = new WeakMap<Element, HTMLElement>();
3238

@@ -37,6 +43,29 @@ const openers = new WeakMap<Element, HTMLElement>();
3743
*/
3844
let pendingReturn: { opener: HTMLElement; stop: () => void } | null = null;
3945

46+
/**
47+
* The control the user last pressed or clicked, already resolved to its
48+
* opener (a menu item to the menu's trigger), and when. Read only when a
49+
* dialog opens with focus on `body`.
50+
*/
51+
let lastActivation: { opener: HTMLElement; at: number } | null = null;
52+
let activationListening = false;
53+
54+
function recordActivation(event: Event): void {
55+
const target = event.target as Element | null;
56+
const control = target && typeof target.closest === 'function' ? target.closest(CONTROL_SELECTOR) : null;
57+
const opener = control ? resolveFocusOpener(control) : null;
58+
lastActivation = opener ? { opener, at: Date.now() } : null;
59+
}
60+
61+
/** Listens once per document, in the capture phase, so no handler can hide an activation. */
62+
function listenForActivations(doc: Document): void {
63+
if (activationListening) return;
64+
activationListening = true;
65+
doc.addEventListener('pointerdown', recordActivation, true);
66+
doc.addEventListener('keydown', recordActivation, true);
67+
}
68+
4069
function isHtmlElement(node: unknown): node is HTMLElement {
4170
return !!node && (node as Node).nodeType === 1 && typeof (node as HTMLElement).focus === 'function';
4271
}
@@ -53,11 +82,15 @@ function focusIsNowhere(doc: Document): boolean {
5382
export function resolveFocusOpener(active: Element | null): HTMLElement | null {
5483
if (!isHtmlElement(active)) return null;
5584
const doc = active.ownerDocument;
56-
if (focusIsNowhere(doc)) {
85+
if (active === doc.body || active === doc.documentElement) {
5786
const pending = pendingReturn;
58-
if (!pending) return null;
59-
pending.stop();
60-
return pending.opener.isConnected ? pending.opener : null;
87+
if (pending) {
88+
pending.stop();
89+
return pending.opener.isConnected ? pending.opener : null;
90+
}
91+
const activation = lastActivation;
92+
if (!activation || Date.now() - activation.at > ACTIVATION_WINDOW_MS) return null;
93+
return activation.opener.isConnected ? activation.opener : null;
6194
}
6295
// Nested menus are walked out one trigger at a time; the bound only guards
6396
// a menu that names itself.
@@ -119,6 +152,10 @@ export function useActionDialogReturnFocus(open: boolean): {
119152
const openerRef = useRef<HTMLElement | null>(null);
120153
const contentNodeRef = useRef<HTMLElement | null>(null);
121154

155+
useEffect(() => {
156+
if (typeof document !== 'undefined') listenForActivations(document);
157+
}, []);
158+
122159
// A layout effect runs before Radix's focus scope mounts (the portal draws
123160
// the content one commit later), so focus is still on the opener here.
124161
useLayoutEffect(() => {

0 commit comments

Comments
 (0)