Skip to content

Commit 3682222

Browse files
author
Balaji Sridharan
committed
🐛 Fix Firefox date input refocus issue on Tab Key press by deferring the blur operation to the next event loop
Close #5084
1 parent 5cbaa12 commit 3682222

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

src/index.tsx

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -452,17 +452,22 @@ export default class DatePicker extends Component<
452452
}
453453
};
454454

455+
safeBlur = () => {
456+
setTimeout(() => {
457+
if (this.input && this.input.blur) {
458+
this.input.blur();
459+
}
460+
}, 0);
461+
};
462+
455463
setFocus = () => {
456464
if (this.input && this.input.focus) {
457465
this.input.focus({ preventScroll: true });
458466
}
459467
};
460468

461469
setBlur = () => {
462-
if (this.input && this.input.blur) {
463-
this.input.blur();
464-
}
465-
470+
this.safeBlur();
466471
this.cancelFocusInput();
467472
};
468473

src/test/datepicker_test.test.tsx

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,24 @@ describe("DatePicker", () => {
580580
});
581581
});
582582

583-
it("should hide the calendar when the pressing Shift + Tab in the date input", () => {
583+
it("should auto-close the datepicker and lose focus when Tab key is pressed when the date input is focused", async () => {
584+
const { container } = render(<DatePicker />);
585+
const input = safeQuerySelector(container, "input");
586+
fireEvent.focus(input);
587+
588+
let reactCalendar = container.querySelector("div.react-datepicker");
589+
expect(reactCalendar).not.toBeNull();
590+
591+
fireEvent.keyDown(input, getKey(KeyType.Tab));
592+
593+
reactCalendar = container.querySelector("div.react-datepicker");
594+
expect(reactCalendar).toBeNull();
595+
await waitFor(() => {
596+
expect(document.activeElement).not.toBe(input);
597+
});
598+
});
599+
600+
it("should hide the calendar when the pressing Shift + Tab in the date input", async () => {
584601
// eslint-disable-next-line prefer-const
585602
let onBlurSpy: ReturnType<typeof jest.spyOn>;
586603
const onBlur: React.FocusEventHandler<HTMLElement> = (
@@ -594,7 +611,9 @@ describe("DatePicker", () => {
594611
fireEvent.focus(input);
595612
fireEvent.keyDown(input, getKey(KeyType.Tab, true));
596613
expect(container.querySelector(".react-datepicker")).toBeNull();
597-
expect(onBlurSpy).toHaveBeenCalled();
614+
await waitFor(() => {
615+
expect(onBlurSpy).toHaveBeenCalled();
616+
});
598617
});
599618

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

0 commit comments

Comments
 (0)