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
28 changes: 28 additions & 0 deletions packages/react-aria-components/test/DateField.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -562,4 +562,32 @@ describe('DateField', () => {
expect(segements[1]).toHaveTextContent('dd');
expect(segements[2]).toHaveTextContent('yyyy');
});

// Regression test for #10259: in Firefox a stale selection anchor can remain inside a segment
// after focus moves away, and the selectionchange handler would collapse onto it, stealing focus.
it('does not collapse the selection onto a segment while another element is focused', () => {
let {getByRole} = render(
<>
<button>sibling</button>
<DateField defaultValue={new CalendarDate(2020, 2, 3)}>
<Label>Date</Label>
<DateInput>{segment => <DateSegment segment={segment} />}</DateInput>
</DateField>
</>
);

let button = getByRole('button');
let segment = within(getByRole('group')).getAllByRole('spinbutton').at(-1);
act(() => button.focus());
expect(document.activeElement).toBe(button);

let collapse = jest.fn();
jest.spyOn(window, 'getSelection').mockReturnValue({anchorNode: segment.firstChild, collapse});
act(() => {
document.dispatchEvent(new Event('selectionchange'));
});

expect(collapse).not.toHaveBeenCalled();
jest.restoreAllMocks();
});
});
8 changes: 7 additions & 1 deletion packages/react-aria/src/datepicker/useDateSegment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,13 @@ export function useDateSegment(
// Otherwise, when tapping on a segment in Android Chrome and then entering text,
// composition events will be fired that break the DOM structure and crash the page.
let selection = window.getSelection();
if (selection?.anchorNode && nodeContains(ref.current, selection?.anchorNode)) {
// Only collapse while focused, otherwise a stale anchor left in the segment (e.g. on Firefox)
// steals focus back into it on selectionchange. See #10259.
if (
selection?.anchorNode &&
nodeContains(ref.current, selection?.anchorNode) &&
getActiveElement() === ref.current
) {
selection.collapse(ref.current);
}
});
Expand Down