datepicker.js 112 KB

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