diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 3b89d7633a0a..2edfd618ed34 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -8977,8 +8977,11 @@ const CONST = { }, CALENDAR_PICKER: { YEAR_PICKER: 'CalendarPicker-YearPicker', + MONTH_PICKER: 'CalendarPicker-MonthPicker', PREV_MONTH: 'CalendarPicker-PrevMonth', NEXT_MONTH: 'CalendarPicker-NextMonth', + PREV_YEAR: 'CalendarPicker-PrevYear', + NEXT_YEAR: 'CalendarPicker-NextYear', DAY: 'CalendarPicker-Day', }, PREV_NEXT_BUTTONS: { diff --git a/src/components/DatePicker/CalendarPicker/MonthPickerModal.tsx b/src/components/DatePicker/CalendarPicker/MonthPickerModal.tsx new file mode 100644 index 000000000000..e9273e363073 --- /dev/null +++ b/src/components/DatePicker/CalendarPicker/MonthPickerModal.tsx @@ -0,0 +1,109 @@ +import React, {useEffect, useMemo, useState} from 'react'; +import {Keyboard} from 'react-native'; +import HeaderWithBackButton from '@components/HeaderWithBackButton'; +import Modal from '@components/Modal'; +import ScreenWrapper from '@components/ScreenWrapper'; +import SelectionList from '@components/SelectionList'; +import RadioListItem from '@components/SelectionList/ListItem/RadioListItem'; +import useLocalize from '@hooks/useLocalize'; +import useThemeStyles from '@hooks/useThemeStyles'; +import DateUtils from '@libs/DateUtils'; +import CONST from '@src/CONST'; + +type MonthPickerModalProps = { + /** Whether the modal is visible */ + isVisible: boolean; + + /** Currently selected month (0-indexed) */ + currentMonth?: number; + + /** The year currently being viewed */ + currentYear?: number; + + /** A minimum date (earliest) allowed to select */ + minDate?: Date; + + /** A maximum date (latest) allowed to select */ + maxDate?: Date; + + /** Function to call when the user selects a month */ + onMonthChange?: (month: number) => void; + + /** Function to call when the user closes the month picker */ + onClose?: () => void; +}; + +function MonthPickerModal({isVisible, currentMonth = new Date().getMonth(), currentYear = new Date().getFullYear(), minDate, maxDate, onMonthChange, onClose}: MonthPickerModalProps) { + const styles = useThemeStyles(); + const {translate} = useLocalize(); + const [searchText, setSearchText] = useState(''); + const monthNames = DateUtils.getMonthNames(); + + const allMonths = useMemo(() => DateUtils.getFilteredMonthItems(monthNames, currentYear, currentMonth, minDate, maxDate), [monthNames, currentMonth, currentYear, minDate, maxDate]); + + const {data, headerMessage} = useMemo(() => { + const filteredMonths = searchText === '' ? allMonths : allMonths.filter((month) => month.text.toLowerCase().includes(searchText.toLowerCase())); + return { + headerMessage: !filteredMonths.length ? translate('common.noResultsFound') : '', + data: filteredMonths, + }; + }, [allMonths, searchText, translate]); + + useEffect(() => { + if (isVisible) { + return; + } + setSearchText(''); + }, [isVisible]); + + const textInputOptions = useMemo( + () => ({ + label: translate('monthPickerPage.selectMonth'), + value: searchText, + onChangeText: setSearchText, + headerMessage, + }), + [headerMessage, searchText, translate], + ); + + return ( + onClose?.()} + onModalHide={onClose} + shouldHandleNavigationBack + shouldUseCustomBackdrop + onBackdropPress={onClose} + enableEdgeToEdgeBottomSafeAreaPadding + > + + + { + Keyboard.dismiss(); + onMonthChange?.(option.value); + }} + textInputOptions={textInputOptions} + initiallyFocusedItemKey={currentMonth.toString()} + disableMaintainingScrollPosition + addBottomSafeAreaPadding + shouldStopPropagation + showScrollIndicator + /> + + + ); +} + +export default MonthPickerModal; diff --git a/src/components/DatePicker/CalendarPicker/index.tsx b/src/components/DatePicker/CalendarPicker/index.tsx index 26c0be13e293..f51e0e54eedf 100644 --- a/src/components/DatePicker/CalendarPicker/index.tsx +++ b/src/components/DatePicker/CalendarPicker/index.tsx @@ -1,4 +1,22 @@ -import {addMonths, endOfDay, endOfMonth, format, getYear, isSameDay, parseISO, setDate, setYear, startOfDay, startOfMonth, subMonths} from 'date-fns'; +import { + addMonths, + addYears, + endOfDay, + endOfMonth, + endOfYear, + format, + getYear, + isSameDay, + parseISO, + setDate, + setMonth, + setYear, + startOfDay, + startOfMonth, + startOfYear, + subMonths, + subYears, +} from 'date-fns'; import {Str} from 'expensify-common'; import React, {useCallback, useEffect, useRef, useState} from 'react'; import type {StyleProp, ViewStyle} from 'react-native'; @@ -15,6 +33,7 @@ import CONST from '@src/CONST'; import ArrowIcon from './ArrowIcon'; import Day from './Day'; import generateMonthMatrix from './generateMonthMatrix'; +import MonthPickerModal from './MonthPickerModal'; import type CalendarPickerListItem from './types'; import YearPickerModal from './YearPickerModal'; @@ -68,8 +87,10 @@ function CalendarPicker({ const themeStyles = useThemeStyles(); const {translate} = useLocalize(); const pressableRef = useRef(null); + const monthPressableRef = useRef(null); const [currentDateView, setCurrentDateView] = useState(() => getInitialCurrentDateView(value, minDate, maxDate)); const [isYearPickerVisible, setIsYearPickerVisible] = useState(false); + const [isMonthPickerVisible, setIsMonthPickerVisible] = useState(false); const isFirstRender = useRef(true); const currentMonthView = currentDateView.getMonth(); @@ -104,6 +125,11 @@ function CalendarPicker({ requestAnimationFrame(() => setIsYearPickerVisible(false)); }; + const onMonthSelected = (month: number) => { + setCurrentDateView((prev) => setMonth(new Date(prev), month)); + requestAnimationFrame(() => setIsMonthPickerVisible(false)); + }; + /** * Calls the onSelected function with the selected date. * @param day - The day of the month that was selected. @@ -153,10 +179,34 @@ function CalendarPicker({ }); }; + const moveToPrevYear = () => { + setCurrentDateView((prev) => { + let prevYear = subYears(new Date(prev), 1); + if (prevYear < new Date(minDate)) { + prevYear = new Date(minDate); + } + setYears((prevYears) => prevYears.map((item) => ({...item, isSelected: item.value === prevYear.getFullYear()}))); + return prevYear; + }); + }; + + const moveToNextYear = () => { + setCurrentDateView((prev) => { + let nextYear = addYears(new Date(prev), 1); + if (nextYear > new Date(maxDate)) { + nextYear = new Date(maxDate); + } + setYears((prevYears) => prevYears.map((item) => ({...item, isSelected: item.value === nextYear.getFullYear()}))); + return nextYear; + }); + }; + const monthNames = DateUtils.getMonthNames().map((month) => Str.UCFirst(month)); const daysOfWeek = DateUtils.getDaysOfWeek().map((day) => day.toUpperCase()); const hasAvailableDatesNextMonth = startOfDay(new Date(maxDate)) > endOfMonth(new Date(currentDateView)); const hasAvailableDatesPrevMonth = endOfDay(new Date(minDate)) < startOfMonth(new Date(currentDateView)); + const hasAvailableDatesNextYear = startOfDay(new Date(maxDate)) > endOfYear(new Date(currentDateView)); + const hasAvailableDatesPrevYear = endOfDay(new Date(minDate)) < startOfYear(new Date(currentDateView)); useEffect(() => { if (isSmallScreenWidth || isFirstRender.current) { @@ -178,7 +228,7 @@ function CalendarPicker({ const webOnlyMarginStyle = isSmallScreenWidth ? {} : styles.mh1; const calendarContainerStyle = isSmallScreenWidth ? [webOnlyMarginStyle, themeStyles.calendarBodyContainer] : [webOnlyMarginStyle, animatedStyle]; - const headerPaddingStyle = headerContainerStyle ?? themeStyles.ph5; + const headerPaddingStyle = headerContainerStyle ?? themeStyles.ph3; // On mobile (isSmallScreenWidth is always true on native), the height animation is skipped // so using Animated.View is unnecessary. Using a plain View with collapsable={false} avoids // activating Reanimated's Fabric commit hook, which on Android can interfere with React's @@ -188,49 +238,19 @@ function CalendarPicker({ const getAccessibilityState = useCallback((isSelected: boolean) => ({selected: isSelected}), []); return ( - + - { - pressableRef?.current?.blur(); - setIsYearPickerVisible(true); - }} - ref={pressableRef} - style={[themeStyles.alignItemsCenter, themeStyles.flexRow, themeStyles.flex1, themeStyles.justifyContentStart]} - wrapperStyle={[themeStyles.alignItemsCenter]} - hoverDimmingValue={1} - disabled={years.length <= 1} - testID="currentYearButton" - accessibilityLabel={`${currentYearView}, ${translate('common.currentYear')}`} - role={CONST.ROLE.BUTTON} - sentryLabel={CONST.SENTRY_LABEL.CALENDAR_PICKER.YEAR_PICKER} - > - - {currentYearView} - - - - - - {monthNames.at(currentMonthView)} - + @@ -239,19 +259,96 @@ function CalendarPicker({ direction={CONST.DIRECTION.LEFT} /> + + { + monthPressableRef?.current?.blur(); + setIsMonthPickerVisible(true); + }} + ref={monthPressableRef} + style={[themeStyles.alignItemsCenter]} + wrapperStyle={[themeStyles.alignItemsCenter]} + hoverDimmingValue={1} + testID="currentMonthButton" + accessibilityLabel={`${monthNames.at(currentMonthView)}, ${translate('common.currentMonth')}`} + role={CONST.ROLE.BUTTON} + sentryLabel={CONST.SENTRY_LABEL.CALENDAR_PICKER.MONTH_PICKER} + > + + {monthNames.at(currentMonthView)} + + + + + + + + + { + pressableRef?.current?.blur(); + setIsYearPickerVisible(true); + }} + ref={pressableRef} + style={[themeStyles.alignItemsCenter]} + wrapperStyle={[themeStyles.alignItemsCenter]} + hoverDimmingValue={1} + disabled={years.length <= 1} + testID="currentYearButton" + accessibilityLabel={`${currentYearView}, ${translate('common.currentYear')}`} + role={CONST.ROLE.BUTTON} + sentryLabel={CONST.SENTRY_LABEL.CALENDAR_PICKER.YEAR_PICKER} + > + + {currentYearView} + + + + + + + {daysOfWeek.map((dayOfWeek) => ( @@ -332,6 +429,15 @@ function CalendarPicker({ onYearChange={onYearSelected} onClose={() => setIsYearPickerVisible(false)} /> + setIsMonthPickerVisible(false)} + /> ); } diff --git a/src/languages/de.ts b/src/languages/de.ts index 4f1c05a2b8a0..57d33c415c03 100644 --- a/src/languages/de.ts +++ b/src/languages/de.ts @@ -534,6 +534,10 @@ const translations: TranslationDeepObject = { approver: 'Genehmiger', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `Ziffer ${digitIndex} von ${totalDigits} eingeben`, copyOfReportName: (reportName: string) => `Kopie von ${reportName}`, + previousMonth: 'Vorheriger Monat', + nextMonth: 'Nächster Monat', + previousYear: 'Vorheriges Jahr', + nextYear: 'Nächstes Jahr', }, socials: { podcast: 'Folgen Sie uns auf Podcast', @@ -8859,5 +8863,6 @@ Hier ist ein *Testbeleg*, um dir zu zeigen, wie es funktioniert:`, positiveButton: 'Ja!', negativeButton: 'Nicht wirklich', }, + monthPickerPage: {month: 'Monat', selectMonth: 'Bitte wählen Sie einen Monat aus'}, }; export default translations; diff --git a/src/languages/en.ts b/src/languages/en.ts index 4515fa15f429..6bda5d2fe86b 100644 --- a/src/languages/en.ts +++ b/src/languages/en.ts @@ -134,6 +134,10 @@ const translations = { searchWithThreeDots: 'Search...', next: 'Next', previous: 'Previous', + previousMonth: 'Previous month', + nextMonth: 'Next month', + previousYear: 'Previous year', + nextYear: 'Next year', // @context Navigation button that returns the user to the previous screen. Should be interpreted as a UI action label. goBack: 'Go back', create: 'Create', @@ -3310,6 +3314,10 @@ const translations = { year: 'Year', selectYear: 'Please select a year', }, + monthPickerPage: { + month: 'Month', + selectMonth: 'Please select a month', + }, focusModeUpdateModal: { title: 'Welcome to #focus mode!', prompt: (priorityModePageUrl: string) => diff --git a/src/languages/es.ts b/src/languages/es.ts index 9869d18a2177..be04f21d8b01 100644 --- a/src/languages/es.ts +++ b/src/languages/es.ts @@ -49,6 +49,10 @@ const translations: TranslationDeepObject = { next: 'Siguiente', create: 'Crear', previous: 'Anterior', + previousMonth: 'Mes anterior', + nextMonth: 'Próximo mes', + previousYear: 'Año anterior', + nextYear: 'Próximo año', goBack: 'Volver', add: 'Añadir', resend: 'Reenviar', @@ -3157,6 +3161,10 @@ ${amount} para ${merchant} - ${date}`, year: 'Año', selectYear: 'Por favor, selecciona un año', }, + monthPickerPage: { + month: 'Mes', + selectMonth: 'Por favor, selecciona un mes', + }, focusModeUpdateModal: { title: '¡Bienvenido al modo #concentración!', prompt: (priorityModePageUrl) => diff --git a/src/languages/fr.ts b/src/languages/fr.ts index 0e8a921d5f5d..84936872dd46 100644 --- a/src/languages/fr.ts +++ b/src/languages/fr.ts @@ -534,6 +534,10 @@ const translations: TranslationDeepObject = { approver: 'Approbateur', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `saisir le chiffre ${digitIndex} sur ${totalDigits}`, copyOfReportName: (reportName: string) => `Copie de ${reportName}`, + previousMonth: 'Mois précédent', + nextMonth: 'Le mois prochain', + previousYear: 'Année précédente', + nextYear: 'L’an prochain', }, socials: { podcast: 'Suivez-nous sur Podcast', @@ -8883,5 +8887,6 @@ Voici un *reçu test* pour vous montrer comment ça fonctionne :`, positiveButton: 'Oui !', negativeButton: 'Pas vraiment', }, + monthPickerPage: {month: 'Mois', selectMonth: 'Veuillez sélectionner un mois'}, }; export default translations; diff --git a/src/languages/it.ts b/src/languages/it.ts index 5788af29bd0f..2f59facf0c7f 100644 --- a/src/languages/it.ts +++ b/src/languages/it.ts @@ -534,6 +534,10 @@ const translations: TranslationDeepObject = { approver: 'Approvante', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `inserire la cifra ${digitIndex} di ${totalDigits}`, copyOfReportName: (reportName: string) => `Copia di ${reportName}`, + previousMonth: 'Mese precedente', + nextMonth: 'Il prossimo mese', + previousYear: 'Anno precedente', + nextYear: "L'anno prossimo", }, socials: { podcast: 'Seguici su Podcast', @@ -8850,5 +8854,6 @@ Ecco una *ricevuta di prova* per mostrarti come funziona:`, positiveButton: 'Sì!', negativeButton: 'Non proprio', }, + monthPickerPage: {month: 'Mese', selectMonth: 'Seleziona un mese'}, }; export default translations; diff --git a/src/languages/ja.ts b/src/languages/ja.ts index 363c2e61be25..c97be8a58c5c 100644 --- a/src/languages/ja.ts +++ b/src/languages/ja.ts @@ -533,6 +533,10 @@ const translations: TranslationDeepObject = { approver: '承認者', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `${totalDigits}桁中${digitIndex}桁目を入力`, copyOfReportName: (reportName: string) => `${reportName} のコピー`, + previousMonth: '前月', + nextMonth: '来月', + previousYear: '前年', + nextYear: '来年', }, socials: { podcast: 'ポッドキャストでフォロー', @@ -8739,5 +8743,6 @@ ${reportName} positiveButton: 'やった!', negativeButton: 'そうでもありません', }, + monthPickerPage: {month: '月', selectMonth: '月を選択してください'}, }; export default translations; diff --git a/src/languages/nl.ts b/src/languages/nl.ts index 714fb58781e3..54dae542ae9d 100644 --- a/src/languages/nl.ts +++ b/src/languages/nl.ts @@ -533,6 +533,10 @@ const translations: TranslationDeepObject = { approver: 'Fiatteur', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `voer cijfer ${digitIndex} van ${totalDigits} in`, copyOfReportName: (reportName: string) => `Kopie van ${reportName}`, + previousMonth: 'Vorige maand', + nextMonth: 'Volgende maand', + previousYear: 'Vorig jaar', + nextYear: 'Volgend jaar', }, socials: { podcast: 'Volg ons op Podcast', @@ -8827,5 +8831,6 @@ Hier is een *proefbon* om je te laten zien hoe het werkt:`, positiveButton: 'Ja!', negativeButton: 'Niet echt', }, + monthPickerPage: {month: 'Maand', selectMonth: 'Selecteer een maand'}, }; export default translations; diff --git a/src/languages/pl.ts b/src/languages/pl.ts index fa6da465e041..348b25108a7b 100644 --- a/src/languages/pl.ts +++ b/src/languages/pl.ts @@ -533,6 +533,10 @@ const translations: TranslationDeepObject = { approver: 'Osoba zatwierdzająca', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `wprowadź cyfrę ${digitIndex} z ${totalDigits}`, copyOfReportName: (reportName: string) => `Kopia raportu ${reportName}`, + previousMonth: 'Poprzedni miesiąc', + nextMonth: 'W przyszłym miesiącu', + previousYear: 'Poprzedni rok', + nextYear: 'W przyszłym roku', }, socials: { podcast: 'Śledź nas na Podcast', @@ -8805,5 +8809,6 @@ Oto *paragon testowy*, żeby pokazać Ci, jak to działa:`, positiveButton: 'Tak!', negativeButton: 'Niekoniecznie', }, + monthPickerPage: {month: 'Miesiąc', selectMonth: 'Wybierz miesiąc'}, }; export default translations; diff --git a/src/languages/pt-BR.ts b/src/languages/pt-BR.ts index 6e387c9a85bc..05826912ea65 100644 --- a/src/languages/pt-BR.ts +++ b/src/languages/pt-BR.ts @@ -532,6 +532,10 @@ const translations: TranslationDeepObject = { approver: 'Aprovador', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `inserir dígito ${digitIndex} de ${totalDigits}`, copyOfReportName: (reportName: string) => `Cópia de ${reportName}`, + previousMonth: 'Mês anterior', + nextMonth: 'Próximo mês', + previousYear: 'Ano anterior', + nextYear: 'Ano que vem', }, socials: { podcast: 'Siga-nos no Podcast', @@ -8814,5 +8818,6 @@ Aqui está um *comprovante de teste* para mostrar como funciona:`, positiveButton: 'Sim!', negativeButton: 'Na verdade, não', }, + monthPickerPage: {month: 'Mês', selectMonth: 'Selecione um mês por favor'}, }; export default translations; diff --git a/src/languages/zh-hans.ts b/src/languages/zh-hans.ts index 070f5626ae42..b5dd415717c6 100644 --- a/src/languages/zh-hans.ts +++ b/src/languages/zh-hans.ts @@ -529,6 +529,10 @@ const translations: TranslationDeepObject = { approver: '审批人', enterDigitLabel: ({digitIndex, totalDigits}: {digitIndex: number; totalDigits: number}) => `输入第 ${digitIndex} 位数字,共 ${totalDigits} 位`, copyOfReportName: (reportName: string) => `${reportName} 的副本`, + previousMonth: '上个月', + nextMonth: '下个月', + previousYear: '上一年', + nextYear: '明年', }, socials: { podcast: '在播客上关注我们', @@ -8568,5 +8572,6 @@ ${reportName} groups: {title: '群组', memberCount: () => ({one: '1 名成员', other: (count: number) => `${count} 名成员`})}, }, proactiveAppReview: {title: '喜欢全新的 Expensify 吗?', description: '请告诉我们,这样我们就能帮助您让报销体验变得更好。', positiveButton: '太棒了!', negativeButton: '不太是'}, + monthPickerPage: {month: '月份', selectMonth: '请选择月份'}, }; export default translations; diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index 834a4391f423..e17429f54562 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -25,6 +25,7 @@ import { parse, set, startOfDay, + startOfMonth, startOfWeek, subDays, subMilliseconds, @@ -304,6 +305,32 @@ function getMonthNames(): string[] { return monthsArray.map((monthDate) => format(monthDate, CONST.DATE.MONTH_FORMAT)); } +/** + * Filters month names by min/max date boundaries and returns list items for SelectionList. + */ +function getFilteredMonthItems(monthNames: string[], currentYear: number, currentMonth: number, minDate?: Date, maxDate?: Date) { + const minMonthStart = minDate ? startOfMonth(new Date(minDate)) : undefined; + const maxMonthEnd = maxDate ? endOfMonth(new Date(maxDate)) : undefined; + + return monthNames + .map((month, index) => { + const monthStart = startOfMonth(new Date(currentYear, index)); + const monthEnd = endOfMonth(new Date(currentYear, index)); + const isBeforeMin = minMonthStart ? monthEnd < minMonthStart : false; + const isAfterMax = maxMonthEnd ? monthStart > maxMonthEnd : false; + if (isBeforeMin || isAfterMax) { + return null; + } + return { + text: month.charAt(0).toUpperCase() + month.slice(1), + value: index, + keyForList: index.toString(), + isSelected: index === currentMonth, + }; + }) + .filter((item): item is NonNullable => item !== null); +} + /** * @returns [Monday, Tuesday, Wednesday, ...] */ @@ -1093,6 +1120,7 @@ const DateUtils = { isTomorrow, isYesterday, getMonthNames, + getFilteredMonthItems, getDaysOfWeek, formatWithUTCTimeZone, getWeekEndsOn, diff --git a/tests/unit/CalendarPickerTest.tsx b/tests/unit/CalendarPickerTest.tsx index 0b8c3a80ce1a..8d90d9595897 100644 --- a/tests/unit/CalendarPickerTest.tsx +++ b/tests/unit/CalendarPickerTest.tsx @@ -281,4 +281,172 @@ describe('CalendarPicker', () => { // then the label 24 should be clickable expect(screen.getByLabelText('Monday, February 24, 2003')).toBeEnabled(); }); + + test('clicking next year arrow updates the displayed year', () => { + const minDate = new Date('2020-01-01'); + const maxDate = new Date('2030-12-31'); + const value = '2025-06-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('next-year-arrow')); + + expect(within(screen.getByTestId('currentYearText')).getByText('2026')).toBeTruthy(); + }); + + test('clicking previous year arrow updates the displayed year', () => { + const minDate = new Date('2020-01-01'); + const maxDate = new Date('2030-12-31'); + const value = '2025-06-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('prev-year-arrow')); + + expect(within(screen.getByTestId('currentYearText')).getByText('2024')).toBeTruthy(); + }); + + test('should block the previous year arrow when there are no available dates in the previous year', async () => { + const minDate = new Date('2023-01-01'); + const value = new Date('2023-06-15'); + render( + , + ); + + const user = userEvent.setup(); + await user.press(screen.getByTestId('prev-year-arrow')); + + // Year should still be 2023 since the button is disabled + expect(within(screen.getByTestId('currentYearText')).getByText('2023')).toBeTruthy(); + }); + + test('should block the next year arrow when there are no available dates in the next year', async () => { + const maxDate = new Date('2023-12-31'); + const value = new Date('2023-06-15'); + render( + , + ); + + const user = userEvent.setup(); + await user.press(screen.getByTestId('next-year-arrow')); + + // Year should still be 2023 since the button is disabled + expect(within(screen.getByTestId('currentYearText')).getByText('2023')).toBeTruthy(); + }); + + test('prev year arrow should clamp to minDate when navigating would go below it', () => { + const minDate = new Date('2023-11-01'); + const maxDate = new Date('2030-12-31'); + const value = '2024-03-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('prev-year-arrow')); + + // Should clamp to minDate (November 2023), not land on March 2023 + expect(within(screen.getByTestId('currentYearText')).getByText('2023')).toBeTruthy(); + expect(within(screen.getByTestId('currentMonthText')).getByText(monthNames.at(10) ?? '')).toBeTruthy(); + }); + + test('next year arrow should clamp to maxDate when navigating would go above it', () => { + const minDate = new Date('2020-01-01'); + const maxDate = new Date('2025-04-20'); + const value = '2024-09-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('next-year-arrow')); + + // Should clamp to maxDate (April 2025), not land on September 2025 + expect(within(screen.getByTestId('currentYearText')).getByText('2025')).toBeTruthy(); + expect(within(screen.getByTestId('currentMonthText')).getByText(monthNames.at(3) ?? '')).toBeTruthy(); + }); + + test('clicking next month arrow in December should update year to next year', () => { + const minDate = new Date('2020-01-01'); + const maxDate = new Date('2030-12-31'); + const value = '2025-12-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('next-month-arrow')); + + expect(within(screen.getByTestId('currentYearText')).getByText('2026')).toBeTruthy(); + expect(screen.getByText(monthNames.at(0) ?? '')).toBeTruthy(); + }); + + test('clicking previous month arrow in January should update year to previous year', () => { + const minDate = new Date('2020-01-01'); + const maxDate = new Date('2030-12-31'); + const value = '2025-01-15'; + render( + , + ); + + fireEvent.press(screen.getByTestId('prev-month-arrow')); + + expect(within(screen.getByTestId('currentYearText')).getByText('2024')).toBeTruthy(); + expect(screen.getByText(monthNames.at(11) ?? '')).toBeTruthy(); + }); + + test('month picker filtering should exclude months before minDate', () => { + const filteredMonths = DateUtils.getFilteredMonthItems(monthNames, 2023, 6, new Date('2023-06-01'), new Date('2030-12-31')); + + // Months before June (index 5) should be excluded + expect(filteredMonths.find((m) => m.value === 0)).toBeUndefined(); + expect(filteredMonths.find((m) => m.value === 4)).toBeUndefined(); + + // June and later months should be included + expect(filteredMonths.find((m) => m.value === 5)).toBeTruthy(); + expect(filteredMonths.find((m) => m.value === 11)).toBeTruthy(); + expect(filteredMonths).toHaveLength(7); + }); + + test('month picker filtering should exclude months after maxDate', () => { + const filteredMonths = DateUtils.getFilteredMonthItems(monthNames, 2023, 0, new Date('2020-01-01'), new Date('2023-09-30')); + + // Months after September (index 8) should be excluded + expect(filteredMonths.find((m) => m.value === 10)).toBeUndefined(); + expect(filteredMonths.find((m) => m.value === 11)).toBeUndefined(); + + // September and earlier months should be included + expect(filteredMonths.find((m) => m.value === 8)).toBeTruthy(); + expect(filteredMonths.find((m) => m.value === 0)).toBeTruthy(); + expect(filteredMonths).toHaveLength(9); + }); });