This repository has been archived by the owner on Aug 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
datepickerDirective.js
1056 lines (897 loc) · 41.4 KB
/
datepickerDirective.js
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
'use strict';
// TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
// TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
// TODO(jelbourn): input behavior (masking? auto-complete?)
angular.module('material.components.datepicker')
.directive('mdDatepicker', datePickerDirective);
/**
* @ngdoc directive
* @name mdDatepicker
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Expects either a JavaScript Date object or a
* value that can be parsed into one (e.g. a ISO 8601 string).
* @param {Object=} ng-model-options Allows tuning of the way in which `ng-model` is being
* updated. Also allows for a timezone to be specified.
* <a href="https://docs.angularjs.org/api/ng/directive/ngModelOptions#usage">
* Read more at the ngModelOptions docs.</a>
* @param {expression=} ng-change Expression evaluated when the model value changes.
* @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar
* is opened.
* @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the
* calendar is closed.
* @param {boolean=} ng-disabled Whether the datepicker is disabled.
* @param {boolean=} ng-required Whether a value is required for the datepicker.
* @param {Date=} md-min-date Expression representing a min date (inclusive).
* @param {Date=} md-max-date Expression representing a max date (inclusive).
* @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a
* boolean whether it can be selected in "day" mode or not. Returning false will also trigger a
* `filtered` model validation error.
* @param {(function(Date): boolean)=} md-month-filter Function expecting a date and returning a
* boolean whether it can be selected in "month" mode or not. Returning false will also trigger a
* `filtered` model validation error.
* @param {string=} md-placeholder The date input placeholder value.
* @param {string=} md-open-on-focus When present, the calendar will be opened when the input
* is focused.
* @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar
* on-demand.
* @param {string=} md-current-view Default open view of the calendar pane. Can be either
* "month" or "year".
* @param {string=} md-mode Restricts the user to only selecting a value from a particular view.
* This option can be used if the user is only supposed to choose from a certain date type
* (e.g. only selecting the month).
* Can be either "month" or "day". **Note** that this will overwrite the `md-current-view` value.
* @param {string=} md-hide-icons Determines which datepicker icons should be hidden. Note that
* this may cause the datepicker to not align properly with other components.
* **Use at your own risk.** Possible values are:
* * `"all"` - Hides all icons.
* * `"calendar"` - Only hides the calendar icon.
* * `"triangle"` - Only hides the triangle icon.
* @param {Object=} md-date-locale Allows for the values from the `$mdDateLocaleProvider` to be
* overwritten on a per-element basis (e.g. `msgOpenCalendar` can be overwritten with
* `md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }"`).
* @param {string=} input-aria-describedby A space-separated list of element IDs. This should
* contain the IDs of any elements that describe this datepicker. Screen readers will read the
* content of these elements at the end of announcing that the datepicker has been selected
* and describing its current state. The descriptive elements do not need to be visible on the
* page.
* @param {string=} input-aria-labelledby A space-separated list of element IDs. The ideal use
* case is that this would contain the ID of a `<label>` element should be associated with this
* datepicker. This is necessary when using `md-datepicker` inside of an `md-input-container`
* with a `<label>`.<br><br>
* For `<label id="start-date">Start Date</label>`, you would set this to
* `input-aria-labelledby="start-date"`.
*
* @description
* `<md-datepicker>` is a component used to select a single date.
* For information on how to configure internationalization for the date picker,
* see <a ng-href="api/service/$mdDateLocaleProvider">$mdDateLocaleProvider</a>.
*
* This component supports
* [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
* Supported attributes are:
* * `required`: whether a required date is not set.
* * `mindate`: whether the selected date is before the minimum allowed date.
* * `maxdate`: whether the selected date is after the maximum allowed date.
* * `debounceInterval`: ms to delay input processing (since last debounce reset);
* default value 500ms
*
* @usage
* <hljs lang="html">
* <md-datepicker ng-model="birthday"></md-datepicker>
* </hljs>
*
*/
function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria, inputDirective) {
return {
template: function(tElement, tAttrs) {
// Buttons are not in the tab order because users can open the calendar via keyboard
// interaction on the text input, and multiple tab stops for one component (picker)
// may be confusing.
var hiddenIcons = tAttrs.mdHideIcons;
var inputAriaDescribedby = tAttrs.inputAriaDescribedby;
var inputAriaLabelledby = tAttrs.inputAriaLabelledby;
var ariaLabelValue = tAttrs.ariaLabel || tAttrs.mdPlaceholder;
var ngModelOptions = tAttrs.ngModelOptions;
var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
'<md-button class="md-datepicker-button md-icon-button" type="button" ' +
'tabindex="-1" aria-hidden="true" ' +
'ng-click="ctrl.openCalendarPane($event)">' +
'<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
'</md-button>';
var triangleButton = '';
if (hiddenIcons !== 'all' && hiddenIcons !== 'triangle') {
triangleButton = '' +
'<md-button type="button" md-no-ink ' +
'class="md-datepicker-triangle-button md-icon-button" ' +
'ng-click="ctrl.openCalendarPane($event)" ' +
'aria-label="{{::ctrl.locale.msgOpenCalendar}}">' +
'<div class="md-datepicker-expand-triangle"></div>' +
'</md-button>';
tElement.addClass(HAS_TRIANGLE_ICON_CLASS);
}
return calendarButton +
'<div class="md-datepicker-input-container" ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
'<input ' +
(ariaLabelValue ? 'aria-label="' + ariaLabelValue + '" ' : '') +
(inputAriaDescribedby ? 'aria-describedby="' + inputAriaDescribedby + '" ' : '') +
(inputAriaLabelledby ? 'aria-labelledby="' + inputAriaLabelledby + '" ' : '') +
'class="md-datepicker-input" ' +
'aria-haspopup="dialog" ' +
'ng-focus="ctrl.setFocused(true)" ' +
'ng-blur="ctrl.setFocused(false)"> ' +
triangleButton +
'</div>' +
// This pane will be detached from here and re-attached to the document body.
'<div class="md-datepicker-calendar-pane md-whiteframe-z1" id="{{::ctrl.calendarPaneId}}">' +
'<div class="md-datepicker-input-mask">' +
'<div class="md-datepicker-input-mask-opaque"></div>' +
'</div>' +
'<div class="md-datepicker-calendar">' +
'<md-calendar role="dialog" aria-label="{{::ctrl.locale.msgCalendar}}" ' +
'md-current-view="{{::ctrl.currentView}}" ' +
'md-mode="{{::ctrl.mode}}" ' +
'md-min-date="ctrl.minDate" ' +
'md-max-date="ctrl.maxDate" ' +
'md-date-filter="ctrl.dateFilter" ' +
'md-month-filter="ctrl.monthFilter" ' +
(ngModelOptions ? 'ng-model-options="' + ngModelOptions + '" ' : '') +
'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
'</md-calendar>' +
'</div>' +
'</div>';
},
require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
placeholder: '@mdPlaceholder',
currentView: '@mdCurrentView',
mode: '@mdMode',
dateFilter: '=mdDateFilter',
monthFilter: '=mdMonthFilter',
isOpen: '=?mdIsOpen',
debounceInterval: '=mdDebounceInterval',
dateLocale: '=mdDateLocale'
},
controller: DatePickerCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attr, controllers) {
var ngModelCtrl = controllers[0];
var mdDatePickerCtrl = controllers[1];
var mdInputContainer = controllers[2];
var parentForm = controllers[3];
var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer, inputDirective);
if (mdInputContainer) {
// We need to move the spacer after the datepicker itself,
// because md-input-container adds it after the
// md-datepicker-input by default. The spacer gets wrapped in a
// div, because it floats and gets aligned next to the datepicker.
// There are easier ways of working around this with CSS (making the
// datepicker 100% wide, change the `display` etc.), however they
// break the alignment with any other form controls.
var spacer = element[0].querySelector('.md-errors-spacer');
if (spacer) {
element.after(angular.element('<div>').append(spacer));
}
mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
mdInputContainer.input = element;
mdInputContainer.element
.addClass(INPUT_CONTAINER_CLASS)
.toggleClass(HAS_CALENDAR_ICON_CLASS,
attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
if (!mdInputContainer.label) {
$mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
} else if (!mdNoAsterisk) {
attr.$observe('required', function(value) {
mdInputContainer.label.toggleClass('md-required', !!value);
});
}
scope.$watch(mdInputContainer.isErrorGetter || function() {
return ngModelCtrl.$invalid && (ngModelCtrl.$touched ||
(parentForm && parentForm.$submitted));
}, mdInputContainer.setInvalid);
} else if (parentForm) {
// If invalid, highlights the input when the parent form is submitted.
var parentSubmittedWatcher = scope.$watch(function() {
return parentForm.$submitted;
}, function(isSubmitted) {
if (isSubmitted) {
mdDatePickerCtrl.updateErrorState();
parentSubmittedWatcher();
}
});
}
}
};
}
/** Additional offset for the input's `size` attribute, which is updated based on its content. */
var EXTRA_INPUT_SIZE = 3;
/** Class applied to the container if the date is invalid. */
var INVALID_CLASS = 'md-datepicker-invalid';
/** Class applied to the datepicker when it's open. */
var OPEN_CLASS = 'md-datepicker-open';
/** Class applied to the md-input-container, if a datepicker is placed inside it */
var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
/** Class to be applied when the calendar icon is enabled. */
var HAS_CALENDAR_ICON_CLASS = '_md-datepicker-has-calendar-icon';
/** Class to be applied when the triangle icon is enabled. */
var HAS_TRIANGLE_ICON_CLASS = '_md-datepicker-has-triangle-icon';
/** Default time in ms to debounce input event by. */
var DEFAULT_DEBOUNCE_INTERVAL = 500;
/**
* Height of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_HEIGHT = 368;
/**
* Width of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_WIDTH = 360;
/** Used for checking whether the current user agent is on iOS or Android. */
var IS_MOBILE_REGEX = /ipad|iphone|ipod|android/i;
/**
* Controller for md-datepicker.
*
* @ngInject @constructor
*/
function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant, $mdTheming, $mdUtil,
$mdDateLocale, $$mdDateUtil, $$rAF, $filter, $timeout) {
/** @final */
this.$window = $window;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdConstant = $mdConstant;
/** @final */
this.$mdUtil = $mdUtil;
/** @final */
this.$$rAF = $$rAF;
/** @final */
this.$mdDateLocale = $mdDateLocale;
/** @final */
this.$timeout = $timeout;
/**
* The root document element. This is used for attaching a top-level click handler to
* close the calendar panel when a click outside said panel occurs. We use `documentElement`
* instead of body because, when scrolling is disabled, some browsers consider the body element
* to be completely off the screen and propagate events directly to the html element.
* @type {!JQLite}
*/
this.documentElement = angular.element(document.documentElement);
/** @type {!ngModel.NgModelController} */
this.ngModelCtrl = null;
/** @type {HTMLInputElement} */
this.inputElement = $element[0].querySelector('input');
/**
* @final
* @type {!JQLite}
*/
this.ngInputElement = angular.element(this.inputElement);
/** @type {HTMLElement} */
this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
/** @type {HTMLElement} Floating calendar pane. */
this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
/** @type {HTMLElement} Calendar icon button. */
this.calendarButton = $element[0].querySelector('.md-datepicker-button');
/**
* Element covering everything but the input in the top of the floating calendar pane.
* @type {!JQLite}
*/
this.inputMask = angular.element($element[0].querySelector('.md-datepicker-input-mask-opaque'));
/**
* @final
* @type {!JQLite}
*/
this.$element = $element;
/**
* @final
* @type {!angular.Attributes}
*/
this.$attrs = $attrs;
/**
* @final
* @type {!angular.Scope}
*/
this.$scope = $scope;
/**
* This holds the model that will be used by the calendar.
* @type {Date|null|undefined}
*/
this.date = null;
/** @type {boolean} */
this.isFocused = false;
/** @type {boolean} */
this.isDisabled = undefined;
this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
/** @type {boolean} Whether the date-picker's calendar pane is open. */
this.isCalendarOpen = false;
/** @type {boolean} Whether the calendar should open when the input is focused. */
this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
/** @type {Object} Instance of the mdInputContainer controller */
this.mdInputContainer = null;
/**
* Element from which the calendar pane was opened. Keep track of this so that we can return
* focus to it when the pane is closed.
* @type {HTMLElement}
*/
this.calendarPaneOpenedFrom = null;
/** @type {String} Unique id for the calendar pane. */
this.calendarPaneId = 'md-date-pane-' + $mdUtil.nextUid();
/** Pre-bound click handler is saved so that the event listener can be removed. */
this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
/**
* Name of the event that will trigger a close. Necessary to sniff the browser, because
* the resize event doesn't make sense on mobile and can have a negative impact since it
* triggers whenever the browser zooms in on a focused input.
*/
this.windowEventName = IS_MOBILE_REGEX.test(
navigator.userAgent || navigator.vendor || window.opera
) ? 'orientationchange' : 'resize';
/** Pre-bound close handler so that the event listener can be removed. */
this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
/** Pre-bound handler for the window blur event. Allows for it to be removed later. */
this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
/** The built-in AngularJS date filter. */
this.ngDateFilter = $filter('date');
/** @type {Number} Extra margin for the left side of the floating calendar pane. */
this.leftMargin = 20;
/** @type {Number} Extra margin for the top of the floating calendar. Gets determined on the first open. */
this.topMargin = null;
// Unless the user specifies so, the datepicker should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if ($attrs.tabindex) {
this.ngInputElement.attr('tabindex', $attrs.tabindex);
$attrs.$set('tabindex', null);
} else {
$attrs.$set('tabindex', '-1');
}
$attrs.$set('aria-owns', this.calendarPaneId);
$mdTheming($element);
$mdTheming(angular.element(this.calendarPane));
var self = this;
$scope.$on('$destroy', function() {
self.detachCalendarPane();
});
if ($attrs.mdIsOpen) {
$scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
if (shouldBeOpen) {
self.openCalendarPane({
target: self.inputElement
});
} else {
self.closeCalendarPane();
}
});
}
// For AngularJS 1.4 and older, where there are no lifecycle hooks but bindings are
// pre-assigned, manually call the $onInit hook.
if (angular.version.major === 1 && angular.version.minor <= 4) {
this.$onInit();
}
}
/**
* AngularJS Lifecycle hook for newer AngularJS versions.
* Bindings are not guaranteed to have been assigned in the controller, but they are in the
* $onInit hook.
*/
DatePickerCtrl.prototype.$onInit = function() {
/**
* Holds locale-specific formatters, parsers, labels etc. Allows
* the user to override specific ones from the $mdDateLocale provider.
* @type {!Object}
*/
this.locale = this.dateLocale ? angular.extend({}, this.$mdDateLocale, this.dateLocale)
: this.$mdDateLocale;
this.installPropertyInterceptors();
this.attachChangeListeners();
this.attachInteractionListeners();
};
/**
* Sets up the controller's reference to ngModelController and
* applies AngularJS's `input[type="date"]` directive.
* @param {!angular.NgModelController} ngModelCtrl Instance of the ngModel controller.
* @param {Object} mdInputContainer Instance of the mdInputContainer controller.
* @param {Object} inputDirective Config for AngularJS's `input` directive.
*/
DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer, inputDirective) {
this.ngModelCtrl = ngModelCtrl;
this.mdInputContainer = mdInputContainer;
// The input needs to be [type="date"] in order to be picked up by AngularJS.
this.$attrs.$set('type', 'date');
// Invoke the `input` directive link function, adding a stub for the element.
// This allows us to re-use AngularJS's logic for setting the timezone via ng-model-options.
// It works by calling the link function directly which then adds the proper `$parsers` and
// `$formatters` to the ngModel controller.
inputDirective[0].link.pre(this.$scope, {
on: angular.noop,
val: angular.noop,
0: {}
}, this.$attrs, [ngModelCtrl]);
var self = this;
// Responds to external changes to the model value.
self.ngModelCtrl.$formatters.push(function(value) {
var parsedValue = angular.isDefined(value) ? value : null;
if (!(value instanceof Date)) {
parsedValue = Date.parse(value);
// `parsedValue` is the time since epoch if valid or `NaN` if invalid.
if (!isNaN(parsedValue) && angular.isNumber(parsedValue)) {
value = new Date(parsedValue);
}
if (value && !(value instanceof Date)) {
throw Error(
'The ng-model for md-datepicker must be a Date instance or a value ' +
'that can be parsed into a date. Currently the model is of type: ' + typeof value
);
}
}
self.onExternalChange(value);
return value;
});
// Responds to external error state changes (e.g. ng-required based on another input).
ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
// Forwards any events from the input to the root element. This is necessary to get `updateOn`
// working for events that don't bubble (e.g. 'blur') since AngularJS binds the handlers to
// the `<md-datepicker>`.
var updateOn = self.$mdUtil.getModelOption(ngModelCtrl, 'updateOn');
if (updateOn) {
this.ngInputElement.on(
updateOn,
angular.bind(this.$element, this.$element.triggerHandler, updateOn)
);
}
};
/**
* Attach event listeners for both the text input and the md-calendar.
* Events are used instead of ng-model so that updates don't infinitely update the other
* on a change. This should also be more performant than using a $watch.
*/
DatePickerCtrl.prototype.attachChangeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-change', function(event, date) {
self.setModelValue(date);
self.onExternalChange(date);
self.closeCalendarPane();
});
self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
var debounceInterval = angular.isDefined(this.debounceInterval) ?
this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
debounceInterval, self));
};
/** Attach event listeners for user interaction. */
DatePickerCtrl.prototype.attachInteractionListeners = function() {
var self = this;
var $scope = this.$scope;
var keyCodes = this.$mdConstant.KEY_CODE;
// Add event listener through angular so that we can triggerHandler in unit tests.
self.ngInputElement.on('keydown', function(event) {
if (event.altKey && event.keyCode === keyCodes.DOWN_ARROW) {
self.openCalendarPane(event);
$scope.$digest();
}
});
if (self.openOnFocus) {
self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
self.ngInputElement.on('click', function(event) {
event.stopPropagation();
});
self.ngInputElement.on('pointerdown',function(event) {
if (event.target && event.target.setPointerCapture) {
event.target.setPointerCapture(event.pointerId);
}
});
angular.element(self.$window).on('blur', self.windowBlurHandler);
$scope.$on('$destroy', function() {
angular.element(self.$window).off('blur', self.windowBlurHandler);
});
}
$scope.$on('md-calendar-close', function() {
self.closeCalendarPane();
});
};
/**
* Capture properties set to the date-picker and imperatively handle internal changes.
* This is done to avoid setting up additional $watches.
*/
DatePickerCtrl.prototype.installPropertyInterceptors = function() {
var self = this;
if (this.$attrs.ngDisabled) {
// The expression is to be evaluated against the directive element's scope and not
// the directive's isolate scope.
var scope = this.$scope.$parent;
if (scope) {
scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
self.setDisabled(isDisabled);
});
}
}
Object.defineProperty(this, 'placeholder', {
get: function() { return self.inputElement.placeholder; },
set: function(value) { self.inputElement.placeholder = value || ''; }
});
};
/**
* Sets whether the date-picker is disabled.
* @param {boolean} isDisabled
*/
DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
this.isDisabled = isDisabled;
this.inputElement.disabled = isDisabled;
if (this.calendarButton) {
this.calendarButton.disabled = isDisabled;
}
};
/**
* Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
* - mindate: whether the selected date is before the minimum date.
* - maxdate: whether the selected flag is after the maximum date.
* - filtered: whether the selected date is allowed by the custom filtering function.
* - valid: whether the entered text input is a valid date
*
* The 'required' flag is handled automatically by ngModel.
*
* @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
*/
DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
var date;
if (opt_date) {
date = new Date(opt_date.valueOf());
} else {
if (angular.isString(this.ngModelCtrl.$modelValue)) {
date = new Date(this.ngModelCtrl.$modelValue);
} else {
date = angular.copy(this.ngModelCtrl.$modelValue);
}
}
// Clear any existing errors to get rid of anything that's no longer relevant.
this.clearErrorState();
if (this.dateUtil.isValidDate(date)) {
// Force all dates to midnight in order to ignore the time portion.
date = this.dateUtil.createDateAtMidnight(date);
if (this.dateUtil.isValidDate(this.minDate)) {
var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
this.ngModelCtrl.$setValidity('mindate', date >= minDate);
}
if (this.dateUtil.isValidDate(this.maxDate)) {
var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
}
if (angular.isFunction(this.dateFilter)) {
this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
}
if (angular.isFunction(this.monthFilter)) {
this.ngModelCtrl.$setValidity('filtered', this.monthFilter(date));
}
} else {
// The date is seen as "not a valid date" if there is *something* set
// (i.e.., not null or undefined), but that something isn't a valid date.
this.ngModelCtrl.$setValidity('valid', date == null);
}
var input = this.inputElement.value;
var parsedDate = this.locale.parseDate(input);
if (!this.isInputValid(input, parsedDate) && this.ngModelCtrl.$valid) {
this.ngModelCtrl.$setValidity('valid', date == null);
}
angular.element(this.inputContainer).toggleClass(INVALID_CLASS,
this.ngModelCtrl.$invalid && (this.ngModelCtrl.$touched || this.ngModelCtrl.$submitted));
};
/**
* Check to see if the input is valid, as the validation should fail if the model is invalid.
*
* @param {string} inputString
* @param {Date} parsedDate
* @return {boolean} Whether the input is valid
*/
DatePickerCtrl.prototype.isInputValid = function (inputString, parsedDate) {
return inputString === '' || (
this.dateUtil.isValidDate(parsedDate) &&
this.locale.isDateComplete(inputString) &&
this.isDateEnabled(parsedDate)
);
};
/** Clears any error flags set by `updateErrorState`. */
DatePickerCtrl.prototype.clearErrorState = function() {
this.inputContainer.classList.remove(INVALID_CLASS);
['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
this.ngModelCtrl.$setValidity(field, true);
}, this);
};
/** Resizes the input element based on the size of its content. */
DatePickerCtrl.prototype.resizeInputElement = function() {
this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
};
/**
* Sets the model value if the user input is a valid date.
* Adds an invalid class to the input element if not.
*/
DatePickerCtrl.prototype.handleInputEvent = function() {
var inputString = this.inputElement.value;
var parsedDate = inputString ? this.locale.parseDate(inputString) : null;
this.dateUtil.setDateTimeToMidnight(parsedDate);
// An input string is valid if it is either empty (representing no date)
// or if it parses to a valid date that the user is allowed to select.
var isValidInput = this.isInputValid(inputString, parsedDate);
// The datepicker's model is only updated when there is a valid input.
if (isValidInput) {
this.setModelValue(parsedDate);
this.date = parsedDate;
}
this.updateErrorState(parsedDate);
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
(!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date)) &&
(!angular.isFunction(this.monthFilter) || this.monthFilter(opt_date));
};
/** Position and attach the floating calendar to the document. */
DatePickerCtrl.prototype.attachCalendarPane = function() {
var calendarPane = this.calendarPane;
var body = document.body;
calendarPane.style.transform = '';
this.$element.addClass(OPEN_CLASS);
this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
angular.element(body).addClass('md-datepicker-is-showing');
var elementRect = this.inputContainer.getBoundingClientRect();
var bodyRect = body.getBoundingClientRect();
if (!this.topMargin || this.topMargin < 0) {
this.topMargin =
(this.inputMask.parent().prop('clientHeight')
- this.ngInputElement.prop('clientHeight')) / 2;
}
// Check to see if the calendar pane would go off the screen. If so, adjust position
// accordingly to keep it within the viewport.
var paneTop = elementRect.top - bodyRect.top - this.topMargin;
var paneLeft = elementRect.left - bodyRect.left - this.leftMargin;
// If ng-material has disabled body scrolling (for example, if a dialog is open),
// then it's possible that the already-scrolled body has a negative top/left. In this case,
// we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
// though, the top of the viewport should just be the body's scroll position.
var viewportTop = (bodyRect.top < 0 && document.body.scrollTop === 0) ?
-bodyRect.top :
document.body.scrollTop;
var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft === 0) ?
-bodyRect.left :
document.body.scrollLeft;
var viewportBottom = viewportTop + this.$window.innerHeight;
var viewportRight = viewportLeft + this.$window.innerWidth;
// Creates an overlay with a hole the same size as element. We remove a pixel or two
// on each end to make it overlap slightly. The overlay's background is added in
// the theme in the form of a box-shadow with a huge spread.
this.inputMask.css({
position: 'absolute',
left: this.leftMargin + 'px',
top: this.topMargin + 'px',
width: (elementRect.width - 1) + 'px',
height: (elementRect.height - 2) + 'px'
});
// If the right edge of the pane would be off the screen and shifting it left by the
// difference would not go past the left edge of the screen. If the calendar pane is too
// big to fit on the screen at all, move it to the left of the screen and scale the entire
// element down to fit.
if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
} else {
paneLeft = viewportLeft;
var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
calendarPane.style.transform = 'scale(' + scale + ')';
}
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
// If the bottom edge of the pane would be off the screen and shifting it up by the
// difference would not go past the top edge of the screen.
if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
calendarPane.style.left = paneLeft + 'px';
calendarPane.style.top = paneTop + 'px';
document.body.appendChild(calendarPane);
// Add CSS class after one frame to trigger open animation.
this.$$rAF(function() {
calendarPane.classList.add('md-pane-open');
});
};
/** Detach the floating calendar pane from the document. */
DatePickerCtrl.prototype.detachCalendarPane = function() {
this.$element.removeClass(OPEN_CLASS);
this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
angular.element(document.body).removeClass('md-datepicker-is-showing');
this.calendarPane.classList.remove('md-pane-open');
this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
if (this.isCalendarOpen) {
this.$mdUtil.enableScrolling();
}
if (this.calendarPane.parentNode) {
// Use native DOM removal because we do not want any of the
// angular state of this element to be disposed.
this.calendarPane.parentNode.removeChild(this.calendarPane);
}
};
/**
* Open the floating calendar pane.
* @param {MouseEvent|KeyboardEvent|{target: HTMLInputElement}} event
*/
DatePickerCtrl.prototype.openCalendarPane = function(event) {
if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
this.isCalendarOpen = this.isOpen = true;
this.calendarPaneOpenedFrom = event.target;
// Because the calendar pane is attached directly to the body, it is possible that the
// rest of the component (input, etc) is in a different scrolling container, such as
// an md-content. This means that, if the container is scrolled, the pane would remain
// stationary. To remedy this, we disable scrolling while the calendar pane is open, which
// also matches the native behavior for things like `<select>` on Mac and Windows.
this.$mdUtil.disableScrollAround(this.calendarPane);
this.attachCalendarPane();
this.focusCalendar();
this.evalAttr('ngFocus');
// Attach click listener inside of a timeout because, if this open call was triggered by a
// click, we don't want it to be immediately propagated up to the body and handled.
var self = this;
this.$mdUtil.nextTick(function() {
// Use 'touchstart` in addition to click in order to work on iOS Safari, where click
// events aren't propagated under most circumstances.
// See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
self.documentElement.on('click touchstart', self.bodyClickHandler);
}, false);
window.addEventListener(this.windowEventName, this.windowEventHandler);
} else if (this.inputFocusedOnWindowBlur) {
this.resetInputFocused();
}
};
/** Close the floating calendar pane. */
DatePickerCtrl.prototype.closeCalendarPane = function() {
if (this.isCalendarOpen) {
var self = this;
self.detachCalendarPane();
self.ngModelCtrl.$setTouched();
self.evalAttr('ngBlur');
self.documentElement.off('click touchstart', self.bodyClickHandler);
window.removeEventListener(self.windowEventName, self.windowEventHandler);
self.calendarPaneOpenedFrom.focus();
self.calendarPaneOpenedFrom = null;
if (self.openOnFocus) {
// Ensures that all focus events have fired before resetting
// the calendar. Prevents the calendar from reopening immediately
// in IE when md-open-on-focus is set. Also it needs to trigger
// a digest, in order to prevent issues where the calendar wasn't
// showing up on the next open.
self.$timeout(reset);
} else {
reset();
}
}
function reset() {
self.isCalendarOpen = self.isOpen = false;
}
};
/** Gets the controller instance for the calendar in the floating pane. */
DatePickerCtrl.prototype.getCalendarCtrl = function() {
return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
};
/** Focus the calendar in the floating pane. */
DatePickerCtrl.prototype.focusCalendar = function() {
// Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
var self = this;
this.$mdUtil.nextTick(function() {
self.getCalendarCtrl().focusDate(self.date);
}, false);
};
/**
* Sets whether the input is currently focused.
* @param {boolean} isFocused
*/
DatePickerCtrl.prototype.setFocused = function(isFocused) {
if (!isFocused) {
this.ngModelCtrl.$setTouched();
}
// The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
// because they also get called when the calendar is opened/closed.
if (!this.openOnFocus) {
this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
}
this.isFocused = isFocused;
};
/**
* Handles a click on the document body when the floating calendar pane is open.
* Closes the floating calendar pane if the click is not inside of it.
* @param {MouseEvent} event
*/
DatePickerCtrl.prototype.handleBodyClick = function(event) {
if (this.isCalendarOpen) {
var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
if (!isInCalendar) {
this.closeCalendarPane();
}
this.$scope.$digest();
}
};
/**
* Handles the event when the user navigates away from the current tab. Keeps track of
* whether the input was focused when the event happened, in order to prevent the calendar
* from re-opening.
*/
DatePickerCtrl.prototype.handleWindowBlur = function() {
this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
};
/**
* Reset the flag inputFocusedOnWindowBlur to default state, to permit user to open calendar
* again when he back to tab with calendar focused.
*/
DatePickerCtrl.prototype.resetInputFocused = function() {
this.inputFocusedOnWindowBlur = false;
};