forked from ng-bootstrap/ng-bootstrap
/
datepicker-input.ts
486 lines (417 loc) · 15.2 KB
/
datepicker-input.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import {
ChangeDetectorRef,
ComponentFactoryResolver,
ComponentRef,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
NgZone,
OnChanges,
OnDestroy,
Output,
Renderer2,
SimpleChanges,
TemplateRef,
ViewContainerRef
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator} from '@angular/forms';
import {ngbAutoClose} from '../util/autoclose';
import {ngbFocusTrap} from '../util/focus-trap';
import {PlacementArray, positionElements} from '../util/positioning';
import {NgbDateAdapter} from './adapters/ngb-date-adapter';
import {NgbDatepicker, NgbDatepickerNavigateEvent} from './datepicker';
import {DayTemplateContext} from './datepicker-day-template-context';
import {NgbCalendar} from './ngb-calendar';
import {NgbDate} from './ngb-date';
import {NgbDateParserFormatter} from './ngb-date-parser-formatter';
import {NgbDateStruct} from './ngb-date-struct';
import {NgbInputDatepickerConfig} from './datepicker-input-config';
import {NgbDatepickerConfig} from './datepicker-config';
const NGB_DATEPICKER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgbInputDatepicker),
multi: true
};
const NGB_DATEPICKER_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NgbInputDatepicker),
multi: true
};
/**
* A directive that allows to stick a datepicker popup to an input field.
*
* Manages interaction with the input field itself, does value formatting and provides forms integration.
*/
@Directive({
selector: 'input[ngbDatepicker]',
exportAs: 'ngbDatepicker',
host: {
'(input)': 'manualDateChange($event.target.value)',
'(change)': 'manualDateChange($event.target.value, true)',
'(focus)': 'onFocus()',
'(blur)': 'onBlur()',
'[disabled]': 'disabled'
},
providers: [
NGB_DATEPICKER_VALUE_ACCESSOR, NGB_DATEPICKER_VALIDATOR,
{provide: NgbDatepickerConfig, useExisting: NgbInputDatepickerConfig}
],
})
export class NgbInputDatepicker implements OnChanges,
OnDestroy, ControlValueAccessor, Validator {
private _cRef: ComponentRef<NgbDatepicker> = null;
private _disabled = false;
private _elWithFocus = null;
private _model: NgbDate;
private _inputValue: string;
private _zoneSubscription: any;
/**
* Indicates whether the datepicker popup should be closed automatically after date selection / outside click or not.
*
* * `true` - the popup will close on both date selection and outside click.
* * `false` - the popup can only be closed manually via `close()` or `toggle()` methods.
* * `"inside"` - the popup will close on date selection, but not outside clicks.
* * `"outside"` - the popup will close only on the outside click and not on date selection/inside clicks.
*
* @since 3.0.0
*/
@Input() autoClose: boolean | 'inside' | 'outside';
/**
* 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 earliest date that can be displayed or selected. Also used for form validation.
*
* If not provided, 'year' select box will display 10 years before the current month.
*/
@Input() minDate: NgbDateStruct;
/**
* The latest date that can be displayed or selected. Also used for form validation.
*
* If not provided, 'year' select box will display 10 years after the current month.
*/
@Input() maxDate: 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';
/**
* The preferred placement of the datepicker popup.
*
* Possible values are `"top"`, `"top-left"`, `"top-right"`, `"bottom"`, `"bottom-left"`,
* `"bottom-right"`, `"left"`, `"left-top"`, `"left-bottom"`, `"right"`, `"right-top"`,
* `"right-bottom"`
*
* Accepts an array of strings or a string with space separated possible values.
*
* The default order of preference is `"bottom-left bottom-right top-left top-right"`
*
* Please see the [positioning overview](#/positioning) for more details.
*/
@Input() placement: PlacementArray;
/**
* 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};
/**
* A selector specifying the element the datepicker popup should be appended to.
*
* Currently only supports `"body"`.
*/
@Input() container: string;
/**
* A css selector or html element specifying the element the datepicker popup should be positioned against.
*
* By default the input is used as a target.
*
* @since 4.2.0
*/
@Input() positionTarget: string | HTMLElement;
/**
* An event emitted when user selects a date using keyboard or mouse.
*
* The payload of the event is currently selected `NgbDate`.
*
* @since 1.1.1
*/
@Output() dateSelect = new EventEmitter<NgbDate>();
/**
* Event emitted right after the navigation happens and displayed month changes.
*
* See [`NgbDatepickerNavigateEvent`](#/components/datepicker/api#NgbDatepickerNavigateEvent) for the payload info.
*/
@Output() navigate = new EventEmitter<NgbDatepickerNavigateEvent>();
/**
* An event fired after closing datepicker window.
*
* @since 4.2.0
*/
@Output() closed = new EventEmitter<void>();
@Input()
get disabled() {
return this._disabled;
}
set disabled(value: any) {
this._disabled = value === '' || (value && value !== 'false');
if (this.isOpen()) {
this._cRef.instance.setDisabledState(this._disabled);
}
}
private _onChange = (_: any) => {};
private _onTouched = () => {};
private _validatorChange = () => {};
constructor(
private _parserFormatter: NgbDateParserFormatter, private _elRef: ElementRef<HTMLInputElement>,
private _vcRef: ViewContainerRef, private _renderer: Renderer2, private _cfr: ComponentFactoryResolver,
private _ngZone: NgZone, private _calendar: NgbCalendar, private _dateAdapter: NgbDateAdapter<any>,
@Inject(DOCUMENT) private _document: any, private _changeDetector: ChangeDetectorRef,
config: NgbInputDatepickerConfig) {
['autoClose', 'container', 'positionTarget', 'placement'].forEach(input => this[input] = config[input]);
this._zoneSubscription = _ngZone.onStable.subscribe(() => this._updatePopupPosition());
}
registerOnChange(fn: (value: any) => any): void { this._onChange = fn; }
registerOnTouched(fn: () => any): void { this._onTouched = fn; }
registerOnValidatorChange(fn: () => void): void { this._validatorChange = fn; }
setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; }
validate(c: AbstractControl): {[key: string]: any} {
const value = c.value;
if (value === null || value === undefined) {
return null;
}
const ngbDate = this._fromDateStruct(this._dateAdapter.fromModel(value));
if (!this._calendar.isValid(ngbDate)) {
return {'ngbDate': {invalid: c.value}};
}
if (this.minDate && ngbDate.before(NgbDate.from(this.minDate))) {
return {'ngbDate': {requiredBefore: this.minDate}};
}
if (this.maxDate && ngbDate.after(NgbDate.from(this.maxDate))) {
return {'ngbDate': {requiredAfter: this.maxDate}};
}
}
writeValue(value) {
this._model = this._fromDateStruct(this._dateAdapter.fromModel(value));
this._writeModelValue(this._model);
}
manualDateChange(value: string, updateView = false) {
const inputValueChanged = value !== this._inputValue;
if (inputValueChanged) {
this._inputValue = value;
this._model = this._fromDateStruct(this._parserFormatter.parse(value));
}
if (inputValueChanged || !updateView) {
this._onChange(this._model ? this._dateAdapter.toModel(this._model) : (value === '' ? null : value));
}
if (updateView && this._model) {
this._writeModelValue(this._model);
}
}
isOpen() { return !!this._cRef; }
/**
* Opens the datepicker popup.
*
* If the related form control contains a valid date, the corresponding month will be opened.
*/
open() {
if (!this.isOpen()) {
const cf = this._cfr.resolveComponentFactory(NgbDatepicker);
this._cRef = this._vcRef.createComponent(cf);
this._applyPopupStyling(this._cRef.location.nativeElement);
this._applyDatepickerInputs(this._cRef.instance);
this._subscribeForDatepickerOutputs(this._cRef.instance);
this._cRef.instance.ngOnInit();
this._cRef.instance.writeValue(this._dateAdapter.toModel(this._model));
// date selection event handling
this._cRef.instance.registerOnChange((selectedDate) => {
this.writeValue(selectedDate);
this._onChange(selectedDate);
this._onTouched();
});
this._cRef.changeDetectorRef.detectChanges();
this._cRef.instance.setDisabledState(this.disabled);
if (this.container === 'body') {
window.document.querySelector(this.container).appendChild(this._cRef.location.nativeElement);
}
// focus handling
this._elWithFocus = this._document.activeElement;
ngbFocusTrap(this._ngZone, this._cRef.location.nativeElement, this.closed, true);
this._cRef.instance.focus();
ngbAutoClose(
this._ngZone, this._document, this.autoClose, () => this.close(), this.closed, [],
[this._elRef.nativeElement, this._cRef.location.nativeElement]);
}
}
/**
* Closes the datepicker popup.
*/
close() {
if (this.isOpen()) {
this._vcRef.remove(this._vcRef.indexOf(this._cRef.hostView));
this._cRef = null;
this.closed.emit();
this._changeDetector.markForCheck();
// restore focus
const elementToFocus = this._elWithFocus && this._elWithFocus['focus'] ? this._elWithFocus : this._document.body;
elementToFocus.focus();
}
}
/**
* Toggles the datepicker popup.
*/
toggle() {
if (this.isOpen()) {
this.close();
} else {
this.open();
}
}
/**
* 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}) {
if (this.isOpen()) {
this._cRef.instance.navigateTo(date);
}
}
onBlur() { this._onTouched(); }
onFocus() { this._elWithFocus = this._elRef.nativeElement; }
ngOnChanges(changes: SimpleChanges) {
if (changes['minDate'] || changes['maxDate']) {
this._validatorChange();
}
}
ngOnDestroy() {
this.close();
this._zoneSubscription.unsubscribe();
}
private _applyDatepickerInputs(datepickerInstance: NgbDatepicker): void {
['dayTemplate', 'dayTemplateData', 'displayMonths', 'firstDayOfWeek', 'footerTemplate', 'markDisabled', 'minDate',
'maxDate', 'navigation', 'outsideDays', 'showNavigation', 'showWeekdays', 'showWeekNumbers']
.forEach((optionName: string) => {
if (this[optionName] !== undefined) {
datepickerInstance[optionName] = this[optionName];
}
});
datepickerInstance.startDate = this.startDate || this._model;
}
private _applyPopupStyling(nativeElement: any) {
this._renderer.addClass(nativeElement, 'dropdown-menu');
this._renderer.addClass(nativeElement, 'show');
if (this.container === 'body') {
this._renderer.addClass(nativeElement, 'ngb-dp-body');
}
}
private _subscribeForDatepickerOutputs(datepickerInstance: NgbDatepicker) {
datepickerInstance.navigate.subscribe(navigateEvent => this.navigate.emit(navigateEvent));
datepickerInstance.dateSelect.subscribe(date => {
this.dateSelect.emit(date);
if (this.autoClose === true || this.autoClose === 'inside') {
this.close();
}
});
}
private _writeModelValue(model: NgbDate) {
const value = this._parserFormatter.format(model);
this._inputValue = value;
this._renderer.setProperty(this._elRef.nativeElement, 'value', value);
if (this.isOpen()) {
this._cRef.instance.writeValue(this._dateAdapter.toModel(model));
this._onTouched();
}
}
private _fromDateStruct(date: NgbDateStruct): NgbDate {
const ngbDate = date ? new NgbDate(date.year, date.month, date.day) : null;
return this._calendar.isValid(ngbDate) ? ngbDate : null;
}
private _updatePopupPosition() {
if (!this._cRef) {
return;
}
let hostElement: HTMLElement;
if (typeof this.positionTarget === 'string') {
hostElement = window.document.querySelector(this.positionTarget);
} else if (this.positionTarget instanceof HTMLElement) {
hostElement = this.positionTarget;
} else {
hostElement = this._elRef.nativeElement;
}
if (this.positionTarget && !hostElement) {
throw new Error('ngbDatepicker could not find element declared in [positionTarget] to position against.');
}
positionElements(hostElement, this._cRef.location.nativeElement, this.placement, this.container === 'body');
}
}