datepicker.js 111 KB

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