/
calendar.ts
376 lines (322 loc) · 12.4 KB
/
calendar.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentPortal, ComponentType, Portal} from '@angular/cdk/portal';
import {
AfterContentInit,
AfterViewChecked,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
forwardRef,
Inject,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
SimpleChanges,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {DateAdapter, MAT_DATE_FORMATS, MatDateFormats} from '@angular/material/core';
import {Subject, Subscription} from 'rxjs';
import {createMissingDateImplError} from './datepicker-errors';
import {MatDatepickerIntl} from './datepicker-intl';
import {MatMonthView} from './month-view';
import {MatMultiYearView, yearsPerPage} from './multi-year-view';
import {MatYearView} from './year-view';
/**
* Possible views for the calendar.
* @docs-private
*/
export type MatCalendarView = 'month' | 'year' | 'multi-year';
/** Default header for MatCalendar */
@Component({
moduleId: module.id,
selector: 'mat-calendar-header',
templateUrl: 'calendar-header.html',
exportAs: 'matCalendarHeader',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatCalendarHeader<D> {
constructor(private _intl: MatDatepickerIntl,
@Inject(forwardRef(() => MatCalendar)) public calendar: MatCalendar<D>,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
changeDetectorRef: ChangeDetectorRef) {
this.calendar.stateChanges.subscribe(() => changeDetectorRef.markForCheck());
}
/** The label for the current calendar view. */
get periodButtonText(): string {
if (this.calendar.currentView == 'month') {
return this._dateAdapter
.format(this.calendar.activeDate, this._dateFormats.display.monthYearLabel)
.toLocaleUpperCase();
}
if (this.calendar.currentView == 'year') {
return this._dateAdapter.getYearName(this.calendar.activeDate);
}
const activeYear = this._dateAdapter.getYear(this.calendar.activeDate);
const firstYearInView = this._dateAdapter.getYearName(
this._dateAdapter.createDate(activeYear - activeYear % 24, 0, 1));
const lastYearInView = this._dateAdapter.getYearName(
this._dateAdapter.createDate(activeYear + yearsPerPage - 1 - activeYear % 24, 0, 1));
return `${firstYearInView} \u2013 ${lastYearInView}`;
}
get periodButtonLabel(): string {
return this.calendar.currentView == 'month' ?
this._intl.switchToMultiYearViewLabel : this._intl.switchToMonthViewLabel;
}
/** The label for the the previous button. */
get prevButtonLabel(): string {
return {
'month': this._intl.prevMonthLabel,
'year': this._intl.prevYearLabel,
'multi-year': this._intl.prevMultiYearLabel
}[this.calendar.currentView];
}
/** The label for the the next button. */
get nextButtonLabel(): string {
return {
'month': this._intl.nextMonthLabel,
'year': this._intl.nextYearLabel,
'multi-year': this._intl.nextMultiYearLabel
}[this.calendar.currentView];
}
/** Handles user clicks on the period label. */
currentPeriodClicked(): void {
this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';
}
/** Handles user clicks on the previous button. */
previousClicked(): void {
this.calendar.activeDate = this.calendar.currentView == 'month' ?
this._dateAdapter.addCalendarMonths(this.calendar.activeDate, -1) :
this._dateAdapter.addCalendarYears(
this.calendar.activeDate, this.calendar.currentView == 'year' ? -1 : -yearsPerPage
);
}
/** Handles user clicks on the next button. */
nextClicked(): void {
this.calendar.activeDate = this.calendar.currentView == 'month' ?
this._dateAdapter.addCalendarMonths(this.calendar.activeDate, 1) :
this._dateAdapter.addCalendarYears(
this.calendar.activeDate,
this.calendar.currentView == 'year' ? 1 : yearsPerPage
);
}
/** Whether the previous period button is enabled. */
previousEnabled(): boolean {
if (!this.calendar.minDate) {
return true;
}
return !this.calendar.minDate ||
!this._isSameView(this.calendar.activeDate, this.calendar.minDate);
}
/** Whether the next period button is enabled. */
nextEnabled(): boolean {
return !this.calendar.maxDate ||
!this._isSameView(this.calendar.activeDate, this.calendar.maxDate);
}
/** Whether the two dates represent the same view in the current view mode (month or year). */
private _isSameView(date1: D, date2: D): boolean {
if (this.calendar.currentView == 'month') {
return this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2) &&
this._dateAdapter.getMonth(date1) == this._dateAdapter.getMonth(date2);
}
if (this.calendar.currentView == 'year') {
return this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2);
}
// Otherwise we are in 'multi-year' view.
return Math.floor(this._dateAdapter.getYear(date1) / yearsPerPage) ==
Math.floor(this._dateAdapter.getYear(date2) / yearsPerPage);
}
}
/**
* A calendar that is used as part of the datepicker.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'mat-calendar',
templateUrl: 'calendar.html',
styleUrls: ['calendar.css'],
host: {
'class': 'mat-calendar',
},
exportAs: 'matCalendar',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatCalendar<D> implements AfterContentInit, AfterViewChecked, OnDestroy, OnChanges {
/** An input indicating the type of the header component, if set. */
@Input() headerComponent: ComponentType<any>;
/** A portal containing the header component type for this calendar. */
_calendarHeaderPortal: Portal<any>;
private _intlChanges: Subscription;
/**
* Used for scheduling that focus should be moved to the active cell on the next tick.
* We need to schedule it, rather than do it immediately, because we have to wait
* for Angular to re-evaluate the view children.
*/
private _moveFocusOnNextTick = false;
/** A date representing the period (month or year) to start the calendar in. */
@Input()
get startAt(): D | null { return this._startAt; }
set startAt(value: D | null) {
this._startAt = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _startAt: D | null;
/** Whether the calendar should be started in month or year view. */
@Input() startView: MatCalendarView = 'month';
/** The currently selected date. */
@Input()
get selected(): D | null { return this._selected; }
set selected(value: D | null) {
this._selected = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _selected: D | null;
/** The minimum selectable date. */
@Input()
get minDate(): D | null { return this._minDate; }
set minDate(value: D | null) {
this._minDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _minDate: D | null;
/** The maximum selectable date. */
@Input()
get maxDate(): D | null { return this._maxDate; }
set maxDate(value: D | null) {
this._maxDate = this._getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _maxDate: D | null;
/** A function used to filter which dates are selectable. */
@Input() dateFilter: (date: D) => boolean;
/** Emits when the currently selected date changes. */
@Output() readonly selectedChange: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits the year chosen in multiyear view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits the month chosen in year view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();
/** Emits when any date is selected. */
@Output() readonly _userSelection: EventEmitter<void> = new EventEmitter<void>();
/** Reference to the current month view component. */
@ViewChild(MatMonthView) monthView: MatMonthView<D>;
/** Reference to the current year view component. */
@ViewChild(MatYearView) yearView: MatYearView<D>;
/** Reference to the current multi-year view component. */
@ViewChild(MatMultiYearView) multiYearView: MatMultiYearView<D>;
/**
* The current active date. This determines which time period is shown and which date is
* highlighted when using keyboard navigation.
*/
get activeDate(): D { return this._clampedActiveDate; }
set activeDate(value: D) {
this._clampedActiveDate = this._dateAdapter.clampDate(value, this.minDate, this.maxDate);
this.stateChanges.next();
}
private _clampedActiveDate: D;
/** Whether the calendar is in month view. */
get currentView(): MatCalendarView { return this._currentView; }
set currentView(value: MatCalendarView) {
this._currentView = value;
this._moveFocusOnNextTick = true;
}
private _currentView: MatCalendarView;
/**
* Emits whenever there is a state change that the header may need to respond to.
*/
stateChanges = new Subject<void>();
constructor(_intl: MatDatepickerIntl,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) private _dateFormats: MatDateFormats,
private _changeDetectorRef: ChangeDetectorRef) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MAT_DATE_FORMATS');
}
this._intlChanges = _intl.changes.subscribe(() => {
_changeDetectorRef.markForCheck();
this.stateChanges.next();
});
}
ngAfterContentInit() {
this._calendarHeaderPortal = new ComponentPortal(this.headerComponent || MatCalendarHeader);
this.activeDate = this.startAt || this._dateAdapter.today();
// Assign to the private property since we don't want to move focus on init.
this._currentView = this.startView;
}
ngAfterViewChecked() {
if (this._moveFocusOnNextTick) {
this._moveFocusOnNextTick = false;
this.focusActiveCell();
}
}
ngOnDestroy() {
this._intlChanges.unsubscribe();
this.stateChanges.complete();
}
ngOnChanges(changes: SimpleChanges) {
const change = changes.minDate || changes.maxDate || changes.dateFilter;
if (change && !change.firstChange) {
const view = this._getCurrentViewComponent();
if (view) {
// We need to `detectChanges` manually here, because the `minDate`, `maxDate` etc. are
// passed down to the view via data bindings which won't be up-to-date when we call `_init`.
this._changeDetectorRef.detectChanges();
view._init();
}
}
this.stateChanges.next();
}
focusActiveCell() {
this._getCurrentViewComponent()._focusActiveCell();
}
/** Handles date selection in the month view. */
_dateSelected(date: D): void {
if (!this._dateAdapter.sameDate(date, this.selected)) {
this.selectedChange.emit(date);
}
}
/** Handles year selection in the multiyear view. */
_yearSelectedInMultiYearView(normalizedYear: D) {
this.yearSelected.emit(normalizedYear);
}
/** Handles month selection in the year view. */
_monthSelectedInYearView(normalizedMonth: D) {
this.monthSelected.emit(normalizedMonth);
}
_userSelected(): void {
this._userSelection.emit();
}
/** Handles year/month selection in the multi-year/year views. */
_goToDateInView(date: D, view: 'month' | 'year' | 'multi-year'): void {
this.activeDate = date;
this.currentView = view;
}
/**
* @param obj The object to check.
* @returns The given object if it is both a date instance and valid, otherwise null.
*/
private _getValidDateOrNull(obj: any): D | null {
return (this._dateAdapter.isDateInstance(obj) && this._dateAdapter.isValid(obj)) ? obj : null;
}
/** Returns the component instance that corresponds to the current calendar view. */
private _getCurrentViewComponent() {
return this.monthView || this.yearView || this.multiYearView;
}
}