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.

2946 lines
105 KiB

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