diff --git a/packages/react/src/utils/popups/focus/FloatingFocusManager.test.tsx b/packages/react/src/utils/popups/focus/FloatingFocusManager.test.tsx index afa62ead946..042012ffbb0 100644 --- a/packages/react/src/utils/popups/focus/FloatingFocusManager.test.tsx +++ b/packages/react/src/utils/popups/focus/FloatingFocusManager.test.tsx @@ -2237,6 +2237,116 @@ describe('FloatingFocusManager', () => { }); }); + describe('focus that moved inside before the initial focus resolved', () => { + // The popup is open and its initial focus is queued: focus reaches an element inside after the + // effect ran and before the microtask resolves the target. + async function openThenFocus(testId: string) { + fireEvent.click(screen.getByTestId('reference')); + screen.getByTestId(testId).focus(); + expect(screen.getByTestId(testId)).toHaveFocus(); + await flushMicrotasks(); + } + + // Frames the test runs by hand, with working cancellation (`enqueueFocus` cancels its own). + function holdFrames() { + const frames = new Map(); + let nextHandle = 1; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + const handle = nextHandle; + nextHandle += 1; + frames.set(handle, callback); + return handle; + }); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((handle) => { + frames.delete(handle); + }); + + return { + run() { + const callbacks = [...frames.values()]; + frames.clear(); + act(() => callbacks.forEach((callback) => callback(0))); + }, + }; + } + + test('keeps it', async () => { + const frames = holdFrames(); + render(); + + await openThenFocus('three'); + frames.run(); + + expect(screen.getByTestId('three')).toHaveFocus(); + }); + + test('keeps it across a real frame', async () => { + vi.mocked(window.requestAnimationFrame).mockRestore(); + render(); + + await openThenFocus('three'); + await act( + () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + }), + ); + + expect(screen.getByTestId('three')).toHaveFocus(); + }); + + test('keeps it over an explicit initialFocus target', async () => { + const frames = holdFrames(); + render(); + + await openThenFocus('three'); + frames.run(); + + expect(screen.getByTestId('three')).toHaveFocus(); + }); + + test('keeps a focused SVG element', async () => { + const frames = holdFrames(); + render( + + + , + ); + + await openThenFocus('svg'); + frames.run(); + + expect(screen.getByTestId('svg')).toHaveFocus(); + }); + + test('yields to a later move before the frame', async () => { + const frames = holdFrames(); + render(); + + await openThenFocus('three'); + screen.getByTestId('two').focus(); + frames.run(); + + expect(screen.getByTestId('two')).toHaveFocus(); + }); + + test('falls back to the initial focus if that focus is lost by the frame', async () => { + const frames = holdFrames(); + const { rerender } = render( + + + , + ); + + await openThenFocus('field'); + rerender(); + expect(document.activeElement).toBe(document.body); + frames.run(); + + expect(screen.getByTestId('one')).toHaveFocus(); + }); + }); + describe('prop: restoreFocus', () => { function App({ restoreFocus = true }: { restoreFocus?: boolean }) { const [isOpen, setIsOpen] = React.useState(false); diff --git a/packages/react/src/utils/popups/focus/FloatingFocusManager.tsx b/packages/react/src/utils/popups/focus/FloatingFocusManager.tsx index 25b175bc948..e315806409e 100644 --- a/packages/react/src/utils/popups/focus/FloatingFocusManager.tsx +++ b/packages/react/src/utils/popups/focus/FloatingFocusManager.tsx @@ -724,7 +724,13 @@ export function FloatingFocusManager(props: FloatingFocusManagerProps): React.JS } elToFocus = elToFocus || getDefaultFocusElement(); - const hadFocusInside = contains(floatingFocusElement, activeElement(doc)); + const focusedElement = activeElement(doc); + const hadFocusInside = contains(floatingFocusElement, focusedElement); + // Focus that reached an element inside after `previouslyFocusedElement` was captured is kept, + // like focus that was inside before. The queued focus then only steps in if that focus has + // been lost by the time the frame runs, e.g. because the element was removed. + const focusMovedInsideBeforeResolve = + hadFocusInside && focusedElement !== floatingFocusElement; // Screen readers re-sync focus to their cursor right after a synthesized press. A focus // that lands a frame later reads as a stray move and gets pulled back to the reference. @@ -744,11 +750,16 @@ export function FloatingFocusManager(props: FloatingFocusManagerProps): React.JS return false; } + const currentActiveElement = activeElement(doc); + + if (focusMovedInsideBeforeResolve) { + return currentActiveElement == null || currentActiveElement === doc.body; + } + if (hadFocusInside) { return true; } - const currentActiveElement = activeElement(doc); const focusMovedInside = currentActiveElement !== elToFocus && contains(floatingFocusElement, currentActiveElement); diff --git a/test/setupVitest.ts b/test/setupVitest.ts index c0a54965796..9ca9c861969 100644 --- a/test/setupVitest.ts +++ b/test/setupVitest.ts @@ -43,8 +43,8 @@ afterEach(() => { globalThis.BASE_UI_ANIMATIONS_DISABLED = true; if (typeof window !== 'undefined' && window?.navigator?.userAgent?.includes('jsdom')) { - globalThis.requestAnimationFrame = (cb) => { - setTimeout(() => cb(0), 0); - return 0; - }; + // Return the timer's id as the frame handle, so `cancelAnimationFrame` cancels it as it does in a + // browser. jsdom's own `cancelAnimationFrame` does not know these handles. + globalThis.requestAnimationFrame = (cb) => Number(setTimeout(() => cb(0), 0)); + globalThis.cancelAnimationFrame = (handle) => clearTimeout(handle); }