forked from angular/components
/
date-range-input-parts.ts
406 lines (357 loc) · 14.4 KB
/
date-range-input-parts.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
/**
* @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 {
Directive,
ElementRef,
Optional,
InjectionToken,
Inject,
OnInit,
Injector,
InjectFlags,
DoCheck,
} from '@angular/core';
import {
NG_VALUE_ACCESSOR,
NG_VALIDATORS,
NgForm,
FormGroupDirective,
NgControl,
ValidatorFn,
Validators,
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import {
CanUpdateErrorState,
CanUpdateErrorStateCtor,
mixinErrorState,
MAT_DATE_FORMATS,
DateAdapter,
MatDateFormats,
ErrorStateMatcher,
} from '@angular/material/core';
import {BooleanInput} from '@angular/cdk/coercion';
import {BACKSPACE} from '@angular/cdk/keycodes';
import {MatDatepickerInputBase, DateFilterFn} from './datepicker-input-base';
import {DateRange, DateSelectionModelChange} from './date-selection-model';
/** Parent component that should be wrapped around `MatStartDate` and `MatEndDate`. */
export interface MatDateRangeInputParent<D> {
id: string;
min: D | null;
max: D | null;
dateFilter: DateFilterFn<D>;
rangePicker: {
opened: boolean;
id: string;
};
_startInput: MatDateRangeInputPartBase<D>;
_endInput: MatDateRangeInputPartBase<D>;
_groupDisabled: boolean;
_handleChildValueChange(): void;
_openDatepicker(): void;
}
/**
* Used to provide the date range input wrapper component
* to the parts without circular dependencies.
*/
export const MAT_DATE_RANGE_INPUT_PARENT =
new InjectionToken<MatDateRangeInputParent<unknown>>('MAT_DATE_RANGE_INPUT_PARENT');
/**
* Base class for the individual inputs that can be projected inside a `mat-date-range-input`.
*/
@Directive()
abstract class MatDateRangeInputPartBase<D>
extends MatDatepickerInputBase<DateRange<D>> implements OnInit, DoCheck {
/** @docs-private */
ngControl: NgControl;
/** @docs-private */
abstract updateErrorState(): void;
protected abstract _validator: ValidatorFn | null;
protected abstract _assignValueToModel(value: D | null): void;
protected abstract _getValueFromModel(modelValue: DateRange<D>): D | null;
constructor(
@Inject(MAT_DATE_RANGE_INPUT_PARENT) public _rangeInput: MatDateRangeInputParent<D>,
elementRef: ElementRef<HTMLInputElement>,
public _defaultErrorStateMatcher: ErrorStateMatcher,
private _injector: Injector,
@Optional() public _parentForm: NgForm,
@Optional() public _parentFormGroup: FormGroupDirective,
@Optional() dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) dateFormats: MatDateFormats) {
super(elementRef, dateAdapter, dateFormats);
}
ngOnInit() {
// We need the date input to provide itself as a `ControlValueAccessor` and a `Validator`, while
// injecting its `NgControl` so that the error state is handled correctly. This introduces a
// circular dependency, because both `ControlValueAccessor` and `Validator` depend on the input
// itself. Usually we can work around it for the CVA, but there's no API to do it for the
// validator. We work around it here by injecting the `NgControl` in `ngOnInit`, after
// everything has been resolved.
// tslint:disable-next-line:no-bitwise
const ngControl = this._injector.get(NgControl, null, InjectFlags.Self | InjectFlags.Optional);
if (ngControl) {
this.ngControl = ngControl;
}
}
ngDoCheck() {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
}
}
/** Gets whether the input is empty. */
isEmpty(): boolean {
return this._elementRef.nativeElement.value.length === 0;
}
/** Gets the placeholder of the input. */
_getPlaceholder() {
return this._elementRef.nativeElement.placeholder;
}
/** Focuses the input. */
focus(): void {
this._elementRef.nativeElement.focus();
}
/** Handles `input` events on the input element. */
_onInput(value: string) {
super._onInput(value);
this._rangeInput._handleChildValueChange();
}
/** Opens the datepicker associated with the input. */
protected _openPopup(): void {
this._rangeInput._openDatepicker();
}
/** Gets the minimum date from the range input. */
_getMinDate() {
return this._rangeInput.min;
}
/** Gets the maximum date from the range input. */
_getMaxDate() {
return this._rangeInput.max;
}
/** Gets the date filter function from the range input. */
protected _getDateFilter() {
return this._rangeInput.dateFilter;
}
protected _parentDisabled() {
return this._rangeInput._groupDisabled;
}
protected _shouldHandleChangeEvent({source}: DateSelectionModelChange<DateRange<D>>): boolean {
return source !== this._rangeInput._startInput && source !== this._rangeInput._endInput;
}
protected _assignValueProgrammatically(value: D | null) {
super._assignValueProgrammatically(value);
const opposite = (this === this._rangeInput._startInput ? this._rangeInput._endInput :
this._rangeInput._startInput) as MatDateRangeInputPartBase<D> | undefined;
opposite?._validatorOnChange();
}
}
const _MatDateRangeInputBase:
CanUpdateErrorStateCtor & typeof MatDateRangeInputPartBase =
// Needs to be `as any`, because the base class is abstract.
mixinErrorState(MatDateRangeInputPartBase as any);
/** Input for entering the start date in a `mat-date-range-input`. */
@Directive({
selector: 'input[matStartDate]',
host: {
'class': 'mat-start-date mat-date-range-input-inner',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(keydown)': '_onKeydown($event)',
'[attr.id]': '_rangeInput.id',
'[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
'[attr.aria-owns]': '(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null',
'[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
'[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
'(blur)': '_onBlur()',
'type': 'text',
},
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: MatStartDate, multi: true},
{provide: NG_VALIDATORS, useExisting: MatStartDate, multi: true}
],
// These need to be specified explicitly, because some tooling doesn't
// seem to pick them up from the base class. See #20932.
outputs: ['dateChange', 'dateInput'],
inputs: ['errorStateMatcher']
})
export class MatStartDate<D> extends _MatDateRangeInputBase<D> implements
CanUpdateErrorState, DoCheck, OnInit {
/** Validator that checks that the start date isn't after the end date. */
private _startValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const start = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value));
const end = this._model ? this._model.selection.end : null;
return (!start || !end ||
this._dateAdapter.compareDate(start, end) <= 0) ?
null : {'matStartDateInvalid': {'end': end, 'actual': start}};
}
constructor(
@Inject(MAT_DATE_RANGE_INPUT_PARENT) rangeInput: MatDateRangeInputParent<D>,
elementRef: ElementRef<HTMLInputElement>,
defaultErrorStateMatcher: ErrorStateMatcher,
injector: Injector,
@Optional() parentForm: NgForm,
@Optional() parentFormGroup: FormGroupDirective,
@Optional() dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) dateFormats: MatDateFormats) {
// TODO(crisbeto): this constructor shouldn't be necessary, but ViewEngine doesn't seem to
// handle DI correctly when it is inherited from `MatDateRangeInputPartBase`. We can drop this
// constructor once ViewEngine is removed.
super(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup,
dateAdapter, dateFormats);
}
ngOnInit() {
// Normally this happens automatically, but it seems to break if not added explicitly when all
// of the criteria below are met:
// 1) The class extends a TS mixin.
// 2) The application is running in ViewEngine.
// 3) The application is being transpiled through tsickle.
// This can be removed once google3 is completely migrated to Ivy.
super.ngOnInit();
}
ngDoCheck() {
// Normally this happens automatically, but it seems to break if not added explicitly when all
// of the criteria below are met:
// 1) The class extends a TS mixin.
// 2) The application is running in ViewEngine.
// 3) The application is being transpiled through tsickle.
// This can be removed once google3 is completely migrated to Ivy.
super.ngDoCheck();
}
protected _validator = Validators.compose([...super._getValidators(), this._startValidator]);
protected _getValueFromModel(modelValue: DateRange<D>) {
return modelValue.start;
}
protected _shouldHandleChangeEvent(change: DateSelectionModelChange<DateRange<D>>): boolean {
if (!super._shouldHandleChangeEvent(change)) {
return false;
} else {
return !change.oldValue?.start ? !!change.selection.start :
!change.selection.start ||
!!this._dateAdapter.compareDate(change.oldValue.start, change.selection.start);
}
}
protected _assignValueToModel(value: D | null) {
if (this._model) {
const range = new DateRange(value, this._model.selection.end);
this._model.updateSelection(range, this);
}
}
protected _formatValue(value: D | null) {
super._formatValue(value);
// Any time the input value is reformatted we need to tell the parent.
this._rangeInput._handleChildValueChange();
}
/** Gets the value that should be used when mirroring the input's size. */
getMirrorValue(): string {
const element = this._elementRef.nativeElement;
const value = element.value;
return value.length > 0 ? value : element.placeholder;
}
static ngAcceptInputType_disabled: BooleanInput;
}
/** Input for entering the end date in a `mat-date-range-input`. */
@Directive({
selector: 'input[matEndDate]',
host: {
'class': 'mat-end-date mat-date-range-input-inner',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(keydown)': '_onKeydown($event)',
'[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
'[attr.aria-owns]': '(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null',
'[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
'[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
'(blur)': '_onBlur()',
'type': 'text',
},
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: MatEndDate, multi: true},
{provide: NG_VALIDATORS, useExisting: MatEndDate, multi: true}
],
// These need to be specified explicitly, because some tooling doesn't
// seem to pick them up from the base class. See #20932.
outputs: ['dateChange', 'dateInput'],
inputs: ['errorStateMatcher']
})
export class MatEndDate<D> extends _MatDateRangeInputBase<D> implements
CanUpdateErrorState, DoCheck, OnInit {
/** Validator that checks that the end date isn't before the start date. */
private _endValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const end = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
const start = this._model ? this._model.selection.start : null;
return (!end || !start ||
this._dateAdapter.compareDate(end, start) >= 0) ?
null : {'matEndDateInvalid': {'start': start, 'actual': end}};
}
constructor(
@Inject(MAT_DATE_RANGE_INPUT_PARENT) rangeInput: MatDateRangeInputParent<D>,
elementRef: ElementRef<HTMLInputElement>,
defaultErrorStateMatcher: ErrorStateMatcher,
injector: Injector,
@Optional() parentForm: NgForm,
@Optional() parentFormGroup: FormGroupDirective,
@Optional() dateAdapter: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_FORMATS) dateFormats: MatDateFormats) {
// TODO(crisbeto): this constructor shouldn't be necessary, but ViewEngine doesn't seem to
// handle DI correctly when it is inherited from `MatDateRangeInputPartBase`. We can drop this
// constructor once ViewEngine is removed.
super(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup,
dateAdapter, dateFormats);
}
ngOnInit() {
// Normally this happens automatically, but it seems to break if not added explicitly when all
// of the criteria below are met:
// 1) The class extends a TS mixin.
// 2) The application is running in ViewEngine.
// 3) The application is being transpiled through tsickle.
// This can be removed once google3 is completely migrated to Ivy.
super.ngOnInit();
}
ngDoCheck() {
// Normally this happens automatically, but it seems to break if not added explicitly when all
// of the criteria below are met:
// 1) The class extends a TS mixin.
// 2) The application is running in ViewEngine.
// 3) The application is being transpiled through tsickle.
// This can be removed once google3 is completely migrated to Ivy.
super.ngDoCheck();
}
protected _validator = Validators.compose([...super._getValidators(), this._endValidator]);
protected _getValueFromModel(modelValue: DateRange<D>) {
return modelValue.end;
}
protected _shouldHandleChangeEvent(change: DateSelectionModelChange<DateRange<D>>): boolean {
if (!super._shouldHandleChangeEvent(change)) {
return false;
} else {
return !change.oldValue?.end ? !!change.selection.end :
!change.selection.end ||
!!this._dateAdapter.compareDate(change.oldValue.end, change.selection.end);
}
}
protected _assignValueToModel(value: D | null) {
if (this._model) {
const range = new DateRange(this._model.selection.start, value);
this._model.updateSelection(range, this);
}
}
_onKeydown(event: KeyboardEvent) {
// If the user is pressing backspace on an empty end input, move focus back to the start.
if (event.keyCode === BACKSPACE && !this._elementRef.nativeElement.value) {
this._rangeInput._startInput.focus();
}
super._onKeydown(event);
}
static ngAcceptInputType_disabled: BooleanInput;
}