-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
datepicker-base.ts
789 lines (682 loc) · 24.8 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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/**
* @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, coerceStringArray} from '@angular/cdk/coercion';
import {ESCAPE, hasModifierKey, UP_ARROW} from '@angular/cdk/keycodes';
import {
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
FlexibleConnectedPositionStrategy,
} from '@angular/cdk/overlay';
import {ComponentPortal, ComponentType, TemplatePortal} from '@angular/cdk/portal';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ComponentRef,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
ChangeDetectorRef,
Directive,
OnChanges,
OnInit,
SimpleChanges,
isDevMode,
} from '@angular/core';
import {CanColor, mixinColor, ThemePalette} from '@angular/material/core';
import {merge, Subject, Observable, Subscription} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {_getFocusedElementPierceShadowDom} from '@angular/cdk/platform';
import {DateAdapter} from '@matheo/datepicker/core';
import {MatCalendar} from './calendar';
import {MatCalendarType, MatCalendarView} from './calendar.types';
import {matDatepickerAnimations} from './datepicker-animations';
import {createMissingDateImplError} from './datepicker-errors';
import {MatCalendarUserEvent, MatCalendarCellClassFunction} 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';
import {MatDatepickerIntl} from './datepicker-intl';
/** 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 */
const _MatDatepickerContentBase = mixinColor(
class {
constructor(public _elementRef: ElementRef) {}
},
);
/**
* Component used as the content for the datepicker overlay. 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 overlay 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.scss'],
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 _MatDatepickerContentBase
implements OnInit, AfterViewInit, OnDestroy, CanColor
{
private _subscriptions = new Subscription();
private _model: MatDateSelectionModel<S, D>;
/** 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-dropdown' | 'enter-dialog' | 'void';
/** Emits when an animation has finished. */
readonly _animationDone = new Subject<void>();
/** Text for the close button. */
_closeButtonText: string;
/** Whether the close button currently has focus. */
_closeButtonFocused: boolean;
/** Portal with projected action buttons. */
_actionsPortal: TemplatePortal | null = null;
constructor(
elementRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef,
private _globalModel: MatDateSelectionModel<S, D>,
private _dateAdapter: DateAdapter<D>,
@Optional()
@Inject(MAT_DATE_RANGE_SELECTION_STRATEGY)
private _rangeSelectionStrategy: MatDateRangeSelectionStrategy<D>,
intl: MatDatepickerIntl,
) {
super(elementRef);
this._closeButtonText = intl.closeCalendarLabel;
}
ngOnInit() {
// If we have actions, clone the model so that we have the ability to cancel the selection,
// otherwise update the global model directly. Note that we want to assign this as soon as
// possible, but `_actionsPortal` isn't available in the constructor so we do it in `ngOnInit`.
this._model = this._actionsPortal ? this._globalModel.clone() : this._globalModel;
this._animationState = this.datepicker.touchUi ? 'enter-dialog' : 'enter-dropdown';
}
ngAfterViewInit() {
this._subscriptions.add(
this.datepicker.stateChanges.subscribe(() => {
this._changeDetectorRef.markForCheck();
}),
);
this._calendar.focusActiveCell();
}
ngOnDestroy() {
this._subscriptions.unsubscribe();
this._animationDone.complete();
}
_queueUserSelection(date: D) {
this._model.queue(date);
}
_handleUserSelection(event: MatCalendarUserEvent<D | null>) {
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._calendar.getUnit()))
) {
this._model.add(value);
}
// Delegate closing the overlay to the actions.
if ((!this._model || this._model.isComplete()) && !this._actionsPortal) {
this.datepicker.close();
}
}
_startExitAnimation() {
this._animationState = 'void';
this._changeDetectorRef.markForCheck();
}
_getSelected() {
return this._model.selection as unknown as D | DateRange<D> | null;
}
/** Applies the current pending selection to the global model. */
_applyPendingSelection() {
this._model.processQueue();
if (this._model !== this._globalModel) {
this._globalModel.updateSelection(this._model.selection, this);
}
}
}
/** Form control that can be associated with a datepicker. */
export interface MatDatepickerControl<D> {
type: MatCalendarType;
getStartValue(): D | null;
getThemePalette(): ThemePalette;
min: D | null;
max: D | null;
disabled: boolean;
dateFilter: DateFilterFn<D>;
getConnectedOverlayOrigin(): ElementRef;
getOverlayLabelId(): string | null;
stateChanges: Observable<void>;
}
/** A datepicker that can be attached to a {@link MatDatepickerControl}. */
export interface MatDatepickerPanel<
C extends MatDatepickerControl<D>,
S,
D = ExtractDateTypeFromSelection<S>,
> {
/** Stream that emits whenever the date picker is closed. */
closedStream: EventEmitter<void>;
/** The type of value handled by the calendar. */
type: MatCalendarType;
/** Color palette to use on the datepicker's calendar. */
color: ThemePalette;
/** The input element the datepicker is associated with. */
datepickerInput: C;
/** Whether the datepicker pop-up should be disabled. */
disabled: boolean;
/** The id for the datepicker's calendar. */
id: string;
/** Whether the datepicker is open. */
opened: boolean;
/** Stream that emits whenever the date picker is opened. */
openedStream: EventEmitter<void>;
/** Emits when the datepicker's state changes. */
stateChanges: Subject<void>;
/** Opens the datepicker. */
open(): void;
/** Register an input with the datepicker. */
registerInput(input: C): MatDateSelectionModel<S, D>;
}
/** Base class for a datepicker. */
@Directive()
export abstract class MatDatepickerBase<
C extends MatDatepickerControl<D>,
S,
D = ExtractDateTypeFromSelection<S>,
> implements MatDatepickerPanel<C, S, D>, OnDestroy, 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 type of value handled by the calendar. */
@Input() type: MatCalendarType = 'date';
/** The view that the calendar should start in. */
@Input() startView: MatCalendarView = 'month';
/** multi-year inputs */
@Input() yearsPerPage = 24;
@Input() yearsPerRow = 4;
/** Clock interval */
@Input() clockStep = 1;
/** Clock hour format */
@Input() twelveHour = true;
/** 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 dropdown 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';
/**
* Whether to restore focus to the previously-focused element when the calendar is closed.
* Note that automatic focus restoration is an accessibility feature and it is recommended that
* you provide your own equivalent, if you decide to turn it off.
*/
@Input()
get restoreFocus(): boolean {
return this._restoreFocus;
}
set restoreFocus(value: boolean) {
this._restoreFocus = coerceBooleanProperty(value);
}
private _restoreFocus = true;
/**
* 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>();
/**
* Emits when the current view changes.
*/
@Output() readonly viewChanged: EventEmitter<MatCalendarView> = new EventEmitter<MatCalendarView>(
true,
);
/** Function that can be used to add custom CSS classes to dates. */
@Input() dateClass: MatCalendarCellClassFunction<D>;
/** Emits when the datepicker has been opened. */
@Output('opened') readonly openedStream = new EventEmitter<void>();
/** Emits when the datepicker has been closed. */
@Output('closed') readonly closedStream = new EventEmitter<void>();
/**
* Classes to be passed to the date picker panel.
* Supports string and string array values, similar to `ngClass`.
*/
@Input()
get panelClass(): string | string[] {
return this._panelClass;
}
set panelClass(value: string | string[]) {
this._panelClass = coerceStringArray(value);
}
private _panelClass: string[];
/** Whether the calendar is open. */
@Input()
get opened(): boolean {
return this._opened;
}
set opened(value: boolean) {
coerceBooleanProperty(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 into which we've rendered the calendar. */
private _overlayRef: OverlayRef | null;
/** Reference to the component instance rendered in the overlay. */
private _componentRef: ComponentRef<MatDatepickerContent<S, D>> | null;
/** The element that was focused before the datepicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
/** Unique class that will be added to the backdrop so that the test harnesses can look it up. */
private _backdropHarnessClass = `${this.id}-backdrop`;
/** Currently-registered actions portal. */
private _actionsPortal: TemplatePortal | 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 _overlay: Overlay,
private _ngZone: NgZone,
private _viewContainerRef: ViewContainerRef,
@Inject(MAT_DATEPICKER_SCROLL_STRATEGY) scrollStrategy: any,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() private _dir: Directionality,
private _model: MatDateSelectionModel<S, D>,
) {
if (!this._dateAdapter && isDevMode()) {
throw createMissingDateImplError('DateAdapter');
}
this._scrollStrategy = scrollStrategy;
}
ngOnChanges(changes: SimpleChanges) {
const positionChange = changes['xPosition'] || changes['yPosition'];
if (positionChange && !positionChange.firstChange && this._overlayRef) {
const positionStrategy = this._overlayRef.getConfig().positionStrategy;
if (positionStrategy instanceof FlexibleConnectedPositionStrategy) {
this._setConnectedPositions(positionStrategy);
if (this.opened) {
this._overlayRef.updatePosition();
}
}
}
if (this.datepickerInput.type !== this.type) {
this.datepickerInput.type = this.type;
}
this.stateChanges.next(undefined);
}
ngOnDestroy() {
this._destroyOverlay();
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);
}
/** Emits changed view */
_viewChanged(view: MatCalendarView): void {
this.viewChanged.emit(view);
}
/**
* 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 && isDevMode()) {
throw Error('A MatDatepicker can only be associated with a single input.');
}
this._inputStateChanges.unsubscribe();
this.datepickerInput = input;
this.datepickerInput.type = this.type;
this._inputStateChanges = input.stateChanges.subscribe(() => this.stateChanges.next(undefined));
return this._model;
}
/**
* Registers a portal containing action buttons with the datepicker.
* @param portal Portal to be registered.
*/
registerActions(portal: TemplatePortal): void {
if (this._actionsPortal && isDevMode()) {
throw Error('A MatDatepicker can only be associated with a single actions row.');
}
this._actionsPortal = portal;
}
/**
* Removes a portal containing action buttons from the datepicker.
* @param portal Portal to be removed.
*/
removeActions(portal: TemplatePortal): void {
if (portal === this._actionsPortal) {
this._actionsPortal = null;
}
}
/** Open the calendar. */
open(): void {
if (this._opened || this.disabled) {
return;
}
if (!this.datepickerInput && isDevMode()) {
throw Error('Attempted to open an MatDatepicker with no associated input.');
}
this._focusedElementBeforeOpen = _getFocusedElementPierceShadowDom();
this._openOverlay();
this._opened = true;
this.openedStream.emit();
}
/** Close the calendar. */
close(): void {
if (!this._opened) {
return;
}
if (this._componentRef) {
const instance = this._componentRef.instance;
instance._startExitAnimation();
instance._animationDone.pipe(take(1)).subscribe(() => this._destroyOverlay());
}
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._restoreFocus &&
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();
}
}
/** Applies the current pending selection on the overlay to the model. */
_applyPendingSelection() {
this._componentRef?.instance?._applyPendingSelection();
}
/** 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;
instance._actionsPortal = this._actionsPortal;
}
/** Opens the overlay with the calendar. */
private _openOverlay(): void {
this._destroyOverlay();
const isDialog = this.touchUi;
const labelId = this.datepickerInput.getOverlayLabelId();
const portal = new ComponentPortal<MatDatepickerContent<S, D>>(
MatDatepickerContent,
this._viewContainerRef,
);
const overlayRef = (this._overlayRef = this._overlay.create(
new OverlayConfig({
positionStrategy: isDialog ? this._getDialogStrategy() : this._getDropdownStrategy(),
hasBackdrop: true,
backdropClass: [
isDialog ? 'cdk-overlay-dark-backdrop' : 'mat-overlay-transparent-backdrop',
this._backdropHarnessClass,
],
direction: this._dir,
scrollStrategy: isDialog ? this._overlay.scrollStrategies.block() : this._scrollStrategy(),
panelClass: `mat-datepicker-${isDialog ? 'dialog' : 'popup'}`,
}),
));
const overlayElement = overlayRef.overlayElement;
overlayElement.setAttribute('role', 'dialog');
if (labelId) {
overlayElement.setAttribute('aria-labelledby', labelId);
}
if (isDialog) {
overlayElement.setAttribute('aria-modal', 'true');
}
this._getCloseStream(overlayRef).subscribe(event => {
if (event) {
event.preventDefault();
}
this.close();
});
this._componentRef = overlayRef.attach(portal);
this._forwardContentValues(this._componentRef.instance);
// Update the position once the calendar has rendered. Only relevant in dropdown mode.
if (!isDialog) {
this._ngZone.onStable.pipe(take(1)).subscribe(() => overlayRef.updatePosition());
}
}
/** Destroys the current overlay. */
private _destroyOverlay() {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = this._componentRef = null;
}
}
/** Gets a position strategy that will open the calendar as a dropdown. */
private _getDialogStrategy() {
return this._overlay.position().global().centerHorizontally().centerVertically();
}
/** Gets a position strategy that will open the calendar as a dropdown. */
private _getDropdownStrategy() {
const strategy = this._overlay
.position()
.flexibleConnectedTo(this.datepickerInput.getConnectedOverlayOrigin())
.withTransformOriginOn('.mat-datepicker-content')
.withFlexibleDimensions(false)
.withViewportMargin(8)
.withLockedPosition();
return this._setConnectedPositions(strategy);
}
/** 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,
},
]);
}
/** Gets an observable that will emit when the overlay is supposed to be closed. */
private _getCloseStream(overlayRef: OverlayRef) {
return merge(
overlayRef.backdropClick(),
overlayRef.detachments(),
overlayRef.keydownEvents().pipe(
filter(event => {
// Closing on alt + up is only valid when there's an input associated with the datepicker.
return (
(event.keyCode === ESCAPE && !hasModifierKey(event)) ||
(this.datepickerInput && hasModifierKey(event, 'altKey') && event.keyCode === UP_ARROW)
);
}),
),
);
}
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_opened: BooleanInput;
static ngAcceptInputType_touchUi: BooleanInput;
static ngAcceptInputType_restoreFocus: BooleanInput;
}