import { addDays , addWeeks , differenceInCalendarDays , endOfMonth , getWeek , getWeeksInMonth , Locale , startOfMonth } from 'date-fns' ; import { getOutsideEndDays } from './getOutsideEndDays' ; import { getOutsideStartDays } from './getOutsideStartDays' ; /**
 * Represents a week in the month.
 */ export type MonthWeek = { /** The week number from the start of the year. */ weekNumber : number ; /** The dates in the week. */ dates : Date [ ] ; } ; /**
 * Return the weeks belonging to the given month.
 */ export function getWeeks ( month , { locale , fixedWeeks } ) { const monthStart = startOfMonth ( month ) ; const monthEnd = endOfMonth ( month ) ; const diff = differenceInCalendarDays ( monthEnd , monthStart ) ; const weeks = [ ] ; let lastWeek = { weekNumber : 0 , dates : [ ] } ; for ( let i = 0 ; i <= diff ; i ++ ) { const date = addDays ( monthStart , i ) ; const week = getWeek ( date , { locale } ) ; if ( lastWeek . weekNumber !== week ) { const startDays = getOutsideStartDays ( date , { locale } ) ; lastWeek = { weekNumber : week , dates : startDays } ; weeks . push ( lastWeek ) ; } lastWeek . dates . push ( date ) ; } const lastDay = lastWeek . dates [ lastWeek . dates . length - 1 ] ; const endDays = getOutsideEndDays ( lastDay , { locale } ) ; lastWeek . dates = lastWeek . dates . concat ( endDays ) ; if ( fixedWeeks ) { const lastWeekDate = lastWeek . dates [ lastWeek . dates . length - 1 ] ; const weeksInMonth = getWeeksInMonth ( month , { locale } ) ; if ( weeksInMonth < 6 ) { const diffDays = differenceInCalendarDays ( addWeeks ( lastWeekDate , 6 - weeksInMonth ) , lastWeekDate ) ; for ( let i = 0 ; i < diffDays ; i ++ ) { const date = addDays ( lastWeekDate , i + 1 ) ; const week = getWeek ( date , { locale } ) ; if ( lastWeek . weekNumber !== week ) { lastWeek = { weekNumber : week , dates : [ ] } ; weeks . push ( lastWeek ) ; } lastWeek . dates . push ( date ) ; } } } return weeks ; }