-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
datepicker-base.ts
646 lines (557 loc) · 21.5 KB
/
datepicker-base.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
/**
* @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 {Directionality} from '@angular/cdk/bidi';
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {ESCAPE, UP_ARROW} from '@angular/cdk/keycodes';
import {
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
FlexibleConnectedPositionStrategy,
} from '@angular/cdk/overlay';
import {ComponentPortal, ComponentType} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ComponentRef,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
ChangeDetectorRef,
Directive,
OnChanges,
SimpleChanges,
} from '@angular/core';
import {
CanColor,
CanColorCtor,
DateAdapter,
mixinColor,
ThemePalette,
} from '@angular/material/core';
import {MatDialog, MatDialogRef} from '@angular/material/dialog';
import {merge, Subject, Observable, Subscription} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {MatCalendar} from './calendar';
import {matDatepickerAnimations} from './datepicker-animations';
import {createMissingDateImplError} from './datepicker-errors';
import {MatCalendarCellCssClasses, MatCalendarUserEvent} from './calendar-body';
import {DateFilterFn} from './datepicker-input-base';
import {
ExtractDateTypeFromSelection,
MatDateSelectionModel,
DateRange,
} from './date-selection-model';
import {
MAT_DATE_RANGE_SELECTION_STRATEGY,
MatDateRangeSelectionStrategy,
} from './date-range-selection-strategy';
/** Used to generate a unique ID for each datepicker instance. */
let datepickerUid = 0;
/** Injection token that determines the scroll handling while the calendar is open. */
export const MAT_DATEPICKER_SCROLL_STRATEGY =
new InjectionToken<() => ScrollStrategy>('mat-datepicker-scroll-strategy');
/** @docs-private */
export function MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** Possible positions for the datepicker dropdown along the X axis. */
export type DatepickerDropdownPositionX = 'start' | 'end';
/** Possible positions for the datepicker dropdown along the Y axis. */
export type DatepickerDropdownPositionY = 'above' | 'below';
/** @docs-private */
export const MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = {
provide: MAT_DATEPICKER_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY,
};
// Boilerplate for applying mixins to MatDatepickerContent.
/** @docs-private */
class MatDatepickerContentBase {
constructor(public _elementRef: ElementRef) { }
}
const _MatDatepickerContentMixinBase: CanColorCtor & typeof MatDatepickerContentBase =
mixinColor(MatDatepickerContentBase);
/**
* Component used as the content for the datepicker dialog and popup. We use this instead of using
* MatCalendar directly as the content so we can control the initial focus. This also gives us a
* place to put additional features of the popup that are not part of the calendar itself in the
* future. (e.g. confirmation buttons).
* @docs-private
*/
@Component({
selector: 'mat-datepicker-content',
templateUrl: 'datepicker-content.html',
styleUrls: ['datepicker-content.css'],
host: {
'class': 'mat-datepicker-content',
'[@transformPanel]': '_animationState',
'(@transformPanel.done)': '_animationDone.next()',
'[class.mat-datepicker-content-touch]': 'datepicker.touchUi',
},
animations: [
matDatepickerAnimations.transformPanel,
matDatepickerAnimations.fadeInCalendar,
],
exportAs: 'matDatepickerContent',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
inputs: ['color'],
})
export class MatDatepickerContent<S, D = ExtractDateTypeFromSelection<S>>
extends _MatDatepickerContentMixinBase implements AfterViewInit, OnDestroy, CanColor {
private _subscriptions = new Subscription();
/** Reference to the internal calendar component. */
@ViewChild(MatCalendar) _calendar: MatCalendar<D>;
/** Reference to the datepicker that created the overlay. */
datepicker: MatDatepickerBase<any, S, D>;
/** Start of the comparison range. */
comparisonStart: D | null;
/** End of the comparison range. */
comparisonEnd: D | null;
/** Whether the datepicker is above or below the input. */
_isAbove: boolean;
/** Current state of the animation. */
_animationState: 'enter' | 'void' = 'enter';
/** Emits when an animation has finished. */
_animationDone = new Subject<void>();
constructor(
elementRef: ElementRef,
/**
* @deprecated `_changeDetectorRef`, `_model` and `_rangeSelectionStrategy`
* parameters to become required.
* @breaking-change 11.0.0
*/
private _changeDetectorRef?: ChangeDetectorRef,
private _model?: MatDateSelectionModel<S, D>,
private _dateAdapter?: DateAdapter<D>,
@Optional() @Inject(MAT_DATE_RANGE_SELECTION_STRATEGY)
private _rangeSelectionStrategy?: MatDateRangeSelectionStrategy<D>) {
super(elementRef);
}
ngAfterViewInit() {
// @breaking-change 11.0.0 Remove null check for `_changeDetectorRef.
if (this._changeDetectorRef) {
this._subscriptions.add(this.datepicker._stateChanges.subscribe(() => {
this._changeDetectorRef!.markForCheck();
}));
}
this._calendar.focusActiveCell();
}
ngOnDestroy() {
this._subscriptions.unsubscribe();
this._animationDone.complete();
}
_handleUserSelection(event: MatCalendarUserEvent<D | null>) {
// @breaking-change 11.0.0 Remove null checks for _model,
// _rangeSelectionStrategy and _dateAdapter.
if (this._model && this._dateAdapter) {
const selection = this._model.selection;
const value = event.value;
const isRange = selection instanceof DateRange;
// If we're selecting a range and we have a selection strategy, always pass the value through
// there. Otherwise don't assign null values to the model, unless we're selecting a range.
// A null value when picking a range means that the user cancelled the selection (e.g. by
// pressing escape), whereas when selecting a single value it means that the value didn't
// change. This isn't very intuitive, but it's here for backwards-compatibility.
if (isRange && this._rangeSelectionStrategy) {
const newSelection = this._rangeSelectionStrategy.selectionFinished(value,
selection as unknown as DateRange<D>, event.event);
this._model.updateSelection(newSelection as unknown as S, this);
} else if (value && (isRange ||
!this._dateAdapter.sameDate(value, selection as unknown as D))) {
this._model.add(value);
}
}
if (!this._model || this._model.isComplete()) {
this.datepicker.close();
}
}
_startExitAnimation() {
this._animationState = 'void';
// @breaking-change 11.0.0 Remove null check for `_changeDetectorRef`.
if (this._changeDetectorRef) {
this._changeDetectorRef.markForCheck();
}
}
_getSelected() {
// @breaking-change 11.0.0 Remove null check for `_model`.
return this._model ? this._model.selection as unknown as D | DateRange<D> | null : null;
}
}
/** Form control that can be associated with a datepicker. */
export interface MatDatepickerControl<D> {
getStartValue(): D | null;
getThemePalette(): ThemePalette;
min: D | null;
max: D | null;
disabled: boolean;
dateFilter: DateFilterFn<D>;
getConnectedOverlayOrigin(): ElementRef;
_stateChanges: Observable<void>;
}
/** Base class for a datepicker. */
@Directive()
export abstract class MatDatepickerBase<C extends MatDatepickerControl<D>, S,
D = ExtractDateTypeFromSelection<S>> implements OnDestroy, CanColor, OnChanges {
private _scrollStrategy: () => ScrollStrategy;
private _inputStateChanges = Subscription.EMPTY;
/** An input indicating the type of the custom header component for the calendar, if set. */
@Input() calendarHeaderComponent: ComponentType<any>;
/** The date to open the calendar to initially. */
@Input()
get startAt(): D | null {
// If an explicit startAt is set we start there, otherwise we start at whatever the currently
// selected value is.
return this._startAt || (this._datepickerInput ? this._datepickerInput.getStartValue() : null);
}
set startAt(value: D | null) {
this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
}
private _startAt: D | null;
/** The view that the calendar should start in. */
@Input() startView: 'month' | 'year' | 'multi-year' = 'month';
/** Color palette to use on the datepicker's calendar. */
@Input()
get color(): ThemePalette {
return this._color ||
(this._datepickerInput ? this._datepickerInput.getThemePalette() : undefined);
}
set color(value: ThemePalette) {
this._color = value;
}
_color: ThemePalette;
/**
* Whether the calendar UI is in touch mode. In touch mode the calendar opens in a dialog rather
* than a popup and elements have more padding to allow for bigger touch targets.
*/
@Input()
get touchUi(): boolean { return this._touchUi; }
set touchUi(value: boolean) {
this._touchUi = coerceBooleanProperty(value);
}
private _touchUi = false;
/** Whether the datepicker pop-up should be disabled. */
@Input()
get disabled(): boolean {
return this._disabled === undefined && this._datepickerInput ?
this._datepickerInput.disabled : !!this._disabled;
}
set disabled(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._disabled) {
this._disabled = newValue;
this._stateChanges.next(undefined);
}
}
private _disabled: boolean;
/** Preferred position of the datepicker in the X axis. */
@Input()
xPosition: DatepickerDropdownPositionX = 'start';
/** Preferred position of the datepicker in the Y axis. */
@Input()
yPosition: DatepickerDropdownPositionY = 'below';
/**
* Emits selected year in multiyear view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly yearSelected: EventEmitter<D> = new EventEmitter<D>();
/**
* Emits selected month in year view.
* This doesn't imply a change on the selected date.
*/
@Output() readonly monthSelected: EventEmitter<D> = new EventEmitter<D>();
/** Classes to be passed to the date picker panel. Supports the same syntax as `ngClass`. */
@Input() panelClass: string | string[];
/** Function that can be used to add custom CSS classes to dates. */
@Input() dateClass: (date: D) => MatCalendarCellCssClasses;
/** Emits when the datepicker has been opened. */
@Output('opened') openedStream: EventEmitter<void> = new EventEmitter<void>();
/** Emits when the datepicker has been closed. */
@Output('closed') closedStream: EventEmitter<void> = new EventEmitter<void>();
/** Whether the calendar is open. */
@Input()
get opened(): boolean { return this._opened; }
set opened(value: boolean) { value ? this.open() : this.close(); }
private _opened = false;
/** The id for the datepicker calendar. */
id: string = `mat-datepicker-${datepickerUid++}`;
/** The minimum selectable date. */
_getMinDate(): D | null {
return this._datepickerInput && this._datepickerInput.min;
}
/** The maximum selectable date. */
_getMaxDate(): D | null {
return this._datepickerInput && this._datepickerInput.max;
}
_getDateFilter(): DateFilterFn<D> {
return this._datepickerInput && this._datepickerInput.dateFilter;
}
/** A reference to the overlay when the calendar is opened as a popup. */
private _popupRef: OverlayRef | null;
/** A reference to the dialog when the calendar is opened as a dialog. */
private _dialogRef: MatDialogRef<MatDatepickerContent<S, D>> | null;
/** Reference to the component instantiated in popup mode. */
private _popupComponentRef: ComponentRef<MatDatepickerContent<S, D>> | null;
/** The element that was focused before the datepicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
/** The input element this datepicker is associated with. */
_datepickerInput: C;
/** Emits when the datepicker's state changes. */
readonly _stateChanges = new Subject<void>();
constructor(private _dialog: MatDialog,
private _overlay: Overlay,
private _ngZone: NgZone,
private _viewContainerRef: ViewContainerRef,
@Inject(MAT_DATEPICKER_SCROLL_STRATEGY) scrollStrategy: any,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() private _dir: Directionality,
@Optional() @Inject(DOCUMENT) private _document: any,
private _model: MatDateSelectionModel<S, D>) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
this._scrollStrategy = scrollStrategy;
}
ngOnChanges(changes: SimpleChanges) {
const positionChange = changes['xPosition'] || changes['yPosition'];
if (positionChange && !positionChange.firstChange && this._popupRef) {
this._setConnectedPositions(
this._popupRef.getConfig().positionStrategy as FlexibleConnectedPositionStrategy);
if (this.opened) {
this._popupRef.updatePosition();
}
}
this._stateChanges.next(undefined);
}
ngOnDestroy() {
this._destroyPopup();
this.close();
this._inputStateChanges.unsubscribe();
this._stateChanges.complete();
}
/** Selects the given date */
select(date: D): void {
this._model.add(date);
}
/** Emits the selected year in multiyear view */
_selectYear(normalizedYear: D): void {
this.yearSelected.emit(normalizedYear);
}
/** Emits selected month in year view */
_selectMonth(normalizedMonth: D): void {
this.monthSelected.emit(normalizedMonth);
}
/**
* Register an input with this datepicker.
* @param input The datepicker input to register with this datepicker.
* @returns Selection model that the input should hook itself up to.
*/
_registerInput(input: C): MatDateSelectionModel<S, D> {
if (this._datepickerInput) {
throw Error('A MatDatepicker can only be associated with a single input.');
}
this._inputStateChanges.unsubscribe();
this._datepickerInput = input;
this._inputStateChanges =
input._stateChanges.subscribe(() => this._stateChanges.next(undefined));
return this._model;
}
/** Open the calendar. */
open(): void {
if (this._opened || this.disabled) {
return;
}
if (!this._datepickerInput) {
throw Error('Attempted to open an MatDatepicker with no associated input.');
}
if (this._document) {
this._focusedElementBeforeOpen = this._document.activeElement;
}
this.touchUi ? this._openAsDialog() : this._openAsPopup();
this._opened = true;
this.openedStream.emit();
}
/** Close the calendar. */
close(): void {
if (!this._opened) {
return;
}
if (this._popupComponentRef && this._popupRef) {
const instance = this._popupComponentRef.instance;
instance._startExitAnimation();
instance._animationDone.pipe(take(1)).subscribe(() => this._destroyPopup());
}
if (this._dialogRef) {
this._dialogRef.close();
this._dialogRef = null;
}
const completeClose = () => {
// The `_opened` could've been reset already if
// we got two events in quick succession.
if (this._opened) {
this._opened = false;
this.closedStream.emit();
this._focusedElementBeforeOpen = null;
}
};
if (this._focusedElementBeforeOpen &&
typeof this._focusedElementBeforeOpen.focus === 'function') {
// Because IE moves focus asynchronously, we can't count on it being restored before we've
// marked the datepicker as closed. If the event fires out of sequence and the element that
// we're refocusing opens the datepicker on focus, the user could be stuck with not being
// able to close the calendar at all. We work around it by making the logic, that marks
// the datepicker as closed, async as well.
this._focusedElementBeforeOpen.focus();
setTimeout(completeClose);
} else {
completeClose();
}
}
/** Open the calendar as a dialog. */
private _openAsDialog(): void {
// Usually this would be handled by `open` which ensures that we can only have one overlay
// open at a time, however since we reset the variables in async handlers some overlays
// may slip through if the user opens and closes multiple times in quick succession (e.g.
// by holding down the enter key).
if (this._dialogRef) {
this._dialogRef.close();
}
this._dialogRef = this._dialog.open<MatDatepickerContent<S, D>>(MatDatepickerContent, {
direction: this._dir ? this._dir.value : 'ltr',
viewContainerRef: this._viewContainerRef,
panelClass: 'mat-datepicker-dialog',
// These values are all the same as the defaults, but we set them explicitly so that the
// datepicker dialog behaves consistently even if the user changed the defaults.
hasBackdrop: true,
disableClose: false,
width: '',
height: '',
minWidth: '',
minHeight: '',
maxWidth: '80vw',
maxHeight: '',
position: {},
autoFocus: true,
// `MatDialog` has focus restoration built in, however we want to disable it since the
// datepicker also has focus restoration for dropdown mode. We want to do this, in order
// to ensure that the timing is consistent between dropdown and dialog modes since `MatDialog`
// restores focus when the animation is finished, but the datepicker does it immediately.
// Furthermore, this avoids any conflicts where the datepicker consumer might move focus
// inside the `closed` event which is dispatched immediately.
restoreFocus: false
});
this._dialogRef.afterClosed().subscribe(() => this.close());
this._forwardContentValues(this._dialogRef.componentInstance);
}
/** Open the calendar as a popup. */
private _openAsPopup(): void {
const portal = new ComponentPortal<MatDatepickerContent<S, D>>(MatDatepickerContent,
this._viewContainerRef);
this._destroyPopup();
this._createPopup();
this._popupComponentRef = this._popupRef!.attach(portal);
this._forwardContentValues(this._popupComponentRef.instance);
// Update the position once the calendar has rendered.
this._ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => {
this._popupRef!.updatePosition();
});
}
/** Forwards relevant values from the datepicker to the datepicker content inside the overlay. */
protected _forwardContentValues(instance: MatDatepickerContent<S, D>) {
instance.datepicker = this;
instance.color = this.color;
}
/** Create the popup. */
private _createPopup(): void {
const positionStrategy = this._overlay.position()
.flexibleConnectedTo(this._datepickerInput.getConnectedOverlayOrigin())
.withTransformOriginOn('.mat-datepicker-content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition();
const overlayConfig = new OverlayConfig({
positionStrategy: this._setConnectedPositions(positionStrategy),
hasBackdrop: true,
backdropClass: 'mat-overlay-transparent-backdrop',
direction: this._dir,
scrollStrategy: this._scrollStrategy(),
panelClass: 'mat-datepicker-popup',
});
this._popupRef = this._overlay.create(overlayConfig);
this._popupRef.overlayElement.setAttribute('role', 'dialog');
merge(
this._popupRef.backdropClick(),
this._popupRef.detachments(),
this._popupRef.keydownEvents().pipe(filter(event => {
// Closing on alt + up is only valid when there's an input associated with the datepicker.
return event.keyCode === ESCAPE ||
(this._datepickerInput && event.altKey && event.keyCode === UP_ARROW);
}))
).subscribe(event => {
if (event) {
event.preventDefault();
}
this.close();
});
}
/** Destroys the current popup overlay. */
private _destroyPopup() {
if (this._popupRef) {
this._popupRef.dispose();
this._popupRef = this._popupComponentRef = null;
}
}
/** Sets the positions of the datepicker in dropdown mode based on the current configuration. */
private _setConnectedPositions(strategy: FlexibleConnectedPositionStrategy) {
const primaryX = this.xPosition === 'end' ? 'end' : 'start';
const secondaryX = primaryX === 'start' ? 'end' : 'start';
const primaryY = this.yPosition === 'above' ? 'bottom' : 'top';
const secondaryY = primaryY === 'top' ? 'bottom' : 'top';
return strategy.withPositions([
{
originX: primaryX,
originY: secondaryY,
overlayX: primaryX,
overlayY: primaryY
},
{
originX: primaryX,
originY: primaryY,
overlayX: primaryX,
overlayY: secondaryY
},
{
originX: secondaryX,
originY: secondaryY,
overlayX: secondaryX,
overlayY: primaryY
},
{
originX: secondaryX,
originY: primaryY,
overlayX: secondaryX,
overlayY: secondaryY
}
]);
}
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_touchUi: BooleanInput;
}