Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,24 @@ describe('FloatingFocusManager', () => {

expect(screen.getByTestId('one')).not.toHaveFocus();
});

test('yields to a newer focus inside the popup before the queued initial focus runs', async () => {
const frames: FrameRequestCallback[] = [];
vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
frames.push(callback);
return frames.length;
});
render(<App initialFocus="two" />);

fireEvent.click(screen.getByTestId('reference'));
act(() => screen.getByTestId('one').focus());
await flushMicrotasks();

act(() => screen.getByTestId('three').focus());
act(() => frames.splice(0).forEach((callback) => callback(performance.now())));

expect(screen.getByTestId('three')).toHaveFocus();
});
});

describe('prop: returnFocus', () => {
Expand Down
34 changes: 27 additions & 7 deletions packages/react/src/utils/popups/focus/FloatingFocusManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -687,17 +687,23 @@ export function FloatingFocusManager(props: FloatingFocusManagerProps): React.JS
// Focus the initial element when the floating element opens.
useIsoLayoutEffect(() => {
if (!open || disabled || !isHTMLElement(floatingFocusElement)) {
return;
return undefined;
}

closeTypeRef.current = '';
lastInteractionTypeRef.current = '';

const doc = ownerDocument(floatingFocusElement);
const previouslyFocusedElement = activeElement(doc);
let cleanedUp = false;
let cancelQueuedFocus: (() => void) | undefined;

// Wait for any layout effect state setters to execute to set `tabIndex`.
queueMicrotask(() => {
if (cleanedUp) {
return;
}

const initialFocusValueOrFn = initialFocusRef.current;
const resolvedInitialFocus =
typeof initialFocusValueOrFn === 'function'
Expand Down Expand Up @@ -732,16 +738,17 @@ 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);

// 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.
const openEvent = storeContext.openEvent;
const openedByVirtualPress =
openEvent?.type === 'mousedown' && isVirtualClick(openEvent as MouseEvent);

// enqueueFocus returns a rAF-cancel function; we intentionally don't cancel this focus.
void enqueueFocus(elToFocus, {
// A request left over from an earlier open would otherwise land after the popup reopens.
cancelQueuedFocus = enqueueFocus(elToFocus, {
sync: openedByVirtualPress,
preventScroll: elToFocus === floatingFocusElement,
shouldFocus() {
Expand All @@ -752,19 +759,30 @@ export function FloatingFocusManager(props: FloatingFocusManagerProps): React.JS
return false;
}

const currentActiveElement = activeElement(doc);

// A focus made inside the popup after this was queued (e.g. by list navigation) wins.
if (hadFocusInside) {
return true;
return currentActiveElement === focusedElement;
}

const currentActiveElement = activeElement(doc);
const focusMovedInside =
currentActiveElement !== elToFocus &&
contains(floatingFocusElement, currentActiveElement);
(contains(floatingFocusElement, currentActiveElement) ||
(tree != null &&
getNodeChildren(tree.nodesRef.current, getNodeId()).some((node) =>
contains(node.context?.elements.floating, currentActiveElement),
)));

return !focusMovedInside;
},
});
});

return () => {
cleanedUp = true;
cancelQueuedFocus?.();
};
}, [
disabled,
open,
Expand All @@ -774,6 +792,8 @@ export function FloatingFocusManager(props: FloatingFocusManagerProps): React.JS
openInteractionTypeRef,
openRef,
storeContext,
tree,
getNodeId,
]);

// A return-focus queued by the effect cleanup. If the effect re-arms in the same commit, a
Expand Down
120 changes: 120 additions & 0 deletions packages/react/src/utils/popups/focus/enqueueFocus.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { enqueueFocus } from './enqueueFocus';

function createButton() {
const button = document.createElement('button');
document.body.append(button);
return button;
}

describe('enqueueFocus', () => {
beforeEach(() => {
vi.useFakeTimers();
});

afterEach(() => {
vi.useRealTimers();
document.body.innerHTML = '';
});

it('focuses the element on the next frame', () => {
const button = createButton();

enqueueFocus(button);
expect(document.activeElement).not.toBe(button);

vi.advanceTimersToNextFrame();
expect(document.activeElement).toBe(button);
});

it('does not cancel focus queued for a different element', () => {
const first = createButton();
const second = createButton();
const received: HTMLElement[] = [];
first.addEventListener('focus', () => received.push(first));
second.addEventListener('focus', () => received.push(second));

enqueueFocus(first);
enqueueFocus(second);
vi.advanceTimersToNextFrame();

expect(received).toEqual([first, second]);
expect(document.activeElement).toBe(second);
});

it('keeps only the last queued focus for the same element', () => {
const button = createButton();
const staleShouldFocus = vi.fn(() => true);

enqueueFocus(button, { shouldFocus: staleShouldFocus });
enqueueFocus(button);
vi.advanceTimersToNextFrame();

expect(staleShouldFocus).not.toHaveBeenCalled();
expect(document.activeElement).toBe(button);
});

it('the returned function cancels only its own queued focus', () => {
const first = createButton();
const second = createButton();
let firstFocused = false;
first.addEventListener('focus', () => {
firstFocused = true;
});

const cancelFirst = enqueueFocus(first);
enqueueFocus(second);
cancelFirst();
vi.advanceTimersToNextFrame();

expect(firstFocused).toBe(false);
expect(document.activeElement).toBe(second);
});

it('a stale cancel function does not cancel a newer request for the element', () => {
const button = createButton();
const liveShouldFocus = vi.fn(() => true);
const finalShouldFocus = vi.fn(() => true);

const staleCancel = enqueueFocus(button);
enqueueFocus(button, { shouldFocus: liveShouldFocus });
staleCancel();
enqueueFocus(button, { shouldFocus: finalShouldFocus });
vi.advanceTimersToNextFrame();

expect(liveShouldFocus).not.toHaveBeenCalled();
expect(finalShouldFocus).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(button);
});

it('sync focus cancels the pending queued focus for the element', () => {
const button = createButton();
const staleShouldFocus = vi.fn(() => true);

enqueueFocus(button, { shouldFocus: staleShouldFocus });
enqueueFocus(button, { sync: true });
expect(document.activeElement).toBe(button);

vi.advanceTimersToNextFrame();
expect(staleShouldFocus).not.toHaveBeenCalled();
});

it('a null element is a no-op and leaves queued focus for other elements alone', () => {
const button = createButton();

enqueueFocus(button);
enqueueFocus(null);
vi.advanceTimersToNextFrame();

expect(document.activeElement).toBe(button);
});

it('skips focusing when shouldFocus returns false', () => {
const button = createButton();

enqueueFocus(button, { shouldFocus: () => false });
vi.advanceTimersToNextFrame();

expect(document.activeElement).not.toBe(button);
});
});
41 changes: 31 additions & 10 deletions packages/react/src/utils/popups/focus/enqueueFocus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,51 @@ interface Options {
shouldFocus?: (() => boolean) | undefined;
}

let rafId = 0;
// Pending focus frames are keyed per element so concurrent callers targeting
// different elements can't cancel each other's queued focus.
const pendingFocus = new WeakMap<FocusableElement, { rafId: number }>();

export function enqueueFocus(el: FocusableElement | null, options: Options = {}) {
const { preventScroll = false, sync = false, shouldFocus } = options;

cancelAnimationFrame(rafId);
if (!el) {
return NOOP;
}

const pending = pendingFocus.get(el);
if (pending) {
cancelAnimationFrame(pending.rafId);
pendingFocus.delete(el);
}

function exec() {
const exec = () => {
if (shouldFocus && !shouldFocus()) {
return;
}
el?.focus({ preventScroll });
}
el.focus({ preventScroll });
};

if (sync) {
exec();
return NOOP;
}

const currentRafId = requestAnimationFrame(exec);
rafId = currentRafId;
const request = { rafId: 0 };
pendingFocus.set(el, request);
request.rafId = requestAnimationFrame(() => {
// A cancelled frame can still run where cancelAnimationFrame is a no-op (e.g. the
// jsdom rAF stub), so only the latest request for this element may focus.
if (pendingFocus.get(el) !== request) {
return;
}
pendingFocus.delete(el);
exec();
});

return () => {
if (rafId === currentRafId) {
cancelAnimationFrame(currentRafId);
rafId = 0;
if (pendingFocus.get(el) === request) {
cancelAnimationFrame(request.rafId);
pendingFocus.delete(el);
}
};
}
Loading
Loading