import { Injectable , OnDestroy } from '@angular/core' ; import { BehaviorSubject , Subscription } from 'rxjs' ; import { DateTimePickerService , ModeDirection } from '../date-time-picker.service' ; import { gridify , range } from '../date-time-picker.utils' ; @ Injectable ( ) export class MonthViewService implements OnDestroy { grid$ = new BehaviorSubject < MonthViewItem [ ] [ ] > ( [ [ ] ] ) ; focused$ = new BehaviorSubject < FocusedMonthItem > ( null ) ; private _subscription : Subscription ; constructor ( private _datepicker ) { this . _subscription = _datepicker . year$ . subscribe ( year => this . createMonthGrid ( year ) ) ; } ngOnDestroy ( ) { this . _subscription . unsubscribe ( ) ; } setFocus ( month , year ) { this . focused$ . next ( { month , year } ) ; this . _datepicker . setViewportYear ( year ) ; } private createMonthGrid ( year ) { this . _datepicker . setHeader ( year . toString ( ) ) ; const currentMonth = new Date ( ) . getMonth ( ) ; const currentYear = new Date ( ) . getFullYear ( ) ; const activeMonth = this . _datepicker . selected$ . value ? this . _datepicker . selected$ . value . getMonth ( ) : null ; const activeYear = this . _datepicker . selected$ . value ? this . _datepicker . selected$ . value . getFullYear ( ) : null ; const months = range ( 0 , 11 ) . map ( month => { return { name : this . _datepicker . monthsShort [ month ] , month , year , isCurrentMonth : year === currentYear && month === currentMonth , isActiveMonth : year === activeYear && month === activeMonth } ; } ) ; const items = gridify ( months , 4 ) ; this . grid$ . next ( items ) ; if ( this . _datepicker . modeDirection === ModeDirection . Descend && this . focused$ . value === null ) { const selectedMonth = months . find ( month => month . isActiveMonth ) ; this . setFocus ( selectedMonth ? selectedMonth . month : 0 , year ) ; } } } export interface MonthViewItem { name : string ; month : number ; year : number ; isCurrentMonth : boolean ; isActiveMonth : boolean ; } export interface FocusedMonthItem { month : number ; year : number ; }