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.

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