Skip to content

Commit

Permalink
🐛 Fix Firefox date input refocus issue on Tab Key press by deferring …
Browse files Browse the repository at this point in the history
…the blur operation to the next event loop

Close #5084
  • Loading branch information
Balaji Sridharan committed Oct 20, 2024
1 parent 5cbaa12 commit 3682222
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
13 changes: 9 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -452,17 +452,22 @@ export default class DatePicker extends Component<
}
};

safeBlur = () => {
setTimeout(() => {
if (this.input && this.input.blur) {
this.input.blur();
}
}, 0);
};

setFocus = () => {
if (this.input && this.input.focus) {
this.input.focus({ preventScroll: true });
}
};

setBlur = () => {
if (this.input && this.input.blur) {
this.input.blur();
}

this.safeBlur();
this.cancelFocusInput();
};

Expand Down
23 changes: 21 additions & 2 deletions src/test/datepicker_test.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,24 @@ describe("DatePicker", () => {
});
});

it("should hide the calendar when the pressing Shift + Tab in the date input", () => {
it("should auto-close the datepicker and lose focus when Tab key is pressed when the date input is focused", async () => {
const { container } = render(<DatePicker />);
const input = safeQuerySelector(container, "input");
fireEvent.focus(input);

let reactCalendar = container.querySelector("div.react-datepicker");
expect(reactCalendar).not.toBeNull();

fireEvent.keyDown(input, getKey(KeyType.Tab));

reactCalendar = container.querySelector("div.react-datepicker");
expect(reactCalendar).toBeNull();
await waitFor(() => {
expect(document.activeElement).not.toBe(input);
});
});

it("should hide the calendar when the pressing Shift + Tab in the date input", async () => {
// eslint-disable-next-line prefer-const
let onBlurSpy: ReturnType<typeof jest.spyOn>;
const onBlur: React.FocusEventHandler<HTMLElement> = (
Expand All @@ -594,7 +611,9 @@ describe("DatePicker", () => {
fireEvent.focus(input);
fireEvent.keyDown(input, getKey(KeyType.Tab, true));
expect(container.querySelector(".react-datepicker")).toBeNull();
expect(onBlurSpy).toHaveBeenCalled();
await waitFor(() => {
expect(onBlurSpy).toHaveBeenCalled();
});
});

it("should not apply the react-datepicker-ignore-onclickoutside class to the date input when closed", () => {
Expand Down

0 comments on commit 3682222

Please sign in to comment.