Skip to content

Commit 38eb9c1

Browse files
committed
🐛 Enable --keyboard-selected class to the YearPicker even when there is no selected date available
Closes #5669
1 parent 6e0b763 commit 38eb9c1

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

src/test/year_picker_test.test.tsx

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,23 @@ describe("YearPicker", () => {
617617
describe("keyboard-selected", () => {
618618
const className = "react-datepicker__year-text--keyboard-selected";
619619

620+
it("should set the key-selected class automatically to the current year when there is no selected date passed", () => {
621+
const { container } = render(
622+
<DatePicker showYearPicker dateFormat="yyyy" />,
623+
);
624+
625+
const dateInput = safeQuerySelector(container, "input");
626+
fireEvent.focus(dateInput);
627+
628+
const selectedYear = container.querySelector(
629+
".react-datepicker__year-text--keyboard-selected",
630+
);
631+
expect(selectedYear).toBeDefined();
632+
633+
const currentYear = new Date().getFullYear();
634+
expect(selectedYear?.textContent).toBe(`${currentYear}`);
635+
});
636+
620637
it("should set the date to the selected year of the previous period when previous button clicked", () => {
621638
let date: Date | null;
622639
const expectedDate = getStartOfYear(setYear(newDate(), 2008));

src/year.tsx

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,26 +218,38 @@ export default class Year extends Component<YearProps> {
218218

219219
isKeyboardSelected = (y: number) => {
220220
if (
221+
this.props.disabledKeyboardNavigation ||
221222
this.props.date === undefined ||
222-
this.props.selected == null ||
223223
this.props.preSelection == null
224224
) {
225225
return;
226226
}
227227

228-
const { minDate, maxDate, excludeDates, includeDates, filterDate } =
229-
this.props;
228+
const {
229+
minDate,
230+
maxDate,
231+
excludeDates,
232+
includeDates,
233+
filterDate,
234+
selected,
235+
} = this.props;
230236

231237
const date = getStartOfYear(setYear(this.props.date, y));
232238
const isDisabled =
233239
(minDate || maxDate || excludeDates || includeDates || filterDate) &&
234240
isYearDisabled(y, this.props);
235241

242+
const isSelectedDay =
243+
!!selected && isSameDay(date, getStartOfYear(selected));
244+
const isKeyboardSelectedDay = isSameDay(
245+
date,
246+
getStartOfYear(this.props.preSelection),
247+
);
248+
236249
return (
237-
!this.props.disabledKeyboardNavigation &&
238250
!this.props.inline &&
239-
!isSameDay(date, getStartOfYear(this.props.selected)) &&
240-
isSameDay(date, getStartOfYear(this.props.preSelection)) &&
251+
!isSelectedDay &&
252+
isKeyboardSelectedDay &&
241253
!isDisabled
242254
);
243255
};

0 commit comments

Comments
 (0)