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