/
datepicker.ts
451 lines (391 loc) · 14.2 KB
/
datepicker.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import {fromEvent, merge, Subject} from 'rxjs';
import {filter, take, takeUntil} from 'rxjs/operators';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
TemplateRef,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {NgbCalendar} from './ngb-calendar';
import {NgbDate} from './ngb-date';
import {NgbDatepickerService} from './datepicker-service';
import {NgbDatepickerKeyboardService} from './datepicker-keyboard-service';
import {DatepickerViewModel, NavigationEvent} from './datepicker-view-model';
import {DayTemplateContext} from './datepicker-day-template-context';
import {NgbDatepickerConfig} from './datepicker-config';
import {NgbDateAdapter} from './adapters/ngb-date-adapter';
import {NgbDateStruct} from './ngb-date-struct';
import {NgbDatepickerI18n} from './datepicker-i18n';
import {isChangedDate, isChangedMonth} from './datepicker-tools';
import {hasClassName} from '../util/util';
const NGB_DATEPICKER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgbDatepicker),
multi: true
};
/**
* An event emitted right before the navigation happens and the month displayed by the datepicker changes.
*/
export interface NgbDatepickerNavigateEvent {
/**
* The currently displayed month.
*/
current: {year: number, month: number};
/**
* The month we're navigating to.
*/
next: {year: number, month: number};
/**
* Calling this function will prevent navigation from happening.
*
* @since 4.1.0
*/
preventDefault: () => void;
}
/**
* An object that represents a part of the state of the datepicker.
* Required to override datepicker services i.e. the datepicker-keyboard-service.
*/
export interface NgbDatepickerState {
/**
* The minDate provided as input.
*/
readonly minDate: NgbDate;
/**
* The maxDate provided as input.
*/
readonly maxDate: NgbDate;
/**
* The first date of current month.
*/
readonly firstDate: NgbDate;
/**
* The last date of current month.
*/
readonly lastDate: NgbDate;
/**
* The focused date.
*/
readonly focusDate?: NgbDate;
}
/**
* A highly configurable component that helps you with selecting calendar dates.
*
* `NgbDatepicker` is meant to be displayed inline on a page or put inside a popup.
*/
@Component({
exportAs: 'ngbDatepicker',
selector: 'ngb-datepicker',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
styleUrls: ['./datepicker.scss'],
template: `
<ng-template #dt let-date="date" let-currentMonth="currentMonth" let-selected="selected" let-disabled="disabled" let-focused="focused">
<div ngbDatepickerDayView
[date]="date"
[currentMonth]="currentMonth"
[selected]="selected"
[disabled]="disabled"
[focused]="focused">
</div>
</ng-template>
<div class="ngb-dp-header">
<ngb-datepicker-navigation *ngIf="navigation !== 'none'"
[date]="model.firstDate"
[months]="model.months"
[disabled]="model.disabled"
[showSelect]="model.navigation === 'select'"
[prevDisabled]="model.prevDisabled"
[nextDisabled]="model.nextDisabled"
[selectBoxes]="model.selectBoxes"
(navigate)="onNavigateEvent($event)"
(select)="onNavigateDateSelect($event)">
</ngb-datepicker-navigation>
</div>
<div #months class="ngb-dp-months" (keydown)="onKeyDown($event)">
<ng-template ngFor let-month [ngForOf]="model.months" let-i="index">
<div class="ngb-dp-month">
<div *ngIf="navigation === 'none' || (displayMonths > 1 && navigation === 'select')"
class="ngb-dp-month-name">
{{ i18n.getMonthFullName(month.number, month.year) }} {{ i18n.getYearNumerals(month.year) }}
</div>
<ngb-datepicker-month-view
[month]="month"
[dayTemplate]="dayTemplate || dt"
[showWeekdays]="showWeekdays"
[showWeekNumbers]="showWeekNumbers"
(select)="onDateSelect($event)">
</ngb-datepicker-month-view>
</div>
</ng-template>
</div>
<ng-template [ngTemplateOutlet]="footerTemplate"></ng-template>
`,
providers: [NGB_DATEPICKER_VALUE_ACCESSOR, NgbDatepickerService]
})
export class NgbDatepicker implements OnDestroy,
OnChanges, OnInit, AfterViewInit, ControlValueAccessor {
model: DatepickerViewModel;
@ViewChild('months', {static: true}) private _monthsEl: ElementRef<HTMLElement>;
private _controlValue: NgbDate;
private _destroyed$ = new Subject<void>();
private _publicState: NgbDatepickerState = <any>{};
/**
* The reference to a custom template for the day.
*
* Allows to completely override the way a day 'cell' in the calendar is displayed.
*
* See [`DayTemplateContext`](#/components/datepicker/api#DayTemplateContext) for the data you get inside.
*/
@Input() dayTemplate: TemplateRef<DayTemplateContext>;
/**
* The callback to pass any arbitrary data to the template cell via the
* [`DayTemplateContext`](#/components/datepicker/api#DayTemplateContext)'s `data` parameter.
*
* `current` is the month that is currently displayed by the datepicker.
*
* @since 3.3.0
*/
@Input() dayTemplateData: (date: NgbDate, current: {year: number, month: number}) => any;
/**
* The number of months to display.
*/
@Input() displayMonths: number;
/**
* The first day of the week.
*
* With default calendar we use ISO 8601: 'weekday' is 1=Mon ... 7=Sun.
*/
@Input() firstDayOfWeek: number;
/**
* The reference to the custom template for the datepicker footer.
*
* @since 3.3.0
*/
@Input() footerTemplate: TemplateRef<any>;
/**
* The callback to mark some dates as disabled.
*
* It is called for each new date when navigating to a different month.
*
* `current` is the month that is currently displayed by the datepicker.
*/
@Input() markDisabled: (date: NgbDate, current: {year: number, month: number}) => boolean;
/**
* The latest date that can be displayed or selected.
*
* If not provided, 'year' select box will display 10 years after the current month.
*/
@Input() maxDate: NgbDateStruct;
/**
* The earliest date that can be displayed or selected.
*
* If not provided, 'year' select box will display 10 years before the current month.
*/
@Input() minDate: NgbDateStruct;
/**
* Navigation type.
*
* * `"select"` - select boxes for month and navigation arrows
* * `"arrows"` - only navigation arrows
* * `"none"` - no navigation visible at all
*/
@Input() navigation: 'select' | 'arrows' | 'none';
/**
* The way of displaying days that don't belong to the current month.
*
* * `"visible"` - days are visible
* * `"hidden"` - days are hidden, white space preserved
* * `"collapsed"` - days are collapsed, so the datepicker height might change between months
*
* For the 2+ months view, days in between months are never shown.
*/
@Input() outsideDays: 'visible' | 'collapsed' | 'hidden';
/**
* If `true`, weekdays will be displayed.
*/
@Input() showWeekdays: boolean;
/**
* If `true`, week numbers will be displayed.
*/
@Input() showWeekNumbers: boolean;
/**
* The date to open calendar with.
*
* With the default calendar we use ISO 8601: 'month' is 1=Jan ... 12=Dec.
* If nothing or invalid date is provided, calendar will open with current month.
*
* You could use `navigateTo(date)` method as an alternative.
*/
@Input() startDate: {year: number, month: number, day?: number};
/**
* An event emitted right before the navigation happens and displayed month changes.
*
* See [`NgbDatepickerNavigateEvent`](#/components/datepicker/api#NgbDatepickerNavigateEvent) for the payload info.
*/
@Output() navigate = new EventEmitter<NgbDatepickerNavigateEvent>();
/**
* An event emitted when user selects a date using keyboard or mouse.
*
* The payload of the event is currently selected `NgbDate`.
*/
@Output() select = new EventEmitter<NgbDate>();
onChange = (_: any) => {};
onTouched = () => {};
constructor(
public _service: NgbDatepickerService, private _calendar: NgbCalendar, public i18n: NgbDatepickerI18n,
config: NgbDatepickerConfig, private _keyboardService: NgbDatepickerKeyboardService,
private _cd: ChangeDetectorRef, private _elementRef: ElementRef<HTMLElement>,
private _ngbDateAdapter: NgbDateAdapter<any>, private _ngZone: NgZone) {
['dayTemplate', 'dayTemplateData', 'displayMonths', 'firstDayOfWeek', 'footerTemplate', 'markDisabled', 'minDate',
'maxDate', 'navigation', 'outsideDays', 'showWeekdays', 'showWeekNumbers', 'startDate']
.forEach(input => this[input] = config[input]);
_service.select$.pipe(takeUntil(this._destroyed$)).subscribe(date => { this.select.emit(date); });
_service.model$.pipe(takeUntil(this._destroyed$)).subscribe(model => {
const newDate = model.firstDate;
const oldDate = this.model ? this.model.firstDate : null;
// update public state
this._publicState = {
maxDate: model.maxDate,
minDate: model.minDate,
firstDate: model.firstDate,
lastDate: model.lastDate,
focusedDate: model.focusDate
};
let navigationPrevented = false;
// emitting navigation event if the first month changes
if (!newDate.equals(oldDate)) {
this.navigate.emit({
current: oldDate ? {year: oldDate.year, month: oldDate.month} : null,
next: {year: newDate.year, month: newDate.month},
preventDefault: () => navigationPrevented = true
});
// can't prevent the very first navigation
if (navigationPrevented && oldDate !== null) {
this._service.open(oldDate);
return;
}
}
const newSelectedDate = model.selectedDate;
const newFocusedDate = model.focusDate;
const oldFocusedDate = this.model ? this.model.focusDate : null;
this.model = model;
// handling selection change
if (isChangedDate(newSelectedDate, this._controlValue)) {
this._controlValue = newSelectedDate;
this.onTouched();
this.onChange(this._ngbDateAdapter.toModel(newSelectedDate));
}
// handling focus change
if (isChangedDate(newFocusedDate, oldFocusedDate) && oldFocusedDate && model.focusVisible) {
this.focus();
}
_cd.markForCheck();
});
}
/**
* Returns a copy of the state of the datepicker.
*/
get state(): NgbDatepickerState { return this._publicState; }
/**
* Focuses on given date.
*/
focusDate(date: NgbDateStruct): void { this._service.focus(NgbDate.from(date)); }
/**
* Selects focused date.
*/
focusSelect(): void { this._service.focusSelect(); }
focus() {
this._ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => {
const elementToFocus =
this._elementRef.nativeElement.querySelector<HTMLDivElement>('div.ngb-dp-day[tabindex="0"]');
if (elementToFocus) {
elementToFocus.focus();
}
});
}
/**
* Navigates to the provided date.
*
* With the default calendar we use ISO 8601: 'month' is 1=Jan ... 12=Dec.
* If nothing or invalid date provided calendar will open current month.
*
* Use the `[startDate]` input as an alternative.
*/
navigateTo(date?: {year: number, month: number, day?: number}) {
this._service.open(NgbDate.from(date ? date.day ? date as NgbDateStruct : {...date, day: 1} : null));
}
ngAfterViewInit() {
this._ngZone.runOutsideAngular(() => {
const focusIns$ = fromEvent<FocusEvent>(this._monthsEl.nativeElement, 'focusin');
const focusOuts$ = fromEvent<FocusEvent>(this._monthsEl.nativeElement, 'focusout');
// we're changing 'focusVisible' only when entering or leaving months view
// and ignoring all focus events where both 'target' and 'related' target are day cells
merge(focusIns$, focusOuts$)
.pipe(
filter(
({target, relatedTarget}) =>
!(hasClassName(target, 'ngb-dp-day') && hasClassName(relatedTarget, 'ngb-dp-day'))),
takeUntil(this._destroyed$))
.subscribe(({type}) => this._ngZone.run(() => this._service.focusVisible = type === 'focusin'));
});
}
ngOnDestroy() { this._destroyed$.next(); }
ngOnInit() {
if (this.model === undefined) {
['dayTemplateData', 'displayMonths', 'markDisabled', 'firstDayOfWeek', 'navigation', 'minDate', 'maxDate',
'outsideDays']
.forEach(input => this._service[input] = this[input]);
this.navigateTo(this.startDate);
}
}
ngOnChanges(changes: SimpleChanges) {
['dayTemplateData', 'displayMonths', 'markDisabled', 'firstDayOfWeek', 'navigation', 'minDate', 'maxDate',
'outsideDays']
.filter(input => input in changes)
.forEach(input => this._service[input] = this[input]);
if ('startDate' in changes) {
const {currentValue, previousValue} = changes.startDate;
if (isChangedMonth(previousValue, currentValue)) {
this.navigateTo(this.startDate);
}
}
}
onDateSelect(date: NgbDate) {
this._service.focus(date);
this._service.select(date, {emitEvent: true});
}
onKeyDown(event: KeyboardEvent) { this._keyboardService.processKey(event, this, this._calendar); }
onNavigateDateSelect(date: NgbDate) { this._service.open(date); }
onNavigateEvent(event: NavigationEvent) {
switch (event) {
case NavigationEvent.PREV:
this._service.open(this._calendar.getPrev(this.model.firstDate, 'm', 1));
break;
case NavigationEvent.NEXT:
this._service.open(this._calendar.getNext(this.model.firstDate, 'm', 1));
break;
}
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
setDisabledState(isDisabled: boolean) { this._service.disabled = isDisabled; }
writeValue(value) {
this._controlValue = NgbDate.from(this._ngbDateAdapter.fromModel(value));
this._service.select(this._controlValue);
}
}