Skip to content
Closed
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
110 changes: 110 additions & 0 deletions packages/react/src/utils/popups/focus/FloatingFocusManager.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<number, FrameRequestCallback>();
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(<App />);

await openThenFocus('three');
frames.run();

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

test('keeps it across a real frame', async () => {
vi.mocked(window.requestAnimationFrame).mockRestore();
render(<App />);

await openThenFocus('three');
await act(
() =>
new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
}),
);

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

test('keeps it over an explicit initialFocus target', async () => {
const frames = holdFrames();
render(<App initialFocus="two" />);

await openThenFocus('three');
frames.run();

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

test('keeps a focused SVG element', async () => {
const frames = holdFrames();
render(
<App>
<svg data-testid="svg" tabIndex={-1} />
</App>,
);

await openThenFocus('svg');
frames.run();

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

test('yields to a later move before the frame', async () => {
const frames = holdFrames();
render(<App />);

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(
<App>
<input data-testid="field" />
</App>,
);

await openThenFocus('field');
rerender(<App />);
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);
Expand Down
15 changes: 13 additions & 2 deletions packages/react/src/utils/popups/focus/FloatingFocusManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions test/setupVitest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Loading