Repository: Hacker0x01/react-datepicker (ts)

Issue:
Keyboard Navigation to the days of a month is not working if the pre-selected date is disabled
**Describe the bug**

If we select a date and disable the same date in the next or previous months, then when we navigate to the corresponding month and try using arrow keys (Tab) to navigate to the date, it won't work as there is no pre-selected date available in the month due to the fact that the corresponding date we selected previously is disabled in the corresponding month. 

**To Reproduce**
```
() => {
  const [startDate, setStartDate] = useState(new Date("2024-06-01"));
  return (
    <DatePicker
      selected={startDate}
      onChange={(date) => setStartDate(date)}
      excludeDates={[new Date("2024-07-01")]}
    />
  );
};
```
In the above example, I programmatically selected 1st June, 2024 and disabled 1st July, 2024 (same day in the next month).  Here once we navigate to July Month using the next month arrow keys, we can't able to switch the focus back any days of the month.


**Expected behavior**
It should pre-select the first enabled date in a month in case of the previously selected date is disabled in the corresponding month.


Pull request:
Fix #5147: 🐛 Fix navigation issue with disabled dates in date picker
Closes #5147

**Problem**
As I described in the linked ticket, the issue is if we select a date and disable the same date in the next or previous months, then when we navigate to the corresponding month and try using arrow keys (Tab) to navigate to the date, it won't work as there is no pre-selected date available in the month due to the fact that the corresponding date we selected previously is disabled in the corresponding month.

**Changes**
- Whenever month gets switched, instead of auto-preselecting the already selected day from the selected date.  I first checked if the same day in the month is disabled, if not pre-select the same day, else pre-select the first enabled date in the month.  If all the days are disabled in the rendered month, didn't pre-select any days.

