You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3047 lines
109 KiB

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