2  * Angular Material Design
 
   3  * https://github.com/angular/material
 
   7 goog.provide('ngmaterial.components.datepicker');
 
   8 goog.require('ngmaterial.components.icon');
 
   9 goog.require('ngmaterial.components.virtualRepeat');
 
  10 goog.require('ngmaterial.core');
 
  13  * @name material.components.datepicker
 
  14  * @description Module for the datepicker component.
 
  17 angular.module('material.components.datepicker', [
 
  19   'material.components.icon',
 
  20   'material.components.virtualRepeat'
 
  29    * @module material.components.datepicker
 
  31    * @param {Date} ng-model The component's model. Should be a Date object.
 
  32    * @param {Date=} md-min-date Expression representing the minimum date.
 
  33    * @param {Date=} md-max-date Expression representing the maximum date.
 
  34    * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
 
  37    * `<md-calendar>` is a component that renders a calendar that can be used to select a date.
 
  38    * It is a part of the `<md-datepicker` pane, however it can also be used on it's own.
 
  43    *   <md-calendar ng-model="birthday"></md-calendar>
 
  46   CalendarCtrl['$inject'] = ["$element", "$scope", "$$mdDateUtil", "$mdUtil", "$mdConstant", "$mdTheming", "$$rAF", "$attrs", "$mdDateLocale"];
 
  47   angular.module('material.components.datepicker')
 
  48     .directive('mdCalendar', calendarDirective);
 
  51   // TODO(jelbourn): Mac Cmd + left / right == Home / End
 
  52   // TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
 
  53   // TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
 
  54   // TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
 
  55   // TODO(jelbourn): Scroll snapping (virtual repeat)
 
  56   // TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
 
  57   // TODO(jelbourn): Month headers stick to top when scrolling.
 
  58   // TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
 
  59   // TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
 
  60   //     announcement and key handling).
 
  61   // Read-only calendar (not just date-picker).
 
  63   function calendarDirective() {
 
  65       template: function(tElement, tAttr) {
 
  66         // TODO(crisbeto): This is a workaround that allows the calendar to work, without
 
  67         // a datepicker, until issue #8585 gets resolved. It can safely be removed
 
  68         // afterwards. This ensures that the virtual repeater scrolls to the proper place on load by
 
  69         // deferring the execution until the next digest. It's necessary only if the calendar is used
 
  70         // without a datepicker, otherwise it's already wrapped in an ngIf.
 
  71         var extraAttrs = tAttr.hasOwnProperty('ngIf') ? '' : 'ng-if="calendarCtrl.isInitialized"';
 
  73           '<div ng-switch="calendarCtrl.currentView" ' + extraAttrs + '>' +
 
  74             '<md-calendar-year ng-switch-when="year"></md-calendar-year>' +
 
  75             '<md-calendar-month ng-switch-default></md-calendar-month>' +
 
  81         minDate: '=mdMinDate',
 
  82         maxDate: '=mdMaxDate',
 
  83         dateFilter: '=mdDateFilter',
 
  84         _currentView: '@mdCurrentView'
 
  86       require: ['ngModel', 'mdCalendar'],
 
  87       controller: CalendarCtrl,
 
  88       controllerAs: 'calendarCtrl',
 
  89       bindToController: true,
 
  90       link: function(scope, element, attrs, controllers) {
 
  91         var ngModelCtrl = controllers[0];
 
  92         var mdCalendarCtrl = controllers[1];
 
  93         mdCalendarCtrl.configureNgModel(ngModelCtrl);
 
  99    * Occasionally the hideVerticalScrollbar method might read an element's
 
 100    * width as 0, because it hasn't been laid out yet. This value will be used
 
 101    * as a fallback, in order to prevent scenarios where the element's width
 
 102    * would otherwise have been set to 0. This value is the "usual" width of a
 
 103    * calendar within a floating calendar pane.
 
 105   var FALLBACK_WIDTH = 340;
 
 107   /** Next identifier for calendar instance. */
 
 108   var nextUniqueId = 0;
 
 111    * Controller for the mdCalendar component.
 
 112    * ngInject @constructor
 
 114   function CalendarCtrl($element, $scope, $$mdDateUtil, $mdUtil,
 
 115     $mdConstant, $mdTheming, $$rAF, $attrs, $mdDateLocale) {
 
 117     $mdTheming($element);
 
 119     /** @final {!angular.JQLite} */
 
 120     this.$element = $element;
 
 122     /** @final {!angular.Scope} */
 
 123     this.$scope = $scope;
 
 126     this.dateUtil = $$mdDateUtil;
 
 129     this.$mdUtil = $mdUtil;
 
 132     this.keyCode = $mdConstant.KEY_CODE;
 
 138     this.$mdDateLocale = $mdDateLocale;
 
 141     this.today = this.dateUtil.createDateAtMidnight();
 
 143     /** @type {!angular.NgModelController} */
 
 144     this.ngModelCtrl = null;
 
 146     /** @type {String} Class applied to the selected date cell. */
 
 147     this.SELECTED_DATE_CLASS = 'md-calendar-selected-date';
 
 149     /** @type {String} Class applied to the cell for today. */
 
 150     this.TODAY_CLASS = 'md-calendar-date-today';
 
 152     /** @type {String} Class applied to the focused cell. */
 
 153     this.FOCUSED_DATE_CLASS = 'md-focus';
 
 155     /** @final {number} Unique ID for this calendar instance. */
 
 156     this.id = nextUniqueId++;
 
 159      * The date that is currently focused or showing in the calendar. This will initially be set
 
 160      * to the ng-model value if set, otherwise to today. It will be updated as the user navigates
 
 161      * to other months. The cell corresponding to the displayDate does not necesarily always have
 
 162      * focus in the document (such as for cases when the user is scrolling the calendar).
 
 165     this.displayDate = null;
 
 168      * The selected date. Keep track of this separately from the ng-model value so that we
 
 169      * can know, when the ng-model value changes, what the previous value was before it's updated
 
 170      * in the component's UI.
 
 174     this.selectedDate = null;
 
 177      * The first date that can be rendered by the calendar. The default is taken
 
 178      * from the mdDateLocale provider and is limited by the mdMinDate.
 
 181     this.firstRenderableDate = null;
 
 184      * The last date that can be rendered by the calendar. The default comes
 
 185      * from the mdDateLocale provider and is limited by the maxDate.
 
 188     this.lastRenderableDate = null;
 
 191      * Used to toggle initialize the root element in the next digest.
 
 194     this.isInitialized = false;
 
 197      * Cache for the  width of the element without a scrollbar. Used to hide the scrollbar later on
 
 198      * and to avoid extra reflows when switching between views.
 
 204      * Caches the width of the scrollbar in order to be used when hiding it and to avoid extra reflows.
 
 207     this.scrollbarWidth = 0;
 
 209     // Unless the user specifies so, the calendar should not be a tab stop.
 
 210     // This is necessary because ngAria might add a tabindex to anything with an ng-model
 
 211     // (based on whether or not the user has turned that particular feature on/off).
 
 212     if (!$attrs.tabindex) {
 
 213       $element.attr('tabindex', '-1');
 
 216     var boundKeyHandler = angular.bind(this, this.handleKeyEvent);
 
 220     // If use the md-calendar directly in the body without datepicker,
 
 221     // handleKeyEvent will disable other inputs on the page.
 
 222     // So only apply the handleKeyEvent on the body when the md-calendar inside datepicker,
 
 223     // otherwise apply on the calendar element only.
 
 225     var handleKeyElement;
 
 226     if ($element.parent().hasClass('md-datepicker-calendar')) {
 
 227       handleKeyElement = angular.element(document.body);
 
 229       handleKeyElement = $element;
 
 232     // Bind the keydown handler to the body, in order to handle cases where the focused
 
 233     // element gets removed from the DOM and stops propagating click events.
 
 234     handleKeyElement.on('keydown', boundKeyHandler);
 
 236     $scope.$on('$destroy', function() {
 
 237       handleKeyElement.off('keydown', boundKeyHandler);
 
 240     // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
 
 241     // manually call the $onInit hook.
 
 242     if (angular.version.major === 1 && angular.version.minor <= 4) {
 
 249    * Angular Lifecycle hook for newer Angular versions.
 
 250    * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
 
 252   CalendarCtrl.prototype.$onInit = function() {
 
 255      * The currently visible calendar view. Note the prefix on the scope value,
 
 256      * which is necessary, because the datepicker seems to reset the real one value if the
 
 257      * calendar is open, but the value on the datepicker's scope is empty.
 
 260     this.currentView = this._currentView || 'month';
 
 262     var dateLocale = this.$mdDateLocale;
 
 264     if (this.minDate && this.minDate > dateLocale.firstRenderableDate) {
 
 265       this.firstRenderableDate = this.minDate;
 
 267       this.firstRenderableDate = dateLocale.firstRenderableDate;
 
 270     if (this.maxDate && this.maxDate < dateLocale.lastRenderableDate) {
 
 271       this.lastRenderableDate = this.maxDate;
 
 273       this.lastRenderableDate = dateLocale.lastRenderableDate;
 
 278    * Sets up the controller's reference to ngModelController.
 
 279    * @param {!angular.NgModelController} ngModelCtrl
 
 281   CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
 
 284     self.ngModelCtrl = ngModelCtrl;
 
 286     self.$mdUtil.nextTick(function() {
 
 287       self.isInitialized = true;
 
 290     ngModelCtrl.$render = function() {
 
 291       var value = this.$viewValue;
 
 293       // Notify the child scopes of any changes.
 
 294       self.$scope.$broadcast('md-calendar-parent-changed', value);
 
 296       // Set up the selectedDate if it hasn't been already.
 
 297       if (!self.selectedDate) {
 
 298         self.selectedDate = value;
 
 301       // Also set up the displayDate.
 
 302       if (!self.displayDate) {
 
 303         self.displayDate = self.selectedDate || self.today;
 
 309    * Sets the ng-model value for the calendar and emits a change event.
 
 312   CalendarCtrl.prototype.setNgModelValue = function(date) {
 
 313     var value = this.dateUtil.createDateAtMidnight(date);
 
 315     this.$scope.$emit('md-calendar-change', value);
 
 316     this.ngModelCtrl.$setViewValue(value);
 
 317     this.ngModelCtrl.$render();
 
 322    * Sets the current view that should be visible in the calendar
 
 323    * @param {string} newView View name to be set.
 
 324    * @param {number|Date} time Date object or a timestamp for the new display date.
 
 326   CalendarCtrl.prototype.setCurrentView = function(newView, time) {
 
 329     self.$mdUtil.nextTick(function() {
 
 330       self.currentView = newView;
 
 333         self.displayDate = angular.isDate(time) ? time : new Date(time);
 
 339    * Focus the cell corresponding to the given date.
 
 340    * @param {Date} date The date to be focused.
 
 342   CalendarCtrl.prototype.focus = function(date) {
 
 343     if (this.dateUtil.isValidDate(date)) {
 
 344       var previousFocus = this.$element[0].querySelector('.md-focus');
 
 346         previousFocus.classList.remove(this.FOCUSED_DATE_CLASS);
 
 349       var cellId = this.getDateId(date, this.currentView);
 
 350       var cell = document.getElementById(cellId);
 
 352         cell.classList.add(this.FOCUSED_DATE_CLASS);
 
 354         this.displayDate = date;
 
 357       var rootElement = this.$element[0].querySelector('[ng-switch]');
 
 366    * Normalizes the key event into an action name. The action will be broadcast
 
 367    * to the child controllers.
 
 368    * @param {KeyboardEvent} event
 
 369    * @returns {String} The action that should be taken, or null if the key
 
 370    * does not match a calendar shortcut.
 
 372   CalendarCtrl.prototype.getActionFromKeyEvent = function(event) {
 
 373     var keyCode = this.keyCode;
 
 375     switch (event.which) {
 
 376       case keyCode.ENTER: return 'select';
 
 378       case keyCode.RIGHT_ARROW: return 'move-right';
 
 379       case keyCode.LEFT_ARROW: return 'move-left';
 
 381       // TODO(crisbeto): Might want to reconsider using metaKey, because it maps
 
 382       // to the "Windows" key on PC, which opens the start menu or resizes the browser.
 
 383       case keyCode.DOWN_ARROW: return event.metaKey ? 'move-page-down' : 'move-row-down';
 
 384       case keyCode.UP_ARROW: return event.metaKey ? 'move-page-up' : 'move-row-up';
 
 386       case keyCode.PAGE_DOWN: return 'move-page-down';
 
 387       case keyCode.PAGE_UP: return 'move-page-up';
 
 389       case keyCode.HOME: return 'start';
 
 390       case keyCode.END: return 'end';
 
 392       default: return null;
 
 397    * Handles a key event in the calendar with the appropriate action. The action will either
 
 398    * be to select the focused date or to navigate to focus a new date.
 
 399    * @param {KeyboardEvent} event
 
 401   CalendarCtrl.prototype.handleKeyEvent = function(event) {
 
 404     this.$scope.$apply(function() {
 
 405       // Capture escape and emit back up so that a wrapping component
 
 406       // (such as a date-picker) can decide to close.
 
 407       if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
 
 408         self.$scope.$emit('md-calendar-close');
 
 410         if (event.which == self.keyCode.TAB) {
 
 411           event.preventDefault();
 
 417       // Broadcast the action that any child controllers should take.
 
 418       var action = self.getActionFromKeyEvent(event);
 
 420         event.preventDefault();
 
 421         event.stopPropagation();
 
 422         self.$scope.$broadcast('md-calendar-parent-action', action);
 
 428    * Hides the vertical scrollbar on the calendar scroller of a child controller by
 
 429    * setting the width on the calendar scroller and the `overflow: hidden` wrapper
 
 430    * around the scroller, and then setting a padding-right on the scroller equal
 
 431    * to the width of the browser's scrollbar.
 
 433    * This will cause a reflow.
 
 435    * @param {object} childCtrl The child controller whose scrollbar should be hidden.
 
 437   CalendarCtrl.prototype.hideVerticalScrollbar = function(childCtrl) {
 
 439     var element = childCtrl.$element[0];
 
 440     var scrollMask = element.querySelector('.md-calendar-scroll-mask');
 
 442     if (self.width > 0) {
 
 445       self.$$rAF(function() {
 
 446         var scroller = childCtrl.calendarScroller;
 
 448         self.scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
 
 449         self.width = element.querySelector('table').offsetWidth;
 
 454     function setWidth() {
 
 455       var width = self.width || FALLBACK_WIDTH;
 
 456       var scrollbarWidth = self.scrollbarWidth;
 
 457       var scroller = childCtrl.calendarScroller;
 
 459       scrollMask.style.width = width + 'px';
 
 460       scroller.style.width = (width + scrollbarWidth) + 'px';
 
 461       scroller.style.paddingRight = scrollbarWidth + 'px';
 
 466    * Gets an identifier for a date unique to the calendar instance for internal
 
 467    * purposes. Not to be displayed.
 
 468    * @param {Date} date The date for which the id is being generated
 
 469    * @param {string} namespace Namespace for the id. (month, year etc.)
 
 472   CalendarCtrl.prototype.getDateId = function(date, namespace) {
 
 474       throw new Error('A namespace for the date id has to be specified.');
 
 488    * Util to trigger an extra digest on a parent scope, in order to to ensure that
 
 489    * any child virtual repeaters have updated. This is necessary, because the virtual
 
 490    * repeater doesn't update the $index the first time around since the content isn't
 
 491    * in place yet. The case, in which this is an issue, is when the repeater has less
 
 492    * than a page of content (e.g. a month or year view has a min or max date).
 
 494   CalendarCtrl.prototype.updateVirtualRepeat = function() {
 
 495     var scope = this.$scope;
 
 496     var virtualRepeatResizeListener = scope.$on('$md-resize-enable', function() {
 
 497       if (!scope.$$phase) {
 
 501       virtualRepeatResizeListener();
 
 509   CalendarMonthCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil", "$mdDateLocale"];
 
 510   angular.module('material.components.datepicker')
 
 511     .directive('mdCalendarMonth', calendarDirective);
 
 514    * Height of one calendar month tbody. This must be made known to the virtual-repeat and is
 
 515    * subsequently used for scrolling to specific months.
 
 517   var TBODY_HEIGHT = 265;
 
 520    * Height of a calendar month with a single row. This is needed to calculate the offset for
 
 521    * rendering an extra month in virtual-repeat that only contains one row.
 
 523   var TBODY_SINGLE_ROW_HEIGHT = 45;
 
 525   /** Private directive that represents a list of months inside the calendar. */
 
 526   function calendarDirective() {
 
 529         '<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
 
 530         '<div class="md-calendar-scroll-mask">' +
 
 531         '<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
 
 532               'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
 
 533             '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
 
 535                   'md-calendar-month-body ' +
 
 537                   'md-virtual-repeat="i in monthCtrl.items" ' +
 
 538                   'md-month-offset="$index" ' +
 
 539                   'class="md-calendar-month" ' +
 
 540                   'md-start-index="monthCtrl.getSelectedMonthIndex()" ' +
 
 541                   'md-item-size="' + TBODY_HEIGHT + '">' +
 
 543                 // The <tr> ensures that the <tbody> will always have the
 
 544                 // proper height, even if it's empty. If it's content is
 
 545                 // compiled, the <tr> will be overwritten.
 
 546                 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
 
 549           '</md-virtual-repeat-container>' +
 
 551       require: ['^^mdCalendar', 'mdCalendarMonth'],
 
 552       controller: CalendarMonthCtrl,
 
 553       controllerAs: 'monthCtrl',
 
 554       bindToController: true,
 
 555       link: function(scope, element, attrs, controllers) {
 
 556         var calendarCtrl = controllers[0];
 
 557         var monthCtrl = controllers[1];
 
 558         monthCtrl.initialize(calendarCtrl);
 
 564    * Controller for the calendar month component.
 
 565    * ngInject @constructor
 
 567   function CalendarMonthCtrl($element, $scope, $animate, $q,
 
 568     $$mdDateUtil, $mdDateLocale) {
 
 570     /** @final {!angular.JQLite} */
 
 571     this.$element = $element;
 
 573     /** @final {!angular.Scope} */
 
 574     this.$scope = $scope;
 
 576     /** @final {!angular.$animate} */
 
 577     this.$animate = $animate;
 
 579     /** @final {!angular.$q} */
 
 583     this.dateUtil = $$mdDateUtil;
 
 586     this.dateLocale = $mdDateLocale;
 
 588     /** @final {HTMLElement} */
 
 589     this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
 
 591     /** @type {boolean} */
 
 592     this.isInitialized = false;
 
 594     /** @type {boolean} */
 
 595     this.isMonthTransitionInProgress = false;
 
 600      * Handles a click event on a date cell.
 
 601      * Created here so that every cell can use the same function instance.
 
 602      * @this {HTMLTableCellElement} The cell that was clicked.
 
 604     this.cellClickHandler = function() {
 
 605       var timestamp = $$mdDateUtil.getTimestampFromNode(this);
 
 606       self.$scope.$apply(function() {
 
 607         self.calendarCtrl.setNgModelValue(timestamp);
 
 612      * Handles click events on the month headers. Switches
 
 613      * the calendar to the year view.
 
 614      * @this {HTMLTableCellElement} The cell that was clicked.
 
 616     this.headerClickHandler = function() {
 
 617       self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
 
 621   /*** Initialization ***/
 
 624    * Initialize the controller by saving a reference to the calendar and
 
 625    * setting up the object that will be iterated by the virtual repeater.
 
 627   CalendarMonthCtrl.prototype.initialize = function(calendarCtrl) {
 
 629      * Dummy array-like object for virtual-repeat to iterate over. The length is the total
 
 630      * number of months that can be viewed. We add 2 months: one to include the current month
 
 631      * and one for the last dummy month.
 
 633      * This is shorter than ideal because of a (potential) Firefox bug
 
 634      * https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
 
 638       length: this.dateUtil.getMonthDistance(
 
 639         calendarCtrl.firstRenderableDate,
 
 640         calendarCtrl.lastRenderableDate
 
 644     this.calendarCtrl = calendarCtrl;
 
 645     this.attachScopeListeners();
 
 646     calendarCtrl.updateVirtualRepeat();
 
 648     // Fire the initial render, since we might have missed it the first time it fired.
 
 649     calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
 
 653    * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
 
 656   CalendarMonthCtrl.prototype.getSelectedMonthIndex = function() {
 
 657     var calendarCtrl = this.calendarCtrl;
 
 659     return this.dateUtil.getMonthDistance(
 
 660       calendarCtrl.firstRenderableDate,
 
 661       calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
 
 666    * Change the selected date in the calendar (ngModel value has already been changed).
 
 669   CalendarMonthCtrl.prototype.changeSelectedDate = function(date) {
 
 671     var calendarCtrl = self.calendarCtrl;
 
 672     var previousSelectedDate = calendarCtrl.selectedDate;
 
 673     calendarCtrl.selectedDate = date;
 
 675     this.changeDisplayDate(date).then(function() {
 
 676       var selectedDateClass = calendarCtrl.SELECTED_DATE_CLASS;
 
 677       var namespace = 'month';
 
 679       // Remove the selected class from the previously selected date, if any.
 
 680       if (previousSelectedDate) {
 
 681         var prevDateCell = document.getElementById(calendarCtrl.getDateId(previousSelectedDate, namespace));
 
 683           prevDateCell.classList.remove(selectedDateClass);
 
 684           prevDateCell.setAttribute('aria-selected', 'false');
 
 688       // Apply the select class to the new selected date if it is set.
 
 690         var dateCell = document.getElementById(calendarCtrl.getDateId(date, namespace));
 
 692           dateCell.classList.add(selectedDateClass);
 
 693           dateCell.setAttribute('aria-selected', 'true');
 
 700    * Change the date that is being shown in the calendar. If the given date is in a different
 
 701    * month, the displayed month will be transitioned.
 
 704   CalendarMonthCtrl.prototype.changeDisplayDate = function(date) {
 
 705     // Initialization is deferred until this function is called because we want to reflect
 
 706     // the starting value of ngModel.
 
 707     if (!this.isInitialized) {
 
 708       this.buildWeekHeader();
 
 709       this.calendarCtrl.hideVerticalScrollbar(this);
 
 710       this.isInitialized = true;
 
 711       return this.$q.when();
 
 714     // If trying to show an invalid date or a transition is in progress, do nothing.
 
 715     if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
 
 716       return this.$q.when();
 
 719     this.isMonthTransitionInProgress = true;
 
 720     var animationPromise = this.animateDateChange(date);
 
 722     this.calendarCtrl.displayDate = date;
 
 725     animationPromise.then(function() {
 
 726       self.isMonthTransitionInProgress = false;
 
 729     return animationPromise;
 
 733    * Animates the transition from the calendar's current month to the given month.
 
 735    * @returns {angular.$q.Promise} The animation promise.
 
 737   CalendarMonthCtrl.prototype.animateDateChange = function(date) {
 
 738     if (this.dateUtil.isValidDate(date)) {
 
 739       var monthDistance = this.dateUtil.getMonthDistance(this.calendarCtrl.firstRenderableDate, date);
 
 740       this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
 
 743     return this.$q.when();
 
 747    * Builds and appends a day-of-the-week header to the calendar.
 
 748    * This should only need to be called once during initialization.
 
 750   CalendarMonthCtrl.prototype.buildWeekHeader = function() {
 
 751     var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
 
 752     var shortDays = this.dateLocale.shortDays;
 
 754     var row = document.createElement('tr');
 
 755     for (var i = 0; i < 7; i++) {
 
 756       var th = document.createElement('th');
 
 757       th.textContent = shortDays[(i + firstDayOfWeek) % 7];
 
 761     this.$element.find('thead').append(row);
 
 765    * Attaches listeners for the scope events that are broadcast by the calendar.
 
 767   CalendarMonthCtrl.prototype.attachScopeListeners = function() {
 
 770     self.$scope.$on('md-calendar-parent-changed', function(event, value) {
 
 771       self.changeSelectedDate(value);
 
 774     self.$scope.$on('md-calendar-parent-action', angular.bind(this, this.handleKeyEvent));
 
 778    * Handles the month-specific keyboard interactions.
 
 779    * @param {Object} event Scope event object passed by the calendar.
 
 780    * @param {String} action Action, corresponding to the key that was pressed.
 
 782   CalendarMonthCtrl.prototype.handleKeyEvent = function(event, action) {
 
 783     var calendarCtrl = this.calendarCtrl;
 
 784     var displayDate = calendarCtrl.displayDate;
 
 786     if (action === 'select') {
 
 787       calendarCtrl.setNgModelValue(displayDate);
 
 790       var dateUtil = this.dateUtil;
 
 793         case 'move-right': date = dateUtil.incrementDays(displayDate, 1); break;
 
 794         case 'move-left': date = dateUtil.incrementDays(displayDate, -1); break;
 
 796         case 'move-page-down': date = dateUtil.incrementMonths(displayDate, 1); break;
 
 797         case 'move-page-up': date = dateUtil.incrementMonths(displayDate, -1); break;
 
 799         case 'move-row-down': date = dateUtil.incrementDays(displayDate, 7); break;
 
 800         case 'move-row-up': date = dateUtil.incrementDays(displayDate, -7); break;
 
 802         case 'start': date = dateUtil.getFirstDateOfMonth(displayDate); break;
 
 803         case 'end': date = dateUtil.getLastDateOfMonth(displayDate); break;
 
 807         date = this.dateUtil.clampDate(date, calendarCtrl.minDate, calendarCtrl.maxDate);
 
 809         this.changeDisplayDate(date).then(function() {
 
 810           calendarCtrl.focus(date);
 
 820   mdCalendarMonthBodyDirective['$inject'] = ["$compile", "$$mdSvgRegistry"];
 
 821   CalendarMonthBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
 
 822   angular.module('material.components.datepicker')
 
 823       .directive('mdCalendarMonthBody', mdCalendarMonthBodyDirective);
 
 826    * Private directive consumed by md-calendar-month. Having this directive lets the calender use
 
 827    * md-virtual-repeat and also cleanly separates the month DOM construction functions from
 
 828    * the rest of the calendar controller logic.
 
 831   function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
 
 832     var ARROW_ICON = $compile('<md-icon md-svg-src="' +
 
 833       $$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
 
 836       require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
 
 837       scope: { offset: '=mdMonthOffset' },
 
 838       controller: CalendarMonthBodyCtrl,
 
 839       controllerAs: 'mdMonthBodyCtrl',
 
 840       bindToController: true,
 
 841       link: function(scope, element, attrs, controllers) {
 
 842         var calendarCtrl = controllers[0];
 
 843         var monthCtrl = controllers[1];
 
 844         var monthBodyCtrl = controllers[2];
 
 846         monthBodyCtrl.calendarCtrl = calendarCtrl;
 
 847         monthBodyCtrl.monthCtrl = monthCtrl;
 
 848         monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
 
 850         // The virtual-repeat re-uses the same DOM elements, so there are only a limited number
 
 851         // of repeated items that are linked, and then those elements have their bindings updated.
 
 852         // Since the months are not generated by bindings, we simply regenerate the entire thing
 
 853         // when the binding (offset) changes.
 
 854         scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset) {
 
 855           if (angular.isNumber(offset)) {
 
 856             monthBodyCtrl.generateContent();
 
 864    * Controller for a single calendar month.
 
 865    * ngInject @constructor
 
 867   function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
 
 868     /** @final {!angular.JQLite} */
 
 869     this.$element = $element;
 
 872     this.dateUtil = $$mdDateUtil;
 
 875     this.dateLocale = $mdDateLocale;
 
 877     /** @type {Object} Reference to the month view. */
 
 878     this.monthCtrl = null;
 
 880     /** @type {Object} Reference to the calendar. */
 
 881     this.calendarCtrl = null;
 
 884      * Number of months from the start of the month "items" that the currently rendered month
 
 885      * occurs. Set via angular data binding.
 
 891      * Date cell to focus after appending the month to the document.
 
 892      * @type {HTMLElement}
 
 894     this.focusAfterAppend = null;
 
 897   /** Generate and append the content for this month to the directive element. */
 
 898   CalendarMonthBodyCtrl.prototype.generateContent = function() {
 
 899     var date = this.dateUtil.incrementMonths(this.calendarCtrl.firstRenderableDate, this.offset);
 
 903       .append(this.buildCalendarForMonth(date));
 
 905     if (this.focusAfterAppend) {
 
 906       this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
 
 907       this.focusAfterAppend.focus();
 
 908       this.focusAfterAppend = null;
 
 913    * Creates a single cell to contain a date in the calendar with all appropriate
 
 914    * attributes and classes added. If a date is given, the cell content will be set
 
 916    * @param {Date=} opt_date
 
 917    * @returns {HTMLElement}
 
 919   CalendarMonthBodyCtrl.prototype.buildDateCell = function(opt_date) {
 
 920     var monthCtrl = this.monthCtrl;
 
 921     var calendarCtrl = this.calendarCtrl;
 
 923     // TODO(jelbourn): cloneNode is likely a faster way of doing this.
 
 924     var cell = document.createElement('td');
 
 926     cell.classList.add('md-calendar-date');
 
 927     cell.setAttribute('role', 'gridcell');
 
 930       cell.setAttribute('tabindex', '-1');
 
 931       cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
 
 932       cell.id = calendarCtrl.getDateId(opt_date, 'month');
 
 934       // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
 
 935       cell.setAttribute('data-timestamp', opt_date.getTime());
 
 937       // TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
 
 938       // It may be better to finish the construction and then query the node and add the class.
 
 939       if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
 
 940         cell.classList.add(calendarCtrl.TODAY_CLASS);
 
 943       if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
 
 944           this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
 
 945         cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
 
 946         cell.setAttribute('aria-selected', 'true');
 
 949       var cellText = this.dateLocale.dates[opt_date.getDate()];
 
 951       if (this.isDateEnabled(opt_date)) {
 
 952         // Add a indicator for select, hover, and focus states.
 
 953         var selectionIndicator = document.createElement('span');
 
 954         selectionIndicator.classList.add('md-calendar-date-selection-indicator');
 
 955         selectionIndicator.textContent = cellText;
 
 956         cell.appendChild(selectionIndicator);
 
 957         cell.addEventListener('click', monthCtrl.cellClickHandler);
 
 959         if (calendarCtrl.displayDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.displayDate)) {
 
 960           this.focusAfterAppend = cell;
 
 963         cell.classList.add('md-calendar-date-disabled');
 
 964         cell.textContent = cellText;
 
 972    * Check whether date is in range and enabled
 
 973    * @param {Date=} opt_date
 
 974    * @return {boolean} Whether the date is enabled.
 
 976   CalendarMonthBodyCtrl.prototype.isDateEnabled = function(opt_date) {
 
 977     return this.dateUtil.isDateWithinRange(opt_date,
 
 978           this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
 
 979           (!angular.isFunction(this.calendarCtrl.dateFilter)
 
 980            || this.calendarCtrl.dateFilter(opt_date));
 
 984    * Builds a `tr` element for the calendar grid.
 
 985    * @param rowNumber The week number within the month.
 
 986    * @returns {HTMLElement}
 
 988   CalendarMonthBodyCtrl.prototype.buildDateRow = function(rowNumber) {
 
 989     var row = document.createElement('tr');
 
 990     row.setAttribute('role', 'row');
 
 992     // Because of an NVDA bug (with Firefox), the row needs an aria-label in order
 
 993     // to prevent the entire row being read aloud when the user moves between rows.
 
 994     // See http://community.nvda-project.org/ticket/4643.
 
 995     row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
 
1001    * Builds the <tbody> content for the given date's month.
 
1002    * @param {Date=} opt_dateInMonth
 
1003    * @returns {DocumentFragment} A document fragment containing the <tr> elements.
 
1005   CalendarMonthBodyCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
 
1006     var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
 
1008     var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
 
1009     var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
 
1010     var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
 
1012     // Store rows for the month in a document fragment so that we can append them all at once.
 
1013     var monthBody = document.createDocumentFragment();
 
1016     var row = this.buildDateRow(rowNumber);
 
1017     monthBody.appendChild(row);
 
1019     // If this is the final month in the list of items, only the first week should render,
 
1020     // so we should return immediately after the first row is complete and has been
 
1021     // attached to the body.
 
1022     var isFinalMonth = this.offset === this.monthCtrl.items.length - 1;
 
1024     // Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
 
1025     // goes on a row above the first of the month. Otherwise, the month label takes up the first
 
1026     // two cells of the first row.
 
1027     var blankCellOffset = 0;
 
1028     var monthLabelCell = document.createElement('td');
 
1029     var monthLabelCellContent = document.createElement('span');
 
1031     monthLabelCellContent.textContent = this.dateLocale.monthHeaderFormatter(date);
 
1032     monthLabelCell.appendChild(monthLabelCellContent);
 
1033     monthLabelCell.classList.add('md-calendar-month-label');
 
1034     // If the entire month is after the max date, render the label as a disabled state.
 
1035     if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
 
1036       monthLabelCell.classList.add('md-calendar-month-label-disabled');
 
1038       monthLabelCell.addEventListener('click', this.monthCtrl.headerClickHandler);
 
1039       monthLabelCell.setAttribute('data-timestamp', firstDayOfMonth.getTime());
 
1040       monthLabelCell.setAttribute('aria-label', this.dateLocale.monthFormatter(date));
 
1041       monthLabelCell.appendChild(this.arrowIcon.cloneNode(true));
 
1044     if (firstDayOfTheWeek <= 2) {
 
1045       monthLabelCell.setAttribute('colspan', '7');
 
1047       var monthLabelRow = this.buildDateRow();
 
1048       monthLabelRow.appendChild(monthLabelCell);
 
1049       monthBody.insertBefore(monthLabelRow, row);
 
1055       blankCellOffset = 3;
 
1056       monthLabelCell.setAttribute('colspan', '3');
 
1057       row.appendChild(monthLabelCell);
 
1060     // Add a blank cell for each day of the week that occurs before the first of the month.
 
1061     // For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
 
1062     // The blankCellOffset is needed in cases where the first N cells are used by the month label.
 
1063     for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
 
1064       row.appendChild(this.buildDateCell());
 
1067     // Add a cell for each day of the month, keeping track of the day of the week so that
 
1068     // we know when to start a new row.
 
1069     var dayOfWeek = firstDayOfTheWeek;
 
1070     var iterationDate = firstDayOfMonth;
 
1071     for (var d = 1; d <= numberOfDaysInMonth; d++) {
 
1072       // If we've reached the end of the week, start a new row.
 
1073       if (dayOfWeek === 7) {
 
1074         // We've finished the first row, so we're done if this is the final month.
 
1080         row = this.buildDateRow(rowNumber);
 
1081         monthBody.appendChild(row);
 
1084       iterationDate.setDate(d);
 
1085       var cell = this.buildDateCell(iterationDate);
 
1086       row.appendChild(cell);
 
1091     // Ensure that the last row of the month has 7 cells.
 
1092     while (row.childNodes.length < 7) {
 
1093       row.appendChild(this.buildDateCell());
 
1096     // Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
 
1097     // requires that all items have exactly the same height.
 
1098     while (monthBody.childNodes.length < 6) {
 
1099       var whitespaceRow = this.buildDateRow();
 
1100       for (var j = 0; j < 7; j++) {
 
1101         whitespaceRow.appendChild(this.buildDateCell());
 
1103       monthBody.appendChild(whitespaceRow);
 
1110    * Gets the day-of-the-week index for a date for the current locale.
 
1112    * @param {Date} date
 
1113    * @returns {number} The column index of the date in the calendar.
 
1115   CalendarMonthBodyCtrl.prototype.getLocaleDay_ = function(date) {
 
1116     return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7;
 
1123   CalendarYearCtrl['$inject'] = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil"];
 
1124   angular.module('material.components.datepicker')
 
1125     .directive('mdCalendarYear', calendarDirective);
 
1128    * Height of one calendar year tbody. This must be made known to the virtual-repeat and is
 
1129    * subsequently used for scrolling to specific years.
 
1131   var TBODY_HEIGHT = 88;
 
1133   /** Private component, representing a list of years in the calendar. */
 
1134   function calendarDirective() {
 
1137         '<div class="md-calendar-scroll-mask">' +
 
1138           '<md-virtual-repeat-container class="md-calendar-scroll-container">' +
 
1139             '<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
 
1141                   'md-calendar-year-body ' +
 
1142                   'role="rowgroup" ' +
 
1143                   'md-virtual-repeat="i in yearCtrl.items" ' +
 
1144                   'md-year-offset="$index" class="md-calendar-year" ' +
 
1145                   'md-start-index="yearCtrl.getFocusedYearIndex()" ' +
 
1146                   'md-item-size="' + TBODY_HEIGHT + '">' +
 
1147                 // The <tr> ensures that the <tbody> will have the proper
 
1148                 // height, even though it may be empty.
 
1149                 '<tr aria-hidden="true" style="height:' + TBODY_HEIGHT + 'px;"></tr>' +
 
1152           '</md-virtual-repeat-container>' +
 
1154       require: ['^^mdCalendar', 'mdCalendarYear'],
 
1155       controller: CalendarYearCtrl,
 
1156       controllerAs: 'yearCtrl',
 
1157       bindToController: true,
 
1158       link: function(scope, element, attrs, controllers) {
 
1159         var calendarCtrl = controllers[0];
 
1160         var yearCtrl = controllers[1];
 
1161         yearCtrl.initialize(calendarCtrl);
 
1167    * Controller for the mdCalendar component.
 
1168    * ngInject @constructor
 
1170   function CalendarYearCtrl($element, $scope, $animate, $q, $$mdDateUtil) {
 
1172     /** @final {!angular.JQLite} */
 
1173     this.$element = $element;
 
1175     /** @final {!angular.Scope} */
 
1176     this.$scope = $scope;
 
1178     /** @final {!angular.$animate} */
 
1179     this.$animate = $animate;
 
1181     /** @final {!angular.$q} */
 
1185     this.dateUtil = $$mdDateUtil;
 
1187     /** @final {HTMLElement} */
 
1188     this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
 
1190     /** @type {boolean} */
 
1191     this.isInitialized = false;
 
1193     /** @type {boolean} */
 
1194     this.isMonthTransitionInProgress = false;
 
1199      * Handles a click event on a date cell.
 
1200      * Created here so that every cell can use the same function instance.
 
1201      * @this {HTMLTableCellElement} The cell that was clicked.
 
1203     this.cellClickHandler = function() {
 
1204       self.calendarCtrl.setCurrentView('month', $$mdDateUtil.getTimestampFromNode(this));
 
1209    * Initialize the controller by saving a reference to the calendar and
 
1210    * setting up the object that will be iterated by the virtual repeater.
 
1212   CalendarYearCtrl.prototype.initialize = function(calendarCtrl) {
 
1214      * Dummy array-like object for virtual-repeat to iterate over. The length is the total
 
1215      * number of years that can be viewed. We add 1 extra in order to include the current year.
 
1218       length: this.dateUtil.getYearDistance(
 
1219         calendarCtrl.firstRenderableDate,
 
1220         calendarCtrl.lastRenderableDate
 
1224     this.calendarCtrl = calendarCtrl;
 
1225     this.attachScopeListeners();
 
1226     calendarCtrl.updateVirtualRepeat();
 
1228     // Fire the initial render, since we might have missed it the first time it fired.
 
1229     calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
 
1233    * Gets the "index" of the currently selected date as it would be in the virtual-repeat.
 
1236   CalendarYearCtrl.prototype.getFocusedYearIndex = function() {
 
1237     var calendarCtrl = this.calendarCtrl;
 
1239     return this.dateUtil.getYearDistance(
 
1240       calendarCtrl.firstRenderableDate,
 
1241       calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today
 
1246    * Change the date that is highlighted in the calendar.
 
1247    * @param {Date} date
 
1249   CalendarYearCtrl.prototype.changeDate = function(date) {
 
1250     // Initialization is deferred until this function is called because we want to reflect
 
1251     // the starting value of ngModel.
 
1252     if (!this.isInitialized) {
 
1253       this.calendarCtrl.hideVerticalScrollbar(this);
 
1254       this.isInitialized = true;
 
1255       return this.$q.when();
 
1256     } else if (this.dateUtil.isValidDate(date) && !this.isMonthTransitionInProgress) {
 
1258       var animationPromise = this.animateDateChange(date);
 
1260       self.isMonthTransitionInProgress = true;
 
1261       self.calendarCtrl.displayDate = date;
 
1263       return animationPromise.then(function() {
 
1264         self.isMonthTransitionInProgress = false;
 
1270    * Animates the transition from the calendar's current month to the given month.
 
1271    * @param {Date} date
 
1272    * @returns {angular.$q.Promise} The animation promise.
 
1274   CalendarYearCtrl.prototype.animateDateChange = function(date) {
 
1275     if (this.dateUtil.isValidDate(date)) {
 
1276       var monthDistance = this.dateUtil.getYearDistance(this.calendarCtrl.firstRenderableDate, date);
 
1277       this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
 
1280     return this.$q.when();
 
1284    * Handles the year-view-specific keyboard interactions.
 
1285    * @param {Object} event Scope event object passed by the calendar.
 
1286    * @param {String} action Action, corresponding to the key that was pressed.
 
1288   CalendarYearCtrl.prototype.handleKeyEvent = function(event, action) {
 
1289     var calendarCtrl = this.calendarCtrl;
 
1290     var displayDate = calendarCtrl.displayDate;
 
1292     if (action === 'select') {
 
1293       this.changeDate(displayDate).then(function() {
 
1294         calendarCtrl.setCurrentView('month', displayDate);
 
1295         calendarCtrl.focus(displayDate);
 
1299       var dateUtil = this.dateUtil;
 
1302         case 'move-right': date = dateUtil.incrementMonths(displayDate, 1); break;
 
1303         case 'move-left': date = dateUtil.incrementMonths(displayDate, -1); break;
 
1305         case 'move-row-down': date = dateUtil.incrementMonths(displayDate, 6); break;
 
1306         case 'move-row-up': date = dateUtil.incrementMonths(displayDate, -6); break;
 
1310         var min = calendarCtrl.minDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.minDate) : null;
 
1311         var max = calendarCtrl.maxDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.maxDate) : null;
 
1312         date = dateUtil.getFirstDateOfMonth(this.dateUtil.clampDate(date, min, max));
 
1314         this.changeDate(date).then(function() {
 
1315           calendarCtrl.focus(date);
 
1322    * Attaches listeners for the scope events that are broadcast by the calendar.
 
1324   CalendarYearCtrl.prototype.attachScopeListeners = function() {
 
1327     self.$scope.$on('md-calendar-parent-changed', function(event, value) {
 
1328       self.changeDate(value);
 
1331     self.$scope.$on('md-calendar-parent-action', angular.bind(self, self.handleKeyEvent));
 
1338   CalendarYearBodyCtrl['$inject'] = ["$element", "$$mdDateUtil", "$mdDateLocale"];
 
1339   angular.module('material.components.datepicker')
 
1340       .directive('mdCalendarYearBody', mdCalendarYearDirective);
 
1343    * Private component, consumed by the md-calendar-year, which separates the DOM construction logic
 
1344    * and allows for the year view to use md-virtual-repeat.
 
1346   function mdCalendarYearDirective() {
 
1348       require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
 
1349       scope: { offset: '=mdYearOffset' },
 
1350       controller: CalendarYearBodyCtrl,
 
1351       controllerAs: 'mdYearBodyCtrl',
 
1352       bindToController: true,
 
1353       link: function(scope, element, attrs, controllers) {
 
1354         var calendarCtrl = controllers[0];
 
1355         var yearCtrl = controllers[1];
 
1356         var yearBodyCtrl = controllers[2];
 
1358         yearBodyCtrl.calendarCtrl = calendarCtrl;
 
1359         yearBodyCtrl.yearCtrl = yearCtrl;
 
1361         scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset) {
 
1362           if (angular.isNumber(offset)) {
 
1363             yearBodyCtrl.generateContent();
 
1371    * Controller for a single year.
 
1372    * ngInject @constructor
 
1374   function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
 
1375     /** @final {!angular.JQLite} */
 
1376     this.$element = $element;
 
1379     this.dateUtil = $$mdDateUtil;
 
1382     this.dateLocale = $mdDateLocale;
 
1384     /** @type {Object} Reference to the calendar. */
 
1385     this.calendarCtrl = null;
 
1387     /** @type {Object} Reference to the year view. */
 
1388     this.yearCtrl = null;
 
1391      * Number of months from the start of the month "items" that the currently rendered month
 
1392      * occurs. Set via angular data binding.
 
1398      * Date cell to focus after appending the month to the document.
 
1399      * @type {HTMLElement}
 
1401     this.focusAfterAppend = null;
 
1404   /** Generate and append the content for this year to the directive element. */
 
1405   CalendarYearBodyCtrl.prototype.generateContent = function() {
 
1406     var date = this.dateUtil.incrementYears(this.calendarCtrl.firstRenderableDate, this.offset);
 
1410       .append(this.buildCalendarForYear(date));
 
1412     if (this.focusAfterAppend) {
 
1413       this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
 
1414       this.focusAfterAppend.focus();
 
1415       this.focusAfterAppend = null;
 
1420    * Creates a single cell to contain a year in the calendar.
 
1421    * @param {number} opt_year Four-digit year.
 
1422    * @param {number} opt_month Zero-indexed month.
 
1423    * @returns {HTMLElement}
 
1425   CalendarYearBodyCtrl.prototype.buildMonthCell = function(year, month) {
 
1426     var calendarCtrl = this.calendarCtrl;
 
1427     var yearCtrl = this.yearCtrl;
 
1428     var cell = this.buildBlankCell();
 
1430     // Represent this month/year as a date.
 
1431     var firstOfMonth = new Date(year, month, 1);
 
1432     cell.setAttribute('aria-label', this.dateLocale.monthFormatter(firstOfMonth));
 
1433     cell.id = calendarCtrl.getDateId(firstOfMonth, 'year');
 
1435     // Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
 
1436     cell.setAttribute('data-timestamp', firstOfMonth.getTime());
 
1438     if (this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.today)) {
 
1439       cell.classList.add(calendarCtrl.TODAY_CLASS);
 
1442     if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
 
1443         this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.selectedDate)) {
 
1444       cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
 
1445       cell.setAttribute('aria-selected', 'true');
 
1448     var cellText = this.dateLocale.shortMonths[month];
 
1450     if (this.dateUtil.isMonthWithinRange(firstOfMonth,
 
1451         calendarCtrl.minDate, calendarCtrl.maxDate)) {
 
1452       var selectionIndicator = document.createElement('span');
 
1453       selectionIndicator.classList.add('md-calendar-date-selection-indicator');
 
1454       selectionIndicator.textContent = cellText;
 
1455       cell.appendChild(selectionIndicator);
 
1456       cell.addEventListener('click', yearCtrl.cellClickHandler);
 
1458       if (calendarCtrl.displayDate && this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.displayDate)) {
 
1459         this.focusAfterAppend = cell;
 
1462       cell.classList.add('md-calendar-date-disabled');
 
1463       cell.textContent = cellText;
 
1470    * Builds a blank cell.
 
1471    * @return {HTMLTableCellElement}
 
1473   CalendarYearBodyCtrl.prototype.buildBlankCell = function() {
 
1474     var cell = document.createElement('td');
 
1476     cell.classList.add('md-calendar-date');
 
1477     cell.setAttribute('role', 'gridcell');
 
1479     cell.setAttribute('tabindex', '-1');
 
1484    * Builds the <tbody> content for the given year.
 
1485    * @param {Date} date Date for which the content should be built.
 
1486    * @returns {DocumentFragment} A document fragment containing the months within the year.
 
1488   CalendarYearBodyCtrl.prototype.buildCalendarForYear = function(date) {
 
1489     // Store rows for the month in a document fragment so that we can append them all at once.
 
1490     var year = date.getFullYear();
 
1491     var yearBody = document.createDocumentFragment();
 
1494     // First row contains label and Jan-Jun.
 
1495     var firstRow = document.createElement('tr');
 
1496     var labelCell = document.createElement('td');
 
1497     labelCell.className = 'md-calendar-month-label';
 
1498     labelCell.textContent = year;
 
1499     firstRow.appendChild(labelCell);
 
1501     for (i = 0; i < 6; i++) {
 
1502       firstRow.appendChild(this.buildMonthCell(year, i));
 
1504     yearBody.appendChild(firstRow);
 
1506     // Second row contains a blank cell and Jul-Dec.
 
1507     var secondRow = document.createElement('tr');
 
1508     secondRow.appendChild(this.buildBlankCell());
 
1509     for (i = 6; i < 12; i++) {
 
1510       secondRow.appendChild(this.buildMonthCell(year, i));
 
1512     yearBody.appendChild(secondRow);
 
1523    * @name $mdDateLocaleProvider
 
1524    * @module material.components.datepicker
 
1527    * The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
 
1528    * This provider that allows the user to specify messages, formatters, and parsers for date
 
1529    * internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
 
1530    * components that deal with dates.
 
1532    * @property {(Array<string>)=} months Array of month names (in order).
 
1533    * @property {(Array<string>)=} shortMonths Array of abbreviated month names.
 
1534    * @property {(Array<string>)=} days Array of the days of the week (in order).
 
1535    * @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
 
1536    * @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
 
1537    *     using a numeral system other than [1, 2, 3...].
 
1538    * @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
 
1540    * @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
 
1541    * @property {(function(Date, string): string)=} formatDate Function to format a date object to a
 
1542    *     string. The datepicker directive also provides the time zone, if it was specified.
 
1543    * @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
 
1544    *     a month given a date.
 
1545    * @property {(function(Date): string)=} monthFormatter Function that returns the full name of a month
 
1547    * @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
 
1548    *     a week given the week number.
 
1549    * @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
 
1550    * @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
 
1552    * @property {Date=} firstRenderableDate The date from which the datepicker calendar will begin
 
1553    * rendering. Note that this will be ignored if a minimum date is set. Defaults to January 1st 1880.
 
1554    * @property {Date=} lastRenderableDate The last date that will be rendered by the datepicker
 
1555    * calendar. Note that this will be ignored if a maximum date is set. Defaults to January 1st 2130.
 
1559    * myAppModule.config(function($mdDateLocaleProvider) {
 
1561    *     // Example of a French localization.
 
1562    *     $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
 
1563    *     $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
 
1564    *     $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
 
1565    *     $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
 
1567    *     // Can change week display to start on Monday.
 
1568    *     $mdDateLocaleProvider.firstDayOfWeek = 1;
 
1571    *     $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
 
1573    *     // Example uses moment.js to parse and format dates.
 
1574    *     $mdDateLocaleProvider.parseDate = function(dateString) {
 
1575    *       var m = moment(dateString, 'L', true);
 
1576    *       return m.isValid() ? m.toDate() : new Date(NaN);
 
1579    *     $mdDateLocaleProvider.formatDate = function(date) {
 
1580    *       var m = moment(date);
 
1581    *       return m.isValid() ? m.format('L') : '';
 
1584    *     $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
 
1585    *       return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
 
1588    *     // In addition to date display, date components also need localized messages
 
1589    *     // for aria-labels for screen-reader users.
 
1591    *     $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
 
1592    *       return 'Semaine ' + weekNumber;
 
1595    *     $mdDateLocaleProvider.msgCalendar = 'Calendrier';
 
1596    *     $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
 
1598    *     // You can also set when your calendar begins and ends.
 
1599    *     $mdDateLocaleProvider.firstRenderableDate = new Date(1776, 6, 4);
 
1600    *     $mdDateLocaleProvider.lastRenderableDate = new Date(2012, 11, 21);
 
1605   angular.module('material.components.datepicker').config(["$provide", function($provide) {
 
1606     // TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
 
1609     function DateLocaleProvider() {
 
1610       /** Array of full month names. E.g., ['January', 'Febuary', ...] */
 
1613       /** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
 
1614       this.shortMonths = null;
 
1616       /** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
 
1619       /** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
 
1620       this.shortDays = null;
 
1622       /** Array of dates of a month (1 - 31). Characters might be different in some locales. */
 
1625       /** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
 
1626       this.firstDayOfWeek = 0;
 
1629        * Function that converts the date portion of a Date to a string.
 
1630        * @type {(function(Date): string)}
 
1632       this.formatDate = null;
 
1635        * Function that converts a date string to a Date object (the date portion)
 
1636        * @type {function(string): Date}
 
1638       this.parseDate = null;
 
1641        * Function that formats a Date into a month header string.
 
1642        * @type {function(Date): string}
 
1644       this.monthHeaderFormatter = null;
 
1647        * Function that formats a week number into a label for the week.
 
1648        * @type {function(number): string}
 
1650       this.weekNumberFormatter = null;
 
1653        * Function that formats a date into a long aria-label that is read
 
1654        * when the focused date changes.
 
1655        * @type {function(Date): string}
 
1657       this.longDateFormatter = null;
 
1660        * ARIA label for the calendar "dialog" used in the datepicker.
 
1663       this.msgCalendar = '';
 
1666        * ARIA label for the datepicker's "Open calendar" buttons.
 
1669       this.msgOpenCalendar = '';
 
1673      * Factory function that returns an instance of the dateLocale service.
 
1676      * @returns {DateLocale}
 
1678     DateLocaleProvider.prototype.$get = function($locale, $filter) {
 
1680        * Default date-to-string formatting function.
 
1681        * @param {!Date} date
 
1682        * @param {string=} timezone
 
1685       function defaultFormatDate(date, timezone) {
 
1690         // All of the dates created through ng-material *should* be set to midnight.
 
1691         // If we encounter a date where the localeTime shows at 11pm instead of midnight,
 
1692         // we have run into an issue with DST where we need to increment the hour by one:
 
1693         // var d = new Date(1992, 9, 8, 0, 0, 0);
 
1694         // d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
 
1695         var localeTime = date.toLocaleTimeString();
 
1696         var formatDate = date;
 
1697         if (date.getHours() === 0 &&
 
1698             (localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
 
1699           formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
 
1702         return $filter('date')(formatDate, 'M/d/yyyy', timezone);
 
1706        * Default string-to-date parsing function.
 
1707        * @param {string} dateString
 
1710       function defaultParseDate(dateString) {
 
1711         return new Date(dateString);
 
1715        * Default function to determine whether a string makes sense to be
 
1716        * parsed to a Date object.
 
1718        * This is very permissive and is just a basic sanity check to ensure that
 
1719        * things like single integers aren't able to be parsed into dates.
 
1720        * @param {string} dateString
 
1721        * @returns {boolean}
 
1723       function defaultIsDateComplete(dateString) {
 
1724         dateString = dateString.trim();
 
1726         // Looks for three chunks of content (either numbers or text) separated
 
1728         var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
 
1729         return re.test(dateString);
 
1733        * Default date-to-string formatter to get a month header.
 
1734        * @param {!Date} date
 
1737       function defaultMonthHeaderFormatter(date) {
 
1738         return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
 
1742        * Default formatter for a month.
 
1743        * @param {!Date} date
 
1746       function defaultMonthFormatter(date) {
 
1747         return service.months[date.getMonth()] + ' ' + date.getFullYear();
 
1751        * Default week number formatter.
 
1755       function defaultWeekNumberFormatter(number) {
 
1756         return 'Week ' + number;
 
1760        * Default formatter for date cell aria-labels.
 
1761        * @param {!Date} date
 
1764       function defaultLongDateFormatter(date) {
 
1765         // Example: 'Thursday June 18 2015'
 
1767           service.days[date.getDay()],
 
1768           service.months[date.getMonth()],
 
1769           service.dates[date.getDate()],
 
1774       // The default "short" day strings are the first character of each day,
 
1775       // e.g., "Monday" => "M".
 
1776       var defaultShortDays = $locale.DATETIME_FORMATS.SHORTDAY.map(function(day) {
 
1777         return day.substring(0, 1);
 
1780       // The default dates are simply the numbers 1 through 31.
 
1781       var defaultDates = Array(32);
 
1782       for (var i = 1; i <= 31; i++) {
 
1783         defaultDates[i] = i;
 
1786       // Default ARIA messages are in English (US).
 
1787       var defaultMsgCalendar = 'Calendar';
 
1788       var defaultMsgOpenCalendar = 'Open calendar';
 
1790       // Default start/end dates that are rendered in the calendar.
 
1791       var defaultFirstRenderableDate = new Date(1880, 0, 1);
 
1792       var defaultLastRendereableDate = new Date(defaultFirstRenderableDate.getFullYear() + 250, 0, 1);
 
1795         months: this.months || $locale.DATETIME_FORMATS.MONTH,
 
1796         shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
 
1797         days: this.days || $locale.DATETIME_FORMATS.DAY,
 
1798         shortDays: this.shortDays || defaultShortDays,
 
1799         dates: this.dates || defaultDates,
 
1800         firstDayOfWeek: this.firstDayOfWeek || 0,
 
1801         formatDate: this.formatDate || defaultFormatDate,
 
1802         parseDate: this.parseDate || defaultParseDate,
 
1803         isDateComplete: this.isDateComplete || defaultIsDateComplete,
 
1804         monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
 
1805         monthFormatter: this.monthFormatter || defaultMonthFormatter,
 
1806         weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
 
1807         longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
 
1808         msgCalendar: this.msgCalendar || defaultMsgCalendar,
 
1809         msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar,
 
1810         firstRenderableDate: this.firstRenderableDate || defaultFirstRenderableDate,
 
1811         lastRenderableDate: this.lastRenderableDate || defaultLastRendereableDate
 
1816     DateLocaleProvider.prototype.$get['$inject'] = ["$locale", "$filter"];
 
1818     $provide.provider('$mdDateLocale', new DateLocaleProvider());
 
1826    * Utility for performing date calculations to facilitate operation of the calendar and
 
1829   angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
 
1831       getFirstDateOfMonth: getFirstDateOfMonth,
 
1832       getNumberOfDaysInMonth: getNumberOfDaysInMonth,
 
1833       getDateInNextMonth: getDateInNextMonth,
 
1834       getDateInPreviousMonth: getDateInPreviousMonth,
 
1835       isInNextMonth: isInNextMonth,
 
1836       isInPreviousMonth: isInPreviousMonth,
 
1837       getDateMidpoint: getDateMidpoint,
 
1838       isSameMonthAndYear: isSameMonthAndYear,
 
1839       getWeekOfMonth: getWeekOfMonth,
 
1840       incrementDays: incrementDays,
 
1841       incrementMonths: incrementMonths,
 
1842       getLastDateOfMonth: getLastDateOfMonth,
 
1843       isSameDay: isSameDay,
 
1844       getMonthDistance: getMonthDistance,
 
1845       isValidDate: isValidDate,
 
1846       setDateTimeToMidnight: setDateTimeToMidnight,
 
1847       createDateAtMidnight: createDateAtMidnight,
 
1848       isDateWithinRange: isDateWithinRange,
 
1849       incrementYears: incrementYears,
 
1850       getYearDistance: getYearDistance,
 
1851       clampDate: clampDate,
 
1852       getTimestampFromNode: getTimestampFromNode,
 
1853       isMonthWithinRange: isMonthWithinRange
 
1857      * Gets the first day of the month for the given date's month.
 
1858      * @param {Date} date
 
1861     function getFirstDateOfMonth(date) {
 
1862       return new Date(date.getFullYear(), date.getMonth(), 1);
 
1866      * Gets the number of days in the month for the given date's month.
 
1870     function getNumberOfDaysInMonth(date) {
 
1871       return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
 
1875      * Get an arbitrary date in the month after the given date's month.
 
1879     function getDateInNextMonth(date) {
 
1880       return new Date(date.getFullYear(), date.getMonth() + 1, 1);
 
1884      * Get an arbitrary date in the month before the given date's month.
 
1888     function getDateInPreviousMonth(date) {
 
1889       return new Date(date.getFullYear(), date.getMonth() - 1, 1);
 
1893      * Gets whether two dates have the same month and year.
 
1896      * @returns {boolean}
 
1898     function isSameMonthAndYear(d1, d2) {
 
1899       return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
 
1903      * Gets whether two dates are the same day (not not necesarily the same time).
 
1906      * @returns {boolean}
 
1908     function isSameDay(d1, d2) {
 
1909       return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
 
1913      * Gets whether a date is in the month immediately after some date.
 
1914      * @param {Date} startDate The date from which to compare.
 
1915      * @param {Date} endDate The date to check.
 
1916      * @returns {boolean}
 
1918     function isInNextMonth(startDate, endDate) {
 
1919       var nextMonth = getDateInNextMonth(startDate);
 
1920       return isSameMonthAndYear(nextMonth, endDate);
 
1924      * Gets whether a date is in the month immediately before some date.
 
1925      * @param {Date} startDate The date from which to compare.
 
1926      * @param {Date} endDate The date to check.
 
1927      * @returns {boolean}
 
1929     function isInPreviousMonth(startDate, endDate) {
 
1930       var previousMonth = getDateInPreviousMonth(startDate);
 
1931       return isSameMonthAndYear(endDate, previousMonth);
 
1935      * Gets the midpoint between two dates.
 
1940     function getDateMidpoint(d1, d2) {
 
1941       return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
 
1945      * Gets the week of the month that a given date occurs in.
 
1946      * @param {Date} date
 
1947      * @returns {number} Index of the week of the month (zero-based).
 
1949     function getWeekOfMonth(date) {
 
1950       var firstDayOfMonth = getFirstDateOfMonth(date);
 
1951       return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
 
1955      * Gets a new date incremented by the given number of days. Number of days can be negative.
 
1956      * @param {Date} date
 
1957      * @param {number} numberOfDays
 
1960     function incrementDays(date, numberOfDays) {
 
1961       return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
 
1965      * Gets a new date incremented by the given number of months. Number of months can be negative.
 
1966      * If the date of the given month does not match the target month, the date will be set to the
 
1967      * last day of the month.
 
1968      * @param {Date} date
 
1969      * @param {number} numberOfMonths
 
1972     function incrementMonths(date, numberOfMonths) {
 
1973       // If the same date in the target month does not actually exist, the Date object will
 
1974       // automatically advance *another* month by the number of missing days.
 
1975       // For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
 
1976       // So, we check if the month overflowed and go to the last day of the target month instead.
 
1977       var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
 
1978       var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
 
1979       if (numberOfDaysInMonth < date.getDate()) {
 
1980         dateInTargetMonth.setDate(numberOfDaysInMonth);
 
1982         dateInTargetMonth.setDate(date.getDate());
 
1985       return dateInTargetMonth;
 
1989      * Get the integer distance between two months. This *only* considers the month and year
 
1990      * portion of the Date instances.
 
1992      * @param {Date} start
 
1994      * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
 
1995      *     chronologically, this number will be negative.
 
1997     function getMonthDistance(start, end) {
 
1998       return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
 
2002      * Gets the last day of the month for the given date.
 
2003      * @param {Date} date
 
2006     function getLastDateOfMonth(date) {
 
2007       return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
 
2011      * Checks whether a date is valid.
 
2012      * @param {Date} date
 
2013      * @return {boolean} Whether the date is a valid Date.
 
2015     function isValidDate(date) {
 
2016       return date && date.getTime && !isNaN(date.getTime());
 
2020      * Sets a date's time to midnight.
 
2021      * @param {Date} date
 
2023     function setDateTimeToMidnight(date) {
 
2024       if (isValidDate(date)) {
 
2025         date.setHours(0, 0, 0, 0);
 
2030      * Creates a date with the time set to midnight.
 
2031      * Drop-in replacement for two forms of the Date constructor:
 
2032      * 1. No argument for Date representing now.
 
2033      * 2. Single-argument value representing number of seconds since Unix Epoch
 
2035      * @param {number|Date=} opt_value
 
2036      * @return {Date} New date with time set to midnight.
 
2038     function createDateAtMidnight(opt_value) {
 
2040       if (angular.isUndefined(opt_value)) {
 
2043         date = new Date(opt_value);
 
2045       setDateTimeToMidnight(date);
 
2050       * Checks if a date is within a min and max range, ignoring the time component.
 
2051       * If minDate or maxDate are not dates, they are ignored.
 
2052       * @param {Date} date
 
2053       * @param {Date} minDate
 
2054       * @param {Date} maxDate
 
2056      function isDateWithinRange(date, minDate, maxDate) {
 
2057        var dateAtMidnight = createDateAtMidnight(date);
 
2058        var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
 
2059        var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
 
2060        return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
 
2061            (!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
 
2065      * Gets a new date incremented by the given number of years. Number of years can be negative.
 
2066      * See `incrementMonths` for notes on overflow for specific dates.
 
2067      * @param {Date} date
 
2068      * @param {number} numberOfYears
 
2071      function incrementYears(date, numberOfYears) {
 
2072        return incrementMonths(date, numberOfYears * 12);
 
2076       * Get the integer distance between two years. This *only* considers the year portion of the
 
2079       * @param {Date} start
 
2081       * @returns {number} Number of months between `start` and `end`. If `end` is before `start`
 
2082       *     chronologically, this number will be negative.
 
2084      function getYearDistance(start, end) {
 
2085        return end.getFullYear() - start.getFullYear();
 
2089       * Clamps a date between a minimum and a maximum date.
 
2090       * @param {Date} date Date to be clamped
 
2091       * @param {Date=} minDate Minimum date
 
2092       * @param {Date=} maxDate Maximum date
 
2095      function clampDate(date, minDate, maxDate) {
 
2096        var boundDate = date;
 
2097        if (minDate && date < minDate) {
 
2098          boundDate = new Date(minDate.getTime());
 
2100        if (maxDate && date > maxDate) {
 
2101          boundDate = new Date(maxDate.getTime());
 
2107       * Extracts and parses the timestamp from a DOM node.
 
2108       * @param  {HTMLElement} node Node from which the timestamp will be extracted.
 
2109       * @return {number} Time since epoch.
 
2111      function getTimestampFromNode(node) {
 
2112        if (node && node.hasAttribute('data-timestamp')) {
 
2113          return Number(node.getAttribute('data-timestamp'));
 
2118       * Checks if a month is within a min and max range, ignoring the date and time components.
 
2119       * If minDate or maxDate are not dates, they are ignored.
 
2120       * @param {Date} date
 
2121       * @param {Date} minDate
 
2122       * @param {Date} maxDate
 
2124      function isMonthWithinRange(date, minDate, maxDate) {
 
2125        var month = date.getMonth();
 
2126        var year = date.getFullYear();
 
2128        return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
 
2129         (!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
 
2138   // TODO(jelbourn): Demo that uses moment.js
 
2139   // TODO(jelbourn): make sure this plays well with validation and ngMessages.
 
2140   // TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
 
2141   // TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
 
2142   // TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
 
2143   // TODO(jelbourn): input behavior (masking? auto-complete?)
 
2146   DatePickerCtrl['$inject'] = ["$scope", "$element", "$attrs", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF", "$filter"];
 
2147   datePickerDirective['$inject'] = ["$$mdSvgRegistry", "$mdUtil", "$mdAria", "inputDirective"];
 
2148   angular.module('material.components.datepicker')
 
2149       .directive('mdDatepicker', datePickerDirective);
 
2153    * @name mdDatepicker
 
2154    * @module material.components.datepicker
 
2156    * @param {Date} ng-model The component's model. Expects a JavaScript Date object.
 
2157    * @param {Object=} ng-model-options Allows tuning of the way in which `ng-model` is being updated. Also allows
 
2158    * for a timezone to be specified. <a href="https://docs.angularjs.org/api/ng/directive/ngModelOptions#usage">Read more at the ngModelOptions docs.</a>
 
2159    * @param {expression=} ng-change Expression evaluated when the model value changes.
 
2160    * @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar is opened.
 
2161    * @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the calendar is closed.
 
2162    * @param {boolean=} ng-disabled Whether the datepicker is disabled.
 
2163    * @param {boolean=} ng-required Whether a value is required for the datepicker.
 
2164    * @param {Date=} md-min-date Expression representing a min date (inclusive).
 
2165    * @param {Date=} md-max-date Expression representing a max date (inclusive).
 
2166    * @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
 
2167    * @param {String=} md-placeholder The date input placeholder value.
 
2168    * @param {String=} md-open-on-focus When present, the calendar will be opened when the input is focused.
 
2169    * @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar on-demand.
 
2170    * @param {String=} md-current-view Default open view of the calendar pane. Can be either "month" or "year".
 
2171    * @param {String=} md-hide-icons Determines which datepicker icons should be hidden. Note that this may cause the
 
2172    * datepicker to not align properly with other components. **Use at your own risk.** Possible values are:
 
2173    * * `"all"` - Hides all icons.
 
2174    * * `"calendar"` - Only hides the calendar icon.
 
2175    * * `"triangle"` - Only hides the triangle icon.
 
2176    * @param {Object=} md-date-locale Allows for the values from the `$mdDateLocaleProvider` to be
 
2177    * ovewritten on a per-element basis (e.g. `msgOpenCalendar` can be overwritten with
 
2178    * `md-date-locale="{ msgOpenCalendar: 'Open a special calendar' }"`).
 
2181    * `<md-datepicker>` is a component used to select a single date.
 
2182    * For information on how to configure internationalization for the date picker,
 
2183    * see `$mdDateLocaleProvider`.
 
2185    * This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
 
2186    * Supported attributes are:
 
2187    * * `required`: whether a required date is not set.
 
2188    * * `mindate`: whether the selected date is before the minimum allowed date.
 
2189    * * `maxdate`: whether the selected date is after the maximum allowed date.
 
2190    * * `debounceInterval`: ms to delay input processing (since last debounce reset); default value 500ms
 
2193    * <hljs lang="html">
 
2194    *   <md-datepicker ng-model="birthday"></md-datepicker>
 
2199   function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria, inputDirective) {
 
2201       template: function(tElement, tAttrs) {
 
2202         // Buttons are not in the tab order because users can open the calendar via keyboard
 
2203         // interaction on the text input, and multiple tab stops for one component (picker)
 
2204         // may be confusing.
 
2205         var hiddenIcons = tAttrs.mdHideIcons;
 
2206         var ariaLabelValue = tAttrs.ariaLabel || tAttrs.mdPlaceholder;
 
2208         var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
 
2209           '<md-button class="md-datepicker-button md-icon-button" type="button" ' +
 
2210               'tabindex="-1" aria-hidden="true" ' +
 
2211               'ng-click="ctrl.openCalendarPane($event)">' +
 
2212             '<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
 
2213                      'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
 
2216         var triangleButton = '';
 
2218         if (hiddenIcons !== 'all' && hiddenIcons !== 'triangle') {
 
2219           triangleButton = '' +
 
2220             '<md-button type="button" md-no-ink ' +
 
2221               'class="md-datepicker-triangle-button md-icon-button" ' +
 
2222               'ng-click="ctrl.openCalendarPane($event)" ' +
 
2223               'aria-label="{{::ctrl.locale.msgOpenCalendar}}">' +
 
2224             '<div class="md-datepicker-expand-triangle"></div>' +
 
2227           tElement.addClass(HAS_TRIANGLE_ICON_CLASS);
 
2230         return calendarButton +
 
2231         '<div class="md-datepicker-input-container" ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
 
2233             (ariaLabelValue ? 'aria-label="' + ariaLabelValue + '" ' : '') +
 
2234             'class="md-datepicker-input" ' +
 
2235             'aria-haspopup="true" ' +
 
2236             'aria-expanded="{{ctrl.isCalendarOpen}}" ' +
 
2237             'ng-focus="ctrl.setFocused(true)" ' +
 
2238             'ng-blur="ctrl.setFocused(false)"> ' +
 
2242         // This pane will be detached from here and re-attached to the document body.
 
2243         '<div class="md-datepicker-calendar-pane md-whiteframe-z1" id="{{::ctrl.calendarPaneId}}">' +
 
2244           '<div class="md-datepicker-input-mask">' +
 
2245             '<div class="md-datepicker-input-mask-opaque"></div>' +
 
2247           '<div class="md-datepicker-calendar">' +
 
2248             '<md-calendar role="dialog" aria-label="{{::ctrl.locale.msgCalendar}}" ' +
 
2249                 'md-current-view="{{::ctrl.currentView}}"' +
 
2250                 'md-min-date="ctrl.minDate"' +
 
2251                 'md-max-date="ctrl.maxDate"' +
 
2252                 'md-date-filter="ctrl.dateFilter"' +
 
2253                 'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
 
2258       require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
 
2260         minDate: '=mdMinDate',
 
2261         maxDate: '=mdMaxDate',
 
2262         placeholder: '@mdPlaceholder',
 
2263         currentView: '@mdCurrentView',
 
2264         dateFilter: '=mdDateFilter',
 
2265         isOpen: '=?mdIsOpen',
 
2266         debounceInterval: '=mdDebounceInterval',
 
2267         dateLocale: '=mdDateLocale'
 
2269       controller: DatePickerCtrl,
 
2270       controllerAs: 'ctrl',
 
2271       bindToController: true,
 
2272       link: function(scope, element, attr, controllers) {
 
2273         var ngModelCtrl = controllers[0];
 
2274         var mdDatePickerCtrl = controllers[1];
 
2275         var mdInputContainer = controllers[2];
 
2276         var parentForm = controllers[3];
 
2277         var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
 
2279         mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer, inputDirective);
 
2281         if (mdInputContainer) {
 
2282           // We need to move the spacer after the datepicker itself,
 
2283           // because md-input-container adds it after the
 
2284           // md-datepicker-input by default. The spacer gets wrapped in a
 
2285           // div, because it floats and gets aligned next to the datepicker.
 
2286           // There are easier ways of working around this with CSS (making the
 
2287           // datepicker 100% wide, change the `display` etc.), however they
 
2288           // break the alignment with any other form controls.
 
2289           var spacer = element[0].querySelector('.md-errors-spacer');
 
2292             element.after(angular.element('<div>').append(spacer));
 
2295           mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
 
2296           mdInputContainer.input = element;
 
2297           mdInputContainer.element
 
2298             .addClass(INPUT_CONTAINER_CLASS)
 
2299             .toggleClass(HAS_CALENDAR_ICON_CLASS, attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
 
2301           if (!mdInputContainer.label) {
 
2302             $mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
 
2303           } else if(!mdNoAsterisk) {
 
2304             attr.$observe('required', function(value) {
 
2305               mdInputContainer.label.toggleClass('md-required', !!value);
 
2309           scope.$watch(mdInputContainer.isErrorGetter || function() {
 
2310             return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted));
 
2311           }, mdInputContainer.setInvalid);
 
2312         } else if (parentForm) {
 
2313           // If invalid, highlights the input when the parent form is submitted.
 
2314           var parentSubmittedWatcher = scope.$watch(function() {
 
2315             return parentForm.$submitted;
 
2316           }, function(isSubmitted) {
 
2318               mdDatePickerCtrl.updateErrorState();
 
2319               parentSubmittedWatcher();
 
2327   /** Additional offset for the input's `size` attribute, which is updated based on its content. */
 
2328   var EXTRA_INPUT_SIZE = 3;
 
2330   /** Class applied to the container if the date is invalid. */
 
2331   var INVALID_CLASS = 'md-datepicker-invalid';
 
2333   /** Class applied to the datepicker when it's open. */
 
2334   var OPEN_CLASS = 'md-datepicker-open';
 
2336   /** Class applied to the md-input-container, if a datepicker is placed inside it */
 
2337   var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
 
2339   /** Class to be applied when the calendar icon is enabled. */
 
2340   var HAS_CALENDAR_ICON_CLASS = '_md-datepicker-has-calendar-icon';
 
2342   /** Class to be applied when the triangle icon is enabled. */
 
2343   var HAS_TRIANGLE_ICON_CLASS = '_md-datepicker-has-triangle-icon';
 
2345   /** Default time in ms to debounce input event by. */
 
2346   var DEFAULT_DEBOUNCE_INTERVAL = 500;
 
2349    * Height of the calendar pane used to check if the pane is going outside the boundary of
 
2350    * the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
 
2351    * also added to space the pane away from the exact edge of the screen.
 
2353    *  This is computed statically now, but can be changed to be measured if the circumstances
 
2354    *  of calendar sizing are changed.
 
2356   var CALENDAR_PANE_HEIGHT = 368;
 
2359    * Width of the calendar pane used to check if the pane is going outside the boundary of
 
2360    * the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
 
2361    * also added to space the pane away from the exact edge of the screen.
 
2363    *  This is computed statically now, but can be changed to be measured if the circumstances
 
2364    *  of calendar sizing are changed.
 
2366   var CALENDAR_PANE_WIDTH = 360;
 
2368   /** Used for checking whether the current user agent is on iOS or Android. */
 
2369   var IS_MOBILE_REGEX = /ipad|iphone|ipod|android/i;
 
2372    * Controller for md-datepicker.
 
2374    * ngInject @constructor
 
2376   function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant,
 
2377     $mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF, $filter) {
 
2380     this.$window = $window;
 
2383     this.dateUtil = $$mdDateUtil;
 
2386     this.$mdConstant = $mdConstant;
 
2389     this.$mdUtil = $mdUtil;
 
2395     this.$mdDateLocale = $mdDateLocale;
 
2398      * The root document element. This is used for attaching a top-level click handler to
 
2399      * close the calendar panel when a click outside said panel occurs. We use `documentElement`
 
2400      * instead of body because, when scrolling is disabled, some browsers consider the body element
 
2401      * to be completely off the screen and propagate events directly to the html element.
 
2402      * @type {!angular.JQLite}
 
2404     this.documentElement = angular.element(document.documentElement);
 
2406     /** @type {!angular.NgModelController} */
 
2407     this.ngModelCtrl = null;
 
2409     /** @type {HTMLInputElement} */
 
2410     this.inputElement = $element[0].querySelector('input');
 
2412     /** @final {!angular.JQLite} */
 
2413     this.ngInputElement = angular.element(this.inputElement);
 
2415     /** @type {HTMLElement} */
 
2416     this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
 
2418     /** @type {HTMLElement} Floating calendar pane. */
 
2419     this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
 
2421     /** @type {HTMLElement} Calendar icon button. */
 
2422     this.calendarButton = $element[0].querySelector('.md-datepicker-button');
 
2425      * Element covering everything but the input in the top of the floating calendar pane.
 
2426      * @type {!angular.JQLite}
 
2428     this.inputMask = angular.element($element[0].querySelector('.md-datepicker-input-mask-opaque'));
 
2430     /** @final {!angular.JQLite} */
 
2431     this.$element = $element;
 
2433     /** @final {!angular.Attributes} */
 
2434     this.$attrs = $attrs;
 
2436     /** @final {!angular.Scope} */
 
2437     this.$scope = $scope;
 
2442     /** @type {boolean} */
 
2443     this.isFocused = false;
 
2445     /** @type {boolean} */
 
2447     this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
 
2449     /** @type {boolean} Whether the date-picker's calendar pane is open. */
 
2450     this.isCalendarOpen = false;
 
2452     /** @type {boolean} Whether the calendar should open when the input is focused. */
 
2453     this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
 
2456     this.mdInputContainer = null;
 
2459      * Element from which the calendar pane was opened. Keep track of this so that we can return
 
2460      * focus to it when the pane is closed.
 
2461      * @type {HTMLElement}
 
2463     this.calendarPaneOpenedFrom = null;
 
2465     /** @type {String} Unique id for the calendar pane. */
 
2466     this.calendarPaneId = 'md-date-pane-' + $mdUtil.nextUid();
 
2468     /** Pre-bound click handler is saved so that the event listener can be removed. */
 
2469     this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
 
2472      * Name of the event that will trigger a close. Necessary to sniff the browser, because
 
2473      * the resize event doesn't make sense on mobile and can have a negative impact since it
 
2474      * triggers whenever the browser zooms in on a focused input.
 
2476     this.windowEventName = IS_MOBILE_REGEX.test(
 
2477       navigator.userAgent || navigator.vendor || window.opera
 
2478     ) ? 'orientationchange' : 'resize';
 
2480     /** Pre-bound close handler so that the event listener can be removed. */
 
2481     this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
 
2483     /** Pre-bound handler for the window blur event. Allows for it to be removed later. */
 
2484     this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
 
2486     /** The built-in Angular date filter. */
 
2487     this.ngDateFilter = $filter('date');
 
2489     /** @type {Number} Extra margin for the left side of the floating calendar pane. */
 
2490     this.leftMargin = 20;
 
2492     /** @type {Number} Extra margin for the top of the floating calendar. Gets determined on the first open. */
 
2493     this.topMargin = null;
 
2495     // Unless the user specifies so, the datepicker should not be a tab stop.
 
2496     // This is necessary because ngAria might add a tabindex to anything with an ng-model
 
2497     // (based on whether or not the user has turned that particular feature on/off).
 
2498     if ($attrs.tabindex) {
 
2499       this.ngInputElement.attr('tabindex', $attrs.tabindex);
 
2500       $attrs.$set('tabindex', null);
 
2502       $attrs.$set('tabindex', '-1');
 
2505     $attrs.$set('aria-owns', this.calendarPaneId);
 
2507     $mdTheming($element);
 
2508     $mdTheming(angular.element(this.calendarPane));
 
2512     $scope.$on('$destroy', function() {
 
2513       self.detachCalendarPane();
 
2516     if ($attrs.mdIsOpen) {
 
2517       $scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
 
2519           self.openCalendarPane({
 
2520             target: self.inputElement
 
2523           self.closeCalendarPane();
 
2528     // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
 
2529     // manually call the $onInit hook.
 
2530     if (angular.version.major === 1 && angular.version.minor <= 4) {
 
2537    * Angular Lifecycle hook for newer Angular versions.
 
2538    * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
 
2540   DatePickerCtrl.prototype.$onInit = function() {
 
2543      * Holds locale-specific formatters, parsers, labels etc. Allows
 
2544      * the user to override specific ones from the $mdDateLocale provider.
 
2547     this.locale = this.dateLocale ? angular.extend({}, this.$mdDateLocale, this.dateLocale) : this.$mdDateLocale;
 
2549     this.installPropertyInterceptors();
 
2550     this.attachChangeListeners();
 
2551     this.attachInteractionListeners();
 
2555    * Sets up the controller's reference to ngModelController and
 
2556    * applies Angular's `input[type="date"]` directive.
 
2557    * @param {!angular.NgModelController} ngModelCtrl Instance of the ngModel controller.
 
2558    * @param {Object} mdInputContainer Instance of the mdInputContainer controller.
 
2559    * @param {Object} inputDirective Config for Angular's `input` directive.
 
2561   DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer, inputDirective) {
 
2562     this.ngModelCtrl = ngModelCtrl;
 
2563     this.mdInputContainer = mdInputContainer;
 
2565     // The input needs to be [type="date"] in order to be picked up by Angular.
 
2566     this.$attrs.$set('type', 'date');
 
2568     // Invoke the `input` directive link function, adding a stub for the element.
 
2569     // This allows us to re-use Angular's logic for setting the timezone via ng-model-options.
 
2570     // It works by calling the link function directly which then adds the proper `$parsers` and
 
2571     // `$formatters` to the ngModel controller.
 
2572     inputDirective[0].link.pre(this.$scope, {
 
2576     }, this.$attrs, [ngModelCtrl]);
 
2580     // Responds to external changes to the model value.
 
2581     self.ngModelCtrl.$formatters.push(function(value) {
 
2582       if (value && !(value instanceof Date)) {
 
2583         throw Error('The ng-model for md-datepicker must be a Date instance. ' +
 
2584             'Currently the model is a: ' + (typeof value));
 
2587       self.onExternalChange(value);
 
2592     // Responds to external error state changes (e.g. ng-required based on another input).
 
2593     ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
 
2595     // Forwards any events from the input to the root element. This is necessary to get `updateOn`
 
2596     // working for events that don't bubble (e.g. 'blur') since Angular binds the handlers to
 
2597     // the `<md-datepicker>`.
 
2598     var updateOn = self.$mdUtil.getModelOption(ngModelCtrl, 'updateOn');
 
2601       this.ngInputElement.on(
 
2603         angular.bind(this.$element, this.$element.triggerHandler, updateOn)
 
2609    * Attach event listeners for both the text input and the md-calendar.
 
2610    * Events are used instead of ng-model so that updates don't infinitely update the other
 
2611    * on a change. This should also be more performant than using a $watch.
 
2613   DatePickerCtrl.prototype.attachChangeListeners = function() {
 
2616     self.$scope.$on('md-calendar-change', function(event, date) {
 
2617       self.setModelValue(date);
 
2618       self.onExternalChange(date);
 
2619       self.closeCalendarPane();
 
2622     self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
 
2624     var debounceInterval = angular.isDefined(this.debounceInterval) ?
 
2625         this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
 
2626     self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
 
2627         debounceInterval, self));
 
2630   /** Attach event listeners for user interaction. */
 
2631   DatePickerCtrl.prototype.attachInteractionListeners = function() {
 
2633     var $scope = this.$scope;
 
2634     var keyCodes = this.$mdConstant.KEY_CODE;
 
2636     // Add event listener through angular so that we can triggerHandler in unit tests.
 
2637     self.ngInputElement.on('keydown', function(event) {
 
2638       if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
 
2639         self.openCalendarPane(event);
 
2644     if (self.openOnFocus) {
 
2645       self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
 
2646       angular.element(self.$window).on('blur', self.windowBlurHandler);
 
2648       $scope.$on('$destroy', function() {
 
2649         angular.element(self.$window).off('blur', self.windowBlurHandler);
 
2653     $scope.$on('md-calendar-close', function() {
 
2654       self.closeCalendarPane();
 
2659    * Capture properties set to the date-picker and imperitively handle internal changes.
 
2660    * This is done to avoid setting up additional $watches.
 
2662   DatePickerCtrl.prototype.installPropertyInterceptors = function() {
 
2665     if (this.$attrs.ngDisabled) {
 
2666       // The expression is to be evaluated against the directive element's scope and not
 
2667       // the directive's isolate scope.
 
2668       var scope = this.$scope.$parent;
 
2671         scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
 
2672           self.setDisabled(isDisabled);
 
2677     Object.defineProperty(this, 'placeholder', {
 
2678       get: function() { return self.inputElement.placeholder; },
 
2679       set: function(value) { self.inputElement.placeholder = value || ''; }
 
2684    * Sets whether the date-picker is disabled.
 
2685    * @param {boolean} isDisabled
 
2687   DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
 
2688     this.isDisabled = isDisabled;
 
2689     this.inputElement.disabled = isDisabled;
 
2691     if (this.calendarButton) {
 
2692       this.calendarButton.disabled = isDisabled;
 
2697    * Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
 
2698    *   - mindate: whether the selected date is before the minimum date.
 
2699    *   - maxdate: whether the selected flag is after the maximum date.
 
2700    *   - filtered: whether the selected date is allowed by the custom filtering function.
 
2701    *   - valid: whether the entered text input is a valid date
 
2703    * The 'required' flag is handled automatically by ngModel.
 
2705    * @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
 
2707   DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
 
2708     var date = opt_date || this.date;
 
2710     // Clear any existing errors to get rid of anything that's no longer relevant.
 
2711     this.clearErrorState();
 
2713     if (this.dateUtil.isValidDate(date)) {
 
2714       // Force all dates to midnight in order to ignore the time portion.
 
2715       date = this.dateUtil.createDateAtMidnight(date);
 
2717       if (this.dateUtil.isValidDate(this.minDate)) {
 
2718         var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
 
2719         this.ngModelCtrl.$setValidity('mindate', date >= minDate);
 
2722       if (this.dateUtil.isValidDate(this.maxDate)) {
 
2723         var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
 
2724         this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
 
2727       if (angular.isFunction(this.dateFilter)) {
 
2728         this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
 
2731       // The date is seen as "not a valid date" if there is *something* set
 
2732       // (i.e.., not null or undefined), but that something isn't a valid date.
 
2733       this.ngModelCtrl.$setValidity('valid', date == null);
 
2736     angular.element(this.inputContainer).toggleClass(INVALID_CLASS, !this.ngModelCtrl.$valid);
 
2739   /** Clears any error flags set by `updateErrorState`. */
 
2740   DatePickerCtrl.prototype.clearErrorState = function() {
 
2741     this.inputContainer.classList.remove(INVALID_CLASS);
 
2742     ['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
 
2743       this.ngModelCtrl.$setValidity(field, true);
 
2747   /** Resizes the input element based on the size of its content. */
 
2748   DatePickerCtrl.prototype.resizeInputElement = function() {
 
2749     this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
 
2753    * Sets the model value if the user input is a valid date.
 
2754    * Adds an invalid class to the input element if not.
 
2756   DatePickerCtrl.prototype.handleInputEvent = function() {
 
2757     var inputString = this.inputElement.value;
 
2758     var parsedDate = inputString ? this.locale.parseDate(inputString) : null;
 
2759     this.dateUtil.setDateTimeToMidnight(parsedDate);
 
2761     // An input string is valid if it is either empty (representing no date)
 
2762     // or if it parses to a valid date that the user is allowed to select.
 
2763     var isValidInput = inputString == '' || (
 
2764       this.dateUtil.isValidDate(parsedDate) &&
 
2765       this.locale.isDateComplete(inputString) &&
 
2766       this.isDateEnabled(parsedDate)
 
2769     // The datepicker's model is only updated when there is a valid input.
 
2771       this.setModelValue(parsedDate);
 
2772       this.date = parsedDate;
 
2775     this.updateErrorState(parsedDate);
 
2779    * Check whether date is in range and enabled
 
2780    * @param {Date=} opt_date
 
2781    * @return {boolean} Whether the date is enabled.
 
2783   DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
 
2784     return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
 
2785           (!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
 
2788   /** Position and attach the floating calendar to the document. */
 
2789   DatePickerCtrl.prototype.attachCalendarPane = function() {
 
2790     var calendarPane = this.calendarPane;
 
2791     var body = document.body;
 
2793     calendarPane.style.transform = '';
 
2794     this.$element.addClass(OPEN_CLASS);
 
2795     this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
 
2796     angular.element(body).addClass('md-datepicker-is-showing');
 
2798     var elementRect = this.inputContainer.getBoundingClientRect();
 
2799     var bodyRect = body.getBoundingClientRect();
 
2801     if (!this.topMargin || this.topMargin < 0) {
 
2802       this.topMargin = (this.inputMask.parent().prop('clientHeight') - this.ngInputElement.prop('clientHeight')) / 2;
 
2805     // Check to see if the calendar pane would go off the screen. If so, adjust position
 
2806     // accordingly to keep it within the viewport.
 
2807     var paneTop = elementRect.top - bodyRect.top - this.topMargin;
 
2808     var paneLeft = elementRect.left - bodyRect.left - this.leftMargin;
 
2810     // If ng-material has disabled body scrolling (for example, if a dialog is open),
 
2811     // then it's possible that the already-scrolled body has a negative top/left. In this case,
 
2812     // we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
 
2813     // though, the top of the viewport should just be the body's scroll position.
 
2814     var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
 
2816         document.body.scrollTop;
 
2818     var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
 
2820         document.body.scrollLeft;
 
2822     var viewportBottom = viewportTop + this.$window.innerHeight;
 
2823     var viewportRight = viewportLeft + this.$window.innerWidth;
 
2825     // Creates an overlay with a hole the same size as element. We remove a pixel or two
 
2826     // on each end to make it overlap slightly. The overlay's background is added in
 
2827     // the theme in the form of a box-shadow with a huge spread.
 
2828     this.inputMask.css({
 
2829       position: 'absolute',
 
2830       left: this.leftMargin + 'px',
 
2831       top: this.topMargin + 'px',
 
2832       width: (elementRect.width - 1) + 'px',
 
2833       height: (elementRect.height - 2) + 'px'
 
2836     // If the right edge of the pane would be off the screen and shifting it left by the
 
2837     // difference would not go past the left edge of the screen. If the calendar pane is too
 
2838     // big to fit on the screen at all, move it to the left of the screen and scale the entire
 
2839     // element down to fit.
 
2840     if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
 
2841       if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
 
2842         paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
 
2844         paneLeft = viewportLeft;
 
2845         var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
 
2846         calendarPane.style.transform = 'scale(' + scale + ')';
 
2849       calendarPane.classList.add('md-datepicker-pos-adjusted');
 
2852     // If the bottom edge of the pane would be off the screen and shifting it up by the
 
2853     // difference would not go past the top edge of the screen.
 
2854     if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
 
2855         viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
 
2856       paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
 
2857       calendarPane.classList.add('md-datepicker-pos-adjusted');
 
2860     calendarPane.style.left = paneLeft + 'px';
 
2861     calendarPane.style.top = paneTop + 'px';
 
2862     document.body.appendChild(calendarPane);
 
2864     // Add CSS class after one frame to trigger open animation.
 
2865     this.$$rAF(function() {
 
2866       calendarPane.classList.add('md-pane-open');
 
2870   /** Detach the floating calendar pane from the document. */
 
2871   DatePickerCtrl.prototype.detachCalendarPane = function() {
 
2872     this.$element.removeClass(OPEN_CLASS);
 
2873     this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
 
2874     angular.element(document.body).removeClass('md-datepicker-is-showing');
 
2875     this.calendarPane.classList.remove('md-pane-open');
 
2876     this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
 
2878     if (this.isCalendarOpen) {
 
2879       this.$mdUtil.enableScrolling();
 
2882     if (this.calendarPane.parentNode) {
 
2883       // Use native DOM removal because we do not want any of the
 
2884       // angular state of this element to be disposed.
 
2885       this.calendarPane.parentNode.removeChild(this.calendarPane);
 
2890    * Open the floating calendar pane.
 
2891    * @param {Event} event
 
2893   DatePickerCtrl.prototype.openCalendarPane = function(event) {
 
2894     if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
 
2895       this.isCalendarOpen = this.isOpen = true;
 
2896       this.calendarPaneOpenedFrom = event.target;
 
2898       // Because the calendar pane is attached directly to the body, it is possible that the
 
2899       // rest of the component (input, etc) is in a different scrolling container, such as
 
2900       // an md-content. This means that, if the container is scrolled, the pane would remain
 
2901       // stationary. To remedy this, we disable scrolling while the calendar pane is open, which
 
2902       // also matches the native behavior for things like `<select>` on Mac and Windows.
 
2903       this.$mdUtil.disableScrollAround(this.calendarPane);
 
2905       this.attachCalendarPane();
 
2906       this.focusCalendar();
 
2907       this.evalAttr('ngFocus');
 
2909       // Attach click listener inside of a timeout because, if this open call was triggered by a
 
2910       // click, we don't want it to be immediately propogated up to the body and handled.
 
2912       this.$mdUtil.nextTick(function() {
 
2913         // Use 'touchstart` in addition to click in order to work on iOS Safari, where click
 
2914         // events aren't propogated under most circumstances.
 
2915         // See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
 
2916         self.documentElement.on('click touchstart', self.bodyClickHandler);
 
2919       window.addEventListener(this.windowEventName, this.windowEventHandler);
 
2923   /** Close the floating calendar pane. */
 
2924   DatePickerCtrl.prototype.closeCalendarPane = function() {
 
2925     if (this.isCalendarOpen) {
 
2928       self.detachCalendarPane();
 
2929       self.ngModelCtrl.$setTouched();
 
2930       self.evalAttr('ngBlur');
 
2932       self.documentElement.off('click touchstart', self.bodyClickHandler);
 
2933       window.removeEventListener(self.windowEventName, self.windowEventHandler);
 
2935       self.calendarPaneOpenedFrom.focus();
 
2936       self.calendarPaneOpenedFrom = null;
 
2938       if (self.openOnFocus) {
 
2939         // Ensures that all focus events have fired before resetting
 
2940         // the calendar. Prevents the calendar from reopening immediately
 
2941         // in IE when md-open-on-focus is set. Also it needs to trigger
 
2942         // a digest, in order to prevent issues where the calendar wasn't
 
2943         // showing up on the next open.
 
2944         self.$mdUtil.nextTick(reset);
 
2951       self.isCalendarOpen = self.isOpen = false;
 
2955   /** Gets the controller instance for the calendar in the floating pane. */
 
2956   DatePickerCtrl.prototype.getCalendarCtrl = function() {
 
2957     return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
 
2960   /** Focus the calendar in the floating pane. */
 
2961   DatePickerCtrl.prototype.focusCalendar = function() {
 
2962     // Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
 
2964     this.$mdUtil.nextTick(function() {
 
2965       self.getCalendarCtrl().focus();
 
2970    * Sets whether the input is currently focused.
 
2971    * @param {boolean} isFocused
 
2973   DatePickerCtrl.prototype.setFocused = function(isFocused) {
 
2975       this.ngModelCtrl.$setTouched();
 
2978     // The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
 
2979     // because they also get called when the calendar is opened/closed.
 
2980     if (!this.openOnFocus) {
 
2981       this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
 
2984     this.isFocused = isFocused;
 
2988    * Handles a click on the document body when the floating calendar pane is open.
 
2989    * Closes the floating calendar pane if the click is not inside of it.
 
2990    * @param {MouseEvent} event
 
2992   DatePickerCtrl.prototype.handleBodyClick = function(event) {
 
2993     if (this.isCalendarOpen) {
 
2994       var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
 
2996       if (!isInCalendar) {
 
2997         this.closeCalendarPane();
 
3000       this.$scope.$digest();
 
3005    * Handles the event when the user navigates away from the current tab. Keeps track of
 
3006    * whether the input was focused when the event happened, in order to prevent the calendar
 
3009   DatePickerCtrl.prototype.handleWindowBlur = function() {
 
3010     this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
 
3014    * Evaluates an attribute expression against the parent scope.
 
3015    * @param {String} attr Name of the attribute to be evaluated.
 
3017   DatePickerCtrl.prototype.evalAttr = function(attr) {
 
3018     if (this.$attrs[attr]) {
 
3019       this.$scope.$parent.$eval(this.$attrs[attr]);
 
3024    * Sets the ng-model value by first converting the date object into a strng. Converting it
 
3025    * is necessary, in order to pass Angular's `input[type="date"]` validations. Angular turns
 
3026    * the value into a Date object afterwards, before setting it on the model.
 
3027    * @param {Date=} value Date to be set as the model value.
 
3029   DatePickerCtrl.prototype.setModelValue = function(value) {
 
3030     var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
 
3031     this.ngModelCtrl.$setViewValue(this.ngDateFilter(value, 'yyyy-MM-dd', timezone));
 
3035    * Updates the datepicker when a model change occurred externally.
 
3036    * @param {Date=} value Value that was set to the model.
 
3038   DatePickerCtrl.prototype.onExternalChange = function(value) {
 
3039     var timezone = this.$mdUtil.getModelOption(this.ngModelCtrl, 'timezone');
 
3042     this.inputElement.value = this.locale.formatDate(value, timezone);
 
3043     this.mdInputContainer && this.mdInputContainer.setHasValue(!!value);
 
3044     this.resizeInputElement();
 
3045     this.updateErrorState();
 
3049 ngmaterial.components.datepicker = angular.module("material.components.datepicker");