## Contribution checklist
- [x] I have followed the [contributing guidelines](https://github.com/Hacker0x01/react-datepicker/blob/main/CONTRIBUTING.md).
- [x] I have added sufficient test coverage for my changes.
- [x] I have formatted my code with Prettier and checked for linting issues with ESLint for code readability.


Patch:
diff --git a/src/calendar.tsx b/src/calendar.tsx
index 74eaef19..461e1c81 100644
--- a/src/calendar.tsx
+++ b/src/calendar.tsx
@@ -1,4 +1,5 @@
 import { clsx } from "clsx";
+import { differenceInDays } from "date-fns";
 import React, { Component, createRef } from "react";
 
 import CalendarContainer from "./calendar_container";
@@ -40,6 +41,9 @@ import {
   DEFAULT_YEAR_ITEM_NUMBER,
   getMonthInLocale,
   type Locale,
+  getStartOfMonth,
+  getEndOfMonth,
+  isDayDisabled,
 } from "./date_utils";
 import InputTime from "./input_time";
 import Month from "./month";
@@ -379,14 +383,42 @@ export default class Calendar extends Component<CalendarProps, CalendarState> {
     this.props.setPreSelection && this.props.setPreSelection(date);
   };
 
+  getEnabledPreSelectionDateForMonth = (date: Date) => {
+    if (!isDayDisabled(date, this.props)) {
+      return date;
+    }
+
+    const startOfMonth = getStartOfMonth(date);
+    const endOfMonth = getEndOfMonth(date);
+
+    const totalDays = differenceInDays(endOfMonth, startOfMonth);
+
+    let preSelectedDate = null;
+
+    for (let dayIdx = 0; dayIdx <= totalDays; dayIdx++) {
+      const processingDate = addDays(startOfMonth, dayIdx);
+
+      if (!isDayDisabled(processingDate, this.props)) {
+        preSelectedDate = processingDate;
+        break;
+      }
+    }
+
+    return preSelectedDate;
+  };
+
   handleMonthChange = (date: Date): void => {
-    this.handleCustomMonthChange(date);
+    const enabledPreSelectionDate =
+      this.getEnabledPreSelectionDateForMonth(date) ?? date;
+
+    this.handleCustomMonthChange(enabledPreSelectionDate);
     if (this.props.adjustDateOnChange) {
-      this.props.onSelect(date);
+      this.props.onSelect(enabledPreSelectionDate);
       this.props.setOpen?.(true);
     }
 
-    this.props.setPreSelection && this.props.setPreSelection(date);
+    this.props.setPreSelection &&
+      this.props.setPreSelection(enabledPreSelectionDate);
   };
 
   handleCustomMonthChange = (date: Date): void => {
diff --git a/yarn.lock b/yarn.lock
index 986f30f5..06adc0e6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3160,11 +3160,11 @@ __metadata:
   linkType: hard
 
 "@types/node@npm:*, @types/node@npm:22":
-  version: 22.7.5
-  resolution: "@types/node@npm:22.7.5"
+  version: 22.5.4
+  resolution: "@types/node@npm:22.5.4"
   dependencies:
     undici-types: "npm:~6.19.2"
-  checksum: 10c0/cf11f74f1a26053ec58066616e3a8685b6bcd7259bc569738b8f752009f9f0f7f85a1b2d24908e5b0f752482d1e8b6babdf1fbb25758711ec7bb9500bfcd6e60
+  checksum: 10c0/b445daa7eecd761ad4d778b882d6ff7bcc3b4baad2086ea9804db7c5d4a4ab0298b00d7f5315fc640a73b5a1d52bbf9628e09c9fec0cf44dbf9b4df674a8717d
   languageName: node
   linkType: hard
 
@@ -5517,15 +5517,15 @@ __metadata:
   linkType: hard
 
 "eslint-plugin-unused-imports@npm:^4.1.3":
-  version: 4.1.4
-  resolution: "eslint-plugin-unused-imports@npm:4.1.4"
+  version: 4.1.3
+  resolution: "eslint-plugin-unused-imports@npm:4.1.3"
   peerDependencies:
     "@typescript-eslint/eslint-plugin": ^8.0.0-0 || ^7.0.0 || ^6.0.0 || ^5.0.0
     eslint: ^9.0.0 || ^8.0.0
   peerDependenciesMeta:
     "@typescript-eslint/eslint-plugin":
       optional: true
-  checksum: 10c0/3899f64b0e8b23fa6b81e2754fc10f93d8741e051d70390a8100ca39af7878bde8625f234b76111af69562ef2512104b52c3703e986ccb3ac9adc07911896acf
+  checksum: 10c0/e30120e274554b99756fb4c2af123ca03f502fc55bc7e5b095fa9278b96cb32f1e405cf2e533aa8b0f8ca28c504ecf15daed9e4b5fccb172316e256a994fdebe
   languageName: node
   linkType: hard
 


Test patch:
diff --git a/src/test/calendar_test.test.tsx b/src/test/calendar_test.test.tsx
index f0912d72..9bf6d34e 100644
--- a/src/test/calendar_test.test.tsx
+++ b/src/test/calendar_test.test.tsx
@@ -3,6 +3,7 @@
  */
 
 import { render, fireEvent, act, waitFor } from "@testing-library/react";
+import { setDate, startOfMonth, eachDayOfInterval, endOfMonth } from "date-fns";
 import { endOfYear } from "date-fns/endOfYear";
 import { isSunday } from "date-fns/isSunday";
 import { eo } from "date-fns/locale/eo";
@@ -28,6 +29,8 @@ import {
   isSameDay,
   subMonths,
   subYears,
+  addDays,
+  getDate,
 } from "../date_utils";
 import DatePicker from "../index";
 
@@ -2257,6 +2260,112 @@ describe("Calendar", () => {
         currentMonth === 0 ? 11 : currentMonth - 1,
       );
     });
+
+    describe("pre-selection & disabled dates", () => {
+      it("should update the pre-selected dates to the first enabled day in a month when the next month is selected", () => {
+        const selected = new Date("2024-06-01");
+        const excludeDate = addMonths(selected, 1);
+
+        const { container } = render(
+          <DatePicker selected={selected} excludeDates={[excludeDate]} />,
+        );
+        const input = safeQuerySelector<HTMLInputElement>(container, "input");
+        fireEvent.focus(input);
+
+        const nextButton = safeQuerySelector<HTMLButtonElement>(
+          container,
+          ".react-datepicker__navigation--next",
+        );
+        fireEvent.click(nextButton);
+
+        const preSelectedNewDate = safeQuerySelector(
+          container,
+          ".react-datepicker__day--keyboard-selected",
+        ).textContent;
+        const expectedPreSelectedNewDate = addDays(excludeDate, 1);
+
+        expect(Number(preSelectedNewDate)).toBe(
+          getDate(expectedPreSelectedNewDate),
+        );
+      });
+
+      it("should update the pre-selected dates to the first enabled day in a month when the previous month is selected", () => {
+        const selected = new Date("2024-06-08");
+        const excludeDate = addMonths(selected, 1);
+
+        const { container } = render(
+          <DatePicker selected={selected} excludeDates={[excludeDate]} />,
+        );
+        const input = safeQuerySelector<HTMLInputElement>(container, "input");
+        fireEvent.focus(input);
+
+        const nextButton = safeQuerySelector<HTMLButtonElement>(
+          container,
+          ".react-datepicker__navigation--next",
+        );
+        fireEvent.click(nextButton);
+
+        const preSelectedNewDate = safeQuerySelector(
+          container,
+          ".react-datepicker__day--keyboard-selected",
+        ).textContent;
+        const expectedPreSelectedNewDate = setDate(excludeDate, 1);
+
+        expect(Number(preSelectedNewDate)).toBe(
+          getDate(expectedPreSelectedNewDate),
+        );
+      });
+
+      it("shouldn't set pre-select any date if all dates of a next month is disabled", () => {
+        const selected = new Date("2024-06-08");
+        const nextMonth = addMonths(selected, 1);
+        const excludeDates = eachDayOfInterval({
+          start: startOfMonth(nextMonth),
+          end: endOfMonth(nextMonth),
+        });
+
+        const { container } = render(
+          <DatePicker selected={selected} excludeDates={excludeDates} />,
+        );
+        const input = safeQuerySelector<HTMLInputElement>(container, "input");
+        fireEvent.focus(input);
+
+        const nextButton = safeQuerySelector<HTMLButtonElement>(
+          container,
+          ".react-datepicker__navigation--next",
+        );
+        fireEvent.click(nextButton);
+
+        expect(
+          container.querySelector(".react-datepicker__day--keyboard-selected"),
+        ).toBeNull();
+      });
+
+      it("shouldn't set pre-select any date if all dates of a last month is disabled", () => {
+        const selected = new Date("2024-06-08");
+        const lastMonth = subMonths(selected, 1);
+        const excludeDates = eachDayOfInterval({
+          start: startOfMonth(lastMonth),
+          end: endOfMonth(lastMonth),
+        });
+
+        const { container } = render(
+          <DatePicker selected={selected} excludeDates={excludeDates} />,
+        );
+        const input = safeQuerySelector<HTMLInputElement>(container, "input");
+        fireEvent.focus(input);
+
+        const nextButton = safeQuerySelector<HTMLButtonElement>(
+          container,
+          ".react-datepicker__navigation--previous",
+        );
+        fireEvent.click(nextButton);
+
+        expect(
+          container.querySelector(".react-datepicker__day--keyboard-selected"),
+        ).toBeNull();
+      });
+    });
   });
 
   describe("showTimeSelect", () => {