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.

2947 lines
106 KiB

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