commonroutesApp/www/lib/angular-material/modules/js/datepicker/datepicker.js
www/lib/angular-material/modules/js/datepicker/datepicker.jsRaw
1/*!
2 * Angular Material Design
3 * https://github.com/angular/material
4 * @license MIT
5 * v1.1.1
6 */
7(function( window, angular, undefined ){
8"use strict";
9
10/**
11 * @ngdoc module
12 * @name material.components.datepicker
13 * @description Module for the datepicker component.
14 */
15
16angular.module('material.components.datepicker', [
17 'material.core',
18 'material.components.icon',
19 'material.components.virtualRepeat'
20]);
21
22(function() {
23 'use strict';
24
25 /**
26 * @ngdoc directive
27 * @name mdCalendar
28 * @module material.components.datepicker
29 *
30 * @param {Date} ng-model The component's model. Should be a Date object.
31 * @param {Date=} md-min-date Expression representing the minimum date.
32 * @param {Date=} md-max-date Expression representing the maximum date.
33 * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
34 *
35 * @description
36 * `<md-calendar>` is a component that renders a calendar that can be used to select a date.
37 * It is a part of the `<md-datepicker` pane, however it can also be used on it's own.
38 *
39 * @usage
40 *
41 * <hljs lang="html">
42 * <md-calendar ng-model="birthday"></md-calendar>
43 * </hljs>
44 */
45 CalendarCtrl.$inject = ["$element", "$scope", "$$mdDateUtil", "$mdUtil", "$mdConstant", "$mdTheming", "$$rAF", "$attrs", "$mdDateLocale"];
46 angular.module('material.components.datepicker')
47 .directive('mdCalendar', calendarDirective);
48
49 // POST RELEASE
50 // TODO(jelbourn): Mac Cmd + left / right == Home / End
51 // TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
52 // TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
53 // TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
54 // TODO(jelbourn): Scroll snapping (virtual repeat)
55 // TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
56 // TODO(jelbourn): Month headers stick to top when scrolling.
57 // TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
58 // TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
59 // announcement and key handling).
60 // Read-only calendar (not just date-picker).
61
62 function calendarDirective() {
63 return {
64 template: function(tElement, tAttr) {
65 // TODO(crisbeto): This is a workaround that allows the calendar to work, without
66 // a datepicker, until issue #8585 gets resolved. It can safely be removed
67 // afterwards. This ensures that the virtual repeater scrolls to the proper place on load by
68 // deferring the execution until the next digest. It's necessary only if the calendar is used
69 // without a datepicker, otherwise it's already wrapped in an ngIf.
70 var extraAttrs = tAttr.hasOwnProperty('ngIf') ? '' : 'ng-if="calendarCtrl.isInitialized"';
71 var template = '' +
72 '<div ng-switch="calendarCtrl.currentView" ' + extraAttrs + '>' +
73 '<md-calendar-year ng-switch-when="year"></md-calendar-year>' +
74 '<md-calendar-month ng-switch-default></md-calendar-month>' +
75 '</div>';
76
77 return template;
78 },
79 scope: {
80 minDate: '=mdMinDate',
81 maxDate: '=mdMaxDate',
82 dateFilter: '=mdDateFilter',
83 _currentView: '@mdCurrentView'
84 },
85 require: ['ngModel', 'mdCalendar'],
86 controller: CalendarCtrl,
87 controllerAs: 'calendarCtrl',
88 bindToController: true,
89 link: function(scope, element, attrs, controllers) {
90 var ngModelCtrl = controllers[0];
91 var mdCalendarCtrl = controllers[1];
92 mdCalendarCtrl.configureNgModel(ngModelCtrl);
93 }
94 };
95 }
96
97 /**
98 * Occasionally the hideVerticalScrollbar method might read an element's
99 * width as 0, because it hasn't been laid out yet. This value will be used
100 * as a fallback, in order to prevent scenarios where the element's width
101 * would otherwise have been set to 0. This value is the "usual" width of a
102 * calendar within a floating calendar pane.
103 */
104 var FALLBACK_WIDTH = 340;
105
106 /** Next identifier for calendar instance. */
107 var nextUniqueId = 0;
108
109 /**
110 * Controller for the mdCalendar component.
111 * ngInject @constructor
112 */
113 function CalendarCtrl($element, $scope, $$mdDateUtil, $mdUtil,
114 $mdConstant, $mdTheming, $$rAF, $attrs, $mdDateLocale) {
115
116 $mdTheming($element);
117
118 /** @final {!angular.JQLite} */
119 this.$element = $element;
120
121 /** @final {!angular.Scope} */
122 this.$scope = $scope;
123
124 /** @final */
125 this.dateUtil = $$mdDateUtil;
126
127 /** @final */
128 this.$mdUtil = $mdUtil;
129
130 /** @final */
131 this.keyCode = $mdConstant.KEY_CODE;
132
133 /** @final */
134 this.$$rAF = $$rAF;
135
136 /** @final {Date} */
137 this.today = this.dateUtil.createDateAtMidnight();
138
139 /** @type {!angular.NgModelController} */
140 this.ngModelCtrl = null;
141
142 /**
143 * The currently visible calendar view. Note the prefix on the scope value,
144 * which is necessary, because the datepicker seems to reset the real one value if the
145 * calendar is open, but the value on the datepicker's scope is empty.
146 * @type {String}
147 */
148 this.currentView = this._currentView || 'month';
149
150 /** @type {String} Class applied to the selected date cell. */
151 this.SELECTED_DATE_CLASS = 'md-calendar-selected-date';
152
153 /** @type {String} Class applied to the cell for today. */
154 this.TODAY_CLASS = 'md-calendar-date-today';
155
156 /** @type {String} Class applied to the focused cell. */
157 this.FOCUSED_DATE_CLASS = 'md-focus';
158
159 /** @final {number} Unique ID for this calendar instance. */
160 this.id = nextUniqueId++;
161
162 /**
163 * The date that is currently focused or showing in the calendar. This will initially be set
164 * to the ng-model value if set, otherwise to today. It will be updated as the user navigates
165 * to other months. The cell corresponding to the displayDate does not necesarily always have
166 * focus in the document (such as for cases when the user is scrolling the calendar).
167 * @type {Date}
168 */
169 this.displayDate = null;
170
171 /**
172 * The selected date. Keep track of this separately from the ng-model value so that we
173 * can know, when the ng-model value changes, what the previous value was before it's updated
174 * in the component's UI.
175 *
176 * @type {Date}
177 */
178 this.selectedDate = null;
179
180 /**
181 * The first date that can be rendered by the calendar. The default is taken
182 * from the mdDateLocale provider and is limited by the mdMinDate.
183 * @type {Date}
184 */
185 this.firstRenderableDate = null;
186
187 /**
188 * The last date that can be rendered by the calendar. The default comes
189 * from the mdDateLocale provider and is limited by the maxDate.
190 * @type {Date}
191 */
192 this.lastRenderableDate = null;
193
194 /**
195 * Used to toggle initialize the root element in the next digest.
196 * @type {Boolean}
197 */
198 this.isInitialized = false;
199
200 /**
201 * Cache for the width of the element without a scrollbar. Used to hide the scrollbar later on
202 * and to avoid extra reflows when switching between views.
203 * @type {Number}
204 */
205 this.width = 0;
206
207 /**
208 * Caches the width of the scrollbar in order to be used when hiding it and to avoid extra reflows.
209 * @type {Number}
210 */
211 this.scrollbarWidth = 0;
212
213 // Unless the user specifies so, the calendar should not be a tab stop.
214 // This is necessary because ngAria might add a tabindex to anything with an ng-model
215 // (based on whether or not the user has turned that particular feature on/off).
216 if (!$attrs.tabindex) {
217 $element.attr('tabindex', '-1');
218 }
219
220 var boundKeyHandler = angular.bind(this, this.handleKeyEvent);
221
222 // Bind the keydown handler to the body, in order to handle cases where the focused
223 // element gets removed from the DOM and stops propagating click events.
224 angular.element(document.body).on('keydown', boundKeyHandler);
225
226 $scope.$on('$destroy', function() {
227 angular.element(document.body).off('keydown', boundKeyHandler);
228 });
229
230 if (this.minDate && this.minDate > $mdDateLocale.firstRenderableDate) {
231 this.firstRenderableDate = this.minDate;
232 } else {
233 this.firstRenderableDate = $mdDateLocale.firstRenderableDate;
234 }
235
236 if (this.maxDate && this.maxDate < $mdDateLocale.lastRenderableDate) {
237 this.lastRenderableDate = this.maxDate;
238 } else {
239 this.lastRenderableDate = $mdDateLocale.lastRenderableDate;
240 }
241 }
242
243 /**
244 * Sets up the controller's reference to ngModelController.
245 * @param {!angular.NgModelController} ngModelCtrl
246 */
247 CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
248 var self = this;
249
250 self.ngModelCtrl = ngModelCtrl;
251
252 self.$mdUtil.nextTick(function() {
253 self.isInitialized = true;
254 });
255
256 ngModelCtrl.$render = function() {
257 var value = this.$viewValue;
258
259 // Notify the child scopes of any changes.
260 self.$scope.$broadcast('md-calendar-parent-changed', value);
261
262 // Set up the selectedDate if it hasn't been already.
263 if (!self.selectedDate) {
264 self.selectedDate = value;
265 }
266
267 // Also set up the displayDate.
268 if (!self.displayDate) {
269 self.displayDate = self.selectedDate || self.today;
270 }
271 };
272 };
273
274 /**
275 * Sets the ng-model value for the calendar and emits a change event.
276 * @param {Date} date
277 */
278 CalendarCtrl.prototype.setNgModelValue = function(date) {
279 var value = this.dateUtil.createDateAtMidnight(date);
280 this.focus(value);
281 this.$scope.$emit('md-calendar-change', value);
282 this.ngModelCtrl.$setViewValue(value);
283 this.ngModelCtrl.$render();
284 return value;
285 };
286
287 /**
288 * Sets the current view that should be visible in the calendar
289 * @param {string} newView View name to be set.
290 * @param {number|Date} time Date object or a timestamp for the new display date.
291 */
292 CalendarCtrl.prototype.setCurrentView = function(newView, time) {
293 var self = this;
294
295 self.$mdUtil.nextTick(function() {
296 self.currentView = newView;
297
298 if (time) {
299 self.displayDate = angular.isDate(time) ? time : new Date(time);
300 }
301 });
302 };
303
304 /**
305 * Focus the cell corresponding to the given date.
306 * @param {Date} date The date to be focused.
307 */
308 CalendarCtrl.prototype.focus = function(date) {
309 if (this.dateUtil.isValidDate(date)) {
310 var previousFocus = this.$element[0].querySelector('.md-focus');
311 if (previousFocus) {
312 previousFocus.classList.remove(this.FOCUSED_DATE_CLASS);
313 }
314
315 var cellId = this.getDateId(date, this.currentView);
316 var cell = document.getElementById(cellId);
317 if (cell) {
318 cell.classList.add(this.FOCUSED_DATE_CLASS);
319 cell.focus();
320 this.displayDate = date;
321 }
322 } else {
323 var rootElement = this.$element[0].querySelector('[ng-switch]');
324
325 if (rootElement) {
326 rootElement.focus();
327 }
328 }
329 };
330
331 /**
332 * Normalizes the key event into an action name. The action will be broadcast
333 * to the child controllers.
334 * @param {KeyboardEvent} event
335 * @returns {String} The action that should be taken, or null if the key
336 * does not match a calendar shortcut.
337 */
338 CalendarCtrl.prototype.getActionFromKeyEvent = function(event) {
339 var keyCode = this.keyCode;
340
341 switch (event.which) {
342 case keyCode.ENTER: return 'select';
343
344 case keyCode.RIGHT_ARROW: return 'move-right';
345 case keyCode.LEFT_ARROW: return 'move-left';
346
347 // TODO(crisbeto): Might want to reconsider using metaKey, because it maps
348 // to the "Windows" key on PC, which opens the start menu or resizes the browser.
349 case keyCode.DOWN_ARROW: return event.metaKey ? 'move-page-down' : 'move-row-down';
350 case keyCode.UP_ARROW: return event.metaKey ? 'move-page-up' : 'move-row-up';
351
352 case keyCode.PAGE_DOWN: return 'move-page-down';
353 case keyCode.PAGE_UP: return 'move-page-up';
354
355 case keyCode.HOME: return 'start';
356 case keyCode.END: return 'end';
357
358 default: return null;
359 }
360 };
361
362 /**
363 * Handles a key event in the calendar with the appropriate action. The action will either
364 * be to select the focused date or to navigate to focus a new date.
365 * @param {KeyboardEvent} event
366 */
367 CalendarCtrl.prototype.handleKeyEvent = function(event) {
368 var self = this;
369
370 this.$scope.$apply(function() {
371 // Capture escape and emit back up so that a wrapping component
372 // (such as a date-picker) can decide to close.
373 if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
374 self.$scope.$emit('md-calendar-close');
375
376 if (event.which == self.keyCode.TAB) {
377 event.preventDefault();
378 }
379
380 return;
381 }
382
383 // Broadcast the action that any child controllers should take.
384 var action = self.getActionFromKeyEvent(event);
385 if (action) {
386 event.preventDefault();
387 event.stopPropagation();
388 self.$scope.$broadcast('md-calendar-parent-action', action);
389 }
390 });
391 };
392
393 /**
394 * Hides the vertical scrollbar on the calendar scroller of a child controller by
395 * setting the width on the calendar scroller and the `overflow: hidden` wrapper
396 * around the scroller, and then setting a padding-right on the scroller equal
397 * to the width of the browser's scrollbar.
398 *
399 * This will cause a reflow.
400 *
401 * @param {object} childCtrl The child controller whose scrollbar should be hidden.
402 */
403 CalendarCtrl.prototype.hideVerticalScrollbar = function(childCtrl) {
404 var self = this;
405 var element = childCtrl.$element[0];
406 var scrollMask = element.querySelector('.md-calendar-scroll-mask');
407
408 if (self.width > 0) {
409 setWidth();
410 } else {
411 self.$$rAF(function() {
412 var scroller = childCtrl.calendarScroller;
413
414 self.scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
415 self.width = element.querySelector('table').offsetWidth;
416 setWidth();
417 });
418 }
419
420 function setWidth() {
421 var width = self.width || FALLBACK_WIDTH;
422 var scrollbarWidth = self.scrollbarWidth;
423 var scroller = childCtrl.calendarScroller;
424
425 scrollMask.style.width = width + 'px';
426 scroller.style.width = (width + scrollbarWidth) + 'px';
427 scroller.style.paddingRight = scrollbarWidth + 'px';
428 }
429 };
430
431 /**
432 * Gets an identifier for a date unique to the calendar instance for internal
433 * purposes. Not to be displayed.
434 * @param {Date} date The date for which the id is being generated
435 * @param {string} namespace Namespace for the id. (month, year etc.)
436 * @returns {string}
437 */
438 CalendarCtrl.prototype.getDateId = function(date, namespace) {
439 if (!namespace) {
440 throw new Error('A namespace for the date id has to be specified.');
441 }
442
443 return [
444 'md',
445 this.id,
446 namespace,
447 date.getFullYear(),
448 date.getMonth(),
449 date.getDate()
450 ].join('-');
451 };
452
453 /**
454 * Util to trigger an extra digest on a parent scope, in order to to ensure that
455 * any child virtual repeaters have updated. This is necessary, because the virtual
456 * repeater doesn't update the $index the first time around since the content isn't
457 * in place yet. The case, in which this is an issue, is when the repeater has less
458 * than a page of content (e.g. a month or year view has a min or max date).
459 */
460 CalendarCtrl.prototype.updateVirtualRepeat = function() {
461 var scope = this.$scope;
462 var virtualRepeatResizeListener = scope.$on('$md-resize-enable', function() {
463 if (!scope.$$phase) {
464 scope.$apply();
465 }
466
467 virtualRepeatResizeListener();
468 });
469 };
470})();
471
472(function() {
473 'use strict';
474
475 CalendarMonthCtrl.$inject = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil", "$mdDateLocale"];
476 angular.module('material.components.datepicker')
477 .directive('mdCalendarMonth', calendarDirective);
478
479 /**
480 * Height of one calendar month tbody. This must be made known to the virtual-repeat and is
481 * subsequently used for scrolling to specific months.
482 */
483 var TBODY_HEIGHT = 265;
484
485 /**
486 * Height of a calendar month with a single row. This is needed to calculate the offset for
487 * rendering an extra month in virtual-repeat that only contains one row.
488 */
489 var TBODY_SINGLE_ROW_HEIGHT = 45;
490
491 /** Private directive that represents a list of months inside the calendar. */
492 function calendarDirective() {
493 return {
494 template:
495 '<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
496 '<div class="md-calendar-scroll-mask">' +
497 '<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
498 'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
499 '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
500 '<tbody ' +
501 'md-calendar-month-body ' +
502 'role="rowgroup" ' +
503 'md-virtual-repeat="i in monthCtrl.items" ' +
504 'md-month-offset="$index" ' +
505 'class="md-calendar-month" ' +
506 'md-start-index="monthCtrl.getSelectedMonthIndex()" ' +
507 'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
508 '</table>' +
509 '</md-virtual-repeat-container>' +
510 '</div>',
511 require: ['^^mdCalendar', 'mdCalendarMonth'],
512 controller: CalendarMonthCtrl,
513 controllerAs: 'monthCtrl',
514 bindToController: true,
515 link: function(scope, element, attrs, controllers) {
516 var calendarCtrl = controllers[0];
517 var monthCtrl = controllers[1];
518 monthCtrl.initialize(calendarCtrl);
519 }
520 };
521 }
522
523 /**
524 * Controller for the calendar month component.
525 * ngInject @constructor
526 */
527 function CalendarMonthCtrl($element, $scope, $animate, $q,
528 $$mdDateUtil, $mdDateLocale) {
529
530 /** @final {!angular.JQLite} */
531 this.$element = $element;
532
533 /** @final {!angular.Scope} */
534 this.$scope = $scope;
535
536 /** @final {!angular.$animate} */
537 this.$animate = $animate;
538
539 /** @final {!angular.$q} */
540 this.$q = $q;
541
542 /** @final */
543 this.dateUtil = $$mdDateUtil;
544
545 /** @final */
546 this.dateLocale = $mdDateLocale;
547
548 /** @final {HTMLElement} */
549 this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
550
551 /** @type {boolean} */
552 this.isInitialized = false;
553
554 /** @type {boolean} */
555 this.isMonthTransitionInProgress = false;
556
557 var self = this;
558
559 /**
560 * Handles a click event on a date cell.
561 * Created here so that every cell can use the same function instance.
562 * @this {HTMLTableCellElement} The cell that was clicked.
563 */
564 this.cellClickHandler = function() {
565 var timestamp = $$mdDateUtil.getTimestampFromNode(this);
566 self.$scope.$apply(function() {
567 self.calendarCtrl.setNgModelValue(timestamp);
568 });
569 };
570
571 /**
572 * Handles click events on the month headers. Switches
573 * the calendar to the year view.
574 * @this {HTMLTableCellElement} The cell that was clicked.
575 */
576 this.headerClickHandler = function() {
577 self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
578 };
579 }
580
581 /*** Initialization ***/
582
583 /**
584 * Initialize the controller by saving a reference to the calendar and
585 * setting up the object that will be iterated by the virtual repeater.
586 */
587 CalendarMonthCtrl.prototype.initialize = function(calendarCtrl) {
588 /**
589 * Dummy array-like object for virtual-repeat to iterate over. The length is the total
590 * number of months that can be viewed. We add 2 months: one to include the current month
591 * and one for the last dummy month.
592 *
593 * This is shorter than ideal because of a (potential) Firefox bug
594 * https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
595 */
596
597 this.items = {
598 length: this.dateUtil.getMonthDistance(
599 calendarCtrl.firstRenderableDate,
600 calendarCtrl.lastRenderableDate
601 ) + 2
602 };
603
604 this.calendarCtrl = calendarCtrl;
605 this.attachScopeListeners();
606 calendarCtrl.updateVirtualRepeat();
607
608 // Fire the initial render, since we might have missed it the first time it fired.
609 calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
610 };
611
612 /**
613 * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
614 * @returns {number}
615 */
616 CalendarMonthCtrl.prototype.getSelectedMonthIndex = function() {
617 var calendarCtrl = this.calendarCtrl;
618
619 return this.dateUtil.getMonthDistance(
620 calendarCtrl.firstRenderableDate,
621 calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
622 );
623 };
624
625 /**
626 * Change the selected date in the calendar (ngModel value has already been changed).
627 * @param {Date} date
628 */
629 CalendarMonthCtrl.prototype.changeSelectedDate = function(date) {
630 var self = this;
631 var calendarCtrl = self.calendarCtrl;
632 var previousSelectedDate = calendarCtrl.selectedDate;
633 calendarCtrl.selectedDate = date;
634
635 this.changeDisplayDate(date).then(function() {
636 var selectedDateClass = calendarCtrl.SELECTED_DATE_CLASS;
637 var namespace = 'month';
638
639 // Remove the selected class from the previously selected date, if any.
640 if (previousSelectedDate) {
641 var prevDateCell = document.getElementById(calendarCtrl.getDateId(previousSelectedDate, namespace));
642 if (prevDateCell) {
643 prevDateCell.classList.remove(selectedDateClass);
644 prevDateCell.setAttribute('aria-selected', 'false');
645 }
646 }
647
648 // Apply the select class to the new selected date if it is set.
649 if (date) {
650 var dateCell = document.getElementById(calendarCtrl.getDateId(date, namespace));
651 if (dateCell) {
652 dateCell.classList.add(selectedDateClass);
653 dateCell.setAttribute('aria-selected', 'true');
654 }
655 }
656 });
657 };
658
659 /**
660 * Change the date that is being shown in the calendar. If the given date is in a different
661 * month, the displayed month will be transitioned.
662 * @param {Date} date
663 */
664 CalendarMonthCtrl.prototype.changeDisplayDate = function(date) {
665 // Initialization is deferred until this function is called because we want to reflect
666 // the starting value of ngModel.
667 if (!this.isInitialized) {
668 this.buildWeekHeader();
669 this.calendarCtrl.hideVerticalScrollbar(this);
670 this.isInitialized = true;
671 return this.$q.when();
672 }
673
674 // If trying to show an invalid date or a transition is in progress, do nothing.
675 if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
676 return this.$q.when();
677 }
678
679 this.isMonthTransitionInProgress = true;
680 var animationPromise = this.animateDateChange(date);
681
682 this.calendarCtrl.displayDate = date;
683
684 var self = this;
685 animationPromise.then(function() {
686 self.isMonthTransitionInProgress = false;
687 });
688
689 return animationPromise;
690 };
691
692 /**
693 * Animates the transition from the calendar's current month to the given month.
694 * @param {Date} date
695 * @returns {angular.$q.Promise} The animation promise.
696 */
697 CalendarMonthCtrl.prototype.animateDateChange = function(date) {
698 if (this.dateUtil.isValidDate(date)) {
699 var monthDistance = this.dateUtil.getMonthDistance(this.calendarCtrl.firstRenderableDate, date);
700 this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
701 }
702
703 return this.$q.when();
704 };
705
706 /**
707 * Builds and appends a day-of-the-week header to the calendar.
708 * This should only need to be called once during initialization.
709 */
710 CalendarMonthCtrl.prototype.buildWeekHeader = function() {
711 var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
712 var shortDays = this.dateLocale.shortDays;
713
714 var row = document.createElement('tr');
715 for (var i = 0; i < 7; i++) {
716 var th = document.createElement('th');
717 th.textContent = shortDays[(i + firstDayOfWeek) % 7];
718 row.appendChild(th);
719 }
720
721 this.$element.find('thead').append(row);
722 };
723
724 /**
725 * Attaches listeners for the scope events that are broadcast by the calendar.
726 */
727 CalendarMonthCtrl.prototype.attachScopeListeners = function() {
728 var self = this;
729
730 self.$scope.$on('md-calendar-parent-changed', function(event, value) {
731 self.changeSelectedDate(value);
732 });
733
734 self.$scope.$on('md-calendar-parent-action', angular.bind(this, this.handleKeyEvent));
735 };
736
737 /**
738 * Handles the month-specific keyboard interactions.
739 * @param {Object} event Scope event object passed by the calendar.
740 * @param {String} action Action, corresponding to the key that was pressed.
741 */
742 CalendarMonthCtrl.prototype.handleKeyEvent = function(event, action) {
743 var calendarCtrl = this.calendarCtrl;
744 var displayDate = calendarCtrl.displayDate;
745
746 if (action === 'select') {
747 calendarCtrl.setNgModelValue(displayDate);
748 } else {
749 var date = null;
750 var dateUtil = this.dateUtil;
751
752 switch (action) {
753 case 'move-right': date = dateUtil.incrementDays(displayDate, 1); break;
754 case 'move-left': date = dateUtil.incrementDays(displayDate, -1); break;
755
756 case 'move-page-down': date = dateUtil.incrementMonths(displayDate, 1); break;
757 case 'move-page-up': date = dateUtil.incrementMonths(displayDate, -1); break;
758
759 case 'move-row-down': date = dateUtil.incrementDays(displayDate, 7); break;
760 case 'move-row-up': date = dateUtil.incrementDays(displayDate, -7); break;
761
762 case 'start': date = dateUtil.getFirstDateOfMonth(displayDate); break;
763 case 'end': date = dateUtil.getLastDateOfMonth(displayDate); break;
764 }
765
766 if (date) {
767 date = this.dateUtil.clampDate(date, calendarCtrl.minDate, calendarCtrl.maxDate);
768
769 this.changeDisplayDate(date).then(function() {
770 calendarCtrl.focus(date);
771 });
772 }
773 }
774 };
775})();
776
777(function() {
778 'use strict';
779
780 mdCalendarMonthBodyDirective.$inject = ["$compile", "$$mdSvgRegistry"];
781 CalendarMonthBodyCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
782 angular.module('material.components.datepicker')
783 .directive('mdCalendarMonthBody', mdCalendarMonthBodyDirective);
784
785 /**
786 * Private directive consumed by md-calendar-month. Having this directive lets the calender use
787 * md-virtual-repeat and also cleanly separates the month DOM construction functions from
788 * the rest of the calendar controller logic.
789 * ngInject
790 */
791 function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
792 var ARROW_ICON = $compile('<md-icon md-svg-src="' +
793 $$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
794
795 return {
796 require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
797 scope: { offset: '=mdMonthOffset' },
798 controller: CalendarMonthBodyCtrl,
799 controllerAs: 'mdMonthBodyCtrl',
800 bindToController: true,
801 link: function(scope, element, attrs, controllers) {
802 var calendarCtrl = controllers[0];
803 var monthCtrl = controllers[1];
804 var monthBodyCtrl = controllers[2];
805
806 monthBodyCtrl.calendarCtrl = calendarCtrl;
807 monthBodyCtrl.monthCtrl = monthCtrl;
808 monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
809
810 // The virtual-repeat re-uses the same DOM elements, so there are only a limited number
811 // of repeated items that are linked, and then those elements have their bindings updated.
812 // Since the months are not generated by bindings, we simply regenerate the entire thing
813 // when the binding (offset) changes.
814 scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset, oldOffset) {
815 if (offset !== oldOffset) {
816 monthBodyCtrl.generateContent();
817 }
818 });
819 }
820 };
821 }
822
823 /**
824 * Controller for a single calendar month.
825 * ngInject @constructor
826 */
827 function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
828 /** @final {!angular.JQLite} */
829 this.$element = $element;
830
831 /** @final */
832 this.dateUtil = $$mdDateUtil;
833
834 /** @final */
835 this.dateLocale = $mdDateLocale;
836
837 /** @type {Object} Reference to the month view. */
838 this.monthCtrl = null;
839
840 /** @type {Object} Reference to the calendar. */
841 this.calendarCtrl = null;
842
843 /**
844 * Number of months from the start of the month "items" that the currently rendered month
845 * occurs. Set via angular data binding.
846 * @type {number}
847 */
848 this.offset = null;
849
850 /**
851 * Date cell to focus after appending the month to the document.
852 * @type {HTMLElement}
853 */
854 this.focusAfterAppend = null;
855 }
856
857 /** Generate and append the content for this month to the directive element. */
858 CalendarMonthBodyCtrl.prototype.generateContent = function() {
859 var date = this.dateUtil.incrementMonths(this.calendarCtrl.firstRenderableDate, this.offset);
860
861 this.$element
862 .empty()
863 .append(this.buildCalendarForMonth(date));
864
865 if (this.focusAfterAppend) {
866 this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
867 this.focusAfterAppend.focus();
868 this.focusAfterAppend = null;
869 }
870 };
871
872 /**
873 * Creates a single cell to contain a date in the calendar with all appropriate
874 * attributes and classes added. If a date is given, the cell content will be set
875 * based on the date.
876 * @param {Date=} opt_date
877 * @returns {HTMLElement}
878 */
879 CalendarMonthBodyCtrl.prototype.buildDateCell = function(opt_date) {
880 var monthCtrl = this.monthCtrl;
881 var calendarCtrl = this.calendarCtrl;
882
883 // TODO(jelbourn): cloneNode is likely a faster way of doing this.
884 var cell = document.createElement('td');
885 cell.tabIndex = -1;
886 cell.classList.add('md-calendar-date');
887 cell.setAttribute('role', 'gridcell');
888
889 if (opt_date) {
890 cell.setAttribute('tabindex', '-1');
891 cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
892 cell.id = calendarCtrl.getDateId(opt_date, 'month');
893
894 // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
895 cell.setAttribute('data-timestamp', opt_date.getTime());
896
897 // TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
898 // It may be better to finish the construction and then query the node and add the class.
899 if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
900 cell.classList.add(calendarCtrl.TODAY_CLASS);
901 }
902
903 if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
904 this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
905 cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
906 cell.setAttribute('aria-selected', 'true');
907 }
908
909 var cellText = this.dateLocale.dates[opt_date.getDate()];
910
911 if (this.isDateEnabled(opt_date)) {
912 // Add a indicator for select, hover, and focus states.
913 var selectionIndicator = document.createElement('span');
914 selectionIndicator.classList.add('md-calendar-date-selection-indicator');
915 selectionIndicator.textContent = cellText;
916 cell.appendChild(selectionIndicator);
917 cell.addEventListener('click', monthCtrl.cellClickHandler);
918
919 if (calendarCtrl.displayDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.displayDate)) {
920 this.focusAfterAppend = cell;
921 }
922 } else {
923 cell.classList.add('md-calendar-date-disabled');
924 cell.textContent = cellText;
925 }
926 }
927
928 return cell;
929 };
930
931 /**
932 * Check whether date is in range and enabled
933 * @param {Date=} opt_date
934 * @return {boolean} Whether the date is enabled.
935 */
936 CalendarMonthBodyCtrl.prototype.isDateEnabled = function(opt_date) {
937 return this.dateUtil.isDateWithinRange(opt_date,
938 this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
939 (!angular.isFunction(this.calendarCtrl.dateFilter)
940 || this.calendarCtrl.dateFilter(opt_date));
941 };
942
943 /**
944 * Builds a `tr` element for the calendar grid.
945 * @param rowNumber The week number within the month.
946 * @returns {HTMLElement}
947 */
948 CalendarMonthBodyCtrl.prototype.buildDateRow = function(rowNumber) {
949 var row = document.createElement('tr');
950 row.setAttribute('role', 'row');
951
952 // Because of an NVDA bug (with Firefox), the row needs an aria-label in order
953 // to prevent the entire row being read aloud when the user moves between rows.
954 // See http://community.nvda-project.org/ticket/4643.
955 row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
956
957 return row;
958 };
959
960 /**
961 * Builds the <tbody> content for the given date's month.
962 * @param {Date=} opt_dateInMonth
963 * @returns {DocumentFragment} A document fragment containing the <tr> elements.
964 */
965 CalendarMonthBodyCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
966 var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
967
968 var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
969 var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
970 var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
971
972 // Store rows for the month in a document fragment so that we can append them all at once.
973 var monthBody = document.createDocumentFragment();
974
975 var rowNumber = 1;
976 var row = this.buildDateRow(rowNumber);
977 monthBody.appendChild(row);
978
979 // If this is the final month in the list of items, only the first week should render,
980 // so we should return immediately after the first row is complete and has been
981 // attached to the body.
982 var isFinalMonth = this.offset === this.monthCtrl.items.length - 1;
983
984 // Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
985 // goes on a row above the first of the month. Otherwise, the month label takes up the first
986 // two cells of the first row.
987 var blankCellOffset = 0;
988 var monthLabelCell = document.createElement('td');
989 var monthLabelCellContent = document.createElement('span');
990
991 monthLabelCellContent.textContent = this.dateLocale.monthHeaderFormatter(date);
992 monthLabelCell.appendChild(monthLabelCellContent);
993 monthLabelCell.classList.add('md-calendar-month-label');
994 // If the entire month is after the max date, render the label as a disabled state.
995 if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
996 monthLabelCell.classList.add('md-calendar-month-label-disabled');
997 } else {
998 monthLabelCell.addEventListener('click', this.monthCtrl.headerClickHandler);
999 monthLabelCell.setAttribute('data-timestamp', firstDayOfMonth.getTime());
1000 monthLabelCell.setAttribute('aria-label', this.dateLocale.monthFormatter(date));
1001 monthLabelCell.appendChild(this.arrowIcon.cloneNode(true));
1002 }
1003
1004 if (firstDayOfTheWeek <= 2) {
1005 monthLabelCell.setAttribute('colspan', '7');
1006
1007 var monthLabelRow = this.buildDateRow();
1008 monthLabelRow.appendChild(monthLabelCell);
1009 monthBody.insertBefore(monthLabelRow, row);
1010
1011 if (isFinalMonth) {
1012 return monthBody;
1013 }
1014 } else {
1015 blankCellOffset = 3;
1016 monthLabelCell.setAttribute('colspan', '3');
1017 row.appendChild(monthLabelCell);
1018 }
1019
1020 // Add a blank cell for each day of the week that occurs before the first of the month.
1021 // For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
1022 // The blankCellOffset is needed in cases where the first N cells are used by the month label.
1023 for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
1024 row.appendChild(this.buildDateCell());
1025 }
1026
1027 // Add a cell for each day of the month, keeping track of the day of the week so that
1028 // we know when to start a new row.
1029 var dayOfWeek = firstDayOfTheWeek;
1030 var iterationDate = firstDayOfMonth;
1031 for (var d = 1; d <= numberOfDaysInMonth; d++) {
1032 // If we've reached the end of the week, start a new row.
1033 if (dayOfWeek === 7) {
1034 // We've finished the first row, so we're done if this is the final month.
1035 if (isFinalMonth) {
1036 return monthBody;
1037 }
1038 dayOfWeek = 0;
1039 rowNumber++;
1040 row = this.buildDateRow(rowNumber);
1041 monthBody.appendChild(row);
1042 }
1043
1044 iterationDate.setDate(d);
1045 var cell = this.buildDateCell(iterationDate);
1046 row.appendChild(cell);
1047
1048 dayOfWeek++;
1049 }
1050
1051 // Ensure that the last row of the month has 7 cells.
1052 while (row.childNodes.length < 7) {
1053 row.appendChild(this.buildDateCell());
1054 }
1055
1056 // Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
1057 // requires that all items have exactly the same height.
1058 while (monthBody.childNodes.length < 6) {
1059 var whitespaceRow = this.buildDateRow();
1060 for (var j = 0; j < 7; j++) {
1061 whitespaceRow.appendChild(this.buildDateCell());
1062 }
1063 monthBody.appendChild(whitespaceRow);
1064 }
1065
1066 return monthBody;
1067 };
1068
1069 /**
1070 * Gets the day-of-the-week index for a date for the current locale.
1071 * @private
1072 * @param {Date} date
1073 * @returns {number} The column index of the date in the calendar.
1074 */
1075 CalendarMonthBodyCtrl.prototype.getLocaleDay_ = function(date) {
1076 return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7;
1077 };
1078})();
1079
1080(function() {
1081 'use strict';
1082
1083 CalendarYearCtrl.$inject = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil"];
1084 angular.module('material.components.datepicker')
1085 .directive('mdCalendarYear', calendarDirective);
1086
1087 /**
1088 * Height of one calendar year tbody. This must be made known to the virtual-repeat and is
1089 * subsequently used for scrolling to specific years.
1090 */
1091 var TBODY_HEIGHT = 88;
1092
1093 /** Private component, representing a list of years in the calendar. */
1094 function calendarDirective() {
1095 return {
1096 template:
1097 '<div class="md-calendar-scroll-mask">' +
1098 '<md-virtual-repeat-container class="md-calendar-scroll-container">' +
1099 '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
1100 '<tbody ' +
1101 'md-calendar-year-body ' +
1102 'role="rowgroup" ' +
1103 'md-virtual-repeat="i in yearCtrl.items" ' +
1104 'md-year-offset="$index" class="md-calendar-year" ' +
1105 'md-start-index="yearCtrl.getFocusedYearIndex()" ' +
1106 'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
1107 '</table>' +
1108 '</md-virtual-repeat-container>' +
1109 '</div>',
1110 require: ['^^mdCalendar', 'mdCalendarYear'],
1111 controller: CalendarYearCtrl,
1112 controllerAs: 'yearCtrl',
1113 bindToController: true,
1114 link: function(scope, element, attrs, controllers) {
1115 var calendarCtrl = controllers[0];
1116 var yearCtrl = controllers[1];
1117 yearCtrl.initialize(calendarCtrl);
1118 }
1119 };
1120 }
1121
1122 /**
1123 * Controller for the mdCalendar component.
1124 * ngInject @constructor
1125 */
1126 function CalendarYearCtrl($element, $scope, $animate, $q, $$mdDateUtil) {
1127
1128 /** @final {!angular.JQLite} */
1129 this.$element = $element;
1130
1131 /** @final {!angular.Scope} */
1132 this.$scope = $scope;
1133
1134 /** @final {!angular.$animate} */
1135 this.$animate = $animate;
1136
1137 /** @final {!angular.$q} */
1138 this.$q = $q;
1139
1140 /** @final */
1141 this.dateUtil = $$mdDateUtil;
1142
1143 /** @final {HTMLElement} */
1144 this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
1145
1146 /** @type {boolean} */
1147 this.isInitialized = false;
1148
1149 /** @type {boolean} */
1150 this.isMonthTransitionInProgress = false;
1151
1152 var self = this;
1153
1154 /**
1155 * Handles a click event on a date cell.
1156 * Created here so that every cell can use the same function instance.
1157 * @this {HTMLTableCellElement} The cell that was clicked.
1158 */
1159 this.cellClickHandler = function() {
1160 self.calendarCtrl.setCurrentView('month', $$mdDateUtil.getTimestampFromNode(this));
1161 };
1162 }
1163
1164 /**
1165 * Initialize the controller by saving a reference to the calendar and
1166 * setting up the object that will be iterated by the virtual repeater.
1167 */
1168 CalendarYearCtrl.prototype.initialize = function(calendarCtrl) {
1169 /**
1170 * Dummy array-like object for virtual-repeat to iterate over. The length is the total
1171 * number of years that can be viewed. We add 1 extra in order to include the current year.
1172 */
1173 this.items = {
1174 length: this.dateUtil.getYearDistance(
1175 calendarCtrl.firstRenderableDate,
1176 calendarCtrl.lastRenderableDate
1177 ) + 1
1178 };
1179
1180 this.calendarCtrl = calendarCtrl;
1181 this.attachScopeListeners();
1182 calendarCtrl.updateVirtualRepeat();
1183
1184 // Fire the initial render, since we might have missed it the first time it fired.
1185 calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
1186 };
1187
1188 /**
1189 * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
1190 * @returns {number}
1191 */
1192 CalendarYearCtrl.prototype.getFocusedYearIndex = function() {
1193 var calendarCtrl = this.calendarCtrl;
1194
1195 return this.dateUtil.getYearDistance(
1196 calendarCtrl.firstRenderableDate,
1197 calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
1198 );
1199 };
1200
1201 /**
1202 * Change the date that is highlighted in the calendar.
1203 * @param {Date} date
1204 */
1205 CalendarYearCtrl.prototype.changeDate = function(date) {
1206 // Initialization is deferred until this function is called because we want to reflect
1207 // the starting value of ngModel.
1208 if (!this.isInitialized) {
1209 this.calendarCtrl.hideVerticalScrollbar(this);
1210 this.isInitialized = true;
1211 return this.$q.when();
1212 } else if (this.dateUtil.isValidDate(date) && !this.isMonthTransitionInProgress) {
1213 var self = this;
1214 var animationPromise = this.animateDateChange(date);
1215
1216 self.isMonthTransitionInProgress = true;
1217 self.calendarCtrl.displayDate = date;
1218
1219 return animationPromise.then(function() {
1220 self.isMonthTransitionInProgress = false;
1221 });
1222 }
1223 };
1224
1225 /**
1226 * Animates the transition from the calendar's current month to the given month.
1227 * @param {Date} date
1228 * @returns {angular.$q.Promise} The animation promise.
1229 */
1230 CalendarYearCtrl.prototype.animateDateChange = function(date) {
1231 if (this.dateUtil.isValidDate(date)) {
1232 var monthDistance = this.dateUtil.getYearDistance(this.calendarCtrl.firstRenderableDate, date);
1233 this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
1234 }
1235
1236 return this.$q.when();
1237 };
1238
1239 /**
1240 * Handles the year-view-specific keyboard interactions.
1241 * @param {Object} event Scope event object passed by the calendar.
1242 * @param {String} action Action, corresponding to the key that was pressed.
1243 */
1244 CalendarYearCtrl.prototype.handleKeyEvent = function(event, action) {
1245 var calendarCtrl = this.calendarCtrl;
1246 var displayDate = calendarCtrl.displayDate;
1247
1248 if (action === 'select') {
1249 this.changeDate(displayDate).then(function() {
1250 calendarCtrl.setCurrentView('month', displayDate);
1251 calendarCtrl.focus(displayDate);
1252 });
1253 } else {
1254 var date = null;
1255 var dateUtil = this.dateUtil;
1256
1257 switch (action) {
1258 case 'move-right': date = dateUtil.incrementMonths(displayDate, 1); break;
1259 case 'move-left': date = dateUtil.incrementMonths(displayDate, -1); break;
1260
1261 case 'move-row-down': date = dateUtil.incrementMonths(displayDate, 6); break;
1262 case 'move-row-up': date = dateUtil.incrementMonths(displayDate, -6); break;
1263 }
1264
1265 if (date) {
1266 var min = calendarCtrl.minDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.minDate) : null;
1267 var max = calendarCtrl.maxDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.maxDate) : null;
1268 date = dateUtil.getFirstDateOfMonth(this.dateUtil.clampDate(date, min, max));
1269
1270 this.changeDate(date).then(function() {
1271 calendarCtrl.focus(date);
1272 });
1273 }
1274 }
1275 };
1276
1277 /**
1278 * Attaches listeners for the scope events that are broadcast by the calendar.
1279 */
1280 CalendarYearCtrl.prototype.attachScopeListeners = function() {
1281 var self = this;
1282
1283 self.$scope.$on('md-calendar-parent-changed', function(event, value) {
1284 self.changeDate(value);
1285 });
1286
1287 self.$scope.$on('md-calendar-parent-action', angular.bind(self, self.handleKeyEvent));
1288 };
1289})();
1290
1291(function() {
1292 'use strict';
1293
1294 CalendarYearBodyCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
1295 angular.module('material.components.datepicker')
1296 .directive('mdCalendarYearBody', mdCalendarYearDirective);
1297
1298 /**
1299 * Private component, consumed by the md-calendar-year, which separates the DOM construction logic
1300 * and allows for the year view to use md-virtual-repeat.
1301 */
1302 function mdCalendarYearDirective() {
1303 return {
1304 require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
1305 scope: { offset: '=mdYearOffset' },
1306 controller: CalendarYearBodyCtrl,
1307 controllerAs: 'mdYearBodyCtrl',
1308 bindToController: true,
1309 link: function(scope, element, attrs, controllers) {
1310 var calendarCtrl = controllers[0];
1311 var yearCtrl = controllers[1];
1312 var yearBodyCtrl = controllers[2];
1313
1314 yearBodyCtrl.calendarCtrl = calendarCtrl;
1315 yearBodyCtrl.yearCtrl = yearCtrl;
1316
1317 scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset, oldOffset) {
1318 if (offset !== oldOffset) {
1319 yearBodyCtrl.generateContent();
1320 }
1321 });
1322 }
1323 };
1324 }
1325
1326 /**
1327 * Controller for a single year.
1328 * ngInject @constructor
1329 */
1330 function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
1331 /** @final {!angular.JQLite} */
1332 this.$element = $element;
1333
1334 /** @final */
1335 this.dateUtil = $$mdDateUtil;
1336
1337 /** @final */
1338 this.dateLocale = $mdDateLocale;
1339
1340 /** @type {Object} Reference to the calendar. */
1341 this.calendarCtrl = null;
1342
1343 /** @type {Object} Reference to the year view. */
1344 this.yearCtrl = null;
1345
1346 /**
1347 * Number of months from the start of the month "items" that the currently rendered month
1348 * occurs. Set via angular data binding.
1349 * @type {number}
1350 */
1351 this.offset = null;
1352
1353 /**
1354 * Date cell to focus after appending the month to the document.
1355 * @type {HTMLElement}
1356 */
1357 this.focusAfterAppend = null;
1358 }
1359
1360 /** Generate and append the content for this year to the directive element. */
1361 CalendarYearBodyCtrl.prototype.generateContent = function() {
1362 var date = this.dateUtil.incrementYears(this.calendarCtrl.firstRenderableDate, this.offset);
1363
1364 this.$element
1365 .empty()
1366 .append(this.buildCalendarForYear(date));
1367
1368 if (this.focusAfterAppend) {
1369 this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
1370 this.focusAfterAppend.focus();
1371 this.focusAfterAppend = null;
1372 }
1373 };
1374
1375 /**
1376 * Creates a single cell to contain a year in the calendar.
1377 * @param {number} opt_year Four-digit year.
1378 * @param {number} opt_month Zero-indexed month.
1379 * @returns {HTMLElement}
1380 */
1381 CalendarYearBodyCtrl.prototype.buildMonthCell = function(year, month) {
1382 var calendarCtrl = this.calendarCtrl;
1383 var yearCtrl = this.yearCtrl;
1384 var cell = this.buildBlankCell();
1385
1386 // Represent this month/year as a date.
1387 var firstOfMonth = new Date(year, month, 1);
1388 cell.setAttribute('aria-label', this.dateLocale.monthFormatter(firstOfMonth));
1389 cell.id = calendarCtrl.getDateId(firstOfMonth, 'year');
1390
1391 // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
1392 cell.setAttribute('data-timestamp', firstOfMonth.getTime());
1393
1394 if (this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.today)) {
1395 cell.classList.add(calendarCtrl.TODAY_CLASS);
1396 }
1397
1398 if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
1399 this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.selectedDate)) {
1400 cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
1401 cell.setAttribute('aria-selected', 'true');
1402 }
1403
1404 var cellText = this.dateLocale.shortMonths[month];
1405
1406 if (this.dateUtil.isMonthWithinRange(firstOfMonth,
1407 calendarCtrl.minDate, calendarCtrl.maxDate)) {
1408 var selectionIndicator = document.createElement('span');
1409 selectionIndicator.classList.add('md-calendar-date-selection-indicator');
1410 selectionIndicator.textContent = cellText;
1411 cell.appendChild(selectionIndicator);
1412 cell.addEventListener('click', yearCtrl.cellClickHandler);
1413
1414 if (calendarCtrl.displayDate && this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.displayDate)) {
1415 this.focusAfterAppend = cell;
1416 }
1417 } else {
1418 cell.classList.add('md-calendar-date-disabled');
1419 cell.textContent = cellText;
1420 }
1421
1422 return cell;
1423 };
1424
1425 /**
1426 * Builds a blank cell.
1427 * @return {HTMLTableCellElement}
1428 */
1429 CalendarYearBodyCtrl.prototype.buildBlankCell = function() {
1430 var cell = document.createElement('td');
1431 cell.tabIndex = -1;
1432 cell.classList.add('md-calendar-date');
1433 cell.setAttribute('role', 'gridcell');
1434
1435 cell.setAttribute('tabindex', '-1');
1436 return cell;
1437 };
1438
1439 /**
1440 * Builds the <tbody> content for the given year.
1441 * @param {Date} date Date for which the content should be built.
1442 * @returns {DocumentFragment} A document fragment containing the months within the year.
1443 */
1444 CalendarYearBodyCtrl.prototype.buildCalendarForYear = function(date) {
1445 // Store rows for the month in a document fragment so that we can append them all at once.
1446 var year = date.getFullYear();
1447 var yearBody = document.createDocumentFragment();
1448
1449 var monthCell, i;
1450 // First row contains label and Jan-Jun.
1451 var firstRow = document.createElement('tr');
1452 var labelCell = document.createElement('td');
1453 labelCell.className = 'md-calendar-month-label';
1454 labelCell.textContent = year;
1455 firstRow.appendChild(labelCell);
1456
1457 for (i = 0; i < 6; i++) {
1458 firstRow.appendChild(this.buildMonthCell(year, i));
1459 }
1460 yearBody.appendChild(firstRow);
1461
1462 // Second row contains a blank cell and Jul-Dec.
1463 var secondRow = document.createElement('tr');
1464 secondRow.appendChild(this.buildBlankCell());
1465 for (i = 6; i < 12; i++) {
1466 secondRow.appendChild(this.buildMonthCell(year, i));
1467 }
1468 yearBody.appendChild(secondRow);
1469
1470 return yearBody;
1471 };
1472})();
1473
1474(function() {
1475 'use strict';
1476
1477 /**
1478 * @ngdoc service
1479 * @name $mdDateLocaleProvider
1480 * @module material.components.datepicker
1481 *
1482 * @description
1483 * The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
1484 * This provider that allows the user to specify messages, formatters, and parsers for date
1485 * internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
1486 * components that deal with dates.
1487 *
1488 * @property {(Array<string>)=} months Array of month names (in order).
1489 * @property {(Array<string>)=} shortMonths Array of abbreviated month names.
1490 * @property {(Array<string>)=} days Array of the days of the week (in order).
1491 * @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
1492 * @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
1493 * using a numeral system other than [1, 2, 3...].
1494 * @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
1495 * etc.
1496 * @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
1497 * @property {(function(Date): string)=} formatDate Function to format a date object to a string.
1498 * @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
1499 * a month given a date.
1500 * @property {(function(Date): string)=} monthFormatter Function that returns the full name of a month
1501 * for a giben date.
1502 * @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
1503 * a week given the week number.
1504 * @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
1505 * @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
1506 * current locale.
1507 * @property {Date=} firstRenderableDate The date from which the datepicker calendar will begin
1508 * rendering. Note that this will be ignored if a minimum date is set. Defaults to January 1st 1880.
1509 * @property {Date=} lastRenderableDate The last date that will be rendered by the datepicker
1510 * calendar. Note that this will be ignored if a maximum date is set. Defaults to January 1st 2130.
1511 *
1512 * @usage
1513 * <hljs lang="js">
1514 * myAppModule.config(function($mdDateLocaleProvider) {
1515 *
1516 * // Example of a French localization.
1517 * $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
1518 * $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
1519 * $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
1520 * $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
1521 *
1522 * // Can change week display to start on Monday.
1523 * $mdDateLocaleProvider.firstDayOfWeek = 1;
1524 *
1525 * // Optional.
1526 * $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
1527 *
1528 * // Example uses moment.js to parse and format dates.
1529 * $mdDateLocaleProvider.parseDate = function(dateString) {
1530 * var m = moment(dateString, 'L', true);
1531 * return m.isValid() ? m.toDate() : new Date(NaN);
1532 * };
1533 *
1534 * $mdDateLocaleProvider.formatDate = function(date) {
1535 * var m = moment(date);
1536 * return m.isValid() ? m.format('L') : '';
1537 * };
1538 *
1539 * $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
1540 * return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
1541 * };
1542 *
1543 * // In addition to date display, date components also need localized messages
1544 * // for aria-labels for screen-reader users.
1545 *
1546 * $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
1547 * return 'Semaine ' + weekNumber;
1548 * };
1549 *
1550 * $mdDateLocaleProvider.msgCalendar = 'Calendrier';
1551 * $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
1552 *
1553 * // You can also set when your calendar begins and ends.
1554 * $mdDateLocaleProvider.firstRenderableDate = new Date(1776, 6, 4);
1555 * $mdDateLocaleProvider.lastRenderableDate = new Date(2012, 11, 21);
1556 * });
1557 * </hljs>
1558 *
1559 */
1560 angular.module('material.components.datepicker').config(["$provide", function($provide) {
1561 // TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
1562
1563 /** @constructor */
1564 function DateLocaleProvider() {
1565 /** Array of full month names. E.g., ['January', 'Febuary', ...] */
1566 this.months = null;
1567
1568 /** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
1569 this.shortMonths = null;
1570
1571 /** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
1572 this.days = null;
1573
1574 /** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
1575 this.shortDays = null;
1576
1577 /** Array of dates of a month (1 - 31). Characters might be different in some locales. */
1578 this.dates = null;
1579
1580 /** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
1581 this.firstDayOfWeek = 0;
1582
1583 /**
1584 * Function that converts the date portion of a Date to a string.
1585 * @type {(function(Date): string)}
1586 */
1587 this.formatDate = null;
1588
1589 /**
1590 * Function that converts a date string to a Date object (the date portion)
1591 * @type {function(string): Date}
1592 */
1593 this.parseDate = null;
1594
1595 /**
1596 * Function that formats a Date into a month header string.
1597 * @type {function(Date): string}
1598 */
1599 this.monthHeaderFormatter = null;
1600
1601 /**
1602 * Function that formats a week number into a label for the week.
1603 * @type {function(number): string}
1604 */
1605 this.weekNumberFormatter = null;
1606
1607 /**
1608 * Function that formats a date into a long aria-label that is read
1609 * when the focused date changes.
1610 * @type {function(Date): string}
1611 */
1612 this.longDateFormatter = null;
1613
1614 /**
1615 * ARIA label for the calendar "dialog" used in the datepicker.
1616 * @type {string}
1617 */
1618 this.msgCalendar = '';
1619
1620 /**
1621 * ARIA label for the datepicker's "Open calendar" buttons.
1622 * @type {string}
1623 */
1624 this.msgOpenCalendar = '';
1625 }
1626
1627 /**
1628 * Factory function that returns an instance of the dateLocale service.
1629 * ngInject
1630 * @param $locale
1631 * @returns {DateLocale}
1632 */
1633 DateLocaleProvider.prototype.$get = function($locale, $filter) {
1634 /**
1635 * Default date-to-string formatting function.
1636 * @param {!Date} date
1637 * @returns {string}
1638 */
1639 function defaultFormatDate(date) {
1640 if (!date) {
1641 return '';
1642 }
1643
1644 // All of the dates created through ng-material *should* be set to midnight.
1645 // If we encounter a date where the localeTime shows at 11pm instead of midnight,
1646 // we have run into an issue with DST where we need to increment the hour by one:
1647 // var d = new Date(1992, 9, 8, 0, 0, 0);
1648 // d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
1649 var localeTime = date.toLocaleTimeString();
1650 var formatDate = date;
1651 if (date.getHours() == 0 &&
1652 (localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
1653 formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
1654 }
1655
1656 return $filter('date')(formatDate, 'M/d/yyyy');
1657 }
1658
1659 /**
1660 * Default string-to-date parsing function.
1661 * @param {string} dateString
1662 * @returns {!Date}
1663 */
1664 function defaultParseDate(dateString) {
1665 return new Date(dateString);
1666 }
1667
1668 /**
1669 * Default function to determine whether a string makes sense to be
1670 * parsed to a Date object.
1671 *
1672 * This is very permissive and is just a basic sanity check to ensure that
1673 * things like single integers aren't able to be parsed into dates.
1674 * @param {string} dateString
1675 * @returns {boolean}
1676 */
1677 function defaultIsDateComplete(dateString) {
1678 dateString = dateString.trim();
1679
1680 // Looks for three chunks of content (either numbers or text) separated
1681 // by delimiters.
1682 var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
1683 return re.test(dateString);
1684 }
1685
1686 /**
1687 * Default date-to-string formatter to get a month header.
1688 * @param {!Date} date
1689 * @returns {string}
1690 */
1691 function defaultMonthHeaderFormatter(date) {
1692 return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
1693 }
1694
1695 /**
1696 * Default formatter for a month.
1697 * @param {!Date} date
1698 * @returns {string}
1699 */
1700 function defaultMonthFormatter(date) {
1701 return service.months[date.getMonth()] + ' ' + date.getFullYear();
1702 }
1703
1704 /**
1705 * Default week number formatter.
1706 * @param number
1707 * @returns {string}
1708 */
1709 function defaultWeekNumberFormatter(number) {
1710 return 'Week ' + number;
1711 }
1712
1713 /**
1714 * Default formatter for date cell aria-labels.
1715 * @param {!Date} date
1716 * @returns {string}
1717 */
1718 function defaultLongDateFormatter(date) {
1719 // Example: 'Thursday June 18 2015'
1720 return [
1721 service.days[date.getDay()],
1722 service.months[date.getMonth()],
1723 service.dates[date.getDate()],
1724 date.getFullYear()
1725 ].join(' ');
1726 }
1727
1728 // The default "short" day strings are the first character of each day,
1729 // e.g., "Monday" => "M".
1730 var defaultShortDays = $locale.DATETIME_FORMATS.SHORTDAY.map(function(day) {
1731 return day.substring(0, 1);
1732 });
1733
1734 // The default dates are simply the numbers 1 through 31.
1735 var defaultDates = Array(32);
1736 for (var i = 1; i <= 31; i++) {
1737 defaultDates[i] = i;
1738 }
1739
1740 // Default ARIA messages are in English (US).
1741 var defaultMsgCalendar = 'Calendar';
1742 var defaultMsgOpenCalendar = 'Open calendar';
1743
1744 // Default start/end dates that are rendered in the calendar.
1745 var defaultFirstRenderableDate = new Date(1880, 0, 1);
1746 var defaultLastRendereableDate = new Date(defaultFirstRenderableDate.getFullYear() + 250, 0, 1);
1747
1748 var service = {
1749 months: this.months || $locale.DATETIME_FORMATS.MONTH,
1750 shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
1751 days: this.days || $locale.DATETIME_FORMATS.DAY,
1752 shortDays: this.shortDays || defaultShortDays,
1753 dates: this.dates || defaultDates,
1754 firstDayOfWeek: this.firstDayOfWeek || 0,
1755 formatDate: this.formatDate || defaultFormatDate,
1756 parseDate: this.parseDate || defaultParseDate,
1757 isDateComplete: this.isDateComplete || defaultIsDateComplete,
1758 monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
1759 monthFormatter: this.monthFormatter || defaultMonthFormatter,
1760 weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
1761 longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
1762 msgCalendar: this.msgCalendar || defaultMsgCalendar,
1763 msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar,
1764 firstRenderableDate: this.firstRenderableDate || defaultFirstRenderableDate,
1765 lastRenderableDate: this.lastRenderableDate || defaultLastRendereableDate
1766 };
1767
1768 return service;
1769 };
1770 DateLocaleProvider.prototype.$get.$inject = ["$locale", "$filter"];
1771
1772 $provide.provider('$mdDateLocale', new DateLocaleProvider());
1773 }]);
1774})();
1775
1776(function() {
1777 'use strict';
1778
1779 /**
1780 * Utility for performing date calculations to facilitate operation of the calendar and
1781 * datepicker.
1782 */
1783 angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
1784 return {
1785 getFirstDateOfMonth: getFirstDateOfMonth,
1786 getNumberOfDaysInMonth: getNumberOfDaysInMonth,
1787 getDateInNextMonth: getDateInNextMonth,
1788 getDateInPreviousMonth: getDateInPreviousMonth,
1789 isInNextMonth: isInNextMonth,
1790 isInPreviousMonth: isInPreviousMonth,
1791 getDateMidpoint: getDateMidpoint,
1792 isSameMonthAndYear: isSameMonthAndYear,
1793 getWeekOfMonth: getWeekOfMonth,
1794 incrementDays: incrementDays,
1795 incrementMonths: incrementMonths,
1796 getLastDateOfMonth: getLastDateOfMonth,
1797 isSameDay: isSameDay,
1798 getMonthDistance: getMonthDistance,
1799 isValidDate: isValidDate,
1800 setDateTimeToMidnight: setDateTimeToMidnight,
1801 createDateAtMidnight: createDateAtMidnight,
1802 isDateWithinRange: isDateWithinRange,
1803 incrementYears: incrementYears,
1804 getYearDistance: getYearDistance,
1805 clampDate: clampDate,
1806 getTimestampFromNode: getTimestampFromNode,
1807 isMonthWithinRange: isMonthWithinRange
1808 };
1809
1810 /**
1811 * Gets the first day of the month for the given date's month.
1812 * @param {Date} date
1813 * @returns {Date}
1814 */
1815 function getFirstDateOfMonth(date) {
1816 return new Date(date.getFullYear(), date.getMonth(), 1);
1817 }
1818
1819 /**
1820 * Gets the number of days in the month for the given date's month.
1821 * @param date
1822 * @returns {number}
1823 */
1824 function getNumberOfDaysInMonth(date) {
1825 return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
1826 }
1827
1828 /**
1829 * Get an arbitrary date in the month after the given date's month.
1830 * @param date
1831 * @returns {Date}
1832 */
1833 function getDateInNextMonth(date) {
1834 return new Date(date.getFullYear(), date.getMonth() + 1, 1);
1835 }
1836
1837 /**
1838 * Get an arbitrary date in the month before the given date's month.
1839 * @param date
1840 * @returns {Date}
1841 */
1842 function getDateInPreviousMonth(date) {
1843 return new Date(date.getFullYear(), date.getMonth() - 1, 1);
1844 }
1845
1846 /**
1847 * Gets whether two dates have the same month and year.
1848 * @param {Date} d1
1849 * @param {Date} d2
1850 * @returns {boolean}
1851 */
1852 function isSameMonthAndYear(d1, d2) {
1853 return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
1854 }
1855
1856 /**
1857 * Gets whether two dates are the same day (not not necesarily the same time).
1858 * @param {Date} d1
1859 * @param {Date} d2
1860 * @returns {boolean}
1861 */
1862 function isSameDay(d1, d2) {
1863 return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
1864 }
1865
1866 /**
1867 * Gets whether a date is in the month immediately after some date.
1868 * @param {Date} startDate The date from which to compare.
1869 * @param {Date} endDate The date to check.
1870 * @returns {boolean}
1871 */
1872 function isInNextMonth(startDate, endDate) {
1873 var nextMonth = getDateInNextMonth(startDate);
1874 return isSameMonthAndYear(nextMonth, endDate);
1875 }
1876
1877 /**
1878 * Gets whether a date is in the month immediately before some date.
1879 * @param {Date} startDate The date from which to compare.
1880 * @param {Date} endDate The date to check.
1881 * @returns {boolean}
1882 */
1883 function isInPreviousMonth(startDate, endDate) {
1884 var previousMonth = getDateInPreviousMonth(startDate);
1885 return isSameMonthAndYear(endDate, previousMonth);
1886 }
1887
1888 /**
1889 * Gets the midpoint between two dates.
1890 * @param {Date} d1
1891 * @param {Date} d2
1892 * @returns {Date}
1893 */
1894 function getDateMidpoint(d1, d2) {
1895 return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
1896 }
1897
1898 /**
1899 * Gets the week of the month that a given date occurs in.
1900 * @param {Date} date
1901 * @returns {number} Index of the week of the month (zero-based).
1902 */
1903 function getWeekOfMonth(date) {
1904 var firstDayOfMonth = getFirstDateOfMonth(date);
1905 return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
1906 }
1907
1908 /**
1909 * Gets a new date incremented by the given number of days. Number of days can be negative.
1910 * @param {Date} date
1911 * @param {number} numberOfDays
1912 * @returns {Date}
1913 */
1914 function incrementDays(date, numberOfDays) {
1915 return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
1916 }
1917
1918 /**
1919 * Gets a new date incremented by the given number of months. Number of months can be negative.
1920 * If the date of the given month does not match the target month, the date will be set to the
1921 * last day of the month.
1922 * @param {Date} date
1923 * @param {number} numberOfMonths
1924 * @returns {Date}
1925 */
1926 function incrementMonths(date, numberOfMonths) {
1927 // If the same date in the target month does not actually exist, the Date object will
1928 // automatically advance *another* month by the number of missing days.
1929 // For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
1930 // So, we check if the month overflowed and go to the last day of the target month instead.
1931 var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
1932 var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
1933 if (numberOfDaysInMonth < date.getDate()) {
1934 dateInTargetMonth.setDate(numberOfDaysInMonth);
1935 } else {
1936 dateInTargetMonth.setDate(date.getDate());
1937 }
1938
1939 return dateInTargetMonth;
1940 }
1941
1942 /**
1943 * Get the integer distance between two months. This *only* considers the month and year
1944 * portion of the Date instances.
1945 *
1946 * @param {Date} start
1947 * @param {Date} end
1948 * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
1949 * chronologically, this number will be negative.
1950 */
1951 function getMonthDistance(start, end) {
1952 return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
1953 }
1954
1955 /**
1956 * Gets the last day of the month for the given date.
1957 * @param {Date} date
1958 * @returns {Date}
1959 */
1960 function getLastDateOfMonth(date) {
1961 return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
1962 }
1963
1964 /**
1965 * Checks whether a date is valid.
1966 * @param {Date} date
1967 * @return {boolean} Whether the date is a valid Date.
1968 */
1969 function isValidDate(date) {
1970 return date != null && date.getTime && !isNaN(date.getTime());
1971 }
1972
1973 /**
1974 * Sets a date's time to midnight.
1975 * @param {Date} date
1976 */
1977 function setDateTimeToMidnight(date) {
1978 if (isValidDate(date)) {
1979 date.setHours(0, 0, 0, 0);
1980 }
1981 }
1982
1983 /**
1984 * Creates a date with the time set to midnight.
1985 * Drop-in replacement for two forms of the Date constructor:
1986 * 1. No argument for Date representing now.
1987 * 2. Single-argument value representing number of seconds since Unix Epoch
1988 * or a Date object.
1989 * @param {number|Date=} opt_value
1990 * @return {Date} New date with time set to midnight.
1991 */
1992 function createDateAtMidnight(opt_value) {
1993 var date;
1994 if (angular.isUndefined(opt_value)) {
1995 date = new Date();
1996 } else {
1997 date = new Date(opt_value);
1998 }
1999 setDateTimeToMidnight(date);
2000 return date;
2001 }
2002
2003 /**
2004 * Checks if a date is within a min and max range, ignoring the time component.
2005 * If minDate or maxDate are not dates, they are ignored.
2006 * @param {Date} date
2007 * @param {Date} minDate
2008 * @param {Date} maxDate
2009 */
2010 function isDateWithinRange(date, minDate, maxDate) {
2011 var dateAtMidnight = createDateAtMidnight(date);
2012 var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
2013 var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
2014 return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
2015 (!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
2016 }
2017
2018 /**
2019 * Gets a new date incremented by the given number of years. Number of years can be negative.
2020 * See `incrementMonths` for notes on overflow for specific dates.
2021 * @param {Date} date
2022 * @param {number} numberOfYears
2023 * @returns {Date}
2024 */
2025 function incrementYears(date, numberOfYears) {
2026 return incrementMonths(date, numberOfYears * 12);
2027 }
2028
2029 /**
2030 * Get the integer distance between two years. This *only* considers the year portion of the
2031 * Date instances.
2032 *
2033 * @param {Date} start
2034 * @param {Date} end
2035 * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
2036 * chronologically, this number will be negative.
2037 */
2038 function getYearDistance(start, end) {
2039 return end.getFullYear() - start.getFullYear();
2040 }
2041
2042 /**
2043 * Clamps a date between a minimum and a maximum date.
2044 * @param {Date} date Date to be clamped
2045 * @param {Date=} minDate Minimum date
2046 * @param {Date=} maxDate Maximum date
2047 * @return {Date}
2048 */
2049 function clampDate(date, minDate, maxDate) {
2050 var boundDate = date;
2051 if (minDate && date < minDate) {
2052 boundDate = new Date(minDate.getTime());
2053 }
2054 if (maxDate && date > maxDate) {
2055 boundDate = new Date(maxDate.getTime());
2056 }
2057 return boundDate;
2058 }
2059
2060 /**
2061 * Extracts and parses the timestamp from a DOM node.
2062 * @param {HTMLElement} node Node from which the timestamp will be extracted.
2063 * @return {number} Time since epoch.
2064 */
2065 function getTimestampFromNode(node) {
2066 if (node && node.hasAttribute('data-timestamp')) {
2067 return Number(node.getAttribute('data-timestamp'));
2068 }
2069 }
2070
2071 /**
2072 * Checks if a month is within a min and max range, ignoring the date and time components.
2073 * If minDate or maxDate are not dates, they are ignored.
2074 * @param {Date} date
2075 * @param {Date} minDate
2076 * @param {Date} maxDate
2077 */
2078 function isMonthWithinRange(date, minDate, maxDate) {
2079 var month = date.getMonth();
2080 var year = date.getFullYear();
2081
2082 return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
2083 (!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
2084 }
2085 });
2086})();
2087
2088(function() {
2089 'use strict';
2090
2091 // POST RELEASE
2092 // TODO(jelbourn): Demo that uses moment.js
2093 // TODO(jelbourn): make sure this plays well with validation and ngMessages.
2094 // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
2095 // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
2096 // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
2097 // TODO(jelbourn): input behavior (masking? auto-complete?)
2098
2099
2100 DatePickerCtrl.$inject = ["$scope", "$element", "$attrs", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF", "$mdGesture", "$filter"];
2101 datePickerDirective.$inject = ["$$mdSvgRegistry", "$mdUtil", "$mdAria", "inputDirective"];
2102 angular.module('material.components.datepicker')
2103 .directive('mdDatepicker', datePickerDirective);
2104
2105 /**
2106 * @ngdoc directive
2107 * @name mdDatepicker
2108 * @module material.components.datepicker
2109 *
2110 * @param {Date} ng-model The component's model. Expects a JavaScript Date object.
2111 * @param {Object=} ng-model-options Allows tuning of the way in which `ng-model` is being updated. Also allows
2112 * for a timezone to be specified. <a href="https://docs.angularjs.org/api/ng/directive/ngModelOptions#usage">Read more at the ngModelOptions docs.</a>
2113 * @param {expression=} ng-change Expression evaluated when the model value changes.
2114 * @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar is opened.
2115 * @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the calendar is closed.
2116 * @param {Date=} md-min-date Expression representing a min date (inclusive).
2117 * @param {Date=} md-max-date Expression representing a max date (inclusive).
2118 * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
2119 * @param {String=} md-placeholder The date input placeholder value.
2120 * @param {String=} md-open-on-focus When present, the calendar will be opened when the input is focused.
2121 * @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar on-demand.
2122 * @param {String=} md-current-view Default open view of the calendar pane. Can be either "month" or "year".
2123 * @param {String=} md-hide-icons Determines which datepicker icons should be hidden. Note that this may cause the
2124 * datepicker to not align properly with other components. **Use at your own risk.** Possible values are:
2125 * * `"all"` - Hides all icons.
2126 * * `"calendar"` - Only hides the calendar icon.
2127 * * `"triangle"` - Only hides the triangle icon.
2128 * @param {boolean=} ng-disabled Whether the datepicker is disabled.
2129 * @param {boolean=} ng-required Whether a value is required for the datepicker.
2130 *
2131 * @description
2132 * `<md-datepicker>` is a component used to select a single date.
2133 * For information on how to configure internationalization for the date picker,
2134 * see `$mdDateLocaleProvider`.
2135 *
2136 * This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
2137 * Supported attributes are:
2138 * * `required`: whether a required date is not set.
2139 * * `mindate`: whether the selected date is before the minimum allowed date.
2140 * * `maxdate`: whether the selected date is after the maximum allowed date.
2141 * * `debounceInterval`: ms to delay input processing (since last debounce reset); default value 500ms
2142 *
2143 * @usage
2144 * <hljs lang="html">
2145 * <md-datepicker ng-model="birthday"></md-datepicker>
2146 * </hljs>
2147 *
2148 */
2149
2150 function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria, inputDirective) {
2151 return {
2152 template: function(tElement, tAttrs) {
2153 // Buttons are not in the tab order because users can open the calendar via keyboard
2154 // interaction on the text input, and multiple tab stops for one component (picker)
2155 // may be confusing.
2156 var hiddenIcons = tAttrs.mdHideIcons;
2157 var ariaLabelValue = tAttrs.ariaLabel || tAttrs.mdPlaceholder;
2158
2159 var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
2160 '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
2161 'tabindex="-1" aria-hidden="true" ' +
2162 'ng-click="ctrl.openCalendarPane($event)">' +
2163 '<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
2164 'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
2165 '</md-button>';
2166
2167 var triangleButton = (hiddenIcons === 'all' || hiddenIcons === 'triangle') ? '' :
2168 '<md-button type="button" md-no-ink ' +
2169 'class="md-datepicker-triangle-button md-icon-button" ' +
2170 'ng-click="ctrl.openCalendarPane($event)" ' +
2171 'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
2172 '<div class="md-datepicker-expand-triangle"></div>' +
2173 '</md-button>';
2174
2175 return calendarButton +
2176 '<div class="md-datepicker-input-container" ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
2177 '<input ' +
2178 (ariaLabelValue ? 'aria-label="' + ariaLabelValue + '" ' : '') +
2179 'class="md-datepicker-input" ' +
2180 'aria-haspopup="true" ' +
2181 'ng-focus="ctrl.setFocused(true)" ' +
2182 'ng-blur="ctrl.setFocused(false)"> ' +
2183 triangleButton +
2184 '</div>' +
2185
2186 // This pane will be detached from here and re-attached to the document body.
2187 '<div class="md-datepicker-calendar-pane md-whiteframe-z1">' +
2188 '<div class="md-datepicker-input-mask">' +
2189 '<div class="md-datepicker-input-mask-opaque"></div>' +
2190 '</div>' +
2191 '<div class="md-datepicker-calendar">' +
2192 '<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
2193 'md-current-view="{{::ctrl.currentView}}"' +
2194 'md-min-date="ctrl.minDate"' +
2195 'md-max-date="ctrl.maxDate"' +
2196 'md-date-filter="ctrl.dateFilter"' +
2197 'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
2198 '</md-calendar>' +
2199 '</div>' +
2200 '</div>';
2201 },
2202 require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
2203 scope: {
2204 minDate: '=mdMinDate',
2205 maxDate: '=mdMaxDate',
2206 placeholder: '@mdPlaceholder',
2207 currentView: '@mdCurrentView',
2208 dateFilter: '=mdDateFilter',
2209 isOpen: '=?mdIsOpen',
2210 debounceInterval: '=mdDebounceInterval'
2211 },
2212 controller: DatePickerCtrl,
2213 controllerAs: 'ctrl',
2214 bindToController: true,
2215 link: function(scope, element, attr, controllers) {
2216 var ngModelCtrl = controllers[0];
2217 var mdDatePickerCtrl = controllers[1];
2218 var mdInputContainer = controllers[2];
2219 var parentForm = controllers[3];
2220 var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
2221
2222 mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer, inputDirective);
2223
2224 if (mdInputContainer) {
2225 // We need to move the spacer after the datepicker itself,
2226 // because md-input-container adds it after the
2227 // md-datepicker-input by default. The spacer gets wrapped in a
2228 // div, because it floats and gets aligned next to the datepicker.
2229 // There are easier ways of working around this with CSS (making the
2230 // datepicker 100% wide, change the `display` etc.), however they
2231 // break the alignment with any other form controls.
2232 var spacer = element[0].querySelector('.md-errors-spacer');
2233
2234 if (spacer) {
2235 element.after(angular.element('<div>').append(spacer));
2236 }
2237
2238 mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
2239 mdInputContainer.input = element;
2240 mdInputContainer.element
2241 .addClass(INPUT_CONTAINER_CLASS)
2242 .toggleClass(HAS_ICON_CLASS, attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
2243
2244 if (!mdInputContainer.label) {
2245 $mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
2246 } else if(!mdNoAsterisk) {
2247 attr.$observe('required', function(value) {
2248 mdInputContainer.label.toggleClass('md-required', !!value);
2249 });
2250 }
2251
2252 scope.$watch(mdInputContainer.isErrorGetter || function() {
2253 return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted));
2254 }, mdInputContainer.setInvalid);
2255 } else if (parentForm) {
2256 // If invalid, highlights the input when the parent form is submitted.
2257 var parentSubmittedWatcher = scope.$watch(function() {
2258 return parentForm.$submitted;
2259 }, function(isSubmitted) {
2260 if (isSubmitted) {
2261 mdDatePickerCtrl.updateErrorState();
2262 parentSubmittedWatcher();
2263 }
2264 });
2265 }
2266 }
2267 };
2268 }
2269
2270 /** Additional offset for the input's `size` attribute, which is updated based on its content. */
2271 var EXTRA_INPUT_SIZE = 3;
2272
2273 /** Class applied to the container if the date is invalid. */
2274 var INVALID_CLASS = 'md-datepicker-invalid';
2275
2276 /** Class applied to the datepicker when it's open. */
2277 var OPEN_CLASS = 'md-datepicker-open';
2278
2279 /** Class applied to the md-input-container, if a datepicker is placed inside it */
2280 var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
2281
2282 /** Class to be applied when the calendar icon is enabled. */
2283 var HAS_ICON_CLASS = '_md-datepicker-has-calendar-icon';
2284
2285 /** Default time in ms to debounce input event by. */
2286 var DEFAULT_DEBOUNCE_INTERVAL = 500;
2287
2288 /**
2289 * Height of the calendar pane used to check if the pane is going outside the boundary of
2290 * the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
2291 * also added to space the pane away from the exact edge of the screen.
2292 *
2293 * This is computed statically now, but can be changed to be measured if the circumstances
2294 * of calendar sizing are changed.
2295 */
2296 var CALENDAR_PANE_HEIGHT = 368;
2297
2298 /**
2299 * Width of the calendar pane used to check if the pane is going outside the boundary of
2300 * the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
2301 * also added to space the pane away from the exact edge of the screen.
2302 *
2303 * This is computed statically now, but can be changed to be measured if the circumstances
2304 * of calendar sizing are changed.
2305 */
2306 var CALENDAR_PANE_WIDTH = 360;
2307
2308 /**
2309 * Controller for md-datepicker.
2310 *
2311 * ngInject @constructor
2312 */
2313 function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant,
2314 $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF, $mdGesture, $filter) {
2315
2316 /** @final */
2317 this.$window = $window;
2318
2319 /** @final */
2320 this.dateLocale = $mdDateLocale;
2321
2322 /** @final */
2323 this.dateUtil = $$mdDateUtil;
2324
2325 /** @final */
2326 this.$mdConstant = $mdConstant;
2327
2328 /* @final */
2329 this.$mdUtil = $mdUtil;
2330
2331 /** @final */
2332 this.$$rAF = $$rAF;
2333
2334 /**
2335 * The root document element. This is used for attaching a top-level click handler to
2336 * close the calendar panel when a click outside said panel occurs. We use `documentElement`
2337 * instead of body because, when scrolling is disabled, some browsers consider the body element
2338 * to be completely off the screen and propagate events directly to the html element.
2339 * @type {!angular.JQLite}
2340 */
2341 this.documentElement = angular.element(document.documentElement);
2342
2343 /** @type {!angular.NgModelController} */
2344 this.ngModelCtrl = null;
2345
2346 /** @type {HTMLInputElement} */
2347 this.inputElement = $element[0].querySelector('input');
2348
2349 /** @final {!angular.JQLite} */
2350 this.ngInputElement = angular.element(this.inputElement);
2351
2352 /** @type {HTMLElement} */
2353 this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
2354
2355 /** @type {HTMLElement} Floating calendar pane. */
2356 this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
2357
2358 /** @type {HTMLElement} Calendar icon button. */
2359 this.calendarButton = $element[0].querySelector('.md-datepicker-button');
2360
2361 /**
2362 * Element covering everything but the input in the top of the floating calendar pane.
2363 * @type {!angular.JQLite}
2364 */
2365 this.inputMask = angular.element($element[0].querySelector('.md-datepicker-input-mask-opaque'));
2366
2367 /** @final {!angular.JQLite} */
2368 this.$element = $element;
2369
2370 /** @final {!angular.Attributes} */
2371 this.$attrs = $attrs;
2372
2373 /** @final {!angular.Scope} */
2374 this.$scope = $scope;
2375
2376 /** @type {Date} */
2377 this.date = null;
2378
2379 /** @type {boolean} */
2380 this.isFocused = false;
2381
2382 /** @type {boolean} */
2383 this.isDisabled;
2384 this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
2385
2386 /** @type {boolean} Whether the date-picker's calendar pane is open. */
2387 this.isCalendarOpen = false;
2388
2389 /** @type {boolean} Whether the calendar should open when the input is focused. */
2390 this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
2391
2392 /** @final */
2393 this.mdInputContainer = null;
2394
2395 /**
2396 * Element from which the calendar pane was opened. Keep track of this so that we can return
2397 * focus to it when the pane is closed.
2398 * @type {HTMLElement}
2399 */
2400 this.calendarPaneOpenedFrom = null;
2401
2402 /** @type {String} Unique id for the calendar pane. */
2403 this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();
2404
2405 /** Pre-bound click handler is saved so that the event listener can be removed. */
2406 this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
2407
2408 /**
2409 * Name of the event that will trigger a close. Necessary to sniff the browser, because
2410 * the resize event doesn't make sense on mobile and can have a negative impact since it
2411 * triggers whenever the browser zooms in on a focused input.
2412 */
2413 this.windowEventName = ($mdGesture.isIos || $mdGesture.isAndroid) ? 'orientationchange' : 'resize';
2414
2415 /** Pre-bound close handler so that the event listener can be removed. */
2416 this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
2417
2418 /** Pre-bound handler for the window blur event. Allows for it to be removed later. */
2419 this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
2420
2421 /** The built-in Angular date filter. */
2422 this.ngDateFilter = $filter('date');
2423
2424 /** @type {Number} Extra margin for the left side of the floating calendar pane. */
2425 this.leftMargin = 20;
2426
2427 /** @type {Number} Extra margin for the top of the floating calendar. Gets determined on the first open. */
2428 this.topMargin = null;
2429
2430 // Unless the user specifies so, the datepicker should not be a tab stop.
2431 // This is necessary because ngAria might add a tabindex to anything with an ng-model
2432 // (based on whether or not the user has turned that particular feature on/off).
2433 if ($attrs.tabindex) {
2434 this.ngInputElement.attr('tabindex', $attrs.tabindex);
2435 $attrs.$set('tabindex', null);
2436 } else {
2437 $attrs.$set('tabindex', '-1');
2438 }
2439
2440 $mdTheming($element);
2441 $mdTheming(angular.element(this.calendarPane));
2442
2443 this.installPropertyInterceptors();
2444 this.attachChangeListeners();
2445 this.attachInteractionListeners();
2446
2447 var self = this;
2448
2449 $scope.$on('$destroy', function() {
2450 self.detachCalendarPane();
2451 });
2452
2453 if ($attrs.mdIsOpen) {
2454 $scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
2455 if (shouldBeOpen) {
2456 self.openCalendarPane({
2457 target: self.inputElement
2458 });
2459 } else {
2460 self.closeCalendarPane();
2461 }
2462 });
2463 }
2464 }
2465
2466 /**
2467 * Sets up the controller's reference to ngModelController and
2468 * applies Angular's `input[type="date"]` directive.
2469 * @param {!angular.NgModelController} ngModelCtrl Instance of the ngModel controller.
2470 * @param {Object} mdInputContainer Instance of the mdInputContainer controller.
2471 * @param {Object} inputDirective Config for Angular's `input` directive.
2472 */
2473 DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer, inputDirective) {
2474 this.ngModelCtrl = ngModelCtrl;
2475 this.mdInputContainer = mdInputContainer;
2476
2477 // The input needs to be [type="date"] in order to be picked up by Angular.
2478 this.$attrs.$set('type', 'date');
2479
2480 // Invoke the `input` directive link function, adding a stub for the element.
2481 // This allows us to re-use Angular's logic for setting the timezone via ng-model-options.
2482 // It works by calling the link function directly which then adds the proper `$parsers` and
2483 // `$formatters` to the ngModel controller.
2484 inputDirective[0].link.pre(this.$scope, {
2485 on: angular.noop,
2486 val: angular.noop,
2487 0: {}
2488 }, this.$attrs, [ngModelCtrl]);
2489
2490 var self = this;
2491
2492 // Responds to external changes to the model value.
2493 self.ngModelCtrl.$formatters.push(function(value) {
2494 if (value && !(value instanceof Date)) {
2495 throw Error('The ng-model for md-datepicker must be a Date instance. ' +
2496 'Currently the model is a: ' + (typeof value));
2497 }
2498
2499 self.date = value;
2500 self.inputElement.value = self.dateLocale.formatDate(value);
2501 self.mdInputContainer && self.mdInputContainer.setHasValue(!!value);
2502 self.resizeInputElement();
2503 self.updateErrorState();
2504
2505 return value;
2506 });
2507
2508 // Responds to external error state changes (e.g. ng-required based on another input).
2509 ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
2510 };
2511
2512 /**
2513 * Attach event listeners for both the text input and the md-calendar.
2514 * Events are used instead of ng-model so that updates don't infinitely update the other
2515 * on a change. This should also be more performant than using a $watch.
2516 */
2517 DatePickerCtrl.prototype.attachChangeListeners = function() {
2518 var self = this;
2519
2520 self.$scope.$on('md-calendar-change', function(event, date) {
2521 self.setModelValue(date);
2522 self.date = date;
2523 self.inputElement.value = self.dateLocale.formatDate(date);
2524 self.mdInputContainer && self.mdInputContainer.setHasValue(!!date);
2525 self.closeCalendarPane();
2526 self.resizeInputElement();
2527 self.updateErrorState();
2528 });
2529
2530 self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
2531
2532 var debounceInterval = angular.isDefined(this.debounceInterval) ?
2533 this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
2534 self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
2535 debounceInterval, self));
2536 };
2537
2538 /** Attach event listeners for user interaction. */
2539 DatePickerCtrl.prototype.attachInteractionListeners = function() {
2540 var self = this;
2541 var $scope = this.$scope;
2542 var keyCodes = this.$mdConstant.KEY_CODE;
2543
2544 // Add event listener through angular so that we can triggerHandler in unit tests.
2545 self.ngInputElement.on('keydown', function(event) {
2546 if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
2547 self.openCalendarPane(event);
2548 $scope.$digest();
2549 }
2550 });
2551
2552 if (self.openOnFocus) {
2553 self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
2554 angular.element(self.$window).on('blur', self.windowBlurHandler);
2555
2556 $scope.$on('$destroy', function() {
2557 angular.element(self.$window).off('blur', self.windowBlurHandler);
2558 });
2559 }
2560
2561 $scope.$on('md-calendar-close', function() {
2562 self.closeCalendarPane();
2563 });
2564 };
2565
2566 /**
2567 * Capture properties set to the date-picker and imperitively handle internal changes.
2568 * This is done to avoid setting up additional $watches.
2569 */
2570 DatePickerCtrl.prototype.installPropertyInterceptors = function() {
2571 var self = this;
2572
2573 if (this.$attrs.ngDisabled) {
2574 // The expression is to be evaluated against the directive element's scope and not
2575 // the directive's isolate scope.
2576 var scope = this.$scope.$parent;
2577
2578 if (scope) {
2579 scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
2580 self.setDisabled(isDisabled);
2581 });
2582 }
2583 }
2584
2585 Object.defineProperty(this, 'placeholder', {
2586 get: function() { return self.inputElement.placeholder; },
2587 set: function(value) { self.inputElement.placeholder = value || ''; }
2588 });
2589 };
2590
2591 /**
2592 * Sets whether the date-picker is disabled.
2593 * @param {boolean} isDisabled
2594 */
2595 DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
2596 this.isDisabled = isDisabled;
2597 this.inputElement.disabled = isDisabled;
2598
2599 if (this.calendarButton) {
2600 this.calendarButton.disabled = isDisabled;
2601 }
2602 };
2603
2604 /**
2605 * Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
2606 * - mindate: whether the selected date is before the minimum date.
2607 * - maxdate: whether the selected flag is after the maximum date.
2608 * - filtered: whether the selected date is allowed by the custom filtering function.
2609 * - valid: whether the entered text input is a valid date
2610 *
2611 * The 'required' flag is handled automatically by ngModel.
2612 *
2613 * @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
2614 */
2615 DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
2616 var date = opt_date || this.date;
2617
2618 // Clear any existing errors to get rid of anything that's no longer relevant.
2619 this.clearErrorState();
2620
2621 if (this.dateUtil.isValidDate(date)) {
2622 // Force all dates to midnight in order to ignore the time portion.
2623 date = this.dateUtil.createDateAtMidnight(date);
2624
2625 if (this.dateUtil.isValidDate(this.minDate)) {
2626 var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
2627 this.ngModelCtrl.$setValidity('mindate', date >= minDate);
2628 }
2629
2630 if (this.dateUtil.isValidDate(this.maxDate)) {
2631 var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
2632 this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
2633 }
2634
2635 if (angular.isFunction(this.dateFilter)) {
2636 this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
2637 }
2638 } else {
2639 // The date is seen as "not a valid date" if there is *something* set
2640 // (i.e.., not null or undefined), but that something isn't a valid date.
2641 this.ngModelCtrl.$setValidity('valid', date == null);
2642 }
2643
2644 // TODO(jelbourn): Change this to classList.toggle when we stop using PhantomJS in unit tests
2645 // because it doesn't conform to the DOMTokenList spec.
2646 // See https://github.com/ariya/phantomjs/issues/12782.
2647 if (!this.ngModelCtrl.$valid) {
2648 this.inputContainer.classList.add(INVALID_CLASS);
2649 }
2650 };
2651
2652 /** Clears any error flags set by `updateErrorState`. */
2653 DatePickerCtrl.prototype.clearErrorState = function() {
2654 this.inputContainer.classList.remove(INVALID_CLASS);
2655 ['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
2656 this.ngModelCtrl.$setValidity(field, true);
2657 }, this);
2658 };
2659
2660 /** Resizes the input element based on the size of its content. */
2661 DatePickerCtrl.prototype.resizeInputElement = function() {
2662 this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
2663 };
2664
2665 /**
2666 * Sets the model value if the user input is a valid date.
2667 * Adds an invalid class to the input element if not.
2668 */
2669 DatePickerCtrl.prototype.handleInputEvent = function() {
2670 var inputString = this.inputElement.value;
2671 var parsedDate = inputString ? this.dateLocale.parseDate(inputString) : null;
2672 this.dateUtil.setDateTimeToMidnight(parsedDate);
2673
2674 // An input string is valid if it is either empty (representing no date)
2675 // or if it parses to a valid date that the user is allowed to select.
2676 var isValidInput = inputString == '' || (
2677 this.dateUtil.isValidDate(parsedDate) &&
2678 this.dateLocale.isDateComplete(inputString) &&
2679 this.isDateEnabled(parsedDate)
2680 );
2681
2682 // The datepicker's model is only updated when there is a valid input.
2683 if (isValidInput) {
2684 this.setModelValue(parsedDate);
2685 this.date = parsedDate;
2686 }
2687
2688 this.updateErrorState(parsedDate);
2689 };
2690
2691 /**
2692 * Check whether date is in range and enabled
2693 * @param {Date=} opt_date
2694 * @return {boolean} Whether the date is enabled.
2695 */
2696 DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
2697 return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
2698 (!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
2699 };
2700
2701 /** Position and attach the floating calendar to the document. */
2702 DatePickerCtrl.prototype.attachCalendarPane = function() {
2703 var calendarPane = this.calendarPane;
2704 var body = document.body;
2705
2706 calendarPane.style.transform = '';
2707 this.$element.addClass(OPEN_CLASS);
2708 this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
2709 angular.element(body).addClass('md-datepicker-is-showing');
2710
2711 var elementRect = this.inputContainer.getBoundingClientRect();
2712 var bodyRect = body.getBoundingClientRect();
2713
2714 if (!this.topMargin || this.topMargin < 0) {
2715 this.topMargin = (this.inputMask.parent().prop('clientHeight') - this.ngInputElement.prop('clientHeight')) / 2;
2716 }
2717
2718 // Check to see if the calendar pane would go off the screen. If so, adjust position
2719 // accordingly to keep it within the viewport.
2720 var paneTop = elementRect.top - bodyRect.top - this.topMargin;
2721 var paneLeft = elementRect.left - bodyRect.left - this.leftMargin;
2722
2723 // If ng-material has disabled body scrolling (for example, if a dialog is open),
2724 // then it's possible that the already-scrolled body has a negative top/left. In this case,
2725 // we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
2726 // though, the top of the viewport should just be the body's scroll position.
2727 var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
2728 -bodyRect.top :
2729 document.body.scrollTop;
2730
2731 var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
2732 -bodyRect.left :
2733 document.body.scrollLeft;
2734
2735 var viewportBottom = viewportTop + this.$window.innerHeight;
2736 var viewportRight = viewportLeft + this.$window.innerWidth;
2737
2738 // Creates an overlay with a hole the same size as element. We remove a pixel or two
2739 // on each end to make it overlap slightly. The overlay's background is added in
2740 // the theme in the form of a box-shadow with a huge spread.
2741 this.inputMask.css({
2742 position: 'absolute',
2743 left: this.leftMargin + 'px',
2744 top: this.topMargin + 'px',
2745 width: (elementRect.width - 1) + 'px',
2746 height: (elementRect.height - 2) + 'px'
2747 });
2748
2749 // If the right edge of the pane would be off the screen and shifting it left by the
2750 // difference would not go past the left edge of the screen. If the calendar pane is too
2751 // big to fit on the screen at all, move it to the left of the screen and scale the entire
2752 // element down to fit.
2753 if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
2754 if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
2755 paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
2756 } else {
2757 paneLeft = viewportLeft;
2758 var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
2759 calendarPane.style.transform = 'scale(' + scale + ')';
2760 }
2761
2762 calendarPane.classList.add('md-datepicker-pos-adjusted');
2763 }
2764
2765 // If the bottom edge of the pane would be off the screen and shifting it up by the
2766 // difference would not go past the top edge of the screen.
2767 if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
2768 viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
2769 paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
2770 calendarPane.classList.add('md-datepicker-pos-adjusted');
2771 }
2772
2773 calendarPane.style.left = paneLeft + 'px';
2774 calendarPane.style.top = paneTop + 'px';
2775 document.body.appendChild(calendarPane);
2776
2777 // Add CSS class after one frame to trigger open animation.
2778 this.$$rAF(function() {
2779 calendarPane.classList.add('md-pane-open');
2780 });
2781 };
2782
2783 /** Detach the floating calendar pane from the document. */
2784 DatePickerCtrl.prototype.detachCalendarPane = function() {
2785 this.$element.removeClass(OPEN_CLASS);
2786 this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
2787 angular.element(document.body).removeClass('md-datepicker-is-showing');
2788 this.calendarPane.classList.remove('md-pane-open');
2789 this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
2790
2791 if (this.isCalendarOpen) {
2792 this.$mdUtil.enableScrolling();
2793 }
2794
2795 if (this.calendarPane.parentNode) {
2796 // Use native DOM removal because we do not want any of the
2797 // angular state of this element to be disposed.
2798 this.calendarPane.parentNode.removeChild(this.calendarPane);
2799 }
2800 };
2801
2802 /**
2803 * Open the floating calendar pane.
2804 * @param {Event} event
2805 */
2806 DatePickerCtrl.prototype.openCalendarPane = function(event) {
2807 if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
2808 this.isCalendarOpen = this.isOpen = true;
2809 this.calendarPaneOpenedFrom = event.target;
2810
2811 // Because the calendar pane is attached directly to the body, it is possible that the
2812 // rest of the component (input, etc) is in a different scrolling container, such as
2813 // an md-content. This means that, if the container is scrolled, the pane would remain
2814 // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
2815 // also matches the native behavior for things like `<select>` on Mac and Windows.
2816 this.$mdUtil.disableScrollAround(this.calendarPane);
2817
2818 this.attachCalendarPane();
2819 this.focusCalendar();
2820 this.evalAttr('ngFocus');
2821
2822 // Attach click listener inside of a timeout because, if this open call was triggered by a
2823 // click, we don't want it to be immediately propogated up to the body and handled.
2824 var self = this;
2825 this.$mdUtil.nextTick(function() {
2826 // Use 'touchstart` in addition to click in order to work on iOS Safari, where click
2827 // events aren't propogated under most circumstances.
2828 // See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
2829 self.documentElement.on('click touchstart', self.bodyClickHandler);
2830 }, false);
2831
2832 window.addEventListener(this.windowEventName, this.windowEventHandler);
2833 }
2834 };
2835
2836 /** Close the floating calendar pane. */
2837 DatePickerCtrl.prototype.closeCalendarPane = function() {
2838 if (this.isCalendarOpen) {
2839 var self = this;
2840
2841 self.detachCalendarPane();
2842 self.ngModelCtrl.$setTouched();
2843 self.evalAttr('ngBlur');
2844
2845 self.documentElement.off('click touchstart', self.bodyClickHandler);
2846 window.removeEventListener(self.windowEventName, self.windowEventHandler);
2847
2848 self.calendarPaneOpenedFrom.focus();
2849 self.calendarPaneOpenedFrom = null;
2850
2851 if (self.openOnFocus) {
2852 // Ensures that all focus events have fired before resetting
2853 // the calendar. Prevents the calendar from reopening immediately
2854 // in IE when md-open-on-focus is set. Also it needs to trigger
2855 // a digest, in order to prevent issues where the calendar wasn't
2856 // showing up on the next open.
2857 self.$mdUtil.nextTick(reset);
2858 } else {
2859 reset();
2860 }
2861 }
2862
2863 function reset(){
2864 self.isCalendarOpen = self.isOpen = false;
2865 }
2866 };
2867
2868 /** Gets the controller instance for the calendar in the floating pane. */
2869 DatePickerCtrl.prototype.getCalendarCtrl = function() {
2870 return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
2871 };
2872
2873 /** Focus the calendar in the floating pane. */
2874 DatePickerCtrl.prototype.focusCalendar = function() {
2875 // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
2876 var self = this;
2877 this.$mdUtil.nextTick(function() {
2878 self.getCalendarCtrl().focus();
2879 }, false);
2880 };
2881
2882 /**
2883 * Sets whether the input is currently focused.
2884 * @param {boolean} isFocused
2885 */
2886 DatePickerCtrl.prototype.setFocused = function(isFocused) {
2887 if (!isFocused) {
2888 this.ngModelCtrl.$setTouched();
2889 }
2890
2891 // The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
2892 // because they also get called when the calendar is opened/closed.
2893 if (!this.openOnFocus) {
2894 this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
2895 }
2896
2897 this.isFocused = isFocused;
2898 };
2899
2900 /**
2901 * Handles a click on the document body when the floating calendar pane is open.
2902 * Closes the floating calendar pane if the click is not inside of it.
2903 * @param {MouseEvent} event
2904 */
2905 DatePickerCtrl.prototype.handleBodyClick = function(event) {
2906 if (this.isCalendarOpen) {
2907 var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
2908
2909 if (!isInCalendar) {
2910 this.closeCalendarPane();
2911 }
2912
2913 this.$scope.$digest();
2914 }
2915 };
2916
2917 /**
2918 * Handles the event when the user navigates away from the current tab. Keeps track of
2919 * whether the input was focused when the event happened, in order to prevent the calendar
2920 * from re-opening.
2921 */
2922 DatePickerCtrl.prototype.handleWindowBlur = function() {
2923 this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
2924 };
2925
2926 /**
2927 * Evaluates an attribute expression against the parent scope.
2928 * @param {String} attr Name of the attribute to be evaluated.
2929 */
2930 DatePickerCtrl.prototype.evalAttr = function(attr) {
2931 if (this.$attrs[attr]) {
2932 this.$scope.$parent.$eval(this.$attrs[attr]);
2933 }
2934 };
2935
2936 /**
2937 * Sets the ng-model value by first converting the date object into a strng. Converting it
2938 * is necessary, in order to pass Angular's `input[type="date"]` validations. Angular turns
2939 * the value into a Date object afterwards, before setting it on the model.
2940 * @param {Date=} value Date to be set as the model value.
2941 */
2942 DatePickerCtrl.prototype.setModelValue = function(value) {
2943 this.ngModelCtrl.$setViewValue(this.ngDateFilter(value, 'yyyy-MM-dd'));
2944 };
2945})();
2946
2947})(window, window.angular);