-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
datepicker.ts
310 lines (268 loc) · 9.72 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
/**
* @license
* Copyright Google Inc. 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 {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ComponentRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
NgZone,
Inject,
} from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';
import {Overlay} from '../core/overlay/overlay';
import {OverlayRef} from '../core/overlay/overlay-ref';
import {ComponentPortal} from '../core/portal/portal';
import {OverlayState} from '../core/overlay/overlay-state';
import {Directionality} from '../core/bidi/index';
import {MdDialog} from '../dialog/dialog';
import {MdDialogRef} from '../dialog/dialog-ref';
import {PositionStrategy} from '../core/overlay/position/position-strategy';
import {MdDatepickerInput} from './datepicker-input';
import {Subscription} from 'rxjs/Subscription';
import {MdDialogConfig} from '../dialog/dialog-config';
import {DateAdapter} from '../core/datetime/index';
import {createMissingDateImplError} from './datepicker-errors';
import {ESCAPE} from '../core/keyboard/keycodes';
import {MdCalendar} from './calendar';
import 'rxjs/add/operator/first';
/** Used to generate a unique ID for each datepicker instance. */
let datepickerUid = 0;
/**
* Component used as the content for the datepicker dialog and popup. We use this instead of using
* MdCalendar 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({
moduleId: module.id,
selector: 'md-datepicker-content',
templateUrl: 'datepicker-content.html',
styleUrls: ['datepicker-content.css'],
host: {
'class': 'mat-datepicker-content',
'[class.mat-datepicker-content-touch]': 'datepicker.touchUi',
'(keydown)': '_handleKeydown($event)',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MdDatepickerContent<D> implements AfterContentInit {
datepicker: MdDatepicker<D>;
@ViewChild(MdCalendar) _calendar: MdCalendar<D>;
ngAfterContentInit() {
this._calendar._focusActiveCell();
}
/**
* Handles keydown event on datepicker content.
* @param event The event.
*/
_handleKeydown(event: KeyboardEvent): void {
if (event.keyCode === ESCAPE) {
this.datepicker.close();
event.preventDefault();
}
}
}
// TODO(mmalerba): We use a component instead of a directive here so the user can use implicit
// template reference variables (e.g. #d vs #d="mdDatepicker"). We can change this to a directive if
// angular adds support for `exportAs: '$implicit'` on directives.
/** Component responsible for managing the datepicker popup/dialog. */
@Component({
moduleId: module.id,
selector: 'md-datepicker, mat-datepicker',
template: '',
})
export class MdDatepicker<D> implements OnDestroy {
/** The date to open the calendar to initially. */
@Input()
get startAt(): D {
// 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.value : null);
}
set startAt(date: D) { this._startAt = date; }
private _startAt: D;
/** The view that the calendar should start in. */
@Input() startView: 'month' | 'year' = 'month';
/**
* 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() touchUi = false;
/** Emits new selected date when selected date changes. */
@Output() selectedChanged = new EventEmitter<D>();
/** Whether the calendar is open. */
opened = false;
/** The id for the datepicker calendar. */
id = `md-datepicker-${datepickerUid++}`;
/** The currently selected date. */
_selected: D | null = null;
/** The minimum selectable date. */
get _minDate(): D {
return this._datepickerInput && this._datepickerInput.min;
}
/** The maximum selectable date. */
get _maxDate(): D {
return this._datepickerInput && this._datepickerInput.max;
}
get _dateFilter(): (date: D | null) => boolean {
return this._datepickerInput && this._datepickerInput._dateFilter;
}
/** A reference to the overlay when the calendar is opened as a popup. */
private _popupRef: OverlayRef;
/** A reference to the dialog when the calendar is opened as a dialog. */
private _dialogRef: MdDialogRef<any> | null;
/** A portal containing the calendar for this datepicker. */
private _calendarPortal: ComponentPortal<MdDatepickerContent<D>>;
/** The input element this datepicker is associated with. */
private _datepickerInput: MdDatepickerInput<D>;
/** The element that was focused before the datepicker was opened. */
private _focusedElementBeforeOpen: HTMLElement | null = null;
private _inputSubscription: Subscription;
constructor(private _dialog: MdDialog,
private _overlay: Overlay,
private _ngZone: NgZone,
private _viewContainerRef: ViewContainerRef,
@Optional() private _dateAdapter: DateAdapter<D>,
@Optional() private _dir: Directionality,
@Optional() @Inject(DOCUMENT) private _document: any) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
}
ngOnDestroy() {
this.close();
if (this._popupRef) {
this._popupRef.dispose();
}
if (this._inputSubscription) {
this._inputSubscription.unsubscribe();
}
}
/** Selects the given date and closes the currently open popup or dialog. */
_selectAndClose(date: D): void {
let oldValue = this._selected;
this._selected = date;
if (!this._dateAdapter.sameDate(oldValue, this._selected)) {
this.selectedChanged.emit(date);
}
this.close();
}
/**
* Register an input with this datepicker.
* @param input The datepicker input to register with this datepicker.
*/
_registerInput(input: MdDatepickerInput<D>): void {
if (this._datepickerInput) {
throw Error('An MdDatepicker can only be associated with a single input.');
}
this._datepickerInput = input;
this._inputSubscription =
this._datepickerInput._valueChange.subscribe((value: D) => this._selected = value);
}
/** Open the calendar. */
open(): void {
if (this.opened) {
return;
}
if (!this._datepickerInput) {
throw Error('Attempted to open an MdDatepicker with no associated input.');
}
if (this._document) {
this._focusedElementBeforeOpen = this._document.activeElement;
}
this.touchUi ? this._openAsDialog() : this._openAsPopup();
this.opened = true;
}
/** Close the calendar. */
close(): void {
if (!this.opened) {
return;
}
if (this._popupRef && this._popupRef.hasAttached()) {
this._popupRef.detach();
}
if (this._dialogRef) {
this._dialogRef.close();
this._dialogRef = null;
}
if (this._calendarPortal && this._calendarPortal.isAttached) {
this._calendarPortal.detach();
}
if (this._focusedElementBeforeOpen && 'focus' in this._focusedElementBeforeOpen) {
this._focusedElementBeforeOpen.focus();
this._focusedElementBeforeOpen = null;
}
this.opened = false;
}
/** Open the calendar as a dialog. */
private _openAsDialog(): void {
this._dialogRef = this._dialog.open(MdDatepickerContent, {
viewContainerRef: this._viewContainerRef,
direction: this._dir ? this._dir.value : 'ltr'
});
this._dialogRef.afterClosed().subscribe(() => this.close());
this._dialogRef.componentInstance.datepicker = this;
}
/** Open the calendar as a popup. */
private _openAsPopup(): void {
if (!this._calendarPortal) {
this._calendarPortal = new ComponentPortal(MdDatepickerContent, this._viewContainerRef);
}
if (!this._popupRef) {
this._createPopup();
}
if (!this._popupRef.hasAttached()) {
let componentRef: ComponentRef<MdDatepickerContent<D>> =
this._popupRef.attach(this._calendarPortal);
componentRef.instance.datepicker = this;
// Update the position once the calendar has rendered.
this._ngZone.onStable.first().subscribe(() => this._popupRef.updatePosition());
}
this._popupRef.backdropClick().subscribe(() => this.close());
}
/** Create the popup. */
private _createPopup(): void {
const overlayState = new OverlayState();
overlayState.positionStrategy = this._createPopupPositionStrategy();
overlayState.hasBackdrop = true;
overlayState.backdropClass = 'md-overlay-transparent-backdrop';
overlayState.direction = this._dir ? this._dir.value : 'ltr';
overlayState.scrollStrategy = this._overlay.scrollStrategies.reposition();
this._popupRef = this._overlay.create(overlayState);
}
/** Create the popup PositionStrategy. */
private _createPopupPositionStrategy(): PositionStrategy {
return this._overlay.position()
.connectedTo(this._datepickerInput.getPopupConnectionElementRef(),
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'}
)
.withFallbackPosition(
{ originX: 'start', originY: 'top' },
{ overlayX: 'start', overlayY: 'bottom' }
)
.withFallbackPosition(
{originX: 'end', originY: 'bottom'},
{overlayX: 'end', overlayY: 'top'}
)
.withFallbackPosition(
{ originX: 'end', originY: 'top' },
{ overlayX: 'end', overlayY: 'bottom' }
);
}
}