datepicker.mjs 273 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529
  1. import * as i5 from '@angular/cdk/a11y';
  2. import { A11yModule } from '@angular/cdk/a11y';
  3. import * as i9 from '@angular/cdk/overlay';
  4. import { Overlay, FlexibleConnectedPositionStrategy, OverlayConfig, OverlayModule } from '@angular/cdk/overlay';
  5. import * as i6 from '@angular/cdk/portal';
  6. import { ComponentPortal, TemplatePortal, PortalModule } from '@angular/cdk/portal';
  7. import * as i1 from '@angular/common';
  8. import { DOCUMENT, CommonModule } from '@angular/common';
  9. import * as i0 from '@angular/core';
  10. import { Injectable, inject, EventEmitter, Component, ViewEncapsulation, ChangeDetectionStrategy, Input, Output, Optional, SkipSelf, InjectionToken, Inject, ViewChild, forwardRef, Directive, Attribute, ContentChild, Self, TemplateRef, NgModule } from '@angular/core';
  11. import * as i3 from '@angular/material/button';
  12. import { MatButtonModule } from '@angular/material/button';
  13. import { CdkScrollableModule } from '@angular/cdk/scrolling';
  14. import * as i1$1 from '@angular/material/core';
  15. import { DateAdapter, MAT_DATE_FORMATS, mixinColor, mixinErrorState, MatCommonModule } from '@angular/material/core';
  16. import { Subject, Subscription, merge, of } from 'rxjs';
  17. import { ESCAPE, hasModifierKey, SPACE, ENTER, PAGE_DOWN, PAGE_UP, END, HOME, DOWN_ARROW, UP_ARROW, RIGHT_ARROW, LEFT_ARROW, BACKSPACE } from '@angular/cdk/keycodes';
  18. import * as i2 from '@angular/cdk/bidi';
  19. import { Directionality } from '@angular/cdk/bidi';
  20. import { normalizePassiveListenerOptions, Platform, _getFocusedElementPierceShadowDom } from '@angular/cdk/platform';
  21. import { take, startWith, filter } from 'rxjs/operators';
  22. import { coerceBooleanProperty, coerceStringArray } from '@angular/cdk/coercion';
  23. import { trigger, transition, animate, keyframes, style, state } from '@angular/animations';
  24. import * as i2$1 from '@angular/forms';
  25. import { NG_VALUE_ACCESSOR, NG_VALIDATORS, Validators, NgControl } from '@angular/forms';
  26. import { MAT_FORM_FIELD, MatFormFieldControl } from '@angular/material/form-field';
  27. import { MAT_INPUT_VALUE_ACCESSOR } from '@angular/material/input';
  28. /** @docs-private */
  29. function createMissingDateImplError(provider) {
  30. return Error(`MatDatepicker: No provider found for ${provider}. You must import one of the following ` +
  31. `modules at your application root: MatNativeDateModule, MatMomentDateModule, or provide a ` +
  32. `custom implementation.`);
  33. }
  34. /** Datepicker data that requires internationalization. */
  35. class MatDatepickerIntl {
  36. constructor() {
  37. /**
  38. * Stream that emits whenever the labels here are changed. Use this to notify
  39. * components if the labels have changed after initialization.
  40. */
  41. this.changes = new Subject();
  42. /** A label for the calendar popup (used by screen readers). */
  43. this.calendarLabel = 'Calendar';
  44. /** A label for the button used to open the calendar popup (used by screen readers). */
  45. this.openCalendarLabel = 'Open calendar';
  46. /** Label for the button used to close the calendar popup. */
  47. this.closeCalendarLabel = 'Close calendar';
  48. /** A label for the previous month button (used by screen readers). */
  49. this.prevMonthLabel = 'Previous month';
  50. /** A label for the next month button (used by screen readers). */
  51. this.nextMonthLabel = 'Next month';
  52. /** A label for the previous year button (used by screen readers). */
  53. this.prevYearLabel = 'Previous year';
  54. /** A label for the next year button (used by screen readers). */
  55. this.nextYearLabel = 'Next year';
  56. /** A label for the previous multi-year button (used by screen readers). */
  57. this.prevMultiYearLabel = 'Previous 24 years';
  58. /** A label for the next multi-year button (used by screen readers). */
  59. this.nextMultiYearLabel = 'Next 24 years';
  60. /** A label for the 'switch to month view' button (used by screen readers). */
  61. this.switchToMonthViewLabel = 'Choose date';
  62. /** A label for the 'switch to year view' button (used by screen readers). */
  63. this.switchToMultiYearViewLabel = 'Choose month and year';
  64. /**
  65. * A label for the first date of a range of dates (used by screen readers).
  66. * @deprecated Provide your own internationalization string.
  67. * @breaking-change 17.0.0
  68. */
  69. this.startDateLabel = 'Start date';
  70. /**
  71. * A label for the last date of a range of dates (used by screen readers).
  72. * @deprecated Provide your own internationalization string.
  73. * @breaking-change 17.0.0
  74. */
  75. this.endDateLabel = 'End date';
  76. }
  77. /** Formats a range of years (used for visuals). */
  78. formatYearRange(start, end) {
  79. return `${start} \u2013 ${end}`;
  80. }
  81. /** Formats a label for a range of years (used by screen readers). */
  82. formatYearRangeLabel(start, end) {
  83. return `${start} to ${end}`;
  84. }
  85. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  86. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, providedIn: 'root' }); }
  87. }
  88. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerIntl, decorators: [{
  89. type: Injectable,
  90. args: [{ providedIn: 'root' }]
  91. }] });
  92. /**
  93. * An internal class that represents the data corresponding to a single calendar cell.
  94. * @docs-private
  95. */
  96. class MatCalendarCell {
  97. constructor(value, displayValue, ariaLabel, enabled, cssClasses = {}, compareValue = value, rawValue) {
  98. this.value = value;
  99. this.displayValue = displayValue;
  100. this.ariaLabel = ariaLabel;
  101. this.enabled = enabled;
  102. this.cssClasses = cssClasses;
  103. this.compareValue = compareValue;
  104. this.rawValue = rawValue;
  105. }
  106. }
  107. let calendarBodyId = 1;
  108. /** Event options that can be used to bind an active, capturing event. */
  109. const activeCapturingEventOptions = normalizePassiveListenerOptions({
  110. passive: false,
  111. capture: true,
  112. });
  113. /** Event options that can be used to bind a passive, capturing event. */
  114. const passiveCapturingEventOptions = normalizePassiveListenerOptions({
  115. passive: true,
  116. capture: true,
  117. });
  118. /** Event options that can be used to bind a passive, non-capturing event. */
  119. const passiveEventOptions = normalizePassiveListenerOptions({ passive: true });
  120. /**
  121. * An internal component used to display calendar data in a table.
  122. * @docs-private
  123. */
  124. class MatCalendarBody {
  125. ngAfterViewChecked() {
  126. if (this._focusActiveCellAfterViewChecked) {
  127. this._focusActiveCell();
  128. this._focusActiveCellAfterViewChecked = false;
  129. }
  130. }
  131. constructor(_elementRef, _ngZone) {
  132. this._elementRef = _elementRef;
  133. this._ngZone = _ngZone;
  134. this._platform = inject(Platform);
  135. /**
  136. * Used to focus the active cell after change detection has run.
  137. */
  138. this._focusActiveCellAfterViewChecked = false;
  139. /** The number of columns in the table. */
  140. this.numCols = 7;
  141. /** The cell number of the active cell in the table. */
  142. this.activeCell = 0;
  143. /** Whether a range is being selected. */
  144. this.isRange = false;
  145. /**
  146. * The aspect ratio (width / height) to use for the cells in the table. This aspect ratio will be
  147. * maintained even as the table resizes.
  148. */
  149. this.cellAspectRatio = 1;
  150. /** Start of the preview range. */
  151. this.previewStart = null;
  152. /** End of the preview range. */
  153. this.previewEnd = null;
  154. /** Emits when a new value is selected. */
  155. this.selectedValueChange = new EventEmitter();
  156. /** Emits when the preview has changed as a result of a user action. */
  157. this.previewChange = new EventEmitter();
  158. this.activeDateChange = new EventEmitter();
  159. /** Emits the date at the possible start of a drag event. */
  160. this.dragStarted = new EventEmitter();
  161. /** Emits the date at the conclusion of a drag, or null if mouse was not released on a date. */
  162. this.dragEnded = new EventEmitter();
  163. this._didDragSinceMouseDown = false;
  164. /**
  165. * Event handler for when the user enters an element
  166. * inside the calendar body (e.g. by hovering in or focus).
  167. */
  168. this._enterHandler = (event) => {
  169. if (this._skipNextFocus && event.type === 'focus') {
  170. this._skipNextFocus = false;
  171. return;
  172. }
  173. // We only need to hit the zone when we're selecting a range.
  174. if (event.target && this.isRange) {
  175. const cell = this._getCellFromElement(event.target);
  176. if (cell) {
  177. this._ngZone.run(() => this.previewChange.emit({ value: cell.enabled ? cell : null, event }));
  178. }
  179. }
  180. };
  181. this._touchmoveHandler = (event) => {
  182. if (!this.isRange)
  183. return;
  184. const target = getActualTouchTarget(event);
  185. const cell = target ? this._getCellFromElement(target) : null;
  186. if (target !== event.target) {
  187. this._didDragSinceMouseDown = true;
  188. }
  189. // If the initial target of the touch is a date cell, prevent default so
  190. // that the move is not handled as a scroll.
  191. if (getCellElement(event.target)) {
  192. event.preventDefault();
  193. }
  194. this._ngZone.run(() => this.previewChange.emit({ value: cell?.enabled ? cell : null, event }));
  195. };
  196. /**
  197. * Event handler for when the user's pointer leaves an element
  198. * inside the calendar body (e.g. by hovering out or blurring).
  199. */
  200. this._leaveHandler = (event) => {
  201. // We only need to hit the zone when we're selecting a range.
  202. if (this.previewEnd !== null && this.isRange) {
  203. if (event.type !== 'blur') {
  204. this._didDragSinceMouseDown = true;
  205. }
  206. // Only reset the preview end value when leaving cells. This looks better, because
  207. // we have a gap between the cells and the rows and we don't want to remove the
  208. // range just for it to show up again when the user moves a few pixels to the side.
  209. if (event.target &&
  210. this._getCellFromElement(event.target) &&
  211. !(event.relatedTarget &&
  212. this._getCellFromElement(event.relatedTarget))) {
  213. this._ngZone.run(() => this.previewChange.emit({ value: null, event }));
  214. }
  215. }
  216. };
  217. /**
  218. * Triggered on mousedown or touchstart on a date cell.
  219. * Respsonsible for starting a drag sequence.
  220. */
  221. this._mousedownHandler = (event) => {
  222. if (!this.isRange)
  223. return;
  224. this._didDragSinceMouseDown = false;
  225. // Begin a drag if a cell within the current range was targeted.
  226. const cell = event.target && this._getCellFromElement(event.target);
  227. if (!cell || !this._isInRange(cell.rawValue)) {
  228. return;
  229. }
  230. this._ngZone.run(() => {
  231. this.dragStarted.emit({
  232. value: cell.rawValue,
  233. event,
  234. });
  235. });
  236. };
  237. /** Triggered on mouseup anywhere. Respsonsible for ending a drag sequence. */
  238. this._mouseupHandler = (event) => {
  239. if (!this.isRange)
  240. return;
  241. const cellElement = getCellElement(event.target);
  242. if (!cellElement) {
  243. // Mouseup happened outside of datepicker. Cancel drag.
  244. this._ngZone.run(() => {
  245. this.dragEnded.emit({ value: null, event });
  246. });
  247. return;
  248. }
  249. if (cellElement.closest('.mat-calendar-body') !== this._elementRef.nativeElement) {
  250. // Mouseup happened inside a different month instance.
  251. // Allow it to handle the event.
  252. return;
  253. }
  254. this._ngZone.run(() => {
  255. const cell = this._getCellFromElement(cellElement);
  256. this.dragEnded.emit({ value: cell?.rawValue ?? null, event });
  257. });
  258. };
  259. /** Triggered on touchend anywhere. Respsonsible for ending a drag sequence. */
  260. this._touchendHandler = (event) => {
  261. const target = getActualTouchTarget(event);
  262. if (target) {
  263. this._mouseupHandler({ target });
  264. }
  265. };
  266. this._id = `mat-calendar-body-${calendarBodyId++}`;
  267. this._startDateLabelId = `${this._id}-start-date`;
  268. this._endDateLabelId = `${this._id}-end-date`;
  269. _ngZone.runOutsideAngular(() => {
  270. const element = _elementRef.nativeElement;
  271. // `touchmove` is active since we need to call `preventDefault`.
  272. element.addEventListener('touchmove', this._touchmoveHandler, activeCapturingEventOptions);
  273. element.addEventListener('mouseenter', this._enterHandler, passiveCapturingEventOptions);
  274. element.addEventListener('focus', this._enterHandler, passiveCapturingEventOptions);
  275. element.addEventListener('mouseleave', this._leaveHandler, passiveCapturingEventOptions);
  276. element.addEventListener('blur', this._leaveHandler, passiveCapturingEventOptions);
  277. element.addEventListener('mousedown', this._mousedownHandler, passiveEventOptions);
  278. element.addEventListener('touchstart', this._mousedownHandler, passiveEventOptions);
  279. if (this._platform.isBrowser) {
  280. window.addEventListener('mouseup', this._mouseupHandler);
  281. window.addEventListener('touchend', this._touchendHandler);
  282. }
  283. });
  284. }
  285. /** Called when a cell is clicked. */
  286. _cellClicked(cell, event) {
  287. // Ignore "clicks" that are actually canceled drags (eg the user dragged
  288. // off and then went back to this cell to undo).
  289. if (this._didDragSinceMouseDown) {
  290. return;
  291. }
  292. if (cell.enabled) {
  293. this.selectedValueChange.emit({ value: cell.value, event });
  294. }
  295. }
  296. _emitActiveDateChange(cell, event) {
  297. if (cell.enabled) {
  298. this.activeDateChange.emit({ value: cell.value, event });
  299. }
  300. }
  301. /** Returns whether a cell should be marked as selected. */
  302. _isSelected(value) {
  303. return this.startValue === value || this.endValue === value;
  304. }
  305. ngOnChanges(changes) {
  306. const columnChanges = changes['numCols'];
  307. const { rows, numCols } = this;
  308. if (changes['rows'] || columnChanges) {
  309. this._firstRowOffset = rows && rows.length && rows[0].length ? numCols - rows[0].length : 0;
  310. }
  311. if (changes['cellAspectRatio'] || columnChanges || !this._cellPadding) {
  312. this._cellPadding = `${(50 * this.cellAspectRatio) / numCols}%`;
  313. }
  314. if (columnChanges || !this._cellWidth) {
  315. this._cellWidth = `${100 / numCols}%`;
  316. }
  317. }
  318. ngOnDestroy() {
  319. const element = this._elementRef.nativeElement;
  320. element.removeEventListener('touchmove', this._touchmoveHandler, activeCapturingEventOptions);
  321. element.removeEventListener('mouseenter', this._enterHandler, passiveCapturingEventOptions);
  322. element.removeEventListener('focus', this._enterHandler, passiveCapturingEventOptions);
  323. element.removeEventListener('mouseleave', this._leaveHandler, passiveCapturingEventOptions);
  324. element.removeEventListener('blur', this._leaveHandler, passiveCapturingEventOptions);
  325. element.removeEventListener('mousedown', this._mousedownHandler, passiveEventOptions);
  326. element.removeEventListener('touchstart', this._mousedownHandler, passiveEventOptions);
  327. if (this._platform.isBrowser) {
  328. window.removeEventListener('mouseup', this._mouseupHandler);
  329. window.removeEventListener('touchend', this._touchendHandler);
  330. }
  331. }
  332. /** Returns whether a cell is active. */
  333. _isActiveCell(rowIndex, colIndex) {
  334. let cellNumber = rowIndex * this.numCols + colIndex;
  335. // Account for the fact that the first row may not have as many cells.
  336. if (rowIndex) {
  337. cellNumber -= this._firstRowOffset;
  338. }
  339. return cellNumber == this.activeCell;
  340. }
  341. /**
  342. * Focuses the active cell after the microtask queue is empty.
  343. *
  344. * Adding a 0ms setTimeout seems to fix Voiceover losing focus when pressing PageUp/PageDown
  345. * (issue #24330).
  346. *
  347. * Determined a 0ms by gradually increasing duration from 0 and testing two use cases with screen
  348. * reader enabled:
  349. *
  350. * 1. Pressing PageUp/PageDown repeatedly with pausing between each key press.
  351. * 2. Pressing and holding the PageDown key with repeated keys enabled.
  352. *
  353. * Test 1 worked roughly 95-99% of the time with 0ms and got a little bit better as the duration
  354. * increased. Test 2 got slightly better until the duration was long enough to interfere with
  355. * repeated keys. If the repeated key speed was faster than the timeout duration, then pressing
  356. * and holding pagedown caused the entire page to scroll.
  357. *
  358. * Since repeated key speed can verify across machines, determined that any duration could
  359. * potentially interfere with repeated keys. 0ms would be best because it almost entirely
  360. * eliminates the focus being lost in Voiceover (#24330) without causing unintended side effects.
  361. * Adding delay also complicates writing tests.
  362. */
  363. _focusActiveCell(movePreview = true) {
  364. this._ngZone.runOutsideAngular(() => {
  365. this._ngZone.onStable.pipe(take(1)).subscribe(() => {
  366. setTimeout(() => {
  367. const activeCell = this._elementRef.nativeElement.querySelector('.mat-calendar-body-active');
  368. if (activeCell) {
  369. if (!movePreview) {
  370. this._skipNextFocus = true;
  371. }
  372. activeCell.focus();
  373. }
  374. });
  375. });
  376. });
  377. }
  378. /** Focuses the active cell after change detection has run and the microtask queue is empty. */
  379. _scheduleFocusActiveCellAfterViewChecked() {
  380. this._focusActiveCellAfterViewChecked = true;
  381. }
  382. /** Gets whether a value is the start of the main range. */
  383. _isRangeStart(value) {
  384. return isStart(value, this.startValue, this.endValue);
  385. }
  386. /** Gets whether a value is the end of the main range. */
  387. _isRangeEnd(value) {
  388. return isEnd(value, this.startValue, this.endValue);
  389. }
  390. /** Gets whether a value is within the currently-selected range. */
  391. _isInRange(value) {
  392. return isInRange(value, this.startValue, this.endValue, this.isRange);
  393. }
  394. /** Gets whether a value is the start of the comparison range. */
  395. _isComparisonStart(value) {
  396. return isStart(value, this.comparisonStart, this.comparisonEnd);
  397. }
  398. /** Whether the cell is a start bridge cell between the main and comparison ranges. */
  399. _isComparisonBridgeStart(value, rowIndex, colIndex) {
  400. if (!this._isComparisonStart(value) || this._isRangeStart(value) || !this._isInRange(value)) {
  401. return false;
  402. }
  403. let previousCell = this.rows[rowIndex][colIndex - 1];
  404. if (!previousCell) {
  405. const previousRow = this.rows[rowIndex - 1];
  406. previousCell = previousRow && previousRow[previousRow.length - 1];
  407. }
  408. return previousCell && !this._isRangeEnd(previousCell.compareValue);
  409. }
  410. /** Whether the cell is an end bridge cell between the main and comparison ranges. */
  411. _isComparisonBridgeEnd(value, rowIndex, colIndex) {
  412. if (!this._isComparisonEnd(value) || this._isRangeEnd(value) || !this._isInRange(value)) {
  413. return false;
  414. }
  415. let nextCell = this.rows[rowIndex][colIndex + 1];
  416. if (!nextCell) {
  417. const nextRow = this.rows[rowIndex + 1];
  418. nextCell = nextRow && nextRow[0];
  419. }
  420. return nextCell && !this._isRangeStart(nextCell.compareValue);
  421. }
  422. /** Gets whether a value is the end of the comparison range. */
  423. _isComparisonEnd(value) {
  424. return isEnd(value, this.comparisonStart, this.comparisonEnd);
  425. }
  426. /** Gets whether a value is within the current comparison range. */
  427. _isInComparisonRange(value) {
  428. return isInRange(value, this.comparisonStart, this.comparisonEnd, this.isRange);
  429. }
  430. /**
  431. * Gets whether a value is the same as the start and end of the comparison range.
  432. * For context, the functions that we use to determine whether something is the start/end of
  433. * a range don't allow for the start and end to be on the same day, because we'd have to use
  434. * much more specific CSS selectors to style them correctly in all scenarios. This is fine for
  435. * the regular range, because when it happens, the selected styles take over and still show where
  436. * the range would've been, however we don't have these selected styles for a comparison range.
  437. * This function is used to apply a class that serves the same purpose as the one for selected
  438. * dates, but it only applies in the context of a comparison range.
  439. */
  440. _isComparisonIdentical(value) {
  441. // Note that we don't need to null check the start/end
  442. // here, because the `value` will always be defined.
  443. return this.comparisonStart === this.comparisonEnd && value === this.comparisonStart;
  444. }
  445. /** Gets whether a value is the start of the preview range. */
  446. _isPreviewStart(value) {
  447. return isStart(value, this.previewStart, this.previewEnd);
  448. }
  449. /** Gets whether a value is the end of the preview range. */
  450. _isPreviewEnd(value) {
  451. return isEnd(value, this.previewStart, this.previewEnd);
  452. }
  453. /** Gets whether a value is inside the preview range. */
  454. _isInPreview(value) {
  455. return isInRange(value, this.previewStart, this.previewEnd, this.isRange);
  456. }
  457. /** Gets ids of aria descriptions for the start and end of a date range. */
  458. _getDescribedby(value) {
  459. if (!this.isRange) {
  460. return null;
  461. }
  462. if (this.startValue === value && this.endValue === value) {
  463. return `${this._startDateLabelId} ${this._endDateLabelId}`;
  464. }
  465. else if (this.startValue === value) {
  466. return this._startDateLabelId;
  467. }
  468. else if (this.endValue === value) {
  469. return this._endDateLabelId;
  470. }
  471. return null;
  472. }
  473. /** Finds the MatCalendarCell that corresponds to a DOM node. */
  474. _getCellFromElement(element) {
  475. const cell = getCellElement(element);
  476. if (cell) {
  477. const row = cell.getAttribute('data-mat-row');
  478. const col = cell.getAttribute('data-mat-col');
  479. if (row && col) {
  480. return this.rows[parseInt(row)][parseInt(col)];
  481. }
  482. }
  483. return null;
  484. }
  485. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarBody, deps: [{ token: i0.ElementRef }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Component }); }
  486. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: { label: "label", rows: "rows", todayValue: "todayValue", startValue: "startValue", endValue: "endValue", labelMinRequiredCells: "labelMinRequiredCells", numCols: "numCols", activeCell: "activeCell", isRange: "isRange", cellAspectRatio: "cellAspectRatio", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", previewStart: "previewStart", previewEnd: "previewEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName" }, outputs: { selectedValueChange: "selectedValueChange", previewChange: "previewChange", activeDateChange: "activeDateChange", dragStarted: "dragStarted", dragEnded: "dragEnded" }, host: { classAttribute: "mat-calendar-body" }, exportAs: ["matCalendarBody"], usesOnChanges: true, ngImport: i0, template: "<!--\n If there's not enough space in the first row, create a separate label row. We mark this row as\n aria-hidden because we don't want it to be read out as one of the weeks in the month.\n-->\n<tr *ngIf=\"_firstRowOffset < labelMinRequiredCells\" aria-hidden=\"true\">\n <td class=\"mat-calendar-body-label\"\n [attr.colspan]=\"numCols\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{label}}\n </td>\n</tr>\n\n<!-- Create the first row separately so we can include a special spacer cell. -->\n<tr *ngFor=\"let row of rows; let rowIndex = index\" role=\"row\">\n <!--\n This cell is purely decorative, but we can't put `aria-hidden` or `role=\"presentation\"` on it,\n because it throws off the week days for the rest of the row on NVDA. The aspect ratio of the\n table cells is maintained by setting the top and bottom padding as a percentage of the width\n (a variant of the trick described here: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp).\n -->\n <td *ngIf=\"rowIndex === 0 && _firstRowOffset\"\n class=\"mat-calendar-body-label\"\n [attr.colspan]=\"_firstRowOffset\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{_firstRowOffset >= labelMinRequiredCells ? label : ''}}\n </td>\n <!--\n Each gridcell in the calendar contains a button, which signals to assistive technology that the\n cell is interactable, as well as the selection state via `aria-pressed`. See #23476 for\n background.\n -->\n <td\n *ngFor=\"let item of row; let colIndex = index\"\n role=\"gridcell\"\n class=\"mat-calendar-body-cell-container\"\n [style.width]=\"_cellWidth\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\"\n [attr.data-mat-row]=\"rowIndex\"\n [attr.data-mat-col]=\"colIndex\"\n >\n <button\n type=\"button\"\n class=\"mat-calendar-body-cell\"\n [ngClass]=\"item.cssClasses\"\n [tabindex]=\"_isActiveCell(rowIndex, colIndex) ? 0 : -1\"\n [class.mat-calendar-body-disabled]=\"!item.enabled\"\n [class.mat-calendar-body-active]=\"_isActiveCell(rowIndex, colIndex)\"\n [class.mat-calendar-body-range-start]=\"_isRangeStart(item.compareValue)\"\n [class.mat-calendar-body-range-end]=\"_isRangeEnd(item.compareValue)\"\n [class.mat-calendar-body-in-range]=\"_isInRange(item.compareValue)\"\n [class.mat-calendar-body-comparison-bridge-start]=\"_isComparisonBridgeStart(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-bridge-end]=\"_isComparisonBridgeEnd(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-start]=\"_isComparisonStart(item.compareValue)\"\n [class.mat-calendar-body-comparison-end]=\"_isComparisonEnd(item.compareValue)\"\n [class.mat-calendar-body-in-comparison-range]=\"_isInComparisonRange(item.compareValue)\"\n [class.mat-calendar-body-preview-start]=\"_isPreviewStart(item.compareValue)\"\n [class.mat-calendar-body-preview-end]=\"_isPreviewEnd(item.compareValue)\"\n [class.mat-calendar-body-in-preview]=\"_isInPreview(item.compareValue)\"\n [attr.aria-label]=\"item.ariaLabel\"\n [attr.aria-disabled]=\"!item.enabled || null\"\n [attr.aria-pressed]=\"_isSelected(item.compareValue)\"\n [attr.aria-current]=\"todayValue === item.compareValue ? 'date' : null\"\n [attr.aria-describedby]=\"_getDescribedby(item.compareValue)\"\n (click)=\"_cellClicked(item, $event)\"\n (focus)=\"_emitActiveDateChange(item, $event)\">\n <span class=\"mat-calendar-body-cell-content mat-focus-indicator\"\n [class.mat-calendar-body-selected]=\"_isSelected(item.compareValue)\"\n [class.mat-calendar-body-comparison-identical]=\"_isComparisonIdentical(item.compareValue)\"\n [class.mat-calendar-body-today]=\"todayValue === item.compareValue\">\n {{item.displayValue}}\n </span>\n <span class=\"mat-calendar-body-cell-preview\" aria-hidden=\"true\"></span>\n </button>\n </td>\n</tr>\n\n<label [id]=\"_startDateLabelId\" class=\"mat-calendar-body-hidden-label\">\n {{startDateAccessibleName}}\n</label>\n<label [id]=\"_endDateLabelId\" class=\"mat-calendar-body-hidden-label\">\n {{endDateAccessibleName}}\n</label>\n", styles: [".mat-calendar-body{min-width:224px}.mat-calendar-body-label{height:0;line-height:0;text-align:left;padding-left:4.7142857143%;padding-right:4.7142857143%}.mat-calendar-body-hidden-label{display:none}.mat-calendar-body-cell-container{position:relative;height:0;line-height:0}.mat-calendar-body-cell{-webkit-user-select:none;user-select:none;cursor:pointer;outline:none;border:none;-webkit-tap-highlight-color:rgba(0,0,0,0);position:absolute;top:0;left:0;width:100%;height:100%;background:none;text-align:center;outline:none;font-family:inherit;margin:0}.mat-calendar-body-cell::-moz-focus-inner{border:0}.mat-calendar-body-cell::before,.mat-calendar-body-cell::after,.mat-calendar-body-cell-preview{content:\"\";position:absolute;top:5%;left:0;z-index:0;box-sizing:border-box;display:block;height:90%;width:100%}.mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,.mat-calendar-body-range-start::after,.mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,.mat-calendar-body-comparison-start::after,.mat-calendar-body-preview-start .mat-calendar-body-cell-preview{left:5%;width:95%;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,[dir=rtl] .mat-calendar-body-comparison-start::after,[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{left:0;border-radius:0;border-top-right-radius:999px;border-bottom-right-radius:999px}.mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,.mat-calendar-body-range-end::after,.mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,.mat-calendar-body-comparison-end::after,.mat-calendar-body-preview-end .mat-calendar-body-cell-preview{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}[dir=rtl] .mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,[dir=rtl] .mat-calendar-body-comparison-end::after,[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{left:5%;border-radius:0;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-comparison-bridge-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-bridge-end.mat-calendar-body-range-start::after{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}.mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,.mat-calendar-body-comparison-end.mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-end.mat-calendar-body-range-start::after{width:90%}.mat-calendar-body-in-preview .mat-calendar-body-cell-preview{border-top:dashed 1px;border-bottom:dashed 1px}.mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:dashed 1px}[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:0;border-right:dashed 1px}.mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:dashed 1px}[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:0;border-left:dashed 1px}.mat-calendar-body-disabled{cursor:default}.cdk-high-contrast-active .mat-calendar-body-disabled{opacity:.5}.mat-calendar-body-cell-content{top:5%;left:5%;z-index:1;display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:90%;height:90%;line-height:1;border-width:1px;border-style:solid;border-radius:999px}.mat-calendar-body-cell-content.mat-focus-indicator{position:absolute}.cdk-high-contrast-active .mat-calendar-body-cell-content{border:none}.cdk-high-contrast-active .mat-datepicker-popup:not(:empty),.cdk-high-contrast-active .mat-calendar-body-cell:not(.mat-calendar-body-in-range) .mat-calendar-body-selected{outline:solid 1px}.cdk-high-contrast-active .mat-calendar-body-today{outline:dotted 1px}.cdk-high-contrast-active .mat-calendar-body-cell::before,.cdk-high-contrast-active .mat-calendar-body-cell::after,.cdk-high-contrast-active .mat-calendar-body-selected{background:none}.cdk-high-contrast-active .mat-calendar-body-in-range::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-start::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-end::before{border-top:solid 1px;border-bottom:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:0;border-right:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:0;border-left:solid 1px}.cdk-high-contrast-active .mat-calendar-body-in-comparison-range::before{border-top:dashed 1px;border-bottom:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:0;border-right:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:0;border-left:dashed 1px}[dir=rtl] .mat-calendar-body-label{text-align:right}"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  487. }
  488. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarBody, decorators: [{
  489. type: Component,
  490. args: [{ selector: '[mat-calendar-body]', host: {
  491. 'class': 'mat-calendar-body',
  492. }, exportAs: 'matCalendarBody', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<!--\n If there's not enough space in the first row, create a separate label row. We mark this row as\n aria-hidden because we don't want it to be read out as one of the weeks in the month.\n-->\n<tr *ngIf=\"_firstRowOffset < labelMinRequiredCells\" aria-hidden=\"true\">\n <td class=\"mat-calendar-body-label\"\n [attr.colspan]=\"numCols\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{label}}\n </td>\n</tr>\n\n<!-- Create the first row separately so we can include a special spacer cell. -->\n<tr *ngFor=\"let row of rows; let rowIndex = index\" role=\"row\">\n <!--\n This cell is purely decorative, but we can't put `aria-hidden` or `role=\"presentation\"` on it,\n because it throws off the week days for the rest of the row on NVDA. The aspect ratio of the\n table cells is maintained by setting the top and bottom padding as a percentage of the width\n (a variant of the trick described here: https://www.w3schools.com/howto/howto_css_aspect_ratio.asp).\n -->\n <td *ngIf=\"rowIndex === 0 && _firstRowOffset\"\n class=\"mat-calendar-body-label\"\n [attr.colspan]=\"_firstRowOffset\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\">\n {{_firstRowOffset >= labelMinRequiredCells ? label : ''}}\n </td>\n <!--\n Each gridcell in the calendar contains a button, which signals to assistive technology that the\n cell is interactable, as well as the selection state via `aria-pressed`. See #23476 for\n background.\n -->\n <td\n *ngFor=\"let item of row; let colIndex = index\"\n role=\"gridcell\"\n class=\"mat-calendar-body-cell-container\"\n [style.width]=\"_cellWidth\"\n [style.paddingTop]=\"_cellPadding\"\n [style.paddingBottom]=\"_cellPadding\"\n [attr.data-mat-row]=\"rowIndex\"\n [attr.data-mat-col]=\"colIndex\"\n >\n <button\n type=\"button\"\n class=\"mat-calendar-body-cell\"\n [ngClass]=\"item.cssClasses\"\n [tabindex]=\"_isActiveCell(rowIndex, colIndex) ? 0 : -1\"\n [class.mat-calendar-body-disabled]=\"!item.enabled\"\n [class.mat-calendar-body-active]=\"_isActiveCell(rowIndex, colIndex)\"\n [class.mat-calendar-body-range-start]=\"_isRangeStart(item.compareValue)\"\n [class.mat-calendar-body-range-end]=\"_isRangeEnd(item.compareValue)\"\n [class.mat-calendar-body-in-range]=\"_isInRange(item.compareValue)\"\n [class.mat-calendar-body-comparison-bridge-start]=\"_isComparisonBridgeStart(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-bridge-end]=\"_isComparisonBridgeEnd(item.compareValue, rowIndex, colIndex)\"\n [class.mat-calendar-body-comparison-start]=\"_isComparisonStart(item.compareValue)\"\n [class.mat-calendar-body-comparison-end]=\"_isComparisonEnd(item.compareValue)\"\n [class.mat-calendar-body-in-comparison-range]=\"_isInComparisonRange(item.compareValue)\"\n [class.mat-calendar-body-preview-start]=\"_isPreviewStart(item.compareValue)\"\n [class.mat-calendar-body-preview-end]=\"_isPreviewEnd(item.compareValue)\"\n [class.mat-calendar-body-in-preview]=\"_isInPreview(item.compareValue)\"\n [attr.aria-label]=\"item.ariaLabel\"\n [attr.aria-disabled]=\"!item.enabled || null\"\n [attr.aria-pressed]=\"_isSelected(item.compareValue)\"\n [attr.aria-current]=\"todayValue === item.compareValue ? 'date' : null\"\n [attr.aria-describedby]=\"_getDescribedby(item.compareValue)\"\n (click)=\"_cellClicked(item, $event)\"\n (focus)=\"_emitActiveDateChange(item, $event)\">\n <span class=\"mat-calendar-body-cell-content mat-focus-indicator\"\n [class.mat-calendar-body-selected]=\"_isSelected(item.compareValue)\"\n [class.mat-calendar-body-comparison-identical]=\"_isComparisonIdentical(item.compareValue)\"\n [class.mat-calendar-body-today]=\"todayValue === item.compareValue\">\n {{item.displayValue}}\n </span>\n <span class=\"mat-calendar-body-cell-preview\" aria-hidden=\"true\"></span>\n </button>\n </td>\n</tr>\n\n<label [id]=\"_startDateLabelId\" class=\"mat-calendar-body-hidden-label\">\n {{startDateAccessibleName}}\n</label>\n<label [id]=\"_endDateLabelId\" class=\"mat-calendar-body-hidden-label\">\n {{endDateAccessibleName}}\n</label>\n", styles: [".mat-calendar-body{min-width:224px}.mat-calendar-body-label{height:0;line-height:0;text-align:left;padding-left:4.7142857143%;padding-right:4.7142857143%}.mat-calendar-body-hidden-label{display:none}.mat-calendar-body-cell-container{position:relative;height:0;line-height:0}.mat-calendar-body-cell{-webkit-user-select:none;user-select:none;cursor:pointer;outline:none;border:none;-webkit-tap-highlight-color:rgba(0,0,0,0);position:absolute;top:0;left:0;width:100%;height:100%;background:none;text-align:center;outline:none;font-family:inherit;margin:0}.mat-calendar-body-cell::-moz-focus-inner{border:0}.mat-calendar-body-cell::before,.mat-calendar-body-cell::after,.mat-calendar-body-cell-preview{content:\"\";position:absolute;top:5%;left:0;z-index:0;box-sizing:border-box;display:block;height:90%;width:100%}.mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,.mat-calendar-body-range-start::after,.mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,.mat-calendar-body-comparison-start::after,.mat-calendar-body-preview-start .mat-calendar-body-cell-preview{left:5%;width:95%;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-range-start:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-start:not(.mat-calendar-body-comparison-bridge-start)::before,[dir=rtl] .mat-calendar-body-comparison-start::after,[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{left:0;border-radius:0;border-top-right-radius:999px;border-bottom-right-radius:999px}.mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,.mat-calendar-body-range-end::after,.mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,.mat-calendar-body-comparison-end::after,.mat-calendar-body-preview-end .mat-calendar-body-cell-preview{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}[dir=rtl] .mat-calendar-body-range-end:not(.mat-calendar-body-in-comparison-range)::before,[dir=rtl] .mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-end:not(.mat-calendar-body-comparison-bridge-end)::before,[dir=rtl] .mat-calendar-body-comparison-end::after,[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{left:5%;border-radius:0;border-top-left-radius:999px;border-bottom-left-radius:999px}[dir=rtl] .mat-calendar-body-comparison-bridge-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-bridge-end.mat-calendar-body-range-start::after{width:95%;border-top-right-radius:999px;border-bottom-right-radius:999px}.mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,[dir=rtl] .mat-calendar-body-comparison-start.mat-calendar-body-range-end::after,.mat-calendar-body-comparison-end.mat-calendar-body-range-start::after,[dir=rtl] .mat-calendar-body-comparison-end.mat-calendar-body-range-start::after{width:90%}.mat-calendar-body-in-preview .mat-calendar-body-cell-preview{border-top:dashed 1px;border-bottom:dashed 1px}.mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:dashed 1px}[dir=rtl] .mat-calendar-body-preview-start .mat-calendar-body-cell-preview{border-left:0;border-right:dashed 1px}.mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:dashed 1px}[dir=rtl] .mat-calendar-body-preview-end .mat-calendar-body-cell-preview{border-right:0;border-left:dashed 1px}.mat-calendar-body-disabled{cursor:default}.cdk-high-contrast-active .mat-calendar-body-disabled{opacity:.5}.mat-calendar-body-cell-content{top:5%;left:5%;z-index:1;display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:90%;height:90%;line-height:1;border-width:1px;border-style:solid;border-radius:999px}.mat-calendar-body-cell-content.mat-focus-indicator{position:absolute}.cdk-high-contrast-active .mat-calendar-body-cell-content{border:none}.cdk-high-contrast-active .mat-datepicker-popup:not(:empty),.cdk-high-contrast-active .mat-calendar-body-cell:not(.mat-calendar-body-in-range) .mat-calendar-body-selected{outline:solid 1px}.cdk-high-contrast-active .mat-calendar-body-today{outline:dotted 1px}.cdk-high-contrast-active .mat-calendar-body-cell::before,.cdk-high-contrast-active .mat-calendar-body-cell::after,.cdk-high-contrast-active .mat-calendar-body-selected{background:none}.cdk-high-contrast-active .mat-calendar-body-in-range::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-start::before,.cdk-high-contrast-active .mat-calendar-body-comparison-bridge-end::before{border-top:solid 1px;border-bottom:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-start::before{border-left:0;border-right:solid 1px}.cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:solid 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-range-end::before{border-right:0;border-left:solid 1px}.cdk-high-contrast-active .mat-calendar-body-in-comparison-range::before{border-top:dashed 1px;border-bottom:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-start::before{border-left:0;border-right:dashed 1px}.cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:dashed 1px}[dir=rtl] .cdk-high-contrast-active .mat-calendar-body-comparison-end::before{border-right:0;border-left:dashed 1px}[dir=rtl] .mat-calendar-body-label{text-align:right}"] }]
  493. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.NgZone }]; }, propDecorators: { label: [{
  494. type: Input
  495. }], rows: [{
  496. type: Input
  497. }], todayValue: [{
  498. type: Input
  499. }], startValue: [{
  500. type: Input
  501. }], endValue: [{
  502. type: Input
  503. }], labelMinRequiredCells: [{
  504. type: Input
  505. }], numCols: [{
  506. type: Input
  507. }], activeCell: [{
  508. type: Input
  509. }], isRange: [{
  510. type: Input
  511. }], cellAspectRatio: [{
  512. type: Input
  513. }], comparisonStart: [{
  514. type: Input
  515. }], comparisonEnd: [{
  516. type: Input
  517. }], previewStart: [{
  518. type: Input
  519. }], previewEnd: [{
  520. type: Input
  521. }], startDateAccessibleName: [{
  522. type: Input
  523. }], endDateAccessibleName: [{
  524. type: Input
  525. }], selectedValueChange: [{
  526. type: Output
  527. }], previewChange: [{
  528. type: Output
  529. }], activeDateChange: [{
  530. type: Output
  531. }], dragStarted: [{
  532. type: Output
  533. }], dragEnded: [{
  534. type: Output
  535. }] } });
  536. /** Checks whether a node is a table cell element. */
  537. function isTableCell(node) {
  538. return node?.nodeName === 'TD';
  539. }
  540. /**
  541. * Gets the date table cell element that is or contains the specified element.
  542. * Or returns null if element is not part of a date cell.
  543. */
  544. function getCellElement(element) {
  545. let cell;
  546. if (isTableCell(element)) {
  547. cell = element;
  548. }
  549. else if (isTableCell(element.parentNode)) {
  550. cell = element.parentNode;
  551. }
  552. else if (isTableCell(element.parentNode?.parentNode)) {
  553. cell = element.parentNode.parentNode;
  554. }
  555. return cell?.getAttribute('data-mat-row') != null ? cell : null;
  556. }
  557. /** Checks whether a value is the start of a range. */
  558. function isStart(value, start, end) {
  559. return end !== null && start !== end && value < end && value === start;
  560. }
  561. /** Checks whether a value is the end of a range. */
  562. function isEnd(value, start, end) {
  563. return start !== null && start !== end && value >= start && value === end;
  564. }
  565. /** Checks whether a value is inside of a range. */
  566. function isInRange(value, start, end, rangeEnabled) {
  567. return (rangeEnabled &&
  568. start !== null &&
  569. end !== null &&
  570. start !== end &&
  571. value >= start &&
  572. value <= end);
  573. }
  574. /**
  575. * Extracts the element that actually corresponds to a touch event's location
  576. * (rather than the element that initiated the sequence of touch events).
  577. */
  578. function getActualTouchTarget(event) {
  579. const touchLocation = event.changedTouches[0];
  580. return document.elementFromPoint(touchLocation.clientX, touchLocation.clientY);
  581. }
  582. /** A class representing a range of dates. */
  583. class DateRange {
  584. constructor(
  585. /** The start date of the range. */
  586. start,
  587. /** The end date of the range. */
  588. end) {
  589. this.start = start;
  590. this.end = end;
  591. }
  592. }
  593. /**
  594. * A selection model containing a date selection.
  595. * @docs-private
  596. */
  597. class MatDateSelectionModel {
  598. constructor(
  599. /** The current selection. */
  600. selection, _adapter) {
  601. this.selection = selection;
  602. this._adapter = _adapter;
  603. this._selectionChanged = new Subject();
  604. /** Emits when the selection has changed. */
  605. this.selectionChanged = this._selectionChanged;
  606. this.selection = selection;
  607. }
  608. /**
  609. * Updates the current selection in the model.
  610. * @param value New selection that should be assigned.
  611. * @param source Object that triggered the selection change.
  612. */
  613. updateSelection(value, source) {
  614. const oldValue = this.selection;
  615. this.selection = value;
  616. this._selectionChanged.next({ selection: value, source, oldValue });
  617. }
  618. ngOnDestroy() {
  619. this._selectionChanged.complete();
  620. }
  621. _isValidDateInstance(date) {
  622. return this._adapter.isDateInstance(date) && this._adapter.isValid(date);
  623. }
  624. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel, deps: "invalid", target: i0.ɵɵFactoryTarget.Injectable }); }
  625. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel }); }
  626. }
  627. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateSelectionModel, decorators: [{
  628. type: Injectable
  629. }], ctorParameters: function () { return [{ type: undefined }, { type: i1$1.DateAdapter }]; } });
  630. /**
  631. * A selection model that contains a single date.
  632. * @docs-private
  633. */
  634. class MatSingleDateSelectionModel extends MatDateSelectionModel {
  635. constructor(adapter) {
  636. super(null, adapter);
  637. }
  638. /**
  639. * Adds a date to the current selection. In the case of a single date selection, the added date
  640. * simply overwrites the previous selection
  641. */
  642. add(date) {
  643. super.updateSelection(date, this);
  644. }
  645. /** Checks whether the current selection is valid. */
  646. isValid() {
  647. return this.selection != null && this._isValidDateInstance(this.selection);
  648. }
  649. /**
  650. * Checks whether the current selection is complete. In the case of a single date selection, this
  651. * is true if the current selection is not null.
  652. */
  653. isComplete() {
  654. return this.selection != null;
  655. }
  656. /** Clones the selection model. */
  657. clone() {
  658. const clone = new MatSingleDateSelectionModel(this._adapter);
  659. clone.updateSelection(this.selection, this);
  660. return clone;
  661. }
  662. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); }
  663. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel }); }
  664. }
  665. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatSingleDateSelectionModel, decorators: [{
  666. type: Injectable
  667. }], ctorParameters: function () { return [{ type: i1$1.DateAdapter }]; } });
  668. /**
  669. * A selection model that contains a date range.
  670. * @docs-private
  671. */
  672. class MatRangeDateSelectionModel extends MatDateSelectionModel {
  673. constructor(adapter) {
  674. super(new DateRange(null, null), adapter);
  675. }
  676. /**
  677. * Adds a date to the current selection. In the case of a date range selection, the added date
  678. * fills in the next `null` value in the range. If both the start and the end already have a date,
  679. * the selection is reset so that the given date is the new `start` and the `end` is null.
  680. */
  681. add(date) {
  682. let { start, end } = this.selection;
  683. if (start == null) {
  684. start = date;
  685. }
  686. else if (end == null) {
  687. end = date;
  688. }
  689. else {
  690. start = date;
  691. end = null;
  692. }
  693. super.updateSelection(new DateRange(start, end), this);
  694. }
  695. /** Checks whether the current selection is valid. */
  696. isValid() {
  697. const { start, end } = this.selection;
  698. // Empty ranges are valid.
  699. if (start == null && end == null) {
  700. return true;
  701. }
  702. // Complete ranges are only valid if both dates are valid and the start is before the end.
  703. if (start != null && end != null) {
  704. return (this._isValidDateInstance(start) &&
  705. this._isValidDateInstance(end) &&
  706. this._adapter.compareDate(start, end) <= 0);
  707. }
  708. // Partial ranges are valid if the start/end is valid.
  709. return ((start == null || this._isValidDateInstance(start)) &&
  710. (end == null || this._isValidDateInstance(end)));
  711. }
  712. /**
  713. * Checks whether the current selection is complete. In the case of a date range selection, this
  714. * is true if the current selection has a non-null `start` and `end`.
  715. */
  716. isComplete() {
  717. return this.selection.start != null && this.selection.end != null;
  718. }
  719. /** Clones the selection model. */
  720. clone() {
  721. const clone = new MatRangeDateSelectionModel(this._adapter);
  722. clone.updateSelection(this.selection, this);
  723. return clone;
  724. }
  725. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); }
  726. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel }); }
  727. }
  728. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatRangeDateSelectionModel, decorators: [{
  729. type: Injectable
  730. }], ctorParameters: function () { return [{ type: i1$1.DateAdapter }]; } });
  731. /** @docs-private */
  732. function MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY(parent, adapter) {
  733. return parent || new MatSingleDateSelectionModel(adapter);
  734. }
  735. /**
  736. * Used to provide a single selection model to a component.
  737. * @docs-private
  738. */
  739. const MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER = {
  740. provide: MatDateSelectionModel,
  741. deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter],
  742. useFactory: MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY,
  743. };
  744. /** @docs-private */
  745. function MAT_RANGE_DATE_SELECTION_MODEL_FACTORY(parent, adapter) {
  746. return parent || new MatRangeDateSelectionModel(adapter);
  747. }
  748. /**
  749. * Used to provide a range selection model to a component.
  750. * @docs-private
  751. */
  752. const MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER = {
  753. provide: MatDateSelectionModel,
  754. deps: [[new Optional(), new SkipSelf(), MatDateSelectionModel], DateAdapter],
  755. useFactory: MAT_RANGE_DATE_SELECTION_MODEL_FACTORY,
  756. };
  757. /** Injection token used to customize the date range selection behavior. */
  758. const MAT_DATE_RANGE_SELECTION_STRATEGY = new InjectionToken('MAT_DATE_RANGE_SELECTION_STRATEGY');
  759. /** Provides the default date range selection behavior. */
  760. class DefaultMatCalendarRangeStrategy {
  761. constructor(_dateAdapter) {
  762. this._dateAdapter = _dateAdapter;
  763. }
  764. selectionFinished(date, currentRange) {
  765. let { start, end } = currentRange;
  766. if (start == null) {
  767. start = date;
  768. }
  769. else if (end == null && date && this._dateAdapter.compareDate(date, start) >= 0) {
  770. end = date;
  771. }
  772. else {
  773. start = date;
  774. end = null;
  775. }
  776. return new DateRange(start, end);
  777. }
  778. createPreview(activeDate, currentRange) {
  779. let start = null;
  780. let end = null;
  781. if (currentRange.start && !currentRange.end && activeDate) {
  782. start = currentRange.start;
  783. end = activeDate;
  784. }
  785. return new DateRange(start, end);
  786. }
  787. createDrag(dragOrigin, originalRange, newDate) {
  788. let start = originalRange.start;
  789. let end = originalRange.end;
  790. if (!start || !end) {
  791. // Can't drag from an incomplete range.
  792. return null;
  793. }
  794. const adapter = this._dateAdapter;
  795. const isRange = adapter.compareDate(start, end) !== 0;
  796. const diffYears = adapter.getYear(newDate) - adapter.getYear(dragOrigin);
  797. const diffMonths = adapter.getMonth(newDate) - adapter.getMonth(dragOrigin);
  798. const diffDays = adapter.getDate(newDate) - adapter.getDate(dragOrigin);
  799. if (isRange && adapter.sameDate(dragOrigin, originalRange.start)) {
  800. start = newDate;
  801. if (adapter.compareDate(newDate, end) > 0) {
  802. end = adapter.addCalendarYears(end, diffYears);
  803. end = adapter.addCalendarMonths(end, diffMonths);
  804. end = adapter.addCalendarDays(end, diffDays);
  805. }
  806. }
  807. else if (isRange && adapter.sameDate(dragOrigin, originalRange.end)) {
  808. end = newDate;
  809. if (adapter.compareDate(newDate, start) < 0) {
  810. start = adapter.addCalendarYears(start, diffYears);
  811. start = adapter.addCalendarMonths(start, diffMonths);
  812. start = adapter.addCalendarDays(start, diffDays);
  813. }
  814. }
  815. else {
  816. start = adapter.addCalendarYears(start, diffYears);
  817. start = adapter.addCalendarMonths(start, diffMonths);
  818. start = adapter.addCalendarDays(start, diffDays);
  819. end = adapter.addCalendarYears(end, diffYears);
  820. end = adapter.addCalendarMonths(end, diffMonths);
  821. end = adapter.addCalendarDays(end, diffDays);
  822. }
  823. return new DateRange(start, end);
  824. }
  825. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy, deps: [{ token: i1$1.DateAdapter }], target: i0.ɵɵFactoryTarget.Injectable }); }
  826. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy }); }
  827. }
  828. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: DefaultMatCalendarRangeStrategy, decorators: [{
  829. type: Injectable
  830. }], ctorParameters: function () { return [{ type: i1$1.DateAdapter }]; } });
  831. /** @docs-private */
  832. function MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY(parent, adapter) {
  833. return parent || new DefaultMatCalendarRangeStrategy(adapter);
  834. }
  835. /** @docs-private */
  836. const MAT_CALENDAR_RANGE_STRATEGY_PROVIDER = {
  837. provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
  838. deps: [[new Optional(), new SkipSelf(), MAT_DATE_RANGE_SELECTION_STRATEGY], DateAdapter],
  839. useFactory: MAT_CALENDAR_RANGE_STRATEGY_PROVIDER_FACTORY,
  840. };
  841. const DAYS_PER_WEEK = 7;
  842. /**
  843. * An internal component used to display a single month in the datepicker.
  844. * @docs-private
  845. */
  846. class MatMonthView {
  847. /**
  848. * The date to display in this month view (everything other than the month and year is ignored).
  849. */
  850. get activeDate() {
  851. return this._activeDate;
  852. }
  853. set activeDate(value) {
  854. const oldActiveDate = this._activeDate;
  855. const validDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)) ||
  856. this._dateAdapter.today();
  857. this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
  858. if (!this._hasSameMonthAndYear(oldActiveDate, this._activeDate)) {
  859. this._init();
  860. }
  861. }
  862. /** The currently selected date. */
  863. get selected() {
  864. return this._selected;
  865. }
  866. set selected(value) {
  867. if (value instanceof DateRange) {
  868. this._selected = value;
  869. }
  870. else {
  871. this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  872. }
  873. this._setRanges(this._selected);
  874. }
  875. /** The minimum selectable date. */
  876. get minDate() {
  877. return this._minDate;
  878. }
  879. set minDate(value) {
  880. this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  881. }
  882. /** The maximum selectable date. */
  883. get maxDate() {
  884. return this._maxDate;
  885. }
  886. set maxDate(value) {
  887. this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  888. }
  889. constructor(_changeDetectorRef, _dateFormats, _dateAdapter, _dir, _rangeStrategy) {
  890. this._changeDetectorRef = _changeDetectorRef;
  891. this._dateFormats = _dateFormats;
  892. this._dateAdapter = _dateAdapter;
  893. this._dir = _dir;
  894. this._rangeStrategy = _rangeStrategy;
  895. this._rerenderSubscription = Subscription.EMPTY;
  896. /** Origin of active drag, or null when dragging is not active. */
  897. this.activeDrag = null;
  898. /** Emits when a new date is selected. */
  899. this.selectedChange = new EventEmitter();
  900. /** Emits when any date is selected. */
  901. this._userSelection = new EventEmitter();
  902. /** Emits when the user initiates a date range drag via mouse or touch. */
  903. this.dragStarted = new EventEmitter();
  904. /**
  905. * Emits when the user completes or cancels a date range drag.
  906. * Emits null when the drag was canceled or the newly selected date range if completed.
  907. */
  908. this.dragEnded = new EventEmitter();
  909. /** Emits when any date is activated. */
  910. this.activeDateChange = new EventEmitter();
  911. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  912. if (!this._dateAdapter) {
  913. throw createMissingDateImplError('DateAdapter');
  914. }
  915. if (!this._dateFormats) {
  916. throw createMissingDateImplError('MAT_DATE_FORMATS');
  917. }
  918. }
  919. this._activeDate = this._dateAdapter.today();
  920. }
  921. ngAfterContentInit() {
  922. this._rerenderSubscription = this._dateAdapter.localeChanges
  923. .pipe(startWith(null))
  924. .subscribe(() => this._init());
  925. }
  926. ngOnChanges(changes) {
  927. const comparisonChange = changes['comparisonStart'] || changes['comparisonEnd'];
  928. if (comparisonChange && !comparisonChange.firstChange) {
  929. this._setRanges(this.selected);
  930. }
  931. if (changes['activeDrag'] && !this.activeDrag) {
  932. this._clearPreview();
  933. }
  934. }
  935. ngOnDestroy() {
  936. this._rerenderSubscription.unsubscribe();
  937. }
  938. /** Handles when a new date is selected. */
  939. _dateSelected(event) {
  940. const date = event.value;
  941. const selectedDate = this._getDateFromDayOfMonth(date);
  942. let rangeStartDate;
  943. let rangeEndDate;
  944. if (this._selected instanceof DateRange) {
  945. rangeStartDate = this._getDateInCurrentMonth(this._selected.start);
  946. rangeEndDate = this._getDateInCurrentMonth(this._selected.end);
  947. }
  948. else {
  949. rangeStartDate = rangeEndDate = this._getDateInCurrentMonth(this._selected);
  950. }
  951. if (rangeStartDate !== date || rangeEndDate !== date) {
  952. this.selectedChange.emit(selectedDate);
  953. }
  954. this._userSelection.emit({ value: selectedDate, event: event.event });
  955. this._clearPreview();
  956. this._changeDetectorRef.markForCheck();
  957. }
  958. /**
  959. * Takes the index of a calendar body cell wrapped in in an event as argument. For the date that
  960. * corresponds to the given cell, set `activeDate` to that date and fire `activeDateChange` with
  961. * that date.
  962. *
  963. * This function is used to match each component's model of the active date with the calendar
  964. * body cell that was focused. It updates its value of `activeDate` synchronously and updates the
  965. * parent's value asynchronously via the `activeDateChange` event. The child component receives an
  966. * updated value asynchronously via the `activeCell` Input.
  967. */
  968. _updateActiveDate(event) {
  969. const month = event.value;
  970. const oldActiveDate = this._activeDate;
  971. this.activeDate = this._getDateFromDayOfMonth(month);
  972. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  973. this.activeDateChange.emit(this._activeDate);
  974. }
  975. }
  976. /** Handles keydown events on the calendar body when calendar is in month view. */
  977. _handleCalendarBodyKeydown(event) {
  978. // TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent
  979. // disabled ones from being selected. This may not be ideal, we should look into whether
  980. // navigation should skip over disabled dates, and if so, how to implement that efficiently.
  981. const oldActiveDate = this._activeDate;
  982. const isRtl = this._isRtl();
  983. switch (event.keyCode) {
  984. case LEFT_ARROW:
  985. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? 1 : -1);
  986. break;
  987. case RIGHT_ARROW:
  988. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, isRtl ? -1 : 1);
  989. break;
  990. case UP_ARROW:
  991. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, -7);
  992. break;
  993. case DOWN_ARROW:
  994. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 7);
  995. break;
  996. case HOME:
  997. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, 1 - this._dateAdapter.getDate(this._activeDate));
  998. break;
  999. case END:
  1000. this.activeDate = this._dateAdapter.addCalendarDays(this._activeDate, this._dateAdapter.getNumDaysInMonth(this._activeDate) -
  1001. this._dateAdapter.getDate(this._activeDate));
  1002. break;
  1003. case PAGE_UP:
  1004. this.activeDate = event.altKey
  1005. ? this._dateAdapter.addCalendarYears(this._activeDate, -1)
  1006. : this._dateAdapter.addCalendarMonths(this._activeDate, -1);
  1007. break;
  1008. case PAGE_DOWN:
  1009. this.activeDate = event.altKey
  1010. ? this._dateAdapter.addCalendarYears(this._activeDate, 1)
  1011. : this._dateAdapter.addCalendarMonths(this._activeDate, 1);
  1012. break;
  1013. case ENTER:
  1014. case SPACE:
  1015. this._selectionKeyPressed = true;
  1016. if (this._canSelect(this._activeDate)) {
  1017. // Prevent unexpected default actions such as form submission.
  1018. // Note that we only prevent the default action here while the selection happens in
  1019. // `keyup` below. We can't do the selection here, because it can cause the calendar to
  1020. // reopen if focus is restored immediately. We also can't call `preventDefault` on `keyup`
  1021. // because it's too late (see #23305).
  1022. event.preventDefault();
  1023. }
  1024. return;
  1025. case ESCAPE:
  1026. // Abort the current range selection if the user presses escape mid-selection.
  1027. if (this._previewEnd != null && !hasModifierKey(event)) {
  1028. this._clearPreview();
  1029. // If a drag is in progress, cancel the drag without changing the
  1030. // current selection.
  1031. if (this.activeDrag) {
  1032. this.dragEnded.emit({ value: null, event });
  1033. }
  1034. else {
  1035. this.selectedChange.emit(null);
  1036. this._userSelection.emit({ value: null, event });
  1037. }
  1038. event.preventDefault();
  1039. event.stopPropagation(); // Prevents the overlay from closing.
  1040. }
  1041. return;
  1042. default:
  1043. // Don't prevent default or focus active cell on keys that we don't explicitly handle.
  1044. return;
  1045. }
  1046. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  1047. this.activeDateChange.emit(this.activeDate);
  1048. this._focusActiveCellAfterViewChecked();
  1049. }
  1050. // Prevent unexpected default actions such as form submission.
  1051. event.preventDefault();
  1052. }
  1053. /** Handles keyup events on the calendar body when calendar is in month view. */
  1054. _handleCalendarBodyKeyup(event) {
  1055. if (event.keyCode === SPACE || event.keyCode === ENTER) {
  1056. if (this._selectionKeyPressed && this._canSelect(this._activeDate)) {
  1057. this._dateSelected({ value: this._dateAdapter.getDate(this._activeDate), event });
  1058. }
  1059. this._selectionKeyPressed = false;
  1060. }
  1061. }
  1062. /** Initializes this month view. */
  1063. _init() {
  1064. this._setRanges(this.selected);
  1065. this._todayDate = this._getCellCompareValue(this._dateAdapter.today());
  1066. this._monthLabel = this._dateFormats.display.monthLabel
  1067. ? this._dateAdapter.format(this.activeDate, this._dateFormats.display.monthLabel)
  1068. : this._dateAdapter
  1069. .getMonthNames('short')[this._dateAdapter.getMonth(this.activeDate)].toLocaleUpperCase();
  1070. let firstOfMonth = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), 1);
  1071. this._firstWeekOffset =
  1072. (DAYS_PER_WEEK +
  1073. this._dateAdapter.getDayOfWeek(firstOfMonth) -
  1074. this._dateAdapter.getFirstDayOfWeek()) %
  1075. DAYS_PER_WEEK;
  1076. this._initWeekdays();
  1077. this._createWeekCells();
  1078. this._changeDetectorRef.markForCheck();
  1079. }
  1080. /** Focuses the active cell after the microtask queue is empty. */
  1081. _focusActiveCell(movePreview) {
  1082. this._matCalendarBody._focusActiveCell(movePreview);
  1083. }
  1084. /** Focuses the active cell after change detection has run and the microtask queue is empty. */
  1085. _focusActiveCellAfterViewChecked() {
  1086. this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
  1087. }
  1088. /** Called when the user has activated a new cell and the preview needs to be updated. */
  1089. _previewChanged({ event, value: cell }) {
  1090. if (this._rangeStrategy) {
  1091. // We can assume that this will be a range, because preview
  1092. // events aren't fired for single date selections.
  1093. const value = cell ? cell.rawValue : null;
  1094. const previewRange = this._rangeStrategy.createPreview(value, this.selected, event);
  1095. this._previewStart = this._getCellCompareValue(previewRange.start);
  1096. this._previewEnd = this._getCellCompareValue(previewRange.end);
  1097. if (this.activeDrag && value) {
  1098. const dragRange = this._rangeStrategy.createDrag?.(this.activeDrag.value, this.selected, value, event);
  1099. if (dragRange) {
  1100. this._previewStart = this._getCellCompareValue(dragRange.start);
  1101. this._previewEnd = this._getCellCompareValue(dragRange.end);
  1102. }
  1103. }
  1104. // Note that here we need to use `detectChanges`, rather than `markForCheck`, because
  1105. // the way `_focusActiveCell` is set up at the moment makes it fire at the wrong time
  1106. // when navigating one month back using the keyboard which will cause this handler
  1107. // to throw a "changed after checked" error when updating the preview state.
  1108. this._changeDetectorRef.detectChanges();
  1109. }
  1110. }
  1111. /**
  1112. * Called when the user has ended a drag. If the drag/drop was successful,
  1113. * computes and emits the new range selection.
  1114. */
  1115. _dragEnded(event) {
  1116. if (!this.activeDrag)
  1117. return;
  1118. if (event.value) {
  1119. // Propagate drag effect
  1120. const dragDropResult = this._rangeStrategy?.createDrag?.(this.activeDrag.value, this.selected, event.value, event.event);
  1121. this.dragEnded.emit({ value: dragDropResult ?? null, event: event.event });
  1122. }
  1123. else {
  1124. this.dragEnded.emit({ value: null, event: event.event });
  1125. }
  1126. }
  1127. /**
  1128. * Takes a day of the month and returns a new date in the same month and year as the currently
  1129. * active date. The returned date will have the same day of the month as the argument date.
  1130. */
  1131. _getDateFromDayOfMonth(dayOfMonth) {
  1132. return this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), dayOfMonth);
  1133. }
  1134. /** Initializes the weekdays. */
  1135. _initWeekdays() {
  1136. const firstDayOfWeek = this._dateAdapter.getFirstDayOfWeek();
  1137. const narrowWeekdays = this._dateAdapter.getDayOfWeekNames('narrow');
  1138. const longWeekdays = this._dateAdapter.getDayOfWeekNames('long');
  1139. // Rotate the labels for days of the week based on the configured first day of the week.
  1140. let weekdays = longWeekdays.map((long, i) => {
  1141. return { long, narrow: narrowWeekdays[i] };
  1142. });
  1143. this._weekdays = weekdays.slice(firstDayOfWeek).concat(weekdays.slice(0, firstDayOfWeek));
  1144. }
  1145. /** Creates MatCalendarCells for the dates in this month. */
  1146. _createWeekCells() {
  1147. const daysInMonth = this._dateAdapter.getNumDaysInMonth(this.activeDate);
  1148. const dateNames = this._dateAdapter.getDateNames();
  1149. this._weeks = [[]];
  1150. for (let i = 0, cell = this._firstWeekOffset; i < daysInMonth; i++, cell++) {
  1151. if (cell == DAYS_PER_WEEK) {
  1152. this._weeks.push([]);
  1153. cell = 0;
  1154. }
  1155. const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), this._dateAdapter.getMonth(this.activeDate), i + 1);
  1156. const enabled = this._shouldEnableDate(date);
  1157. const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.dateA11yLabel);
  1158. const cellClasses = this.dateClass ? this.dateClass(date, 'month') : undefined;
  1159. this._weeks[this._weeks.length - 1].push(new MatCalendarCell(i + 1, dateNames[i], ariaLabel, enabled, cellClasses, this._getCellCompareValue(date), date));
  1160. }
  1161. }
  1162. /** Date filter for the month */
  1163. _shouldEnableDate(date) {
  1164. return (!!date &&
  1165. (!this.minDate || this._dateAdapter.compareDate(date, this.minDate) >= 0) &&
  1166. (!this.maxDate || this._dateAdapter.compareDate(date, this.maxDate) <= 0) &&
  1167. (!this.dateFilter || this.dateFilter(date)));
  1168. }
  1169. /**
  1170. * Gets the date in this month that the given Date falls on.
  1171. * Returns null if the given Date is in another month.
  1172. */
  1173. _getDateInCurrentMonth(date) {
  1174. return date && this._hasSameMonthAndYear(date, this.activeDate)
  1175. ? this._dateAdapter.getDate(date)
  1176. : null;
  1177. }
  1178. /** Checks whether the 2 dates are non-null and fall within the same month of the same year. */
  1179. _hasSameMonthAndYear(d1, d2) {
  1180. return !!(d1 &&
  1181. d2 &&
  1182. this._dateAdapter.getMonth(d1) == this._dateAdapter.getMonth(d2) &&
  1183. this._dateAdapter.getYear(d1) == this._dateAdapter.getYear(d2));
  1184. }
  1185. /** Gets the value that will be used to one cell to another. */
  1186. _getCellCompareValue(date) {
  1187. if (date) {
  1188. // We use the time since the Unix epoch to compare dates in this view, rather than the
  1189. // cell values, because we need to support ranges that span across multiple months/years.
  1190. const year = this._dateAdapter.getYear(date);
  1191. const month = this._dateAdapter.getMonth(date);
  1192. const day = this._dateAdapter.getDate(date);
  1193. return new Date(year, month, day).getTime();
  1194. }
  1195. return null;
  1196. }
  1197. /** Determines whether the user has the RTL layout direction. */
  1198. _isRtl() {
  1199. return this._dir && this._dir.value === 'rtl';
  1200. }
  1201. /** Sets the current range based on a model value. */
  1202. _setRanges(selectedValue) {
  1203. if (selectedValue instanceof DateRange) {
  1204. this._rangeStart = this._getCellCompareValue(selectedValue.start);
  1205. this._rangeEnd = this._getCellCompareValue(selectedValue.end);
  1206. this._isRange = true;
  1207. }
  1208. else {
  1209. this._rangeStart = this._rangeEnd = this._getCellCompareValue(selectedValue);
  1210. this._isRange = false;
  1211. }
  1212. this._comparisonRangeStart = this._getCellCompareValue(this.comparisonStart);
  1213. this._comparisonRangeEnd = this._getCellCompareValue(this.comparisonEnd);
  1214. }
  1215. /** Gets whether a date can be selected in the month view. */
  1216. _canSelect(date) {
  1217. return !this.dateFilter || this.dateFilter(date);
  1218. }
  1219. /** Clears out preview state. */
  1220. _clearPreview() {
  1221. this._previewStart = this._previewEnd = null;
  1222. }
  1223. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMonthView, deps: [{ token: i0.ChangeDetectorRef }, { token: MAT_DATE_FORMATS, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }, { token: MAT_DATE_RANGE_SELECTION_STRATEGY, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
  1224. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatMonthView, selector: "mat-month-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName", activeDrag: "activeDrag" }, outputs: { selectedChange: "selectedChange", _userSelection: "_userSelection", dragStarted: "dragStarted", dragEnded: "dragEnded", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matMonthView"], usesOnChanges: true, ngImport: i0, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead class=\"mat-calendar-table-header\">\n <tr>\n <th scope=\"col\" *ngFor=\"let day of _weekdays\">\n <span class=\"cdk-visually-hidden\">{{day.long}}</span>\n <span aria-hidden=\"true\">{{day.narrow}}</span>\n </th>\n </tr>\n <tr><th aria-hidden=\"true\" class=\"mat-calendar-table-header-divider\" colspan=\"7\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [label]=\"_monthLabel\"\n [rows]=\"_weeks\"\n [todayValue]=\"_todayDate!\"\n [startValue]=\"_rangeStart!\"\n [endValue]=\"_rangeEnd!\"\n [comparisonStart]=\"_comparisonRangeStart\"\n [comparisonEnd]=\"_comparisonRangeEnd\"\n [previewStart]=\"_previewStart\"\n [previewEnd]=\"_previewEnd\"\n [isRange]=\"_isRange\"\n [labelMinRequiredCells]=\"3\"\n [activeCell]=\"_dateAdapter.getDate(activeDate) - 1\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (selectedValueChange)=\"_dateSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (previewChange)=\"_previewChanged($event)\"\n (dragStarted)=\"dragStarted.emit($event)\"\n (dragEnded)=\"_dragEnded($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n", dependencies: [{ kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  1225. }
  1226. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMonthView, decorators: [{
  1227. type: Component,
  1228. args: [{ selector: 'mat-month-view', exportAs: 'matMonthView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead class=\"mat-calendar-table-header\">\n <tr>\n <th scope=\"col\" *ngFor=\"let day of _weekdays\">\n <span class=\"cdk-visually-hidden\">{{day.long}}</span>\n <span aria-hidden=\"true\">{{day.narrow}}</span>\n </th>\n </tr>\n <tr><th aria-hidden=\"true\" class=\"mat-calendar-table-header-divider\" colspan=\"7\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [label]=\"_monthLabel\"\n [rows]=\"_weeks\"\n [todayValue]=\"_todayDate!\"\n [startValue]=\"_rangeStart!\"\n [endValue]=\"_rangeEnd!\"\n [comparisonStart]=\"_comparisonRangeStart\"\n [comparisonEnd]=\"_comparisonRangeEnd\"\n [previewStart]=\"_previewStart\"\n [previewEnd]=\"_previewEnd\"\n [isRange]=\"_isRange\"\n [labelMinRequiredCells]=\"3\"\n [activeCell]=\"_dateAdapter.getDate(activeDate) - 1\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (selectedValueChange)=\"_dateSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (previewChange)=\"_previewChanged($event)\"\n (dragStarted)=\"dragStarted.emit($event)\"\n (dragEnded)=\"_dragEnded($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n" }]
  1229. }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
  1230. type: Optional
  1231. }, {
  1232. type: Inject,
  1233. args: [MAT_DATE_FORMATS]
  1234. }] }, { type: i1$1.DateAdapter, decorators: [{
  1235. type: Optional
  1236. }] }, { type: i2.Directionality, decorators: [{
  1237. type: Optional
  1238. }] }, { type: undefined, decorators: [{
  1239. type: Inject,
  1240. args: [MAT_DATE_RANGE_SELECTION_STRATEGY]
  1241. }, {
  1242. type: Optional
  1243. }] }]; }, propDecorators: { activeDate: [{
  1244. type: Input
  1245. }], selected: [{
  1246. type: Input
  1247. }], minDate: [{
  1248. type: Input
  1249. }], maxDate: [{
  1250. type: Input
  1251. }], dateFilter: [{
  1252. type: Input
  1253. }], dateClass: [{
  1254. type: Input
  1255. }], comparisonStart: [{
  1256. type: Input
  1257. }], comparisonEnd: [{
  1258. type: Input
  1259. }], startDateAccessibleName: [{
  1260. type: Input
  1261. }], endDateAccessibleName: [{
  1262. type: Input
  1263. }], activeDrag: [{
  1264. type: Input
  1265. }], selectedChange: [{
  1266. type: Output
  1267. }], _userSelection: [{
  1268. type: Output
  1269. }], dragStarted: [{
  1270. type: Output
  1271. }], dragEnded: [{
  1272. type: Output
  1273. }], activeDateChange: [{
  1274. type: Output
  1275. }], _matCalendarBody: [{
  1276. type: ViewChild,
  1277. args: [MatCalendarBody]
  1278. }] } });
  1279. const yearsPerPage = 24;
  1280. const yearsPerRow = 4;
  1281. /**
  1282. * An internal component used to display a year selector in the datepicker.
  1283. * @docs-private
  1284. */
  1285. class MatMultiYearView {
  1286. /** The date to display in this multi-year view (everything other than the year is ignored). */
  1287. get activeDate() {
  1288. return this._activeDate;
  1289. }
  1290. set activeDate(value) {
  1291. let oldActiveDate = this._activeDate;
  1292. const validDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)) ||
  1293. this._dateAdapter.today();
  1294. this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
  1295. if (!isSameMultiYearView(this._dateAdapter, oldActiveDate, this._activeDate, this.minDate, this.maxDate)) {
  1296. this._init();
  1297. }
  1298. }
  1299. /** The currently selected date. */
  1300. get selected() {
  1301. return this._selected;
  1302. }
  1303. set selected(value) {
  1304. if (value instanceof DateRange) {
  1305. this._selected = value;
  1306. }
  1307. else {
  1308. this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1309. }
  1310. this._setSelectedYear(value);
  1311. }
  1312. /** The minimum selectable date. */
  1313. get minDate() {
  1314. return this._minDate;
  1315. }
  1316. set minDate(value) {
  1317. this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1318. }
  1319. /** The maximum selectable date. */
  1320. get maxDate() {
  1321. return this._maxDate;
  1322. }
  1323. set maxDate(value) {
  1324. this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1325. }
  1326. constructor(_changeDetectorRef, _dateAdapter, _dir) {
  1327. this._changeDetectorRef = _changeDetectorRef;
  1328. this._dateAdapter = _dateAdapter;
  1329. this._dir = _dir;
  1330. this._rerenderSubscription = Subscription.EMPTY;
  1331. /** Emits when a new year is selected. */
  1332. this.selectedChange = new EventEmitter();
  1333. /** Emits the selected year. This doesn't imply a change on the selected date */
  1334. this.yearSelected = new EventEmitter();
  1335. /** Emits when any date is activated. */
  1336. this.activeDateChange = new EventEmitter();
  1337. if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  1338. throw createMissingDateImplError('DateAdapter');
  1339. }
  1340. this._activeDate = this._dateAdapter.today();
  1341. }
  1342. ngAfterContentInit() {
  1343. this._rerenderSubscription = this._dateAdapter.localeChanges
  1344. .pipe(startWith(null))
  1345. .subscribe(() => this._init());
  1346. }
  1347. ngOnDestroy() {
  1348. this._rerenderSubscription.unsubscribe();
  1349. }
  1350. /** Initializes this multi-year view. */
  1351. _init() {
  1352. this._todayYear = this._dateAdapter.getYear(this._dateAdapter.today());
  1353. // We want a range years such that we maximize the number of
  1354. // enabled dates visible at once. This prevents issues where the minimum year
  1355. // is the last item of a page OR the maximum year is the first item of a page.
  1356. // The offset from the active year to the "slot" for the starting year is the
  1357. // *actual* first rendered year in the multi-year view.
  1358. const activeYear = this._dateAdapter.getYear(this._activeDate);
  1359. const minYearOfPage = activeYear - getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate);
  1360. this._years = [];
  1361. for (let i = 0, row = []; i < yearsPerPage; i++) {
  1362. row.push(minYearOfPage + i);
  1363. if (row.length == yearsPerRow) {
  1364. this._years.push(row.map(year => this._createCellForYear(year)));
  1365. row = [];
  1366. }
  1367. }
  1368. this._changeDetectorRef.markForCheck();
  1369. }
  1370. /** Handles when a new year is selected. */
  1371. _yearSelected(event) {
  1372. const year = event.value;
  1373. const selectedYear = this._dateAdapter.createDate(year, 0, 1);
  1374. const selectedDate = this._getDateFromYear(year);
  1375. this.yearSelected.emit(selectedYear);
  1376. this.selectedChange.emit(selectedDate);
  1377. }
  1378. /**
  1379. * Takes the index of a calendar body cell wrapped in in an event as argument. For the date that
  1380. * corresponds to the given cell, set `activeDate` to that date and fire `activeDateChange` with
  1381. * that date.
  1382. *
  1383. * This function is used to match each component's model of the active date with the calendar
  1384. * body cell that was focused. It updates its value of `activeDate` synchronously and updates the
  1385. * parent's value asynchronously via the `activeDateChange` event. The child component receives an
  1386. * updated value asynchronously via the `activeCell` Input.
  1387. */
  1388. _updateActiveDate(event) {
  1389. const year = event.value;
  1390. const oldActiveDate = this._activeDate;
  1391. this.activeDate = this._getDateFromYear(year);
  1392. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  1393. this.activeDateChange.emit(this.activeDate);
  1394. }
  1395. }
  1396. /** Handles keydown events on the calendar body when calendar is in multi-year view. */
  1397. _handleCalendarBodyKeydown(event) {
  1398. const oldActiveDate = this._activeDate;
  1399. const isRtl = this._isRtl();
  1400. switch (event.keyCode) {
  1401. case LEFT_ARROW:
  1402. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, isRtl ? 1 : -1);
  1403. break;
  1404. case RIGHT_ARROW:
  1405. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, isRtl ? -1 : 1);
  1406. break;
  1407. case UP_ARROW:
  1408. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, -yearsPerRow);
  1409. break;
  1410. case DOWN_ARROW:
  1411. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, yearsPerRow);
  1412. break;
  1413. case HOME:
  1414. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, -getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate));
  1415. break;
  1416. case END:
  1417. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, yearsPerPage -
  1418. getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate) -
  1419. 1);
  1420. break;
  1421. case PAGE_UP:
  1422. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, event.altKey ? -yearsPerPage * 10 : -yearsPerPage);
  1423. break;
  1424. case PAGE_DOWN:
  1425. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, event.altKey ? yearsPerPage * 10 : yearsPerPage);
  1426. break;
  1427. case ENTER:
  1428. case SPACE:
  1429. // Note that we only prevent the default action here while the selection happens in
  1430. // `keyup` below. We can't do the selection here, because it can cause the calendar to
  1431. // reopen if focus is restored immediately. We also can't call `preventDefault` on `keyup`
  1432. // because it's too late (see #23305).
  1433. this._selectionKeyPressed = true;
  1434. break;
  1435. default:
  1436. // Don't prevent default or focus active cell on keys that we don't explicitly handle.
  1437. return;
  1438. }
  1439. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  1440. this.activeDateChange.emit(this.activeDate);
  1441. }
  1442. this._focusActiveCellAfterViewChecked();
  1443. // Prevent unexpected default actions such as form submission.
  1444. event.preventDefault();
  1445. }
  1446. /** Handles keyup events on the calendar body when calendar is in multi-year view. */
  1447. _handleCalendarBodyKeyup(event) {
  1448. if (event.keyCode === SPACE || event.keyCode === ENTER) {
  1449. if (this._selectionKeyPressed) {
  1450. this._yearSelected({ value: this._dateAdapter.getYear(this._activeDate), event });
  1451. }
  1452. this._selectionKeyPressed = false;
  1453. }
  1454. }
  1455. _getActiveCell() {
  1456. return getActiveOffset(this._dateAdapter, this.activeDate, this.minDate, this.maxDate);
  1457. }
  1458. /** Focuses the active cell after the microtask queue is empty. */
  1459. _focusActiveCell() {
  1460. this._matCalendarBody._focusActiveCell();
  1461. }
  1462. /** Focuses the active cell after change detection has run and the microtask queue is empty. */
  1463. _focusActiveCellAfterViewChecked() {
  1464. this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
  1465. }
  1466. /**
  1467. * Takes a year and returns a new date on the same day and month as the currently active date
  1468. * The returned date will have the same year as the argument date.
  1469. */
  1470. _getDateFromYear(year) {
  1471. const activeMonth = this._dateAdapter.getMonth(this.activeDate);
  1472. const daysInMonth = this._dateAdapter.getNumDaysInMonth(this._dateAdapter.createDate(year, activeMonth, 1));
  1473. const normalizedDate = this._dateAdapter.createDate(year, activeMonth, Math.min(this._dateAdapter.getDate(this.activeDate), daysInMonth));
  1474. return normalizedDate;
  1475. }
  1476. /** Creates an MatCalendarCell for the given year. */
  1477. _createCellForYear(year) {
  1478. const date = this._dateAdapter.createDate(year, 0, 1);
  1479. const yearName = this._dateAdapter.getYearName(date);
  1480. const cellClasses = this.dateClass ? this.dateClass(date, 'multi-year') : undefined;
  1481. return new MatCalendarCell(year, yearName, yearName, this._shouldEnableYear(year), cellClasses);
  1482. }
  1483. /** Whether the given year is enabled. */
  1484. _shouldEnableYear(year) {
  1485. // disable if the year is greater than maxDate lower than minDate
  1486. if (year === undefined ||
  1487. year === null ||
  1488. (this.maxDate && year > this._dateAdapter.getYear(this.maxDate)) ||
  1489. (this.minDate && year < this._dateAdapter.getYear(this.minDate))) {
  1490. return false;
  1491. }
  1492. // enable if it reaches here and there's no filter defined
  1493. if (!this.dateFilter) {
  1494. return true;
  1495. }
  1496. const firstOfYear = this._dateAdapter.createDate(year, 0, 1);
  1497. // If any date in the year is enabled count the year as enabled.
  1498. for (let date = firstOfYear; this._dateAdapter.getYear(date) == year; date = this._dateAdapter.addCalendarDays(date, 1)) {
  1499. if (this.dateFilter(date)) {
  1500. return true;
  1501. }
  1502. }
  1503. return false;
  1504. }
  1505. /** Determines whether the user has the RTL layout direction. */
  1506. _isRtl() {
  1507. return this._dir && this._dir.value === 'rtl';
  1508. }
  1509. /** Sets the currently-highlighted year based on a model value. */
  1510. _setSelectedYear(value) {
  1511. this._selectedYear = null;
  1512. if (value instanceof DateRange) {
  1513. const displayValue = value.start || value.end;
  1514. if (displayValue) {
  1515. this._selectedYear = this._dateAdapter.getYear(displayValue);
  1516. }
  1517. }
  1518. else if (value) {
  1519. this._selectedYear = this._dateAdapter.getYear(value);
  1520. }
  1521. }
  1522. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMultiYearView, deps: [{ token: i0.ChangeDetectorRef }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
  1523. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatMultiYearView, selector: "mat-multi-year-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass" }, outputs: { selectedChange: "selectedChange", yearSelected: "yearSelected", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matMultiYearView"], ngImport: i0, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead aria-hidden=\"true\" class=\"mat-calendar-table-header\">\n <tr><th class=\"mat-calendar-table-header-divider\" colspan=\"4\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [rows]=\"_years\"\n [todayValue]=\"_todayYear\"\n [startValue]=\"_selectedYear!\"\n [endValue]=\"_selectedYear!\"\n [numCols]=\"4\"\n [cellAspectRatio]=\"4 / 7\"\n [activeCell]=\"_getActiveCell()\"\n (selectedValueChange)=\"_yearSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n", dependencies: [{ kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  1524. }
  1525. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatMultiYearView, decorators: [{
  1526. type: Component,
  1527. args: [{ selector: 'mat-multi-year-view', exportAs: 'matMultiYearView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead aria-hidden=\"true\" class=\"mat-calendar-table-header\">\n <tr><th class=\"mat-calendar-table-header-divider\" colspan=\"4\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [rows]=\"_years\"\n [todayValue]=\"_todayYear\"\n [startValue]=\"_selectedYear!\"\n [endValue]=\"_selectedYear!\"\n [numCols]=\"4\"\n [cellAspectRatio]=\"4 / 7\"\n [activeCell]=\"_getActiveCell()\"\n (selectedValueChange)=\"_yearSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n" }]
  1528. }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i1$1.DateAdapter, decorators: [{
  1529. type: Optional
  1530. }] }, { type: i2.Directionality, decorators: [{
  1531. type: Optional
  1532. }] }]; }, propDecorators: { activeDate: [{
  1533. type: Input
  1534. }], selected: [{
  1535. type: Input
  1536. }], minDate: [{
  1537. type: Input
  1538. }], maxDate: [{
  1539. type: Input
  1540. }], dateFilter: [{
  1541. type: Input
  1542. }], dateClass: [{
  1543. type: Input
  1544. }], selectedChange: [{
  1545. type: Output
  1546. }], yearSelected: [{
  1547. type: Output
  1548. }], activeDateChange: [{
  1549. type: Output
  1550. }], _matCalendarBody: [{
  1551. type: ViewChild,
  1552. args: [MatCalendarBody]
  1553. }] } });
  1554. function isSameMultiYearView(dateAdapter, date1, date2, minDate, maxDate) {
  1555. const year1 = dateAdapter.getYear(date1);
  1556. const year2 = dateAdapter.getYear(date2);
  1557. const startingYear = getStartingYear(dateAdapter, minDate, maxDate);
  1558. return (Math.floor((year1 - startingYear) / yearsPerPage) ===
  1559. Math.floor((year2 - startingYear) / yearsPerPage));
  1560. }
  1561. /**
  1562. * When the multi-year view is first opened, the active year will be in view.
  1563. * So we compute how many years are between the active year and the *slot* where our
  1564. * "startingYear" will render when paged into view.
  1565. */
  1566. function getActiveOffset(dateAdapter, activeDate, minDate, maxDate) {
  1567. const activeYear = dateAdapter.getYear(activeDate);
  1568. return euclideanModulo(activeYear - getStartingYear(dateAdapter, minDate, maxDate), yearsPerPage);
  1569. }
  1570. /**
  1571. * We pick a "starting" year such that either the maximum year would be at the end
  1572. * or the minimum year would be at the beginning of a page.
  1573. */
  1574. function getStartingYear(dateAdapter, minDate, maxDate) {
  1575. let startingYear = 0;
  1576. if (maxDate) {
  1577. const maxYear = dateAdapter.getYear(maxDate);
  1578. startingYear = maxYear - yearsPerPage + 1;
  1579. }
  1580. else if (minDate) {
  1581. startingYear = dateAdapter.getYear(minDate);
  1582. }
  1583. return startingYear;
  1584. }
  1585. /** Gets remainder that is non-negative, even if first number is negative */
  1586. function euclideanModulo(a, b) {
  1587. return ((a % b) + b) % b;
  1588. }
  1589. /**
  1590. * An internal component used to display a single year in the datepicker.
  1591. * @docs-private
  1592. */
  1593. class MatYearView {
  1594. /** The date to display in this year view (everything other than the year is ignored). */
  1595. get activeDate() {
  1596. return this._activeDate;
  1597. }
  1598. set activeDate(value) {
  1599. let oldActiveDate = this._activeDate;
  1600. const validDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value)) ||
  1601. this._dateAdapter.today();
  1602. this._activeDate = this._dateAdapter.clampDate(validDate, this.minDate, this.maxDate);
  1603. if (this._dateAdapter.getYear(oldActiveDate) !== this._dateAdapter.getYear(this._activeDate)) {
  1604. this._init();
  1605. }
  1606. }
  1607. /** The currently selected date. */
  1608. get selected() {
  1609. return this._selected;
  1610. }
  1611. set selected(value) {
  1612. if (value instanceof DateRange) {
  1613. this._selected = value;
  1614. }
  1615. else {
  1616. this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1617. }
  1618. this._setSelectedMonth(value);
  1619. }
  1620. /** The minimum selectable date. */
  1621. get minDate() {
  1622. return this._minDate;
  1623. }
  1624. set minDate(value) {
  1625. this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1626. }
  1627. /** The maximum selectable date. */
  1628. get maxDate() {
  1629. return this._maxDate;
  1630. }
  1631. set maxDate(value) {
  1632. this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  1633. }
  1634. constructor(_changeDetectorRef, _dateFormats, _dateAdapter, _dir) {
  1635. this._changeDetectorRef = _changeDetectorRef;
  1636. this._dateFormats = _dateFormats;
  1637. this._dateAdapter = _dateAdapter;
  1638. this._dir = _dir;
  1639. this._rerenderSubscription = Subscription.EMPTY;
  1640. /** Emits when a new month is selected. */
  1641. this.selectedChange = new EventEmitter();
  1642. /** Emits the selected month. This doesn't imply a change on the selected date */
  1643. this.monthSelected = new EventEmitter();
  1644. /** Emits when any date is activated. */
  1645. this.activeDateChange = new EventEmitter();
  1646. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  1647. if (!this._dateAdapter) {
  1648. throw createMissingDateImplError('DateAdapter');
  1649. }
  1650. if (!this._dateFormats) {
  1651. throw createMissingDateImplError('MAT_DATE_FORMATS');
  1652. }
  1653. }
  1654. this._activeDate = this._dateAdapter.today();
  1655. }
  1656. ngAfterContentInit() {
  1657. this._rerenderSubscription = this._dateAdapter.localeChanges
  1658. .pipe(startWith(null))
  1659. .subscribe(() => this._init());
  1660. }
  1661. ngOnDestroy() {
  1662. this._rerenderSubscription.unsubscribe();
  1663. }
  1664. /** Handles when a new month is selected. */
  1665. _monthSelected(event) {
  1666. const month = event.value;
  1667. const selectedMonth = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1);
  1668. this.monthSelected.emit(selectedMonth);
  1669. const selectedDate = this._getDateFromMonth(month);
  1670. this.selectedChange.emit(selectedDate);
  1671. }
  1672. /**
  1673. * Takes the index of a calendar body cell wrapped in in an event as argument. For the date that
  1674. * corresponds to the given cell, set `activeDate` to that date and fire `activeDateChange` with
  1675. * that date.
  1676. *
  1677. * This function is used to match each component's model of the active date with the calendar
  1678. * body cell that was focused. It updates its value of `activeDate` synchronously and updates the
  1679. * parent's value asynchronously via the `activeDateChange` event. The child component receives an
  1680. * updated value asynchronously via the `activeCell` Input.
  1681. */
  1682. _updateActiveDate(event) {
  1683. const month = event.value;
  1684. const oldActiveDate = this._activeDate;
  1685. this.activeDate = this._getDateFromMonth(month);
  1686. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  1687. this.activeDateChange.emit(this.activeDate);
  1688. }
  1689. }
  1690. /** Handles keydown events on the calendar body when calendar is in year view. */
  1691. _handleCalendarBodyKeydown(event) {
  1692. // TODO(mmalerba): We currently allow keyboard navigation to disabled dates, but just prevent
  1693. // disabled ones from being selected. This may not be ideal, we should look into whether
  1694. // navigation should skip over disabled dates, and if so, how to implement that efficiently.
  1695. const oldActiveDate = this._activeDate;
  1696. const isRtl = this._isRtl();
  1697. switch (event.keyCode) {
  1698. case LEFT_ARROW:
  1699. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, isRtl ? 1 : -1);
  1700. break;
  1701. case RIGHT_ARROW:
  1702. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, isRtl ? -1 : 1);
  1703. break;
  1704. case UP_ARROW:
  1705. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, -4);
  1706. break;
  1707. case DOWN_ARROW:
  1708. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, 4);
  1709. break;
  1710. case HOME:
  1711. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, -this._dateAdapter.getMonth(this._activeDate));
  1712. break;
  1713. case END:
  1714. this.activeDate = this._dateAdapter.addCalendarMonths(this._activeDate, 11 - this._dateAdapter.getMonth(this._activeDate));
  1715. break;
  1716. case PAGE_UP:
  1717. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, event.altKey ? -10 : -1);
  1718. break;
  1719. case PAGE_DOWN:
  1720. this.activeDate = this._dateAdapter.addCalendarYears(this._activeDate, event.altKey ? 10 : 1);
  1721. break;
  1722. case ENTER:
  1723. case SPACE:
  1724. // Note that we only prevent the default action here while the selection happens in
  1725. // `keyup` below. We can't do the selection here, because it can cause the calendar to
  1726. // reopen if focus is restored immediately. We also can't call `preventDefault` on `keyup`
  1727. // because it's too late (see #23305).
  1728. this._selectionKeyPressed = true;
  1729. break;
  1730. default:
  1731. // Don't prevent default or focus active cell on keys that we don't explicitly handle.
  1732. return;
  1733. }
  1734. if (this._dateAdapter.compareDate(oldActiveDate, this.activeDate)) {
  1735. this.activeDateChange.emit(this.activeDate);
  1736. this._focusActiveCellAfterViewChecked();
  1737. }
  1738. // Prevent unexpected default actions such as form submission.
  1739. event.preventDefault();
  1740. }
  1741. /** Handles keyup events on the calendar body when calendar is in year view. */
  1742. _handleCalendarBodyKeyup(event) {
  1743. if (event.keyCode === SPACE || event.keyCode === ENTER) {
  1744. if (this._selectionKeyPressed) {
  1745. this._monthSelected({ value: this._dateAdapter.getMonth(this._activeDate), event });
  1746. }
  1747. this._selectionKeyPressed = false;
  1748. }
  1749. }
  1750. /** Initializes this year view. */
  1751. _init() {
  1752. this._setSelectedMonth(this.selected);
  1753. this._todayMonth = this._getMonthInCurrentYear(this._dateAdapter.today());
  1754. this._yearLabel = this._dateAdapter.getYearName(this.activeDate);
  1755. let monthNames = this._dateAdapter.getMonthNames('short');
  1756. // First row of months only contains 5 elements so we can fit the year label on the same row.
  1757. this._months = [
  1758. [0, 1, 2, 3],
  1759. [4, 5, 6, 7],
  1760. [8, 9, 10, 11],
  1761. ].map(row => row.map(month => this._createCellForMonth(month, monthNames[month])));
  1762. this._changeDetectorRef.markForCheck();
  1763. }
  1764. /** Focuses the active cell after the microtask queue is empty. */
  1765. _focusActiveCell() {
  1766. this._matCalendarBody._focusActiveCell();
  1767. }
  1768. /** Schedules the matCalendarBody to focus the active cell after change detection has run */
  1769. _focusActiveCellAfterViewChecked() {
  1770. this._matCalendarBody._scheduleFocusActiveCellAfterViewChecked();
  1771. }
  1772. /**
  1773. * Gets the month in this year that the given Date falls on.
  1774. * Returns null if the given Date is in another year.
  1775. */
  1776. _getMonthInCurrentYear(date) {
  1777. return date && this._dateAdapter.getYear(date) == this._dateAdapter.getYear(this.activeDate)
  1778. ? this._dateAdapter.getMonth(date)
  1779. : null;
  1780. }
  1781. /**
  1782. * Takes a month and returns a new date in the same day and year as the currently active date.
  1783. * The returned date will have the same month as the argument date.
  1784. */
  1785. _getDateFromMonth(month) {
  1786. const normalizedDate = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1);
  1787. const daysInMonth = this._dateAdapter.getNumDaysInMonth(normalizedDate);
  1788. return this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, Math.min(this._dateAdapter.getDate(this.activeDate), daysInMonth));
  1789. }
  1790. /** Creates an MatCalendarCell for the given month. */
  1791. _createCellForMonth(month, monthName) {
  1792. const date = this._dateAdapter.createDate(this._dateAdapter.getYear(this.activeDate), month, 1);
  1793. const ariaLabel = this._dateAdapter.format(date, this._dateFormats.display.monthYearA11yLabel);
  1794. const cellClasses = this.dateClass ? this.dateClass(date, 'year') : undefined;
  1795. return new MatCalendarCell(month, monthName.toLocaleUpperCase(), ariaLabel, this._shouldEnableMonth(month), cellClasses);
  1796. }
  1797. /** Whether the given month is enabled. */
  1798. _shouldEnableMonth(month) {
  1799. const activeYear = this._dateAdapter.getYear(this.activeDate);
  1800. if (month === undefined ||
  1801. month === null ||
  1802. this._isYearAndMonthAfterMaxDate(activeYear, month) ||
  1803. this._isYearAndMonthBeforeMinDate(activeYear, month)) {
  1804. return false;
  1805. }
  1806. if (!this.dateFilter) {
  1807. return true;
  1808. }
  1809. const firstOfMonth = this._dateAdapter.createDate(activeYear, month, 1);
  1810. // If any date in the month is enabled count the month as enabled.
  1811. for (let date = firstOfMonth; this._dateAdapter.getMonth(date) == month; date = this._dateAdapter.addCalendarDays(date, 1)) {
  1812. if (this.dateFilter(date)) {
  1813. return true;
  1814. }
  1815. }
  1816. return false;
  1817. }
  1818. /**
  1819. * Tests whether the combination month/year is after this.maxDate, considering
  1820. * just the month and year of this.maxDate
  1821. */
  1822. _isYearAndMonthAfterMaxDate(year, month) {
  1823. if (this.maxDate) {
  1824. const maxYear = this._dateAdapter.getYear(this.maxDate);
  1825. const maxMonth = this._dateAdapter.getMonth(this.maxDate);
  1826. return year > maxYear || (year === maxYear && month > maxMonth);
  1827. }
  1828. return false;
  1829. }
  1830. /**
  1831. * Tests whether the combination month/year is before this.minDate, considering
  1832. * just the month and year of this.minDate
  1833. */
  1834. _isYearAndMonthBeforeMinDate(year, month) {
  1835. if (this.minDate) {
  1836. const minYear = this._dateAdapter.getYear(this.minDate);
  1837. const minMonth = this._dateAdapter.getMonth(this.minDate);
  1838. return year < minYear || (year === minYear && month < minMonth);
  1839. }
  1840. return false;
  1841. }
  1842. /** Determines whether the user has the RTL layout direction. */
  1843. _isRtl() {
  1844. return this._dir && this._dir.value === 'rtl';
  1845. }
  1846. /** Sets the currently-selected month based on a model value. */
  1847. _setSelectedMonth(value) {
  1848. if (value instanceof DateRange) {
  1849. this._selectedMonth =
  1850. this._getMonthInCurrentYear(value.start) || this._getMonthInCurrentYear(value.end);
  1851. }
  1852. else {
  1853. this._selectedMonth = this._getMonthInCurrentYear(value);
  1854. }
  1855. }
  1856. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatYearView, deps: [{ token: i0.ChangeDetectorRef }, { token: MAT_DATE_FORMATS, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
  1857. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatYearView, selector: "mat-year-view", inputs: { activeDate: "activeDate", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass" }, outputs: { selectedChange: "selectedChange", monthSelected: "monthSelected", activeDateChange: "activeDateChange" }, viewQueries: [{ propertyName: "_matCalendarBody", first: true, predicate: MatCalendarBody, descendants: true }], exportAs: ["matYearView"], ngImport: i0, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead aria-hidden=\"true\" class=\"mat-calendar-table-header\">\n <tr><th class=\"mat-calendar-table-header-divider\" colspan=\"4\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [label]=\"_yearLabel\"\n [rows]=\"_months\"\n [todayValue]=\"_todayMonth!\"\n [startValue]=\"_selectedMonth!\"\n [endValue]=\"_selectedMonth!\"\n [labelMinRequiredCells]=\"2\"\n [numCols]=\"4\"\n [cellAspectRatio]=\"4 / 7\"\n [activeCell]=\"_dateAdapter.getMonth(activeDate)\"\n (selectedValueChange)=\"_monthSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n", dependencies: [{ kind: "component", type: MatCalendarBody, selector: "[mat-calendar-body]", inputs: ["label", "rows", "todayValue", "startValue", "endValue", "labelMinRequiredCells", "numCols", "activeCell", "isRange", "cellAspectRatio", "comparisonStart", "comparisonEnd", "previewStart", "previewEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedValueChange", "previewChange", "activeDateChange", "dragStarted", "dragEnded"], exportAs: ["matCalendarBody"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  1858. }
  1859. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatYearView, decorators: [{
  1860. type: Component,
  1861. args: [{ selector: 'mat-year-view', exportAs: 'matYearView', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<table class=\"mat-calendar-table\" role=\"grid\">\n <thead aria-hidden=\"true\" class=\"mat-calendar-table-header\">\n <tr><th class=\"mat-calendar-table-header-divider\" colspan=\"4\"></th></tr>\n </thead>\n <tbody mat-calendar-body\n [label]=\"_yearLabel\"\n [rows]=\"_months\"\n [todayValue]=\"_todayMonth!\"\n [startValue]=\"_selectedMonth!\"\n [endValue]=\"_selectedMonth!\"\n [labelMinRequiredCells]=\"2\"\n [numCols]=\"4\"\n [cellAspectRatio]=\"4 / 7\"\n [activeCell]=\"_dateAdapter.getMonth(activeDate)\"\n (selectedValueChange)=\"_monthSelected($event)\"\n (activeDateChange)=\"_updateActiveDate($event)\"\n (keyup)=\"_handleCalendarBodyKeyup($event)\"\n (keydown)=\"_handleCalendarBodyKeydown($event)\">\n </tbody>\n</table>\n" }]
  1862. }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
  1863. type: Optional
  1864. }, {
  1865. type: Inject,
  1866. args: [MAT_DATE_FORMATS]
  1867. }] }, { type: i1$1.DateAdapter, decorators: [{
  1868. type: Optional
  1869. }] }, { type: i2.Directionality, decorators: [{
  1870. type: Optional
  1871. }] }]; }, propDecorators: { activeDate: [{
  1872. type: Input
  1873. }], selected: [{
  1874. type: Input
  1875. }], minDate: [{
  1876. type: Input
  1877. }], maxDate: [{
  1878. type: Input
  1879. }], dateFilter: [{
  1880. type: Input
  1881. }], dateClass: [{
  1882. type: Input
  1883. }], selectedChange: [{
  1884. type: Output
  1885. }], monthSelected: [{
  1886. type: Output
  1887. }], activeDateChange: [{
  1888. type: Output
  1889. }], _matCalendarBody: [{
  1890. type: ViewChild,
  1891. args: [MatCalendarBody]
  1892. }] } });
  1893. let calendarHeaderId = 1;
  1894. /** Default header for MatCalendar */
  1895. class MatCalendarHeader {
  1896. constructor(_intl, calendar, _dateAdapter, _dateFormats, changeDetectorRef) {
  1897. this._intl = _intl;
  1898. this.calendar = calendar;
  1899. this._dateAdapter = _dateAdapter;
  1900. this._dateFormats = _dateFormats;
  1901. this._id = `mat-calendar-header-${calendarHeaderId++}`;
  1902. this._periodButtonLabelId = `${this._id}-period-label`;
  1903. this.calendar.stateChanges.subscribe(() => changeDetectorRef.markForCheck());
  1904. }
  1905. /** The display text for the current calendar view. */
  1906. get periodButtonText() {
  1907. if (this.calendar.currentView == 'month') {
  1908. return this._dateAdapter
  1909. .format(this.calendar.activeDate, this._dateFormats.display.monthYearLabel)
  1910. .toLocaleUpperCase();
  1911. }
  1912. if (this.calendar.currentView == 'year') {
  1913. return this._dateAdapter.getYearName(this.calendar.activeDate);
  1914. }
  1915. return this._intl.formatYearRange(...this._formatMinAndMaxYearLabels());
  1916. }
  1917. /** The aria description for the current calendar view. */
  1918. get periodButtonDescription() {
  1919. if (this.calendar.currentView == 'month') {
  1920. return this._dateAdapter
  1921. .format(this.calendar.activeDate, this._dateFormats.display.monthYearLabel)
  1922. .toLocaleUpperCase();
  1923. }
  1924. if (this.calendar.currentView == 'year') {
  1925. return this._dateAdapter.getYearName(this.calendar.activeDate);
  1926. }
  1927. // Format a label for the window of years displayed in the multi-year calendar view. Use
  1928. // `formatYearRangeLabel` because it is TTS friendly.
  1929. return this._intl.formatYearRangeLabel(...this._formatMinAndMaxYearLabels());
  1930. }
  1931. /** The `aria-label` for changing the calendar view. */
  1932. get periodButtonLabel() {
  1933. return this.calendar.currentView == 'month'
  1934. ? this._intl.switchToMultiYearViewLabel
  1935. : this._intl.switchToMonthViewLabel;
  1936. }
  1937. /** The label for the previous button. */
  1938. get prevButtonLabel() {
  1939. return {
  1940. 'month': this._intl.prevMonthLabel,
  1941. 'year': this._intl.prevYearLabel,
  1942. 'multi-year': this._intl.prevMultiYearLabel,
  1943. }[this.calendar.currentView];
  1944. }
  1945. /** The label for the next button. */
  1946. get nextButtonLabel() {
  1947. return {
  1948. 'month': this._intl.nextMonthLabel,
  1949. 'year': this._intl.nextYearLabel,
  1950. 'multi-year': this._intl.nextMultiYearLabel,
  1951. }[this.calendar.currentView];
  1952. }
  1953. /** Handles user clicks on the period label. */
  1954. currentPeriodClicked() {
  1955. this.calendar.currentView = this.calendar.currentView == 'month' ? 'multi-year' : 'month';
  1956. }
  1957. /** Handles user clicks on the previous button. */
  1958. previousClicked() {
  1959. this.calendar.activeDate =
  1960. this.calendar.currentView == 'month'
  1961. ? this._dateAdapter.addCalendarMonths(this.calendar.activeDate, -1)
  1962. : this._dateAdapter.addCalendarYears(this.calendar.activeDate, this.calendar.currentView == 'year' ? -1 : -yearsPerPage);
  1963. }
  1964. /** Handles user clicks on the next button. */
  1965. nextClicked() {
  1966. this.calendar.activeDate =
  1967. this.calendar.currentView == 'month'
  1968. ? this._dateAdapter.addCalendarMonths(this.calendar.activeDate, 1)
  1969. : this._dateAdapter.addCalendarYears(this.calendar.activeDate, this.calendar.currentView == 'year' ? 1 : yearsPerPage);
  1970. }
  1971. /** Whether the previous period button is enabled. */
  1972. previousEnabled() {
  1973. if (!this.calendar.minDate) {
  1974. return true;
  1975. }
  1976. return (!this.calendar.minDate || !this._isSameView(this.calendar.activeDate, this.calendar.minDate));
  1977. }
  1978. /** Whether the next period button is enabled. */
  1979. nextEnabled() {
  1980. return (!this.calendar.maxDate || !this._isSameView(this.calendar.activeDate, this.calendar.maxDate));
  1981. }
  1982. /** Whether the two dates represent the same view in the current view mode (month or year). */
  1983. _isSameView(date1, date2) {
  1984. if (this.calendar.currentView == 'month') {
  1985. return (this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2) &&
  1986. this._dateAdapter.getMonth(date1) == this._dateAdapter.getMonth(date2));
  1987. }
  1988. if (this.calendar.currentView == 'year') {
  1989. return this._dateAdapter.getYear(date1) == this._dateAdapter.getYear(date2);
  1990. }
  1991. // Otherwise we are in 'multi-year' view.
  1992. return isSameMultiYearView(this._dateAdapter, date1, date2, this.calendar.minDate, this.calendar.maxDate);
  1993. }
  1994. /**
  1995. * Format two individual labels for the minimum year and maximum year available in the multi-year
  1996. * calendar view. Returns an array of two strings where the first string is the formatted label
  1997. * for the minimum year, and the second string is the formatted label for the maximum year.
  1998. */
  1999. _formatMinAndMaxYearLabels() {
  2000. // The offset from the active year to the "slot" for the starting year is the
  2001. // *actual* first rendered year in the multi-year view, and the last year is
  2002. // just yearsPerPage - 1 away.
  2003. const activeYear = this._dateAdapter.getYear(this.calendar.activeDate);
  2004. const minYearOfPage = activeYear -
  2005. getActiveOffset(this._dateAdapter, this.calendar.activeDate, this.calendar.minDate, this.calendar.maxDate);
  2006. const maxYearOfPage = minYearOfPage + yearsPerPage - 1;
  2007. const minYearLabel = this._dateAdapter.getYearName(this._dateAdapter.createDate(minYearOfPage, 0, 1));
  2008. const maxYearLabel = this._dateAdapter.getYearName(this._dateAdapter.createDate(maxYearOfPage, 0, 1));
  2009. return [minYearLabel, maxYearLabel];
  2010. }
  2011. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarHeader, deps: [{ token: MatDatepickerIntl }, { token: forwardRef(() => MatCalendar) }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
  2012. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendarHeader, selector: "mat-calendar-header", exportAs: ["matCalendarHeader"], ngImport: i0, template: "<div class=\"mat-calendar-header\">\n <div class=\"mat-calendar-controls\">\n <button mat-button type=\"button\" class=\"mat-calendar-period-button\"\n (click)=\"currentPeriodClicked()\" [attr.aria-label]=\"periodButtonLabel\"\n [attr.aria-describedby]=\"_periodButtonLabelId\" aria-live=\"polite\">\n <span aria-hidden=\"true\">{{periodButtonText}}</span>\n <svg class=\"mat-calendar-arrow\" [class.mat-calendar-invert]=\"calendar.currentView !== 'month'\"\n viewBox=\"0 0 10 5\" focusable=\"false\" aria-hidden=\"true\">\n <polygon points=\"0,0 5,5 10,0\"/>\n </svg>\n </button>\n\n <div class=\"mat-calendar-spacer\"></div>\n\n <ng-content></ng-content>\n\n <button mat-icon-button type=\"button\" class=\"mat-calendar-previous-button\"\n [disabled]=\"!previousEnabled()\" (click)=\"previousClicked()\"\n [attr.aria-label]=\"prevButtonLabel\">\n </button>\n\n <button mat-icon-button type=\"button\" class=\"mat-calendar-next-button\"\n [disabled]=\"!nextEnabled()\" (click)=\"nextClicked()\"\n [attr.aria-label]=\"nextButtonLabel\">\n </button>\n </div>\n</div>\n<label [id]=\"_periodButtonLabelId\" class=\"mat-calendar-hidden-label\">{{periodButtonDescription}}</label>\n", dependencies: [{ kind: "component", type: i3.MatButton, selector: " button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button] ", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { kind: "component", type: i3.MatIconButton, selector: "button[mat-icon-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  2013. }
  2014. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendarHeader, decorators: [{
  2015. type: Component,
  2016. args: [{ selector: 'mat-calendar-header', exportAs: 'matCalendarHeader', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<div class=\"mat-calendar-header\">\n <div class=\"mat-calendar-controls\">\n <button mat-button type=\"button\" class=\"mat-calendar-period-button\"\n (click)=\"currentPeriodClicked()\" [attr.aria-label]=\"periodButtonLabel\"\n [attr.aria-describedby]=\"_periodButtonLabelId\" aria-live=\"polite\">\n <span aria-hidden=\"true\">{{periodButtonText}}</span>\n <svg class=\"mat-calendar-arrow\" [class.mat-calendar-invert]=\"calendar.currentView !== 'month'\"\n viewBox=\"0 0 10 5\" focusable=\"false\" aria-hidden=\"true\">\n <polygon points=\"0,0 5,5 10,0\"/>\n </svg>\n </button>\n\n <div class=\"mat-calendar-spacer\"></div>\n\n <ng-content></ng-content>\n\n <button mat-icon-button type=\"button\" class=\"mat-calendar-previous-button\"\n [disabled]=\"!previousEnabled()\" (click)=\"previousClicked()\"\n [attr.aria-label]=\"prevButtonLabel\">\n </button>\n\n <button mat-icon-button type=\"button\" class=\"mat-calendar-next-button\"\n [disabled]=\"!nextEnabled()\" (click)=\"nextClicked()\"\n [attr.aria-label]=\"nextButtonLabel\">\n </button>\n </div>\n</div>\n<label [id]=\"_periodButtonLabelId\" class=\"mat-calendar-hidden-label\">{{periodButtonDescription}}</label>\n" }]
  2017. }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: MatCalendar, decorators: [{
  2018. type: Inject,
  2019. args: [forwardRef(() => MatCalendar)]
  2020. }] }, { type: i1$1.DateAdapter, decorators: [{
  2021. type: Optional
  2022. }] }, { type: undefined, decorators: [{
  2023. type: Optional
  2024. }, {
  2025. type: Inject,
  2026. args: [MAT_DATE_FORMATS]
  2027. }] }, { type: i0.ChangeDetectorRef }]; } });
  2028. /** A calendar that is used as part of the datepicker. */
  2029. class MatCalendar {
  2030. /** A date representing the period (month or year) to start the calendar in. */
  2031. get startAt() {
  2032. return this._startAt;
  2033. }
  2034. set startAt(value) {
  2035. this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  2036. }
  2037. /** The currently selected date. */
  2038. get selected() {
  2039. return this._selected;
  2040. }
  2041. set selected(value) {
  2042. if (value instanceof DateRange) {
  2043. this._selected = value;
  2044. }
  2045. else {
  2046. this._selected = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  2047. }
  2048. }
  2049. /** The minimum selectable date. */
  2050. get minDate() {
  2051. return this._minDate;
  2052. }
  2053. set minDate(value) {
  2054. this._minDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  2055. }
  2056. /** The maximum selectable date. */
  2057. get maxDate() {
  2058. return this._maxDate;
  2059. }
  2060. set maxDate(value) {
  2061. this._maxDate = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  2062. }
  2063. /**
  2064. * The current active date. This determines which time period is shown and which date is
  2065. * highlighted when using keyboard navigation.
  2066. */
  2067. get activeDate() {
  2068. return this._clampedActiveDate;
  2069. }
  2070. set activeDate(value) {
  2071. this._clampedActiveDate = this._dateAdapter.clampDate(value, this.minDate, this.maxDate);
  2072. this.stateChanges.next();
  2073. this._changeDetectorRef.markForCheck();
  2074. }
  2075. /** Whether the calendar is in month view. */
  2076. get currentView() {
  2077. return this._currentView;
  2078. }
  2079. set currentView(value) {
  2080. const viewChangedResult = this._currentView !== value ? value : null;
  2081. this._currentView = value;
  2082. this._moveFocusOnNextTick = true;
  2083. this._changeDetectorRef.markForCheck();
  2084. if (viewChangedResult) {
  2085. this.viewChanged.emit(viewChangedResult);
  2086. }
  2087. }
  2088. constructor(_intl, _dateAdapter, _dateFormats, _changeDetectorRef) {
  2089. this._dateAdapter = _dateAdapter;
  2090. this._dateFormats = _dateFormats;
  2091. this._changeDetectorRef = _changeDetectorRef;
  2092. /**
  2093. * Used for scheduling that focus should be moved to the active cell on the next tick.
  2094. * We need to schedule it, rather than do it immediately, because we have to wait
  2095. * for Angular to re-evaluate the view children.
  2096. */
  2097. this._moveFocusOnNextTick = false;
  2098. /** Whether the calendar should be started in month or year view. */
  2099. this.startView = 'month';
  2100. /** Emits when the currently selected date changes. */
  2101. this.selectedChange = new EventEmitter();
  2102. /**
  2103. * Emits the year chosen in multiyear view.
  2104. * This doesn't imply a change on the selected date.
  2105. */
  2106. this.yearSelected = new EventEmitter();
  2107. /**
  2108. * Emits the month chosen in year view.
  2109. * This doesn't imply a change on the selected date.
  2110. */
  2111. this.monthSelected = new EventEmitter();
  2112. /**
  2113. * Emits when the current view changes.
  2114. */
  2115. this.viewChanged = new EventEmitter(true);
  2116. /** Emits when any date is selected. */
  2117. this._userSelection = new EventEmitter();
  2118. /** Emits a new date range value when the user completes a drag drop operation. */
  2119. this._userDragDrop = new EventEmitter();
  2120. /** Origin of active drag, or null when dragging is not active. */
  2121. this._activeDrag = null;
  2122. /**
  2123. * Emits whenever there is a state change that the header may need to respond to.
  2124. */
  2125. this.stateChanges = new Subject();
  2126. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  2127. if (!this._dateAdapter) {
  2128. throw createMissingDateImplError('DateAdapter');
  2129. }
  2130. if (!this._dateFormats) {
  2131. throw createMissingDateImplError('MAT_DATE_FORMATS');
  2132. }
  2133. }
  2134. this._intlChanges = _intl.changes.subscribe(() => {
  2135. _changeDetectorRef.markForCheck();
  2136. this.stateChanges.next();
  2137. });
  2138. }
  2139. ngAfterContentInit() {
  2140. this._calendarHeaderPortal = new ComponentPortal(this.headerComponent || MatCalendarHeader);
  2141. this.activeDate = this.startAt || this._dateAdapter.today();
  2142. // Assign to the private property since we don't want to move focus on init.
  2143. this._currentView = this.startView;
  2144. }
  2145. ngAfterViewChecked() {
  2146. if (this._moveFocusOnNextTick) {
  2147. this._moveFocusOnNextTick = false;
  2148. this.focusActiveCell();
  2149. }
  2150. }
  2151. ngOnDestroy() {
  2152. this._intlChanges.unsubscribe();
  2153. this.stateChanges.complete();
  2154. }
  2155. ngOnChanges(changes) {
  2156. // Ignore date changes that are at a different time on the same day. This fixes issues where
  2157. // the calendar re-renders when there is no meaningful change to [minDate] or [maxDate]
  2158. // (#24435).
  2159. const minDateChange = changes['minDate'] &&
  2160. !this._dateAdapter.sameDate(changes['minDate'].previousValue, changes['minDate'].currentValue)
  2161. ? changes['minDate']
  2162. : undefined;
  2163. const maxDateChange = changes['maxDate'] &&
  2164. !this._dateAdapter.sameDate(changes['maxDate'].previousValue, changes['maxDate'].currentValue)
  2165. ? changes['maxDate']
  2166. : undefined;
  2167. const change = minDateChange || maxDateChange || changes['dateFilter'];
  2168. if (change && !change.firstChange) {
  2169. const view = this._getCurrentViewComponent();
  2170. if (view) {
  2171. // We need to `detectChanges` manually here, because the `minDate`, `maxDate` etc. are
  2172. // passed down to the view via data bindings which won't be up-to-date when we call `_init`.
  2173. this._changeDetectorRef.detectChanges();
  2174. view._init();
  2175. }
  2176. }
  2177. this.stateChanges.next();
  2178. }
  2179. /** Focuses the active date. */
  2180. focusActiveCell() {
  2181. this._getCurrentViewComponent()._focusActiveCell(false);
  2182. }
  2183. /** Updates today's date after an update of the active date */
  2184. updateTodaysDate() {
  2185. this._getCurrentViewComponent()._init();
  2186. }
  2187. /** Handles date selection in the month view. */
  2188. _dateSelected(event) {
  2189. const date = event.value;
  2190. if (this.selected instanceof DateRange ||
  2191. (date && !this._dateAdapter.sameDate(date, this.selected))) {
  2192. this.selectedChange.emit(date);
  2193. }
  2194. this._userSelection.emit(event);
  2195. }
  2196. /** Handles year selection in the multiyear view. */
  2197. _yearSelectedInMultiYearView(normalizedYear) {
  2198. this.yearSelected.emit(normalizedYear);
  2199. }
  2200. /** Handles month selection in the year view. */
  2201. _monthSelectedInYearView(normalizedMonth) {
  2202. this.monthSelected.emit(normalizedMonth);
  2203. }
  2204. /** Handles year/month selection in the multi-year/year views. */
  2205. _goToDateInView(date, view) {
  2206. this.activeDate = date;
  2207. this.currentView = view;
  2208. }
  2209. /** Called when the user starts dragging to change a date range. */
  2210. _dragStarted(event) {
  2211. this._activeDrag = event;
  2212. }
  2213. /**
  2214. * Called when a drag completes. It may end in cancelation or in the selection
  2215. * of a new range.
  2216. */
  2217. _dragEnded(event) {
  2218. if (!this._activeDrag)
  2219. return;
  2220. if (event.value) {
  2221. this._userDragDrop.emit(event);
  2222. }
  2223. this._activeDrag = null;
  2224. }
  2225. /** Returns the component instance that corresponds to the current calendar view. */
  2226. _getCurrentViewComponent() {
  2227. // The return type is explicitly written as a union to ensure that the Closure compiler does
  2228. // not optimize calls to _init(). Without the explicit return type, TypeScript narrows it to
  2229. // only the first component type. See https://github.com/angular/components/issues/22996.
  2230. return this.monthView || this.yearView || this.multiYearView;
  2231. }
  2232. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendar, deps: [{ token: MatDatepickerIntl }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: i0.ChangeDetectorRef }], target: i0.ɵɵFactoryTarget.Component }); }
  2233. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatCalendar, selector: "mat-calendar", inputs: { headerComponent: "headerComponent", startAt: "startAt", startView: "startView", selected: "selected", minDate: "minDate", maxDate: "maxDate", dateFilter: "dateFilter", dateClass: "dateClass", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd", startDateAccessibleName: "startDateAccessibleName", endDateAccessibleName: "endDateAccessibleName" }, outputs: { selectedChange: "selectedChange", yearSelected: "yearSelected", monthSelected: "monthSelected", viewChanged: "viewChanged", _userSelection: "_userSelection", _userDragDrop: "_userDragDrop" }, host: { classAttribute: "mat-calendar" }, providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER], viewQueries: [{ propertyName: "monthView", first: true, predicate: MatMonthView, descendants: true }, { propertyName: "yearView", first: true, predicate: MatYearView, descendants: true }, { propertyName: "multiYearView", first: true, predicate: MatMultiYearView, descendants: true }], exportAs: ["matCalendar"], usesOnChanges: true, ngImport: i0, template: "<ng-template [cdkPortalOutlet]=\"_calendarHeaderPortal\"></ng-template>\n\n<div class=\"mat-calendar-content\" [ngSwitch]=\"currentView\" cdkMonitorSubtreeFocus tabindex=\"-1\">\n <mat-month-view\n *ngSwitchCase=\"'month'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n [comparisonStart]=\"comparisonStart\"\n [comparisonEnd]=\"comparisonEnd\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (_userSelection)=\"_dateSelected($event)\"\n (dragStarted)=\"_dragStarted($event)\"\n (dragEnded)=\"_dragEnded($event)\"\n [activeDrag]=\"_activeDrag\"\n >\n </mat-month-view>\n\n <mat-year-view\n *ngSwitchCase=\"'year'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n (monthSelected)=\"_monthSelectedInYearView($event)\"\n (selectedChange)=\"_goToDateInView($event, 'month')\">\n </mat-year-view>\n\n <mat-multi-year-view\n *ngSwitchCase=\"'multi-year'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n (yearSelected)=\"_yearSelectedInMultiYearView($event)\"\n (selectedChange)=\"_goToDateInView($event, 'year')\">\n </mat-multi-year-view>\n</div>\n", styles: [".mat-calendar{display:block}.mat-calendar-header{padding:8px 8px 0 8px}.mat-calendar-content{padding:0 8px 8px 8px;outline:none}.mat-calendar-controls{display:flex;align-items:center;margin:5% calc(4.7142857143% - 16px)}.mat-calendar-spacer{flex:1 1 auto}.mat-calendar-period-button{min-width:0;margin:0 8px}.mat-calendar-arrow{display:inline-block;width:10px;height:5px;margin:0 0 0 5px;vertical-align:middle}.mat-calendar-arrow.mat-calendar-invert{transform:rotate(180deg)}[dir=rtl] .mat-calendar-arrow{margin:0 5px 0 0}.cdk-high-contrast-active .mat-calendar-arrow{fill:CanvasText}.mat-calendar-previous-button,.mat-calendar-next-button{position:relative}.mat-calendar-previous-button::after,.mat-calendar-next-button::after{top:0;left:0;right:0;bottom:0;position:absolute;content:\"\";margin:15.5px;border:0 solid currentColor;border-top-width:2px}[dir=rtl] .mat-calendar-previous-button,[dir=rtl] .mat-calendar-next-button{transform:rotate(180deg)}.mat-calendar-previous-button::after{border-left-width:2px;transform:translateX(2px) rotate(-45deg)}.mat-calendar-next-button::after{border-right-width:2px;transform:translateX(-2px) rotate(45deg)}.mat-calendar-table{border-spacing:0;border-collapse:collapse;width:100%}.mat-calendar-table-header th{text-align:center;padding:0 0 8px 0}.mat-calendar-table-header-divider{position:relative;height:1px}.mat-calendar-table-header-divider::after{content:\"\";position:absolute;top:0;left:-8px;right:-8px;height:1px}.mat-calendar-body-cell-content::before{margin:calc(calc(var(--mat-focus-indicator-border-width, 3px) + 3px) * -1)}.mat-calendar-body-cell:focus .mat-focus-indicator::before{content:\"\"}.mat-calendar-hidden-label{display:none}"], dependencies: [{ kind: "directive", type: i1.NgSwitch, selector: "[ngSwitch]", inputs: ["ngSwitch"] }, { kind: "directive", type: i1.NgSwitchCase, selector: "[ngSwitchCase]", inputs: ["ngSwitchCase"] }, { kind: "directive", type: i5.CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }, { kind: "directive", type: i6.CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { kind: "component", type: MatMonthView, selector: "mat-month-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass", "comparisonStart", "comparisonEnd", "startDateAccessibleName", "endDateAccessibleName", "activeDrag"], outputs: ["selectedChange", "_userSelection", "dragStarted", "dragEnded", "activeDateChange"], exportAs: ["matMonthView"] }, { kind: "component", type: MatYearView, selector: "mat-year-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass"], outputs: ["selectedChange", "monthSelected", "activeDateChange"], exportAs: ["matYearView"] }, { kind: "component", type: MatMultiYearView, selector: "mat-multi-year-view", inputs: ["activeDate", "selected", "minDate", "maxDate", "dateFilter", "dateClass"], outputs: ["selectedChange", "yearSelected", "activeDateChange"], exportAs: ["matMultiYearView"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  2234. }
  2235. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatCalendar, decorators: [{
  2236. type: Component,
  2237. args: [{ selector: 'mat-calendar', host: {
  2238. 'class': 'mat-calendar',
  2239. }, exportAs: 'matCalendar', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER], template: "<ng-template [cdkPortalOutlet]=\"_calendarHeaderPortal\"></ng-template>\n\n<div class=\"mat-calendar-content\" [ngSwitch]=\"currentView\" cdkMonitorSubtreeFocus tabindex=\"-1\">\n <mat-month-view\n *ngSwitchCase=\"'month'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n [comparisonStart]=\"comparisonStart\"\n [comparisonEnd]=\"comparisonEnd\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (_userSelection)=\"_dateSelected($event)\"\n (dragStarted)=\"_dragStarted($event)\"\n (dragEnded)=\"_dragEnded($event)\"\n [activeDrag]=\"_activeDrag\"\n >\n </mat-month-view>\n\n <mat-year-view\n *ngSwitchCase=\"'year'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n (monthSelected)=\"_monthSelectedInYearView($event)\"\n (selectedChange)=\"_goToDateInView($event, 'month')\">\n </mat-year-view>\n\n <mat-multi-year-view\n *ngSwitchCase=\"'multi-year'\"\n [(activeDate)]=\"activeDate\"\n [selected]=\"selected\"\n [dateFilter]=\"dateFilter\"\n [maxDate]=\"maxDate\"\n [minDate]=\"minDate\"\n [dateClass]=\"dateClass\"\n (yearSelected)=\"_yearSelectedInMultiYearView($event)\"\n (selectedChange)=\"_goToDateInView($event, 'year')\">\n </mat-multi-year-view>\n</div>\n", styles: [".mat-calendar{display:block}.mat-calendar-header{padding:8px 8px 0 8px}.mat-calendar-content{padding:0 8px 8px 8px;outline:none}.mat-calendar-controls{display:flex;align-items:center;margin:5% calc(4.7142857143% - 16px)}.mat-calendar-spacer{flex:1 1 auto}.mat-calendar-period-button{min-width:0;margin:0 8px}.mat-calendar-arrow{display:inline-block;width:10px;height:5px;margin:0 0 0 5px;vertical-align:middle}.mat-calendar-arrow.mat-calendar-invert{transform:rotate(180deg)}[dir=rtl] .mat-calendar-arrow{margin:0 5px 0 0}.cdk-high-contrast-active .mat-calendar-arrow{fill:CanvasText}.mat-calendar-previous-button,.mat-calendar-next-button{position:relative}.mat-calendar-previous-button::after,.mat-calendar-next-button::after{top:0;left:0;right:0;bottom:0;position:absolute;content:\"\";margin:15.5px;border:0 solid currentColor;border-top-width:2px}[dir=rtl] .mat-calendar-previous-button,[dir=rtl] .mat-calendar-next-button{transform:rotate(180deg)}.mat-calendar-previous-button::after{border-left-width:2px;transform:translateX(2px) rotate(-45deg)}.mat-calendar-next-button::after{border-right-width:2px;transform:translateX(-2px) rotate(45deg)}.mat-calendar-table{border-spacing:0;border-collapse:collapse;width:100%}.mat-calendar-table-header th{text-align:center;padding:0 0 8px 0}.mat-calendar-table-header-divider{position:relative;height:1px}.mat-calendar-table-header-divider::after{content:\"\";position:absolute;top:0;left:-8px;right:-8px;height:1px}.mat-calendar-body-cell-content::before{margin:calc(calc(var(--mat-focus-indicator-border-width, 3px) + 3px) * -1)}.mat-calendar-body-cell:focus .mat-focus-indicator::before{content:\"\"}.mat-calendar-hidden-label{display:none}"] }]
  2240. }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: i1$1.DateAdapter, decorators: [{
  2241. type: Optional
  2242. }] }, { type: undefined, decorators: [{
  2243. type: Optional
  2244. }, {
  2245. type: Inject,
  2246. args: [MAT_DATE_FORMATS]
  2247. }] }, { type: i0.ChangeDetectorRef }]; }, propDecorators: { headerComponent: [{
  2248. type: Input
  2249. }], startAt: [{
  2250. type: Input
  2251. }], startView: [{
  2252. type: Input
  2253. }], selected: [{
  2254. type: Input
  2255. }], minDate: [{
  2256. type: Input
  2257. }], maxDate: [{
  2258. type: Input
  2259. }], dateFilter: [{
  2260. type: Input
  2261. }], dateClass: [{
  2262. type: Input
  2263. }], comparisonStart: [{
  2264. type: Input
  2265. }], comparisonEnd: [{
  2266. type: Input
  2267. }], startDateAccessibleName: [{
  2268. type: Input
  2269. }], endDateAccessibleName: [{
  2270. type: Input
  2271. }], selectedChange: [{
  2272. type: Output
  2273. }], yearSelected: [{
  2274. type: Output
  2275. }], monthSelected: [{
  2276. type: Output
  2277. }], viewChanged: [{
  2278. type: Output
  2279. }], _userSelection: [{
  2280. type: Output
  2281. }], _userDragDrop: [{
  2282. type: Output
  2283. }], monthView: [{
  2284. type: ViewChild,
  2285. args: [MatMonthView]
  2286. }], yearView: [{
  2287. type: ViewChild,
  2288. args: [MatYearView]
  2289. }], multiYearView: [{
  2290. type: ViewChild,
  2291. args: [MatMultiYearView]
  2292. }] } });
  2293. /**
  2294. * Animations used by the Material datepicker.
  2295. * @docs-private
  2296. */
  2297. const matDatepickerAnimations = {
  2298. /** Transforms the height of the datepicker's calendar. */
  2299. transformPanel: trigger('transformPanel', [
  2300. transition('void => enter-dropdown', animate('120ms cubic-bezier(0, 0, 0.2, 1)', keyframes([
  2301. style({ opacity: 0, transform: 'scale(1, 0.8)' }),
  2302. style({ opacity: 1, transform: 'scale(1, 1)' }),
  2303. ]))),
  2304. transition('void => enter-dialog', animate('150ms cubic-bezier(0, 0, 0.2, 1)', keyframes([
  2305. style({ opacity: 0, transform: 'scale(0.7)' }),
  2306. style({ transform: 'none', opacity: 1 }),
  2307. ]))),
  2308. transition('* => void', animate('100ms linear', style({ opacity: 0 }))),
  2309. ]),
  2310. /** Fades in the content of the calendar. */
  2311. fadeInCalendar: trigger('fadeInCalendar', [
  2312. state('void', style({ opacity: 0 })),
  2313. state('enter', style({ opacity: 1 })),
  2314. // TODO(crisbeto): this animation should be removed since it isn't quite on spec, but we
  2315. // need to keep it until #12440 gets in, otherwise the exit animation will look glitchy.
  2316. transition('void => *', animate('120ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)')),
  2317. ]),
  2318. };
  2319. /** Used to generate a unique ID for each datepicker instance. */
  2320. let datepickerUid = 0;
  2321. /** Injection token that determines the scroll handling while the calendar is open. */
  2322. const MAT_DATEPICKER_SCROLL_STRATEGY = new InjectionToken('mat-datepicker-scroll-strategy');
  2323. /** @docs-private */
  2324. function MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY(overlay) {
  2325. return () => overlay.scrollStrategies.reposition();
  2326. }
  2327. /** @docs-private */
  2328. const MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER = {
  2329. provide: MAT_DATEPICKER_SCROLL_STRATEGY,
  2330. deps: [Overlay],
  2331. useFactory: MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY,
  2332. };
  2333. // Boilerplate for applying mixins to MatDatepickerContent.
  2334. /** @docs-private */
  2335. const _MatDatepickerContentBase = mixinColor(class {
  2336. constructor(_elementRef) {
  2337. this._elementRef = _elementRef;
  2338. }
  2339. });
  2340. /**
  2341. * Component used as the content for the datepicker overlay. We use this instead of using
  2342. * MatCalendar directly as the content so we can control the initial focus. This also gives us a
  2343. * place to put additional features of the overlay that are not part of the calendar itself in the
  2344. * future. (e.g. confirmation buttons).
  2345. * @docs-private
  2346. */
  2347. class MatDatepickerContent extends _MatDatepickerContentBase {
  2348. constructor(elementRef, _changeDetectorRef, _globalModel, _dateAdapter, _rangeSelectionStrategy, intl) {
  2349. super(elementRef);
  2350. this._changeDetectorRef = _changeDetectorRef;
  2351. this._globalModel = _globalModel;
  2352. this._dateAdapter = _dateAdapter;
  2353. this._rangeSelectionStrategy = _rangeSelectionStrategy;
  2354. this._subscriptions = new Subscription();
  2355. /** Emits when an animation has finished. */
  2356. this._animationDone = new Subject();
  2357. /** Whether there is an in-progress animation. */
  2358. this._isAnimating = false;
  2359. /** Portal with projected action buttons. */
  2360. this._actionsPortal = null;
  2361. this._closeButtonText = intl.closeCalendarLabel;
  2362. }
  2363. ngOnInit() {
  2364. this._animationState = this.datepicker.touchUi ? 'enter-dialog' : 'enter-dropdown';
  2365. }
  2366. ngAfterViewInit() {
  2367. this._subscriptions.add(this.datepicker.stateChanges.subscribe(() => {
  2368. this._changeDetectorRef.markForCheck();
  2369. }));
  2370. this._calendar.focusActiveCell();
  2371. }
  2372. ngOnDestroy() {
  2373. this._subscriptions.unsubscribe();
  2374. this._animationDone.complete();
  2375. }
  2376. _handleUserSelection(event) {
  2377. const selection = this._model.selection;
  2378. const value = event.value;
  2379. const isRange = selection instanceof DateRange;
  2380. // If we're selecting a range and we have a selection strategy, always pass the value through
  2381. // there. Otherwise don't assign null values to the model, unless we're selecting a range.
  2382. // A null value when picking a range means that the user cancelled the selection (e.g. by
  2383. // pressing escape), whereas when selecting a single value it means that the value didn't
  2384. // change. This isn't very intuitive, but it's here for backwards-compatibility.
  2385. if (isRange && this._rangeSelectionStrategy) {
  2386. const newSelection = this._rangeSelectionStrategy.selectionFinished(value, selection, event.event);
  2387. this._model.updateSelection(newSelection, this);
  2388. }
  2389. else if (value &&
  2390. (isRange || !this._dateAdapter.sameDate(value, selection))) {
  2391. this._model.add(value);
  2392. }
  2393. // Delegate closing the overlay to the actions.
  2394. if ((!this._model || this._model.isComplete()) && !this._actionsPortal) {
  2395. this.datepicker.close();
  2396. }
  2397. }
  2398. _handleUserDragDrop(event) {
  2399. this._model.updateSelection(event.value, this);
  2400. }
  2401. _startExitAnimation() {
  2402. this._animationState = 'void';
  2403. this._changeDetectorRef.markForCheck();
  2404. }
  2405. _handleAnimationEvent(event) {
  2406. this._isAnimating = event.phaseName === 'start';
  2407. if (!this._isAnimating) {
  2408. this._animationDone.next();
  2409. }
  2410. }
  2411. _getSelected() {
  2412. return this._model.selection;
  2413. }
  2414. /** Applies the current pending selection to the global model. */
  2415. _applyPendingSelection() {
  2416. if (this._model !== this._globalModel) {
  2417. this._globalModel.updateSelection(this._model.selection, this);
  2418. }
  2419. }
  2420. /**
  2421. * Assigns a new portal containing the datepicker actions.
  2422. * @param portal Portal with the actions to be assigned.
  2423. * @param forceRerender Whether a re-render of the portal should be triggered. This isn't
  2424. * necessary if the portal is assigned during initialization, but it may be required if it's
  2425. * added at a later point.
  2426. */
  2427. _assignActions(portal, forceRerender) {
  2428. // If we have actions, clone the model so that we have the ability to cancel the selection,
  2429. // otherwise update the global model directly. Note that we want to assign this as soon as
  2430. // possible, but `_actionsPortal` isn't available in the constructor so we do it in `ngOnInit`.
  2431. this._model = portal ? this._globalModel.clone() : this._globalModel;
  2432. this._actionsPortal = portal;
  2433. if (forceRerender) {
  2434. this._changeDetectorRef.detectChanges();
  2435. }
  2436. }
  2437. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerContent, deps: [{ token: i0.ElementRef }, { token: i0.ChangeDetectorRef }, { token: MatDateSelectionModel }, { token: i1$1.DateAdapter }, { token: MAT_DATE_RANGE_SELECTION_STRATEGY, optional: true }, { token: MatDatepickerIntl }], target: i0.ɵɵFactoryTarget.Component }); }
  2438. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerContent, selector: "mat-datepicker-content", inputs: { color: "color" }, host: { listeners: { "@transformPanel.start": "_handleAnimationEvent($event)", "@transformPanel.done": "_handleAnimationEvent($event)" }, properties: { "@transformPanel": "_animationState", "class.mat-datepicker-content-touch": "datepicker.touchUi" }, classAttribute: "mat-datepicker-content" }, viewQueries: [{ propertyName: "_calendar", first: true, predicate: MatCalendar, descendants: true }], exportAs: ["matDatepickerContent"], usesInheritance: true, ngImport: i0, template: "<div\n cdkTrapFocus\n role=\"dialog\"\n [attr.aria-modal]=\"true\"\n [attr.aria-labelledby]=\"_dialogLabelId ?? undefined\"\n class=\"mat-datepicker-content-container\"\n [class.mat-datepicker-content-container-with-custom-header]=\"datepicker.calendarHeaderComponent\"\n [class.mat-datepicker-content-container-with-actions]=\"_actionsPortal\">\n <mat-calendar\n [id]=\"datepicker.id\"\n [ngClass]=\"datepicker.panelClass\"\n [startAt]=\"datepicker.startAt\"\n [startView]=\"datepicker.startView\"\n [minDate]=\"datepicker._getMinDate()\"\n [maxDate]=\"datepicker._getMaxDate()\"\n [dateFilter]=\"datepicker._getDateFilter()\"\n [headerComponent]=\"datepicker.calendarHeaderComponent\"\n [selected]=\"_getSelected()\"\n [dateClass]=\"datepicker.dateClass\"\n [comparisonStart]=\"comparisonStart\"\n [comparisonEnd]=\"comparisonEnd\"\n [@fadeInCalendar]=\"'enter'\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (yearSelected)=\"datepicker._selectYear($event)\"\n (monthSelected)=\"datepicker._selectMonth($event)\"\n (viewChanged)=\"datepicker._viewChanged($event)\"\n (_userSelection)=\"_handleUserSelection($event)\"\n (_userDragDrop)=\"_handleUserDragDrop($event)\"></mat-calendar>\n\n <ng-template [cdkPortalOutlet]=\"_actionsPortal\"></ng-template>\n\n <!-- Invisible close button for screen reader users. -->\n <button\n type=\"button\"\n mat-raised-button\n [color]=\"color || 'primary'\"\n class=\"mat-datepicker-close-button\"\n [class.cdk-visually-hidden]=\"!_closeButtonFocused\"\n (focus)=\"_closeButtonFocused = true\"\n (blur)=\"_closeButtonFocused = false\"\n (click)=\"datepicker.close()\">{{ _closeButtonText }}</button>\n</div>\n", styles: [".mat-datepicker-content{display:block;border-radius:4px}.mat-datepicker-content .mat-calendar{width:296px;height:354px}.mat-datepicker-content .mat-datepicker-content-container-with-custom-header .mat-calendar{height:auto}.mat-datepicker-content .mat-datepicker-close-button{position:absolute;top:100%;left:0;margin-top:8px}.ng-animating .mat-datepicker-content .mat-datepicker-close-button{display:none}.mat-datepicker-content-container{display:flex;flex-direction:column;justify-content:space-between}.mat-datepicker-content-touch{display:block;max-height:80vh;position:relative;overflow:visible}.mat-datepicker-content-touch .mat-datepicker-content-container{min-height:312px;max-height:788px;min-width:250px;max-width:750px}.mat-datepicker-content-touch .mat-calendar{width:100%;height:auto}@media all and (orientation: landscape){.mat-datepicker-content-touch .mat-datepicker-content-container{width:64vh;height:80vh}}@media all and (orientation: portrait){.mat-datepicker-content-touch .mat-datepicker-content-container{width:80vw;height:100vw}.mat-datepicker-content-touch .mat-datepicker-content-container-with-actions{height:115vw}}"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "component", type: i3.MatButton, selector: " button[mat-button], button[mat-raised-button], button[mat-flat-button], button[mat-stroked-button] ", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { kind: "directive", type: i5.CdkTrapFocus, selector: "[cdkTrapFocus]", inputs: ["cdkTrapFocus", "cdkTrapFocusAutoCapture"], exportAs: ["cdkTrapFocus"] }, { kind: "directive", type: i6.CdkPortalOutlet, selector: "[cdkPortalOutlet]", inputs: ["cdkPortalOutlet"], outputs: ["attached"], exportAs: ["cdkPortalOutlet"] }, { kind: "component", type: MatCalendar, selector: "mat-calendar", inputs: ["headerComponent", "startAt", "startView", "selected", "minDate", "maxDate", "dateFilter", "dateClass", "comparisonStart", "comparisonEnd", "startDateAccessibleName", "endDateAccessibleName"], outputs: ["selectedChange", "yearSelected", "monthSelected", "viewChanged", "_userSelection", "_userDragDrop"], exportAs: ["matCalendar"] }], animations: [matDatepickerAnimations.transformPanel, matDatepickerAnimations.fadeInCalendar], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  2439. }
  2440. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerContent, decorators: [{
  2441. type: Component,
  2442. args: [{ selector: 'mat-datepicker-content', host: {
  2443. 'class': 'mat-datepicker-content',
  2444. '[@transformPanel]': '_animationState',
  2445. '(@transformPanel.start)': '_handleAnimationEvent($event)',
  2446. '(@transformPanel.done)': '_handleAnimationEvent($event)',
  2447. '[class.mat-datepicker-content-touch]': 'datepicker.touchUi',
  2448. }, animations: [matDatepickerAnimations.transformPanel, matDatepickerAnimations.fadeInCalendar], exportAs: 'matDatepickerContent', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, inputs: ['color'], template: "<div\n cdkTrapFocus\n role=\"dialog\"\n [attr.aria-modal]=\"true\"\n [attr.aria-labelledby]=\"_dialogLabelId ?? undefined\"\n class=\"mat-datepicker-content-container\"\n [class.mat-datepicker-content-container-with-custom-header]=\"datepicker.calendarHeaderComponent\"\n [class.mat-datepicker-content-container-with-actions]=\"_actionsPortal\">\n <mat-calendar\n [id]=\"datepicker.id\"\n [ngClass]=\"datepicker.panelClass\"\n [startAt]=\"datepicker.startAt\"\n [startView]=\"datepicker.startView\"\n [minDate]=\"datepicker._getMinDate()\"\n [maxDate]=\"datepicker._getMaxDate()\"\n [dateFilter]=\"datepicker._getDateFilter()\"\n [headerComponent]=\"datepicker.calendarHeaderComponent\"\n [selected]=\"_getSelected()\"\n [dateClass]=\"datepicker.dateClass\"\n [comparisonStart]=\"comparisonStart\"\n [comparisonEnd]=\"comparisonEnd\"\n [@fadeInCalendar]=\"'enter'\"\n [startDateAccessibleName]=\"startDateAccessibleName\"\n [endDateAccessibleName]=\"endDateAccessibleName\"\n (yearSelected)=\"datepicker._selectYear($event)\"\n (monthSelected)=\"datepicker._selectMonth($event)\"\n (viewChanged)=\"datepicker._viewChanged($event)\"\n (_userSelection)=\"_handleUserSelection($event)\"\n (_userDragDrop)=\"_handleUserDragDrop($event)\"></mat-calendar>\n\n <ng-template [cdkPortalOutlet]=\"_actionsPortal\"></ng-template>\n\n <!-- Invisible close button for screen reader users. -->\n <button\n type=\"button\"\n mat-raised-button\n [color]=\"color || 'primary'\"\n class=\"mat-datepicker-close-button\"\n [class.cdk-visually-hidden]=\"!_closeButtonFocused\"\n (focus)=\"_closeButtonFocused = true\"\n (blur)=\"_closeButtonFocused = false\"\n (click)=\"datepicker.close()\">{{ _closeButtonText }}</button>\n</div>\n", styles: [".mat-datepicker-content{display:block;border-radius:4px}.mat-datepicker-content .mat-calendar{width:296px;height:354px}.mat-datepicker-content .mat-datepicker-content-container-with-custom-header .mat-calendar{height:auto}.mat-datepicker-content .mat-datepicker-close-button{position:absolute;top:100%;left:0;margin-top:8px}.ng-animating .mat-datepicker-content .mat-datepicker-close-button{display:none}.mat-datepicker-content-container{display:flex;flex-direction:column;justify-content:space-between}.mat-datepicker-content-touch{display:block;max-height:80vh;position:relative;overflow:visible}.mat-datepicker-content-touch .mat-datepicker-content-container{min-height:312px;max-height:788px;min-width:250px;max-width:750px}.mat-datepicker-content-touch .mat-calendar{width:100%;height:auto}@media all and (orientation: landscape){.mat-datepicker-content-touch .mat-datepicker-content-container{width:64vh;height:80vh}}@media all and (orientation: portrait){.mat-datepicker-content-touch .mat-datepicker-content-container{width:80vw;height:100vw}.mat-datepicker-content-touch .mat-datepicker-content-container-with-actions{height:115vw}}"] }]
  2449. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i0.ChangeDetectorRef }, { type: MatDateSelectionModel }, { type: i1$1.DateAdapter }, { type: undefined, decorators: [{
  2450. type: Optional
  2451. }, {
  2452. type: Inject,
  2453. args: [MAT_DATE_RANGE_SELECTION_STRATEGY]
  2454. }] }, { type: MatDatepickerIntl }]; }, propDecorators: { _calendar: [{
  2455. type: ViewChild,
  2456. args: [MatCalendar]
  2457. }] } });
  2458. /** Base class for a datepicker. */
  2459. class MatDatepickerBase {
  2460. /** The date to open the calendar to initially. */
  2461. get startAt() {
  2462. // If an explicit startAt is set we start there, otherwise we start at whatever the currently
  2463. // selected value is.
  2464. return this._startAt || (this.datepickerInput ? this.datepickerInput.getStartValue() : null);
  2465. }
  2466. set startAt(value) {
  2467. this._startAt = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  2468. }
  2469. /** Color palette to use on the datepicker's calendar. */
  2470. get color() {
  2471. return (this._color || (this.datepickerInput ? this.datepickerInput.getThemePalette() : undefined));
  2472. }
  2473. set color(value) {
  2474. this._color = value;
  2475. }
  2476. /**
  2477. * Whether the calendar UI is in touch mode. In touch mode the calendar opens in a dialog rather
  2478. * than a dropdown and elements have more padding to allow for bigger touch targets.
  2479. */
  2480. get touchUi() {
  2481. return this._touchUi;
  2482. }
  2483. set touchUi(value) {
  2484. this._touchUi = coerceBooleanProperty(value);
  2485. }
  2486. /** Whether the datepicker pop-up should be disabled. */
  2487. get disabled() {
  2488. return this._disabled === undefined && this.datepickerInput
  2489. ? this.datepickerInput.disabled
  2490. : !!this._disabled;
  2491. }
  2492. set disabled(value) {
  2493. const newValue = coerceBooleanProperty(value);
  2494. if (newValue !== this._disabled) {
  2495. this._disabled = newValue;
  2496. this.stateChanges.next(undefined);
  2497. }
  2498. }
  2499. /**
  2500. * Whether to restore focus to the previously-focused element when the calendar is closed.
  2501. * Note that automatic focus restoration is an accessibility feature and it is recommended that
  2502. * you provide your own equivalent, if you decide to turn it off.
  2503. */
  2504. get restoreFocus() {
  2505. return this._restoreFocus;
  2506. }
  2507. set restoreFocus(value) {
  2508. this._restoreFocus = coerceBooleanProperty(value);
  2509. }
  2510. /**
  2511. * Classes to be passed to the date picker panel.
  2512. * Supports string and string array values, similar to `ngClass`.
  2513. */
  2514. get panelClass() {
  2515. return this._panelClass;
  2516. }
  2517. set panelClass(value) {
  2518. this._panelClass = coerceStringArray(value);
  2519. }
  2520. /** Whether the calendar is open. */
  2521. get opened() {
  2522. return this._opened;
  2523. }
  2524. set opened(value) {
  2525. coerceBooleanProperty(value) ? this.open() : this.close();
  2526. }
  2527. /** The minimum selectable date. */
  2528. _getMinDate() {
  2529. return this.datepickerInput && this.datepickerInput.min;
  2530. }
  2531. /** The maximum selectable date. */
  2532. _getMaxDate() {
  2533. return this.datepickerInput && this.datepickerInput.max;
  2534. }
  2535. _getDateFilter() {
  2536. return this.datepickerInput && this.datepickerInput.dateFilter;
  2537. }
  2538. constructor(_overlay, _ngZone, _viewContainerRef, scrollStrategy, _dateAdapter, _dir, _model) {
  2539. this._overlay = _overlay;
  2540. this._ngZone = _ngZone;
  2541. this._viewContainerRef = _viewContainerRef;
  2542. this._dateAdapter = _dateAdapter;
  2543. this._dir = _dir;
  2544. this._model = _model;
  2545. this._inputStateChanges = Subscription.EMPTY;
  2546. this._document = inject(DOCUMENT);
  2547. /** The view that the calendar should start in. */
  2548. this.startView = 'month';
  2549. this._touchUi = false;
  2550. /** Preferred position of the datepicker in the X axis. */
  2551. this.xPosition = 'start';
  2552. /** Preferred position of the datepicker in the Y axis. */
  2553. this.yPosition = 'below';
  2554. this._restoreFocus = true;
  2555. /**
  2556. * Emits selected year in multiyear view.
  2557. * This doesn't imply a change on the selected date.
  2558. */
  2559. this.yearSelected = new EventEmitter();
  2560. /**
  2561. * Emits selected month in year view.
  2562. * This doesn't imply a change on the selected date.
  2563. */
  2564. this.monthSelected = new EventEmitter();
  2565. /**
  2566. * Emits when the current view changes.
  2567. */
  2568. this.viewChanged = new EventEmitter(true);
  2569. /** Emits when the datepicker has been opened. */
  2570. this.openedStream = new EventEmitter();
  2571. /** Emits when the datepicker has been closed. */
  2572. this.closedStream = new EventEmitter();
  2573. this._opened = false;
  2574. /** The id for the datepicker calendar. */
  2575. this.id = `mat-datepicker-${datepickerUid++}`;
  2576. /** The element that was focused before the datepicker was opened. */
  2577. this._focusedElementBeforeOpen = null;
  2578. /** Unique class that will be added to the backdrop so that the test harnesses can look it up. */
  2579. this._backdropHarnessClass = `${this.id}-backdrop`;
  2580. /** Emits when the datepicker's state changes. */
  2581. this.stateChanges = new Subject();
  2582. if (!this._dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  2583. throw createMissingDateImplError('DateAdapter');
  2584. }
  2585. this._scrollStrategy = scrollStrategy;
  2586. }
  2587. ngOnChanges(changes) {
  2588. const positionChange = changes['xPosition'] || changes['yPosition'];
  2589. if (positionChange && !positionChange.firstChange && this._overlayRef) {
  2590. const positionStrategy = this._overlayRef.getConfig().positionStrategy;
  2591. if (positionStrategy instanceof FlexibleConnectedPositionStrategy) {
  2592. this._setConnectedPositions(positionStrategy);
  2593. if (this.opened) {
  2594. this._overlayRef.updatePosition();
  2595. }
  2596. }
  2597. }
  2598. this.stateChanges.next(undefined);
  2599. }
  2600. ngOnDestroy() {
  2601. this._destroyOverlay();
  2602. this.close();
  2603. this._inputStateChanges.unsubscribe();
  2604. this.stateChanges.complete();
  2605. }
  2606. /** Selects the given date */
  2607. select(date) {
  2608. this._model.add(date);
  2609. }
  2610. /** Emits the selected year in multiyear view */
  2611. _selectYear(normalizedYear) {
  2612. this.yearSelected.emit(normalizedYear);
  2613. }
  2614. /** Emits selected month in year view */
  2615. _selectMonth(normalizedMonth) {
  2616. this.monthSelected.emit(normalizedMonth);
  2617. }
  2618. /** Emits changed view */
  2619. _viewChanged(view) {
  2620. this.viewChanged.emit(view);
  2621. }
  2622. /**
  2623. * Register an input with this datepicker.
  2624. * @param input The datepicker input to register with this datepicker.
  2625. * @returns Selection model that the input should hook itself up to.
  2626. */
  2627. registerInput(input) {
  2628. if (this.datepickerInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  2629. throw Error('A MatDatepicker can only be associated with a single input.');
  2630. }
  2631. this._inputStateChanges.unsubscribe();
  2632. this.datepickerInput = input;
  2633. this._inputStateChanges = input.stateChanges.subscribe(() => this.stateChanges.next(undefined));
  2634. return this._model;
  2635. }
  2636. /**
  2637. * Registers a portal containing action buttons with the datepicker.
  2638. * @param portal Portal to be registered.
  2639. */
  2640. registerActions(portal) {
  2641. if (this._actionsPortal && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  2642. throw Error('A MatDatepicker can only be associated with a single actions row.');
  2643. }
  2644. this._actionsPortal = portal;
  2645. this._componentRef?.instance._assignActions(portal, true);
  2646. }
  2647. /**
  2648. * Removes a portal containing action buttons from the datepicker.
  2649. * @param portal Portal to be removed.
  2650. */
  2651. removeActions(portal) {
  2652. if (portal === this._actionsPortal) {
  2653. this._actionsPortal = null;
  2654. this._componentRef?.instance._assignActions(null, true);
  2655. }
  2656. }
  2657. /** Open the calendar. */
  2658. open() {
  2659. // Skip reopening if there's an in-progress animation to avoid overlapping
  2660. // sequences which can cause "changed after checked" errors. See #25837.
  2661. if (this._opened || this.disabled || this._componentRef?.instance._isAnimating) {
  2662. return;
  2663. }
  2664. if (!this.datepickerInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  2665. throw Error('Attempted to open an MatDatepicker with no associated input.');
  2666. }
  2667. this._focusedElementBeforeOpen = _getFocusedElementPierceShadowDom();
  2668. this._openOverlay();
  2669. this._opened = true;
  2670. this.openedStream.emit();
  2671. }
  2672. /** Close the calendar. */
  2673. close() {
  2674. // Skip reopening if there's an in-progress animation to avoid overlapping
  2675. // sequences which can cause "changed after checked" errors. See #25837.
  2676. if (!this._opened || this._componentRef?.instance._isAnimating) {
  2677. return;
  2678. }
  2679. const canRestoreFocus = this._restoreFocus &&
  2680. this._focusedElementBeforeOpen &&
  2681. typeof this._focusedElementBeforeOpen.focus === 'function';
  2682. const completeClose = () => {
  2683. // The `_opened` could've been reset already if
  2684. // we got two events in quick succession.
  2685. if (this._opened) {
  2686. this._opened = false;
  2687. this.closedStream.emit();
  2688. }
  2689. };
  2690. if (this._componentRef) {
  2691. const { instance, location } = this._componentRef;
  2692. instance._startExitAnimation();
  2693. instance._animationDone.pipe(take(1)).subscribe(() => {
  2694. const activeElement = this._document.activeElement;
  2695. // Since we restore focus after the exit animation, we have to check that
  2696. // the user didn't move focus themselves inside the `close` handler.
  2697. if (canRestoreFocus &&
  2698. (!activeElement ||
  2699. activeElement === this._document.activeElement ||
  2700. location.nativeElement.contains(activeElement))) {
  2701. this._focusedElementBeforeOpen.focus();
  2702. }
  2703. this._focusedElementBeforeOpen = null;
  2704. this._destroyOverlay();
  2705. });
  2706. }
  2707. if (canRestoreFocus) {
  2708. // Because IE moves focus asynchronously, we can't count on it being restored before we've
  2709. // marked the datepicker as closed. If the event fires out of sequence and the element that
  2710. // we're refocusing opens the datepicker on focus, the user could be stuck with not being
  2711. // able to close the calendar at all. We work around it by making the logic, that marks
  2712. // the datepicker as closed, async as well.
  2713. setTimeout(completeClose);
  2714. }
  2715. else {
  2716. completeClose();
  2717. }
  2718. }
  2719. /** Applies the current pending selection on the overlay to the model. */
  2720. _applyPendingSelection() {
  2721. this._componentRef?.instance?._applyPendingSelection();
  2722. }
  2723. /** Forwards relevant values from the datepicker to the datepicker content inside the overlay. */
  2724. _forwardContentValues(instance) {
  2725. instance.datepicker = this;
  2726. instance.color = this.color;
  2727. instance._dialogLabelId = this.datepickerInput.getOverlayLabelId();
  2728. instance._assignActions(this._actionsPortal, false);
  2729. }
  2730. /** Opens the overlay with the calendar. */
  2731. _openOverlay() {
  2732. this._destroyOverlay();
  2733. const isDialog = this.touchUi;
  2734. const portal = new ComponentPortal(MatDatepickerContent, this._viewContainerRef);
  2735. const overlayRef = (this._overlayRef = this._overlay.create(new OverlayConfig({
  2736. positionStrategy: isDialog ? this._getDialogStrategy() : this._getDropdownStrategy(),
  2737. hasBackdrop: true,
  2738. backdropClass: [
  2739. isDialog ? 'cdk-overlay-dark-backdrop' : 'mat-overlay-transparent-backdrop',
  2740. this._backdropHarnessClass,
  2741. ],
  2742. direction: this._dir,
  2743. scrollStrategy: isDialog ? this._overlay.scrollStrategies.block() : this._scrollStrategy(),
  2744. panelClass: `mat-datepicker-${isDialog ? 'dialog' : 'popup'}`,
  2745. })));
  2746. this._getCloseStream(overlayRef).subscribe(event => {
  2747. if (event) {
  2748. event.preventDefault();
  2749. }
  2750. this.close();
  2751. });
  2752. // The `preventDefault` call happens inside the calendar as well, however focus moves into
  2753. // it inside a timeout which can give browsers a chance to fire off a keyboard event in-between
  2754. // that can scroll the page (see #24969). Always block default actions of arrow keys for the
  2755. // entire overlay so the page doesn't get scrolled by accident.
  2756. overlayRef.keydownEvents().subscribe(event => {
  2757. const keyCode = event.keyCode;
  2758. if (keyCode === UP_ARROW ||
  2759. keyCode === DOWN_ARROW ||
  2760. keyCode === LEFT_ARROW ||
  2761. keyCode === RIGHT_ARROW ||
  2762. keyCode === PAGE_UP ||
  2763. keyCode === PAGE_DOWN) {
  2764. event.preventDefault();
  2765. }
  2766. });
  2767. this._componentRef = overlayRef.attach(portal);
  2768. this._forwardContentValues(this._componentRef.instance);
  2769. // Update the position once the calendar has rendered. Only relevant in dropdown mode.
  2770. if (!isDialog) {
  2771. this._ngZone.onStable.pipe(take(1)).subscribe(() => overlayRef.updatePosition());
  2772. }
  2773. }
  2774. /** Destroys the current overlay. */
  2775. _destroyOverlay() {
  2776. if (this._overlayRef) {
  2777. this._overlayRef.dispose();
  2778. this._overlayRef = this._componentRef = null;
  2779. }
  2780. }
  2781. /** Gets a position strategy that will open the calendar as a dropdown. */
  2782. _getDialogStrategy() {
  2783. return this._overlay.position().global().centerHorizontally().centerVertically();
  2784. }
  2785. /** Gets a position strategy that will open the calendar as a dropdown. */
  2786. _getDropdownStrategy() {
  2787. const strategy = this._overlay
  2788. .position()
  2789. .flexibleConnectedTo(this.datepickerInput.getConnectedOverlayOrigin())
  2790. .withTransformOriginOn('.mat-datepicker-content')
  2791. .withFlexibleDimensions(false)
  2792. .withViewportMargin(8)
  2793. .withLockedPosition();
  2794. return this._setConnectedPositions(strategy);
  2795. }
  2796. /** Sets the positions of the datepicker in dropdown mode based on the current configuration. */
  2797. _setConnectedPositions(strategy) {
  2798. const primaryX = this.xPosition === 'end' ? 'end' : 'start';
  2799. const secondaryX = primaryX === 'start' ? 'end' : 'start';
  2800. const primaryY = this.yPosition === 'above' ? 'bottom' : 'top';
  2801. const secondaryY = primaryY === 'top' ? 'bottom' : 'top';
  2802. return strategy.withPositions([
  2803. {
  2804. originX: primaryX,
  2805. originY: secondaryY,
  2806. overlayX: primaryX,
  2807. overlayY: primaryY,
  2808. },
  2809. {
  2810. originX: primaryX,
  2811. originY: primaryY,
  2812. overlayX: primaryX,
  2813. overlayY: secondaryY,
  2814. },
  2815. {
  2816. originX: secondaryX,
  2817. originY: secondaryY,
  2818. overlayX: secondaryX,
  2819. overlayY: primaryY,
  2820. },
  2821. {
  2822. originX: secondaryX,
  2823. originY: primaryY,
  2824. overlayX: secondaryX,
  2825. overlayY: secondaryY,
  2826. },
  2827. ]);
  2828. }
  2829. /** Gets an observable that will emit when the overlay is supposed to be closed. */
  2830. _getCloseStream(overlayRef) {
  2831. const ctrlShiftMetaModifiers = ['ctrlKey', 'shiftKey', 'metaKey'];
  2832. return merge(overlayRef.backdropClick(), overlayRef.detachments(), overlayRef.keydownEvents().pipe(filter(event => {
  2833. // Closing on alt + up is only valid when there's an input associated with the datepicker.
  2834. return ((event.keyCode === ESCAPE && !hasModifierKey(event)) ||
  2835. (this.datepickerInput &&
  2836. hasModifierKey(event, 'altKey') &&
  2837. event.keyCode === UP_ARROW &&
  2838. ctrlShiftMetaModifiers.every((modifier) => !hasModifierKey(event, modifier))));
  2839. })));
  2840. }
  2841. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerBase, deps: [{ token: i9.Overlay }, { token: i0.NgZone }, { token: i0.ViewContainerRef }, { token: MAT_DATEPICKER_SCROLL_STRATEGY }, { token: i1$1.DateAdapter, optional: true }, { token: i2.Directionality, optional: true }, { token: MatDateSelectionModel }], target: i0.ɵɵFactoryTarget.Directive }); }
  2842. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerBase, inputs: { calendarHeaderComponent: "calendarHeaderComponent", startAt: "startAt", startView: "startView", color: "color", touchUi: "touchUi", disabled: "disabled", xPosition: "xPosition", yPosition: "yPosition", restoreFocus: "restoreFocus", dateClass: "dateClass", panelClass: "panelClass", opened: "opened" }, outputs: { yearSelected: "yearSelected", monthSelected: "monthSelected", viewChanged: "viewChanged", openedStream: "opened", closedStream: "closed" }, usesOnChanges: true, ngImport: i0 }); }
  2843. }
  2844. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerBase, decorators: [{
  2845. type: Directive
  2846. }], ctorParameters: function () { return [{ type: i9.Overlay }, { type: i0.NgZone }, { type: i0.ViewContainerRef }, { type: undefined, decorators: [{
  2847. type: Inject,
  2848. args: [MAT_DATEPICKER_SCROLL_STRATEGY]
  2849. }] }, { type: i1$1.DateAdapter, decorators: [{
  2850. type: Optional
  2851. }] }, { type: i2.Directionality, decorators: [{
  2852. type: Optional
  2853. }] }, { type: MatDateSelectionModel }]; }, propDecorators: { calendarHeaderComponent: [{
  2854. type: Input
  2855. }], startAt: [{
  2856. type: Input
  2857. }], startView: [{
  2858. type: Input
  2859. }], color: [{
  2860. type: Input
  2861. }], touchUi: [{
  2862. type: Input
  2863. }], disabled: [{
  2864. type: Input
  2865. }], xPosition: [{
  2866. type: Input
  2867. }], yPosition: [{
  2868. type: Input
  2869. }], restoreFocus: [{
  2870. type: Input
  2871. }], yearSelected: [{
  2872. type: Output
  2873. }], monthSelected: [{
  2874. type: Output
  2875. }], viewChanged: [{
  2876. type: Output
  2877. }], dateClass: [{
  2878. type: Input
  2879. }], openedStream: [{
  2880. type: Output,
  2881. args: ['opened']
  2882. }], closedStream: [{
  2883. type: Output,
  2884. args: ['closed']
  2885. }], panelClass: [{
  2886. type: Input
  2887. }], opened: [{
  2888. type: Input
  2889. }] } });
  2890. // TODO(mmalerba): We use a component instead of a directive here so the user can use implicit
  2891. // template reference variables (e.g. #d vs #d="matDatepicker"). We can change this to a directive
  2892. // if angular adds support for `exportAs: '$implicit'` on directives.
  2893. /** Component responsible for managing the datepicker popup/dialog. */
  2894. class MatDatepicker extends MatDatepickerBase {
  2895. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepicker, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
  2896. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepicker, selector: "mat-datepicker", providers: [
  2897. MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER,
  2898. { provide: MatDatepickerBase, useExisting: MatDatepicker },
  2899. ], exportAs: ["matDatepicker"], usesInheritance: true, ngImport: i0, template: '', isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  2900. }
  2901. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepicker, decorators: [{
  2902. type: Component,
  2903. args: [{
  2904. selector: 'mat-datepicker',
  2905. template: '',
  2906. exportAs: 'matDatepicker',
  2907. changeDetection: ChangeDetectionStrategy.OnPush,
  2908. encapsulation: ViewEncapsulation.None,
  2909. providers: [
  2910. MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER,
  2911. { provide: MatDatepickerBase, useExisting: MatDatepicker },
  2912. ],
  2913. }]
  2914. }] });
  2915. /**
  2916. * An event used for datepicker input and change events. We don't always have access to a native
  2917. * input or change event because the event may have been triggered by the user clicking on the
  2918. * calendar popup. For consistency, we always use MatDatepickerInputEvent instead.
  2919. */
  2920. class MatDatepickerInputEvent {
  2921. constructor(
  2922. /** Reference to the datepicker input component that emitted the event. */
  2923. target,
  2924. /** Reference to the native input element associated with the datepicker input. */
  2925. targetElement) {
  2926. this.target = target;
  2927. this.targetElement = targetElement;
  2928. this.value = this.target.value;
  2929. }
  2930. }
  2931. /** Base class for datepicker inputs. */
  2932. class MatDatepickerInputBase {
  2933. /** The value of the input. */
  2934. get value() {
  2935. return this._model ? this._getValueFromModel(this._model.selection) : this._pendingValue;
  2936. }
  2937. set value(value) {
  2938. this._assignValueProgrammatically(value);
  2939. }
  2940. /** Whether the datepicker-input is disabled. */
  2941. get disabled() {
  2942. return !!this._disabled || this._parentDisabled();
  2943. }
  2944. set disabled(value) {
  2945. const newValue = coerceBooleanProperty(value);
  2946. const element = this._elementRef.nativeElement;
  2947. if (this._disabled !== newValue) {
  2948. this._disabled = newValue;
  2949. this.stateChanges.next(undefined);
  2950. }
  2951. // We need to null check the `blur` method, because it's undefined during SSR.
  2952. // In Ivy static bindings are invoked earlier, before the element is attached to the DOM.
  2953. // This can cause an error to be thrown in some browsers (IE/Edge) which assert that the
  2954. // element has been inserted.
  2955. if (newValue && this._isInitialized && element.blur) {
  2956. // Normally, native input elements automatically blur if they turn disabled. This behavior
  2957. // is problematic, because it would mean that it triggers another change detection cycle,
  2958. // which then causes a changed after checked error if the input element was focused before.
  2959. element.blur();
  2960. }
  2961. }
  2962. /** Gets the base validator functions. */
  2963. _getValidators() {
  2964. return [this._parseValidator, this._minValidator, this._maxValidator, this._filterValidator];
  2965. }
  2966. /** Registers a date selection model with the input. */
  2967. _registerModel(model) {
  2968. this._model = model;
  2969. this._valueChangesSubscription.unsubscribe();
  2970. if (this._pendingValue) {
  2971. this._assignValue(this._pendingValue);
  2972. }
  2973. this._valueChangesSubscription = this._model.selectionChanged.subscribe(event => {
  2974. if (this._shouldHandleChangeEvent(event)) {
  2975. const value = this._getValueFromModel(event.selection);
  2976. this._lastValueValid = this._isValidValue(value);
  2977. this._cvaOnChange(value);
  2978. this._onTouched();
  2979. this._formatValue(value);
  2980. this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
  2981. this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
  2982. }
  2983. });
  2984. }
  2985. constructor(_elementRef, _dateAdapter, _dateFormats) {
  2986. this._elementRef = _elementRef;
  2987. this._dateAdapter = _dateAdapter;
  2988. this._dateFormats = _dateFormats;
  2989. /** Emits when a `change` event is fired on this `<input>`. */
  2990. this.dateChange = new EventEmitter();
  2991. /** Emits when an `input` event is fired on this `<input>`. */
  2992. this.dateInput = new EventEmitter();
  2993. /** Emits when the internal state has changed */
  2994. this.stateChanges = new Subject();
  2995. this._onTouched = () => { };
  2996. this._validatorOnChange = () => { };
  2997. this._cvaOnChange = () => { };
  2998. this._valueChangesSubscription = Subscription.EMPTY;
  2999. this._localeSubscription = Subscription.EMPTY;
  3000. /** The form control validator for whether the input parses. */
  3001. this._parseValidator = () => {
  3002. return this._lastValueValid
  3003. ? null
  3004. : { 'matDatepickerParse': { 'text': this._elementRef.nativeElement.value } };
  3005. };
  3006. /** The form control validator for the date filter. */
  3007. this._filterValidator = (control) => {
  3008. const controlValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
  3009. return !controlValue || this._matchesFilter(controlValue)
  3010. ? null
  3011. : { 'matDatepickerFilter': true };
  3012. };
  3013. /** The form control validator for the min date. */
  3014. this._minValidator = (control) => {
  3015. const controlValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
  3016. const min = this._getMinDate();
  3017. return !min || !controlValue || this._dateAdapter.compareDate(min, controlValue) <= 0
  3018. ? null
  3019. : { 'matDatepickerMin': { 'min': min, 'actual': controlValue } };
  3020. };
  3021. /** The form control validator for the max date. */
  3022. this._maxValidator = (control) => {
  3023. const controlValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
  3024. const max = this._getMaxDate();
  3025. return !max || !controlValue || this._dateAdapter.compareDate(max, controlValue) >= 0
  3026. ? null
  3027. : { 'matDatepickerMax': { 'max': max, 'actual': controlValue } };
  3028. };
  3029. /** Whether the last value set on the input was valid. */
  3030. this._lastValueValid = false;
  3031. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3032. if (!this._dateAdapter) {
  3033. throw createMissingDateImplError('DateAdapter');
  3034. }
  3035. if (!this._dateFormats) {
  3036. throw createMissingDateImplError('MAT_DATE_FORMATS');
  3037. }
  3038. }
  3039. // Update the displayed date when the locale changes.
  3040. this._localeSubscription = _dateAdapter.localeChanges.subscribe(() => {
  3041. this._assignValueProgrammatically(this.value);
  3042. });
  3043. }
  3044. ngAfterViewInit() {
  3045. this._isInitialized = true;
  3046. }
  3047. ngOnChanges(changes) {
  3048. if (dateInputsHaveChanged(changes, this._dateAdapter)) {
  3049. this.stateChanges.next(undefined);
  3050. }
  3051. }
  3052. ngOnDestroy() {
  3053. this._valueChangesSubscription.unsubscribe();
  3054. this._localeSubscription.unsubscribe();
  3055. this.stateChanges.complete();
  3056. }
  3057. /** @docs-private */
  3058. registerOnValidatorChange(fn) {
  3059. this._validatorOnChange = fn;
  3060. }
  3061. /** @docs-private */
  3062. validate(c) {
  3063. return this._validator ? this._validator(c) : null;
  3064. }
  3065. // Implemented as part of ControlValueAccessor.
  3066. writeValue(value) {
  3067. this._assignValueProgrammatically(value);
  3068. }
  3069. // Implemented as part of ControlValueAccessor.
  3070. registerOnChange(fn) {
  3071. this._cvaOnChange = fn;
  3072. }
  3073. // Implemented as part of ControlValueAccessor.
  3074. registerOnTouched(fn) {
  3075. this._onTouched = fn;
  3076. }
  3077. // Implemented as part of ControlValueAccessor.
  3078. setDisabledState(isDisabled) {
  3079. this.disabled = isDisabled;
  3080. }
  3081. _onKeydown(event) {
  3082. const ctrlShiftMetaModifiers = ['ctrlKey', 'shiftKey', 'metaKey'];
  3083. const isAltDownArrow = hasModifierKey(event, 'altKey') &&
  3084. event.keyCode === DOWN_ARROW &&
  3085. ctrlShiftMetaModifiers.every((modifier) => !hasModifierKey(event, modifier));
  3086. if (isAltDownArrow && !this._elementRef.nativeElement.readOnly) {
  3087. this._openPopup();
  3088. event.preventDefault();
  3089. }
  3090. }
  3091. _onInput(value) {
  3092. const lastValueWasValid = this._lastValueValid;
  3093. let date = this._dateAdapter.parse(value, this._dateFormats.parse.dateInput);
  3094. this._lastValueValid = this._isValidValue(date);
  3095. date = this._dateAdapter.getValidDateOrNull(date);
  3096. const hasChanged = !this._dateAdapter.sameDate(date, this.value);
  3097. // We need to fire the CVA change event for all
  3098. // nulls, otherwise the validators won't run.
  3099. if (!date || hasChanged) {
  3100. this._cvaOnChange(date);
  3101. }
  3102. else {
  3103. // Call the CVA change handler for invalid values
  3104. // since this is what marks the control as dirty.
  3105. if (value && !this.value) {
  3106. this._cvaOnChange(date);
  3107. }
  3108. if (lastValueWasValid !== this._lastValueValid) {
  3109. this._validatorOnChange();
  3110. }
  3111. }
  3112. if (hasChanged) {
  3113. this._assignValue(date);
  3114. this.dateInput.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
  3115. }
  3116. }
  3117. _onChange() {
  3118. this.dateChange.emit(new MatDatepickerInputEvent(this, this._elementRef.nativeElement));
  3119. }
  3120. /** Handles blur events on the input. */
  3121. _onBlur() {
  3122. // Reformat the input only if we have a valid value.
  3123. if (this.value) {
  3124. this._formatValue(this.value);
  3125. }
  3126. this._onTouched();
  3127. }
  3128. /** Formats a value and sets it on the input element. */
  3129. _formatValue(value) {
  3130. this._elementRef.nativeElement.value =
  3131. value != null ? this._dateAdapter.format(value, this._dateFormats.display.dateInput) : '';
  3132. }
  3133. /** Assigns a value to the model. */
  3134. _assignValue(value) {
  3135. // We may get some incoming values before the model was
  3136. // assigned. Save the value so that we can assign it later.
  3137. if (this._model) {
  3138. this._assignValueToModel(value);
  3139. this._pendingValue = null;
  3140. }
  3141. else {
  3142. this._pendingValue = value;
  3143. }
  3144. }
  3145. /** Whether a value is considered valid. */
  3146. _isValidValue(value) {
  3147. return !value || this._dateAdapter.isValid(value);
  3148. }
  3149. /**
  3150. * Checks whether a parent control is disabled. This is in place so that it can be overridden
  3151. * by inputs extending this one which can be placed inside of a group that can be disabled.
  3152. */
  3153. _parentDisabled() {
  3154. return false;
  3155. }
  3156. /** Programmatically assigns a value to the input. */
  3157. _assignValueProgrammatically(value) {
  3158. value = this._dateAdapter.deserialize(value);
  3159. this._lastValueValid = this._isValidValue(value);
  3160. value = this._dateAdapter.getValidDateOrNull(value);
  3161. this._assignValue(value);
  3162. this._formatValue(value);
  3163. }
  3164. /** Gets whether a value matches the current date filter. */
  3165. _matchesFilter(value) {
  3166. const filter = this._getDateFilter();
  3167. return !filter || filter(value);
  3168. }
  3169. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInputBase, deps: [{ token: i0.ElementRef }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3170. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerInputBase, inputs: { value: "value", disabled: "disabled" }, outputs: { dateChange: "dateChange", dateInput: "dateInput" }, usesOnChanges: true, ngImport: i0 }); }
  3171. }
  3172. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInputBase, decorators: [{
  3173. type: Directive
  3174. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1$1.DateAdapter, decorators: [{
  3175. type: Optional
  3176. }] }, { type: undefined, decorators: [{
  3177. type: Optional
  3178. }, {
  3179. type: Inject,
  3180. args: [MAT_DATE_FORMATS]
  3181. }] }]; }, propDecorators: { value: [{
  3182. type: Input
  3183. }], disabled: [{
  3184. type: Input
  3185. }], dateChange: [{
  3186. type: Output
  3187. }], dateInput: [{
  3188. type: Output
  3189. }] } });
  3190. /**
  3191. * Checks whether the `SimpleChanges` object from an `ngOnChanges`
  3192. * callback has any changes, accounting for date objects.
  3193. */
  3194. function dateInputsHaveChanged(changes, adapter) {
  3195. const keys = Object.keys(changes);
  3196. for (let key of keys) {
  3197. const { previousValue, currentValue } = changes[key];
  3198. if (adapter.isDateInstance(previousValue) && adapter.isDateInstance(currentValue)) {
  3199. if (!adapter.sameDate(previousValue, currentValue)) {
  3200. return true;
  3201. }
  3202. }
  3203. else {
  3204. return true;
  3205. }
  3206. }
  3207. return false;
  3208. }
  3209. /** @docs-private */
  3210. const MAT_DATEPICKER_VALUE_ACCESSOR = {
  3211. provide: NG_VALUE_ACCESSOR,
  3212. useExisting: forwardRef(() => MatDatepickerInput),
  3213. multi: true,
  3214. };
  3215. /** @docs-private */
  3216. const MAT_DATEPICKER_VALIDATORS = {
  3217. provide: NG_VALIDATORS,
  3218. useExisting: forwardRef(() => MatDatepickerInput),
  3219. multi: true,
  3220. };
  3221. /** Directive used to connect an input to a MatDatepicker. */
  3222. class MatDatepickerInput extends MatDatepickerInputBase {
  3223. /** The datepicker that this input is associated with. */
  3224. set matDatepicker(datepicker) {
  3225. if (datepicker) {
  3226. this._datepicker = datepicker;
  3227. this._closedSubscription = datepicker.closedStream.subscribe(() => this._onTouched());
  3228. this._registerModel(datepicker.registerInput(this));
  3229. }
  3230. }
  3231. /** The minimum valid date. */
  3232. get min() {
  3233. return this._min;
  3234. }
  3235. set min(value) {
  3236. const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  3237. if (!this._dateAdapter.sameDate(validValue, this._min)) {
  3238. this._min = validValue;
  3239. this._validatorOnChange();
  3240. }
  3241. }
  3242. /** The maximum valid date. */
  3243. get max() {
  3244. return this._max;
  3245. }
  3246. set max(value) {
  3247. const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  3248. if (!this._dateAdapter.sameDate(validValue, this._max)) {
  3249. this._max = validValue;
  3250. this._validatorOnChange();
  3251. }
  3252. }
  3253. /** Function that can be used to filter out dates within the datepicker. */
  3254. get dateFilter() {
  3255. return this._dateFilter;
  3256. }
  3257. set dateFilter(value) {
  3258. const wasMatchingValue = this._matchesFilter(this.value);
  3259. this._dateFilter = value;
  3260. if (this._matchesFilter(this.value) !== wasMatchingValue) {
  3261. this._validatorOnChange();
  3262. }
  3263. }
  3264. constructor(elementRef, dateAdapter, dateFormats, _formField) {
  3265. super(elementRef, dateAdapter, dateFormats);
  3266. this._formField = _formField;
  3267. this._closedSubscription = Subscription.EMPTY;
  3268. this._validator = Validators.compose(super._getValidators());
  3269. }
  3270. /**
  3271. * Gets the element that the datepicker popup should be connected to.
  3272. * @return The element to connect the popup to.
  3273. */
  3274. getConnectedOverlayOrigin() {
  3275. return this._formField ? this._formField.getConnectedOverlayOrigin() : this._elementRef;
  3276. }
  3277. /** Gets the ID of an element that should be used a description for the calendar overlay. */
  3278. getOverlayLabelId() {
  3279. if (this._formField) {
  3280. return this._formField.getLabelId();
  3281. }
  3282. return this._elementRef.nativeElement.getAttribute('aria-labelledby');
  3283. }
  3284. /** Returns the palette used by the input's form field, if any. */
  3285. getThemePalette() {
  3286. return this._formField ? this._formField.color : undefined;
  3287. }
  3288. /** Gets the value at which the calendar should start. */
  3289. getStartValue() {
  3290. return this.value;
  3291. }
  3292. ngOnDestroy() {
  3293. super.ngOnDestroy();
  3294. this._closedSubscription.unsubscribe();
  3295. }
  3296. /** Opens the associated datepicker. */
  3297. _openPopup() {
  3298. if (this._datepicker) {
  3299. this._datepicker.open();
  3300. }
  3301. }
  3302. _getValueFromModel(modelValue) {
  3303. return modelValue;
  3304. }
  3305. _assignValueToModel(value) {
  3306. if (this._model) {
  3307. this._model.updateSelection(value, this);
  3308. }
  3309. }
  3310. /** Gets the input's minimum date. */
  3311. _getMinDate() {
  3312. return this._min;
  3313. }
  3314. /** Gets the input's maximum date. */
  3315. _getMaxDate() {
  3316. return this._max;
  3317. }
  3318. /** Gets the input's date filtering function. */
  3319. _getDateFilter() {
  3320. return this._dateFilter;
  3321. }
  3322. _shouldHandleChangeEvent(event) {
  3323. return event.source !== this;
  3324. }
  3325. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInput, deps: [{ token: i0.ElementRef }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }, { token: MAT_FORM_FIELD, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3326. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerInput, selector: "input[matDatepicker]", inputs: { matDatepicker: "matDatepicker", min: "min", max: "max", dateFilter: ["matDatepickerFilter", "dateFilter"] }, host: { listeners: { "input": "_onInput($event.target.value)", "change": "_onChange()", "blur": "_onBlur()", "keydown": "_onKeydown($event)" }, properties: { "attr.aria-haspopup": "_datepicker ? \"dialog\" : null", "attr.aria-owns": "(_datepicker?.opened && _datepicker.id) || null", "attr.min": "min ? _dateAdapter.toIso8601(min) : null", "attr.max": "max ? _dateAdapter.toIso8601(max) : null", "attr.data-mat-calendar": "_datepicker ? _datepicker.id : null", "disabled": "disabled" }, classAttribute: "mat-datepicker-input" }, providers: [
  3327. MAT_DATEPICKER_VALUE_ACCESSOR,
  3328. MAT_DATEPICKER_VALIDATORS,
  3329. { provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: MatDatepickerInput },
  3330. ], exportAs: ["matDatepickerInput"], usesInheritance: true, ngImport: i0 }); }
  3331. }
  3332. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerInput, decorators: [{
  3333. type: Directive,
  3334. args: [{
  3335. selector: 'input[matDatepicker]',
  3336. providers: [
  3337. MAT_DATEPICKER_VALUE_ACCESSOR,
  3338. MAT_DATEPICKER_VALIDATORS,
  3339. { provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: MatDatepickerInput },
  3340. ],
  3341. host: {
  3342. 'class': 'mat-datepicker-input',
  3343. '[attr.aria-haspopup]': '_datepicker ? "dialog" : null',
  3344. '[attr.aria-owns]': '(_datepicker?.opened && _datepicker.id) || null',
  3345. '[attr.min]': 'min ? _dateAdapter.toIso8601(min) : null',
  3346. '[attr.max]': 'max ? _dateAdapter.toIso8601(max) : null',
  3347. // Used by the test harness to tie this input to its calendar. We can't depend on
  3348. // `aria-owns` for this, because it's only defined while the calendar is open.
  3349. '[attr.data-mat-calendar]': '_datepicker ? _datepicker.id : null',
  3350. '[disabled]': 'disabled',
  3351. '(input)': '_onInput($event.target.value)',
  3352. '(change)': '_onChange()',
  3353. '(blur)': '_onBlur()',
  3354. '(keydown)': '_onKeydown($event)',
  3355. },
  3356. exportAs: 'matDatepickerInput',
  3357. }]
  3358. }], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: i1$1.DateAdapter, decorators: [{
  3359. type: Optional
  3360. }] }, { type: undefined, decorators: [{
  3361. type: Optional
  3362. }, {
  3363. type: Inject,
  3364. args: [MAT_DATE_FORMATS]
  3365. }] }, { type: undefined, decorators: [{
  3366. type: Optional
  3367. }, {
  3368. type: Inject,
  3369. args: [MAT_FORM_FIELD]
  3370. }] }]; }, propDecorators: { matDatepicker: [{
  3371. type: Input
  3372. }], min: [{
  3373. type: Input
  3374. }], max: [{
  3375. type: Input
  3376. }], dateFilter: [{
  3377. type: Input,
  3378. args: ['matDatepickerFilter']
  3379. }] } });
  3380. /** Can be used to override the icon of a `matDatepickerToggle`. */
  3381. class MatDatepickerToggleIcon {
  3382. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggleIcon, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
  3383. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerToggleIcon, selector: "[matDatepickerToggleIcon]", ngImport: i0 }); }
  3384. }
  3385. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggleIcon, decorators: [{
  3386. type: Directive,
  3387. args: [{
  3388. selector: '[matDatepickerToggleIcon]',
  3389. }]
  3390. }] });
  3391. class MatDatepickerToggle {
  3392. /** Whether the toggle button is disabled. */
  3393. get disabled() {
  3394. if (this._disabled === undefined && this.datepicker) {
  3395. return this.datepicker.disabled;
  3396. }
  3397. return !!this._disabled;
  3398. }
  3399. set disabled(value) {
  3400. this._disabled = coerceBooleanProperty(value);
  3401. }
  3402. constructor(_intl, _changeDetectorRef, defaultTabIndex) {
  3403. this._intl = _intl;
  3404. this._changeDetectorRef = _changeDetectorRef;
  3405. this._stateChanges = Subscription.EMPTY;
  3406. const parsedTabIndex = Number(defaultTabIndex);
  3407. this.tabIndex = parsedTabIndex || parsedTabIndex === 0 ? parsedTabIndex : null;
  3408. }
  3409. ngOnChanges(changes) {
  3410. if (changes['datepicker']) {
  3411. this._watchStateChanges();
  3412. }
  3413. }
  3414. ngOnDestroy() {
  3415. this._stateChanges.unsubscribe();
  3416. }
  3417. ngAfterContentInit() {
  3418. this._watchStateChanges();
  3419. }
  3420. _open(event) {
  3421. if (this.datepicker && !this.disabled) {
  3422. this.datepicker.open();
  3423. event.stopPropagation();
  3424. }
  3425. }
  3426. _watchStateChanges() {
  3427. const datepickerStateChanged = this.datepicker ? this.datepicker.stateChanges : of();
  3428. const inputStateChanged = this.datepicker && this.datepicker.datepickerInput
  3429. ? this.datepicker.datepickerInput.stateChanges
  3430. : of();
  3431. const datepickerToggled = this.datepicker
  3432. ? merge(this.datepicker.openedStream, this.datepicker.closedStream)
  3433. : of();
  3434. this._stateChanges.unsubscribe();
  3435. this._stateChanges = merge(this._intl.changes, datepickerStateChanged, inputStateChanged, datepickerToggled).subscribe(() => this._changeDetectorRef.markForCheck());
  3436. }
  3437. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggle, deps: [{ token: MatDatepickerIntl }, { token: i0.ChangeDetectorRef }, { token: 'tabindex', attribute: true }], target: i0.ɵɵFactoryTarget.Component }); }
  3438. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerToggle, selector: "mat-datepicker-toggle", inputs: { datepicker: ["for", "datepicker"], tabIndex: "tabIndex", ariaLabel: ["aria-label", "ariaLabel"], disabled: "disabled", disableRipple: "disableRipple" }, host: { listeners: { "click": "_open($event)" }, properties: { "attr.tabindex": "null", "class.mat-datepicker-toggle-active": "datepicker && datepicker.opened", "class.mat-accent": "datepicker && datepicker.color === \"accent\"", "class.mat-warn": "datepicker && datepicker.color === \"warn\"", "attr.data-mat-calendar": "datepicker ? datepicker.id : null" }, classAttribute: "mat-datepicker-toggle" }, queries: [{ propertyName: "_customIcon", first: true, predicate: MatDatepickerToggleIcon, descendants: true }], viewQueries: [{ propertyName: "_button", first: true, predicate: ["button"], descendants: true }], exportAs: ["matDatepickerToggle"], usesOnChanges: true, ngImport: i0, template: "<button\n #button\n mat-icon-button\n type=\"button\"\n [attr.aria-haspopup]=\"datepicker ? 'dialog' : null\"\n [attr.aria-label]=\"ariaLabel || _intl.openCalendarLabel\"\n [attr.tabindex]=\"disabled ? -1 : tabIndex\"\n [disabled]=\"disabled\"\n [disableRipple]=\"disableRipple\">\n\n <svg\n *ngIf=\"!_customIcon\"\n class=\"mat-datepicker-toggle-default-icon\"\n viewBox=\"0 0 24 24\"\n width=\"24px\"\n height=\"24px\"\n fill=\"currentColor\"\n focusable=\"false\"\n aria-hidden=\"true\">\n <path d=\"M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z\"/>\n </svg>\n\n <ng-content select=\"[matDatepickerToggleIcon]\"></ng-content>\n</button>\n", styles: [".mat-datepicker-toggle{pointer-events:auto}.cdk-high-contrast-active .mat-datepicker-toggle-default-icon{color:CanvasText}"], dependencies: [{ kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i3.MatIconButton, selector: "button[mat-icon-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  3439. }
  3440. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerToggle, decorators: [{
  3441. type: Component,
  3442. args: [{ selector: 'mat-datepicker-toggle', host: {
  3443. 'class': 'mat-datepicker-toggle',
  3444. '[attr.tabindex]': 'null',
  3445. '[class.mat-datepicker-toggle-active]': 'datepicker && datepicker.opened',
  3446. '[class.mat-accent]': 'datepicker && datepicker.color === "accent"',
  3447. '[class.mat-warn]': 'datepicker && datepicker.color === "warn"',
  3448. // Used by the test harness to tie this toggle to its datepicker.
  3449. '[attr.data-mat-calendar]': 'datepicker ? datepicker.id : null',
  3450. // Bind the `click` on the host, rather than the inner `button`, so that we can call
  3451. // `stopPropagation` on it without affecting the user's `click` handlers. We need to stop
  3452. // it so that the input doesn't get focused automatically by the form field (See #21836).
  3453. '(click)': '_open($event)',
  3454. }, exportAs: 'matDatepickerToggle', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, template: "<button\n #button\n mat-icon-button\n type=\"button\"\n [attr.aria-haspopup]=\"datepicker ? 'dialog' : null\"\n [attr.aria-label]=\"ariaLabel || _intl.openCalendarLabel\"\n [attr.tabindex]=\"disabled ? -1 : tabIndex\"\n [disabled]=\"disabled\"\n [disableRipple]=\"disableRipple\">\n\n <svg\n *ngIf=\"!_customIcon\"\n class=\"mat-datepicker-toggle-default-icon\"\n viewBox=\"0 0 24 24\"\n width=\"24px\"\n height=\"24px\"\n fill=\"currentColor\"\n focusable=\"false\"\n aria-hidden=\"true\">\n <path d=\"M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z\"/>\n </svg>\n\n <ng-content select=\"[matDatepickerToggleIcon]\"></ng-content>\n</button>\n", styles: [".mat-datepicker-toggle{pointer-events:auto}.cdk-high-contrast-active .mat-datepicker-toggle-default-icon{color:CanvasText}"] }]
  3455. }], ctorParameters: function () { return [{ type: MatDatepickerIntl }, { type: i0.ChangeDetectorRef }, { type: undefined, decorators: [{
  3456. type: Attribute,
  3457. args: ['tabindex']
  3458. }] }]; }, propDecorators: { datepicker: [{
  3459. type: Input,
  3460. args: ['for']
  3461. }], tabIndex: [{
  3462. type: Input
  3463. }], ariaLabel: [{
  3464. type: Input,
  3465. args: ['aria-label']
  3466. }], disabled: [{
  3467. type: Input
  3468. }], disableRipple: [{
  3469. type: Input
  3470. }], _customIcon: [{
  3471. type: ContentChild,
  3472. args: [MatDatepickerToggleIcon]
  3473. }], _button: [{
  3474. type: ViewChild,
  3475. args: ['button']
  3476. }] } });
  3477. // This file contains the `_computeAriaAccessibleName` function, which computes what the *expected*
  3478. // ARIA accessible name would be for a given element. Implements a subset of ARIA specification
  3479. // [Accessible Name and Description Computation 1.2](https://www.w3.org/TR/accname-1.2/).
  3480. //
  3481. // Specification accname-1.2 can be summarized by returning the result of the first method
  3482. // available.
  3483. //
  3484. // 1. `aria-labelledby` attribute
  3485. // ```
  3486. // <!-- example using aria-labelledby-->
  3487. // <label id='label-id'>Start Date</label>
  3488. // <input aria-labelledby='label-id'/>
  3489. // ```
  3490. // 2. `aria-label` attribute (e.g. `<input aria-label="Departure"/>`)
  3491. // 3. Label with `for`/`id`
  3492. // ```
  3493. // <!-- example using for/id -->
  3494. // <label for="current-node">Label</label>
  3495. // <input id="current-node"/>
  3496. // ```
  3497. // 4. `placeholder` attribute (e.g. `<input placeholder="06/03/1990"/>`)
  3498. // 5. `title` attribute (e.g. `<input title="Check-In"/>`)
  3499. // 6. text content
  3500. // ```
  3501. // <!-- example using text content -->
  3502. // <label for="current-node"><span>Departure</span> Date</label>
  3503. // <input id="current-node"/>
  3504. // ```
  3505. /**
  3506. * Computes the *expected* ARIA accessible name for argument element based on [accname-1.2
  3507. * specification](https://www.w3.org/TR/accname-1.2/). Implements a subset of accname-1.2,
  3508. * and should only be used for the Datepicker's specific use case.
  3509. *
  3510. * Intended use:
  3511. * This is not a general use implementation. Only implements the parts of accname-1.2 that are
  3512. * required for the Datepicker's specific use case. This function is not intended for any other
  3513. * use.
  3514. *
  3515. * Limitations:
  3516. * - Only covers the needs of `matStartDate` and `matEndDate`. Does not support other use cases.
  3517. * - See NOTES's in implementation for specific details on what parts of the accname-1.2
  3518. * specification are not implemented.
  3519. *
  3520. * @param element {HTMLInputElement} native &lt;input/&gt; element of `matStartDate` or
  3521. * `matEndDate` component. Corresponds to the 'Root Element' from accname-1.2
  3522. *
  3523. * @return expected ARIA accessible name of argument &lt;input/&gt;
  3524. */
  3525. function _computeAriaAccessibleName(element) {
  3526. return _computeAriaAccessibleNameInternal(element, true);
  3527. }
  3528. /**
  3529. * Determine if argument node is an Element based on `nodeType` property. This function is safe to
  3530. * use with server-side rendering.
  3531. */
  3532. function ssrSafeIsElement(node) {
  3533. return node.nodeType === Node.ELEMENT_NODE;
  3534. }
  3535. /**
  3536. * Determine if argument node is an HTMLInputElement based on `nodeName` property. This funciton is
  3537. * safe to use with server-side rendering.
  3538. */
  3539. function ssrSafeIsHTMLInputElement(node) {
  3540. return node.nodeName === 'INPUT';
  3541. }
  3542. /**
  3543. * Determine if argument node is an HTMLTextAreaElement based on `nodeName` property. This
  3544. * funciton is safe to use with server-side rendering.
  3545. */
  3546. function ssrSafeIsHTMLTextAreaElement(node) {
  3547. return node.nodeName === 'TEXTAREA';
  3548. }
  3549. /**
  3550. * Calculate the expected ARIA accessible name for given DOM Node. Given DOM Node may be either the
  3551. * "Root node" passed to `_computeAriaAccessibleName` or "Current node" as result of recursion.
  3552. *
  3553. * @return the accessible name of argument DOM Node
  3554. *
  3555. * @param currentNode node to determine accessible name of
  3556. * @param isDirectlyReferenced true if `currentNode` is the root node to calculate ARIA accessible
  3557. * name of. False if it is a result of recursion.
  3558. */
  3559. function _computeAriaAccessibleNameInternal(currentNode, isDirectlyReferenced) {
  3560. // NOTE: this differs from accname-1.2 specification.
  3561. // - Does not implement Step 1. of accname-1.2: '''If `currentNode`'s role prohibits naming,
  3562. // return the empty string ("")'''.
  3563. // - Does not implement Step 2.A. of accname-1.2: '''if current node is hidden and not directly
  3564. // referenced by aria-labelledby... return the empty string.'''
  3565. // acc-name-1.2 Step 2.B.: aria-labelledby
  3566. if (ssrSafeIsElement(currentNode) && isDirectlyReferenced) {
  3567. const labelledbyIds = currentNode.getAttribute?.('aria-labelledby')?.split(/\s+/g) || [];
  3568. const validIdRefs = labelledbyIds.reduce((validIds, id) => {
  3569. const elem = document.getElementById(id);
  3570. if (elem) {
  3571. validIds.push(elem);
  3572. }
  3573. return validIds;
  3574. }, []);
  3575. if (validIdRefs.length) {
  3576. return validIdRefs
  3577. .map(idRef => {
  3578. return _computeAriaAccessibleNameInternal(idRef, false);
  3579. })
  3580. .join(' ');
  3581. }
  3582. }
  3583. // acc-name-1.2 Step 2.C.: aria-label
  3584. if (ssrSafeIsElement(currentNode)) {
  3585. const ariaLabel = currentNode.getAttribute('aria-label')?.trim();
  3586. if (ariaLabel) {
  3587. return ariaLabel;
  3588. }
  3589. }
  3590. // acc-name-1.2 Step 2.D. attribute or element that defines a text alternative
  3591. //
  3592. // NOTE: this differs from accname-1.2 specification.
  3593. // Only implements Step 2.D. for `<label>`,`<input/>`, and `<textarea/>` element. Does not
  3594. // implement other elements that have an attribute or element that defines a text alternative.
  3595. if (ssrSafeIsHTMLInputElement(currentNode) || ssrSafeIsHTMLTextAreaElement(currentNode)) {
  3596. // use label with a `for` attribute referencing the current node
  3597. if (currentNode.labels?.length) {
  3598. return Array.from(currentNode.labels)
  3599. .map(x => _computeAriaAccessibleNameInternal(x, false))
  3600. .join(' ');
  3601. }
  3602. // use placeholder if available
  3603. const placeholder = currentNode.getAttribute('placeholder')?.trim();
  3604. if (placeholder) {
  3605. return placeholder;
  3606. }
  3607. // use title if available
  3608. const title = currentNode.getAttribute('title')?.trim();
  3609. if (title) {
  3610. return title;
  3611. }
  3612. }
  3613. // NOTE: this differs from accname-1.2 specification.
  3614. // - does not implement acc-name-1.2 Step 2.E.: '''if the current node is a control embedded
  3615. // within the label... then include the embedded control as part of the text alternative in
  3616. // the following manner...'''. Step 2E applies to embedded controls such as textbox, listbox,
  3617. // range, etc.
  3618. // - does not implement acc-name-1.2 step 2.F.: check that '''role allows name from content''',
  3619. // which applies to `currentNode` and its children.
  3620. // - does not implement acc-name-1.2 Step 2.F.ii.: '''Check for CSS generated textual content'''
  3621. // (e.g. :before and :after).
  3622. // - does not implement acc-name-1.2 Step 2.I.: '''if the current node has a Tooltip attribute,
  3623. // return its value'''
  3624. // Return text content with whitespace collapsed into a single space character. Accomplish
  3625. // acc-name-1.2 steps 2F, 2G, and 2H.
  3626. return (currentNode.textContent || '').replace(/\s+/g, ' ').trim();
  3627. }
  3628. /**
  3629. * Used to provide the date range input wrapper component
  3630. * to the parts without circular dependencies.
  3631. */
  3632. const MAT_DATE_RANGE_INPUT_PARENT = new InjectionToken('MAT_DATE_RANGE_INPUT_PARENT');
  3633. /**
  3634. * Base class for the individual inputs that can be projected inside a `mat-date-range-input`.
  3635. */
  3636. class MatDateRangeInputPartBase extends MatDatepickerInputBase {
  3637. constructor(_rangeInput, _elementRef, _defaultErrorStateMatcher, _injector, _parentForm, _parentFormGroup, dateAdapter, dateFormats) {
  3638. super(_elementRef, dateAdapter, dateFormats);
  3639. this._rangeInput = _rangeInput;
  3640. this._elementRef = _elementRef;
  3641. this._defaultErrorStateMatcher = _defaultErrorStateMatcher;
  3642. this._injector = _injector;
  3643. this._parentForm = _parentForm;
  3644. this._parentFormGroup = _parentFormGroup;
  3645. this._dir = inject(Directionality, { optional: true });
  3646. }
  3647. ngOnInit() {
  3648. // We need the date input to provide itself as a `ControlValueAccessor` and a `Validator`, while
  3649. // injecting its `NgControl` so that the error state is handled correctly. This introduces a
  3650. // circular dependency, because both `ControlValueAccessor` and `Validator` depend on the input
  3651. // itself. Usually we can work around it for the CVA, but there's no API to do it for the
  3652. // validator. We work around it here by injecting the `NgControl` in `ngOnInit`, after
  3653. // everything has been resolved.
  3654. // tslint:disable-next-line:no-bitwise
  3655. const ngControl = this._injector.get(NgControl, null, { optional: true, self: true });
  3656. if (ngControl) {
  3657. this.ngControl = ngControl;
  3658. }
  3659. }
  3660. ngDoCheck() {
  3661. if (this.ngControl) {
  3662. // We need to re-evaluate this on every change detection cycle, because there are some
  3663. // error triggers that we can't subscribe to (e.g. parent form submissions). This means
  3664. // that whatever logic is in here has to be super lean or we risk destroying the performance.
  3665. this.updateErrorState();
  3666. }
  3667. }
  3668. /** Gets whether the input is empty. */
  3669. isEmpty() {
  3670. return this._elementRef.nativeElement.value.length === 0;
  3671. }
  3672. /** Gets the placeholder of the input. */
  3673. _getPlaceholder() {
  3674. return this._elementRef.nativeElement.placeholder;
  3675. }
  3676. /** Focuses the input. */
  3677. focus() {
  3678. this._elementRef.nativeElement.focus();
  3679. }
  3680. /** Gets the value that should be used when mirroring the input's size. */
  3681. getMirrorValue() {
  3682. const element = this._elementRef.nativeElement;
  3683. const value = element.value;
  3684. return value.length > 0 ? value : element.placeholder;
  3685. }
  3686. /** Handles `input` events on the input element. */
  3687. _onInput(value) {
  3688. super._onInput(value);
  3689. this._rangeInput._handleChildValueChange();
  3690. }
  3691. /** Opens the datepicker associated with the input. */
  3692. _openPopup() {
  3693. this._rangeInput._openDatepicker();
  3694. }
  3695. /** Gets the minimum date from the range input. */
  3696. _getMinDate() {
  3697. return this._rangeInput.min;
  3698. }
  3699. /** Gets the maximum date from the range input. */
  3700. _getMaxDate() {
  3701. return this._rangeInput.max;
  3702. }
  3703. /** Gets the date filter function from the range input. */
  3704. _getDateFilter() {
  3705. return this._rangeInput.dateFilter;
  3706. }
  3707. _parentDisabled() {
  3708. return this._rangeInput._groupDisabled;
  3709. }
  3710. _shouldHandleChangeEvent({ source }) {
  3711. return source !== this._rangeInput._startInput && source !== this._rangeInput._endInput;
  3712. }
  3713. _assignValueProgrammatically(value) {
  3714. super._assignValueProgrammatically(value);
  3715. const opposite = (this === this._rangeInput._startInput
  3716. ? this._rangeInput._endInput
  3717. : this._rangeInput._startInput);
  3718. opposite?._validatorOnChange();
  3719. }
  3720. /** return the ARIA accessible name of the input element */
  3721. _getAccessibleName() {
  3722. return _computeAriaAccessibleName(this._elementRef.nativeElement);
  3723. }
  3724. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangeInputPartBase, deps: [{ token: MAT_DATE_RANGE_INPUT_PARENT }, { token: i0.ElementRef }, { token: i1$1.ErrorStateMatcher }, { token: i0.Injector }, { token: i2$1.NgForm, optional: true }, { token: i2$1.FormGroupDirective, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3725. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDateRangeInputPartBase, usesInheritance: true, ngImport: i0 }); }
  3726. }
  3727. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangeInputPartBase, decorators: [{
  3728. type: Directive
  3729. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  3730. type: Inject,
  3731. args: [MAT_DATE_RANGE_INPUT_PARENT]
  3732. }] }, { type: i0.ElementRef }, { type: i1$1.ErrorStateMatcher }, { type: i0.Injector }, { type: i2$1.NgForm, decorators: [{
  3733. type: Optional
  3734. }] }, { type: i2$1.FormGroupDirective, decorators: [{
  3735. type: Optional
  3736. }] }, { type: i1$1.DateAdapter, decorators: [{
  3737. type: Optional
  3738. }] }, { type: undefined, decorators: [{
  3739. type: Optional
  3740. }, {
  3741. type: Inject,
  3742. args: [MAT_DATE_FORMATS]
  3743. }] }]; } });
  3744. const _MatDateRangeInputBase = mixinErrorState(MatDateRangeInputPartBase);
  3745. /** Input for entering the start date in a `mat-date-range-input`. */
  3746. class MatStartDate extends _MatDateRangeInputBase {
  3747. constructor(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup, dateAdapter, dateFormats) {
  3748. super(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup, dateAdapter, dateFormats);
  3749. /** Validator that checks that the start date isn't after the end date. */
  3750. this._startValidator = (control) => {
  3751. const start = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
  3752. const end = this._model ? this._model.selection.end : null;
  3753. return !start || !end || this._dateAdapter.compareDate(start, end) <= 0
  3754. ? null
  3755. : { 'matStartDateInvalid': { 'end': end, 'actual': start } };
  3756. };
  3757. this._validator = Validators.compose([...super._getValidators(), this._startValidator]);
  3758. }
  3759. _getValueFromModel(modelValue) {
  3760. return modelValue.start;
  3761. }
  3762. _shouldHandleChangeEvent(change) {
  3763. if (!super._shouldHandleChangeEvent(change)) {
  3764. return false;
  3765. }
  3766. else {
  3767. return !change.oldValue?.start
  3768. ? !!change.selection.start
  3769. : !change.selection.start ||
  3770. !!this._dateAdapter.compareDate(change.oldValue.start, change.selection.start);
  3771. }
  3772. }
  3773. _assignValueToModel(value) {
  3774. if (this._model) {
  3775. const range = new DateRange(value, this._model.selection.end);
  3776. this._model.updateSelection(range, this);
  3777. }
  3778. }
  3779. _formatValue(value) {
  3780. super._formatValue(value);
  3781. // Any time the input value is reformatted we need to tell the parent.
  3782. this._rangeInput._handleChildValueChange();
  3783. }
  3784. _onKeydown(event) {
  3785. const endInput = this._rangeInput._endInput;
  3786. const element = this._elementRef.nativeElement;
  3787. const isLtr = this._dir?.value !== 'rtl';
  3788. // If the user hits RIGHT (LTR) when at the end of the input (and no
  3789. // selection), move the cursor to the start of the end input.
  3790. if (((event.keyCode === RIGHT_ARROW && isLtr) || (event.keyCode === LEFT_ARROW && !isLtr)) &&
  3791. element.selectionStart === element.value.length &&
  3792. element.selectionEnd === element.value.length) {
  3793. event.preventDefault();
  3794. endInput._elementRef.nativeElement.setSelectionRange(0, 0);
  3795. endInput.focus();
  3796. }
  3797. else {
  3798. super._onKeydown(event);
  3799. }
  3800. }
  3801. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatStartDate, deps: [{ token: MAT_DATE_RANGE_INPUT_PARENT }, { token: i0.ElementRef }, { token: i1$1.ErrorStateMatcher }, { token: i0.Injector }, { token: i2$1.NgForm, optional: true }, { token: i2$1.FormGroupDirective, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3802. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatStartDate, selector: "input[matStartDate]", inputs: { errorStateMatcher: "errorStateMatcher" }, outputs: { dateChange: "dateChange", dateInput: "dateInput" }, host: { attributes: { "type": "text" }, listeners: { "input": "_onInput($event.target.value)", "change": "_onChange()", "keydown": "_onKeydown($event)", "blur": "_onBlur()" }, properties: { "disabled": "disabled", "attr.aria-haspopup": "_rangeInput.rangePicker ? \"dialog\" : null", "attr.aria-owns": "(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null", "attr.min": "_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null", "attr.max": "_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null" }, classAttribute: "mat-start-date mat-date-range-input-inner" }, providers: [
  3803. { provide: NG_VALUE_ACCESSOR, useExisting: MatStartDate, multi: true },
  3804. { provide: NG_VALIDATORS, useExisting: MatStartDate, multi: true },
  3805. ], usesInheritance: true, ngImport: i0 }); }
  3806. }
  3807. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatStartDate, decorators: [{
  3808. type: Directive,
  3809. args: [{
  3810. selector: 'input[matStartDate]',
  3811. host: {
  3812. 'class': 'mat-start-date mat-date-range-input-inner',
  3813. '[disabled]': 'disabled',
  3814. '(input)': '_onInput($event.target.value)',
  3815. '(change)': '_onChange()',
  3816. '(keydown)': '_onKeydown($event)',
  3817. '[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
  3818. '[attr.aria-owns]': '(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null',
  3819. '[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
  3820. '[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
  3821. '(blur)': '_onBlur()',
  3822. 'type': 'text',
  3823. },
  3824. providers: [
  3825. { provide: NG_VALUE_ACCESSOR, useExisting: MatStartDate, multi: true },
  3826. { provide: NG_VALIDATORS, useExisting: MatStartDate, multi: true },
  3827. ],
  3828. // These need to be specified explicitly, because some tooling doesn't
  3829. // seem to pick them up from the base class. See #20932.
  3830. outputs: ['dateChange', 'dateInput'],
  3831. inputs: ['errorStateMatcher'],
  3832. }]
  3833. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  3834. type: Inject,
  3835. args: [MAT_DATE_RANGE_INPUT_PARENT]
  3836. }] }, { type: i0.ElementRef }, { type: i1$1.ErrorStateMatcher }, { type: i0.Injector }, { type: i2$1.NgForm, decorators: [{
  3837. type: Optional
  3838. }] }, { type: i2$1.FormGroupDirective, decorators: [{
  3839. type: Optional
  3840. }] }, { type: i1$1.DateAdapter, decorators: [{
  3841. type: Optional
  3842. }] }, { type: undefined, decorators: [{
  3843. type: Optional
  3844. }, {
  3845. type: Inject,
  3846. args: [MAT_DATE_FORMATS]
  3847. }] }]; } });
  3848. /** Input for entering the end date in a `mat-date-range-input`. */
  3849. class MatEndDate extends _MatDateRangeInputBase {
  3850. constructor(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup, dateAdapter, dateFormats) {
  3851. super(rangeInput, elementRef, defaultErrorStateMatcher, injector, parentForm, parentFormGroup, dateAdapter, dateFormats);
  3852. /** Validator that checks that the end date isn't before the start date. */
  3853. this._endValidator = (control) => {
  3854. const end = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(control.value));
  3855. const start = this._model ? this._model.selection.start : null;
  3856. return !end || !start || this._dateAdapter.compareDate(end, start) >= 0
  3857. ? null
  3858. : { 'matEndDateInvalid': { 'start': start, 'actual': end } };
  3859. };
  3860. this._validator = Validators.compose([...super._getValidators(), this._endValidator]);
  3861. }
  3862. _getValueFromModel(modelValue) {
  3863. return modelValue.end;
  3864. }
  3865. _shouldHandleChangeEvent(change) {
  3866. if (!super._shouldHandleChangeEvent(change)) {
  3867. return false;
  3868. }
  3869. else {
  3870. return !change.oldValue?.end
  3871. ? !!change.selection.end
  3872. : !change.selection.end ||
  3873. !!this._dateAdapter.compareDate(change.oldValue.end, change.selection.end);
  3874. }
  3875. }
  3876. _assignValueToModel(value) {
  3877. if (this._model) {
  3878. const range = new DateRange(this._model.selection.start, value);
  3879. this._model.updateSelection(range, this);
  3880. }
  3881. }
  3882. _onKeydown(event) {
  3883. const startInput = this._rangeInput._startInput;
  3884. const element = this._elementRef.nativeElement;
  3885. const isLtr = this._dir?.value !== 'rtl';
  3886. // If the user is pressing backspace on an empty end input, move focus back to the start.
  3887. if (event.keyCode === BACKSPACE && !element.value) {
  3888. startInput.focus();
  3889. }
  3890. // If the user hits LEFT (LTR) when at the start of the input (and no
  3891. // selection), move the cursor to the end of the start input.
  3892. else if (((event.keyCode === LEFT_ARROW && isLtr) || (event.keyCode === RIGHT_ARROW && !isLtr)) &&
  3893. element.selectionStart === 0 &&
  3894. element.selectionEnd === 0) {
  3895. event.preventDefault();
  3896. const endPosition = startInput._elementRef.nativeElement.value.length;
  3897. startInput._elementRef.nativeElement.setSelectionRange(endPosition, endPosition);
  3898. startInput.focus();
  3899. }
  3900. else {
  3901. super._onKeydown(event);
  3902. }
  3903. }
  3904. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatEndDate, deps: [{ token: MAT_DATE_RANGE_INPUT_PARENT }, { token: i0.ElementRef }, { token: i1$1.ErrorStateMatcher }, { token: i0.Injector }, { token: i2$1.NgForm, optional: true }, { token: i2$1.FormGroupDirective, optional: true }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_DATE_FORMATS, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  3905. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatEndDate, selector: "input[matEndDate]", inputs: { errorStateMatcher: "errorStateMatcher" }, outputs: { dateChange: "dateChange", dateInput: "dateInput" }, host: { attributes: { "type": "text" }, listeners: { "input": "_onInput($event.target.value)", "change": "_onChange()", "keydown": "_onKeydown($event)", "blur": "_onBlur()" }, properties: { "disabled": "disabled", "attr.aria-haspopup": "_rangeInput.rangePicker ? \"dialog\" : null", "attr.aria-owns": "(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null", "attr.min": "_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null", "attr.max": "_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null" }, classAttribute: "mat-end-date mat-date-range-input-inner" }, providers: [
  3906. { provide: NG_VALUE_ACCESSOR, useExisting: MatEndDate, multi: true },
  3907. { provide: NG_VALIDATORS, useExisting: MatEndDate, multi: true },
  3908. ], usesInheritance: true, ngImport: i0 }); }
  3909. }
  3910. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatEndDate, decorators: [{
  3911. type: Directive,
  3912. args: [{
  3913. selector: 'input[matEndDate]',
  3914. host: {
  3915. 'class': 'mat-end-date mat-date-range-input-inner',
  3916. '[disabled]': 'disabled',
  3917. '(input)': '_onInput($event.target.value)',
  3918. '(change)': '_onChange()',
  3919. '(keydown)': '_onKeydown($event)',
  3920. '[attr.aria-haspopup]': '_rangeInput.rangePicker ? "dialog" : null',
  3921. '[attr.aria-owns]': '(_rangeInput.rangePicker?.opened && _rangeInput.rangePicker.id) || null',
  3922. '[attr.min]': '_getMinDate() ? _dateAdapter.toIso8601(_getMinDate()) : null',
  3923. '[attr.max]': '_getMaxDate() ? _dateAdapter.toIso8601(_getMaxDate()) : null',
  3924. '(blur)': '_onBlur()',
  3925. 'type': 'text',
  3926. },
  3927. providers: [
  3928. { provide: NG_VALUE_ACCESSOR, useExisting: MatEndDate, multi: true },
  3929. { provide: NG_VALIDATORS, useExisting: MatEndDate, multi: true },
  3930. ],
  3931. // These need to be specified explicitly, because some tooling doesn't
  3932. // seem to pick them up from the base class. See #20932.
  3933. outputs: ['dateChange', 'dateInput'],
  3934. inputs: ['errorStateMatcher'],
  3935. }]
  3936. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  3937. type: Inject,
  3938. args: [MAT_DATE_RANGE_INPUT_PARENT]
  3939. }] }, { type: i0.ElementRef }, { type: i1$1.ErrorStateMatcher }, { type: i0.Injector }, { type: i2$1.NgForm, decorators: [{
  3940. type: Optional
  3941. }] }, { type: i2$1.FormGroupDirective, decorators: [{
  3942. type: Optional
  3943. }] }, { type: i1$1.DateAdapter, decorators: [{
  3944. type: Optional
  3945. }] }, { type: undefined, decorators: [{
  3946. type: Optional
  3947. }, {
  3948. type: Inject,
  3949. args: [MAT_DATE_FORMATS]
  3950. }] }]; } });
  3951. let nextUniqueId = 0;
  3952. class MatDateRangeInput {
  3953. /** Current value of the range input. */
  3954. get value() {
  3955. return this._model ? this._model.selection : null;
  3956. }
  3957. /** Whether the control's label should float. */
  3958. get shouldLabelFloat() {
  3959. return this.focused || !this.empty;
  3960. }
  3961. /**
  3962. * Implemented as a part of `MatFormFieldControl`.
  3963. * Set the placeholder attribute on `matStartDate` and `matEndDate`.
  3964. * @docs-private
  3965. */
  3966. get placeholder() {
  3967. const start = this._startInput?._getPlaceholder() || '';
  3968. const end = this._endInput?._getPlaceholder() || '';
  3969. return start || end ? `${start} ${this.separator} ${end}` : '';
  3970. }
  3971. /** The range picker that this input is associated with. */
  3972. get rangePicker() {
  3973. return this._rangePicker;
  3974. }
  3975. set rangePicker(rangePicker) {
  3976. if (rangePicker) {
  3977. this._model = rangePicker.registerInput(this);
  3978. this._rangePicker = rangePicker;
  3979. this._closedSubscription.unsubscribe();
  3980. this._closedSubscription = rangePicker.closedStream.subscribe(() => {
  3981. this._startInput?._onTouched();
  3982. this._endInput?._onTouched();
  3983. });
  3984. this._registerModel(this._model);
  3985. }
  3986. }
  3987. /** Whether the input is required. */
  3988. get required() {
  3989. return (this._required ??
  3990. (this._isTargetRequired(this) ||
  3991. this._isTargetRequired(this._startInput) ||
  3992. this._isTargetRequired(this._endInput)) ??
  3993. false);
  3994. }
  3995. set required(value) {
  3996. this._required = coerceBooleanProperty(value);
  3997. }
  3998. /** Function that can be used to filter out dates within the date range picker. */
  3999. get dateFilter() {
  4000. return this._dateFilter;
  4001. }
  4002. set dateFilter(value) {
  4003. const start = this._startInput;
  4004. const end = this._endInput;
  4005. const wasMatchingStart = start && start._matchesFilter(start.value);
  4006. const wasMatchingEnd = end && end._matchesFilter(start.value);
  4007. this._dateFilter = value;
  4008. if (start && start._matchesFilter(start.value) !== wasMatchingStart) {
  4009. start._validatorOnChange();
  4010. }
  4011. if (end && end._matchesFilter(end.value) !== wasMatchingEnd) {
  4012. end._validatorOnChange();
  4013. }
  4014. }
  4015. /** The minimum valid date. */
  4016. get min() {
  4017. return this._min;
  4018. }
  4019. set min(value) {
  4020. const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  4021. if (!this._dateAdapter.sameDate(validValue, this._min)) {
  4022. this._min = validValue;
  4023. this._revalidate();
  4024. }
  4025. }
  4026. /** The maximum valid date. */
  4027. get max() {
  4028. return this._max;
  4029. }
  4030. set max(value) {
  4031. const validValue = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
  4032. if (!this._dateAdapter.sameDate(validValue, this._max)) {
  4033. this._max = validValue;
  4034. this._revalidate();
  4035. }
  4036. }
  4037. /** Whether the input is disabled. */
  4038. get disabled() {
  4039. return this._startInput && this._endInput
  4040. ? this._startInput.disabled && this._endInput.disabled
  4041. : this._groupDisabled;
  4042. }
  4043. set disabled(value) {
  4044. const newValue = coerceBooleanProperty(value);
  4045. if (newValue !== this._groupDisabled) {
  4046. this._groupDisabled = newValue;
  4047. this.stateChanges.next(undefined);
  4048. }
  4049. }
  4050. /** Whether the input is in an error state. */
  4051. get errorState() {
  4052. if (this._startInput && this._endInput) {
  4053. return this._startInput.errorState || this._endInput.errorState;
  4054. }
  4055. return false;
  4056. }
  4057. /** Whether the datepicker input is empty. */
  4058. get empty() {
  4059. const startEmpty = this._startInput ? this._startInput.isEmpty() : false;
  4060. const endEmpty = this._endInput ? this._endInput.isEmpty() : false;
  4061. return startEmpty && endEmpty;
  4062. }
  4063. constructor(_changeDetectorRef, _elementRef, control, _dateAdapter, _formField) {
  4064. this._changeDetectorRef = _changeDetectorRef;
  4065. this._elementRef = _elementRef;
  4066. this._dateAdapter = _dateAdapter;
  4067. this._formField = _formField;
  4068. this._closedSubscription = Subscription.EMPTY;
  4069. /** Unique ID for the group. */
  4070. this.id = `mat-date-range-input-${nextUniqueId++}`;
  4071. /** Whether the control is focused. */
  4072. this.focused = false;
  4073. /** Name of the form control. */
  4074. this.controlType = 'mat-date-range-input';
  4075. this._groupDisabled = false;
  4076. /** Value for the `aria-describedby` attribute of the inputs. */
  4077. this._ariaDescribedBy = null;
  4078. /** Separator text to be shown between the inputs. */
  4079. this.separator = '–';
  4080. /** Start of the comparison range that should be shown in the calendar. */
  4081. this.comparisonStart = null;
  4082. /** End of the comparison range that should be shown in the calendar. */
  4083. this.comparisonEnd = null;
  4084. /** Emits when the input's state has changed. */
  4085. this.stateChanges = new Subject();
  4086. if (!_dateAdapter && (typeof ngDevMode === 'undefined' || ngDevMode)) {
  4087. throw createMissingDateImplError('DateAdapter');
  4088. }
  4089. // The datepicker module can be used both with MDC and non-MDC form fields. We have
  4090. // to conditionally add the MDC input class so that the range picker looks correctly.
  4091. if (_formField?._elementRef.nativeElement.classList.contains('mat-mdc-form-field')) {
  4092. _elementRef.nativeElement.classList.add('mat-mdc-input-element', 'mat-mdc-form-field-input-control', 'mdc-text-field__input');
  4093. }
  4094. // TODO(crisbeto): remove `as any` after #18206 lands.
  4095. this.ngControl = control;
  4096. }
  4097. /**
  4098. * Implemented as a part of `MatFormFieldControl`.
  4099. * @docs-private
  4100. */
  4101. setDescribedByIds(ids) {
  4102. this._ariaDescribedBy = ids.length ? ids.join(' ') : null;
  4103. }
  4104. /**
  4105. * Implemented as a part of `MatFormFieldControl`.
  4106. * @docs-private
  4107. */
  4108. onContainerClick() {
  4109. if (!this.focused && !this.disabled) {
  4110. if (!this._model || !this._model.selection.start) {
  4111. this._startInput.focus();
  4112. }
  4113. else {
  4114. this._endInput.focus();
  4115. }
  4116. }
  4117. }
  4118. ngAfterContentInit() {
  4119. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  4120. if (!this._startInput) {
  4121. throw Error('mat-date-range-input must contain a matStartDate input');
  4122. }
  4123. if (!this._endInput) {
  4124. throw Error('mat-date-range-input must contain a matEndDate input');
  4125. }
  4126. }
  4127. if (this._model) {
  4128. this._registerModel(this._model);
  4129. }
  4130. // We don't need to unsubscribe from this, because we
  4131. // know that the input streams will be completed on destroy.
  4132. merge(this._startInput.stateChanges, this._endInput.stateChanges).subscribe(() => {
  4133. this.stateChanges.next(undefined);
  4134. });
  4135. }
  4136. ngOnChanges(changes) {
  4137. if (dateInputsHaveChanged(changes, this._dateAdapter)) {
  4138. this.stateChanges.next(undefined);
  4139. }
  4140. }
  4141. ngOnDestroy() {
  4142. this._closedSubscription.unsubscribe();
  4143. this.stateChanges.complete();
  4144. }
  4145. /** Gets the date at which the calendar should start. */
  4146. getStartValue() {
  4147. return this.value ? this.value.start : null;
  4148. }
  4149. /** Gets the input's theme palette. */
  4150. getThemePalette() {
  4151. return this._formField ? this._formField.color : undefined;
  4152. }
  4153. /** Gets the element to which the calendar overlay should be attached. */
  4154. getConnectedOverlayOrigin() {
  4155. return this._formField ? this._formField.getConnectedOverlayOrigin() : this._elementRef;
  4156. }
  4157. /** Gets the ID of an element that should be used a description for the calendar overlay. */
  4158. getOverlayLabelId() {
  4159. return this._formField ? this._formField.getLabelId() : null;
  4160. }
  4161. /** Gets the value that is used to mirror the state input. */
  4162. _getInputMirrorValue(part) {
  4163. const input = part === 'start' ? this._startInput : this._endInput;
  4164. return input ? input.getMirrorValue() : '';
  4165. }
  4166. /** Whether the input placeholders should be hidden. */
  4167. _shouldHidePlaceholders() {
  4168. return this._startInput ? !this._startInput.isEmpty() : false;
  4169. }
  4170. /** Handles the value in one of the child inputs changing. */
  4171. _handleChildValueChange() {
  4172. this.stateChanges.next(undefined);
  4173. this._changeDetectorRef.markForCheck();
  4174. }
  4175. /** Opens the date range picker associated with the input. */
  4176. _openDatepicker() {
  4177. if (this._rangePicker) {
  4178. this._rangePicker.open();
  4179. }
  4180. }
  4181. /** Whether the separate text should be hidden. */
  4182. _shouldHideSeparator() {
  4183. return ((!this._formField ||
  4184. (this._formField.getLabelId() && !this._formField._shouldLabelFloat())) &&
  4185. this.empty);
  4186. }
  4187. /** Gets the value for the `aria-labelledby` attribute of the inputs. */
  4188. _getAriaLabelledby() {
  4189. const formField = this._formField;
  4190. return formField && formField._hasFloatingLabel() ? formField._labelId : null;
  4191. }
  4192. _getStartDateAccessibleName() {
  4193. return this._startInput._getAccessibleName();
  4194. }
  4195. _getEndDateAccessibleName() {
  4196. return this._endInput._getAccessibleName();
  4197. }
  4198. /** Updates the focused state of the range input. */
  4199. _updateFocus(origin) {
  4200. this.focused = origin !== null;
  4201. this.stateChanges.next();
  4202. }
  4203. /** Re-runs the validators on the start/end inputs. */
  4204. _revalidate() {
  4205. if (this._startInput) {
  4206. this._startInput._validatorOnChange();
  4207. }
  4208. if (this._endInput) {
  4209. this._endInput._validatorOnChange();
  4210. }
  4211. }
  4212. /** Registers the current date selection model with the start/end inputs. */
  4213. _registerModel(model) {
  4214. if (this._startInput) {
  4215. this._startInput._registerModel(model);
  4216. }
  4217. if (this._endInput) {
  4218. this._endInput._registerModel(model);
  4219. }
  4220. }
  4221. /** Checks whether a specific range input directive is required. */
  4222. _isTargetRequired(target) {
  4223. return target?.ngControl?.control?.hasValidator(Validators.required);
  4224. }
  4225. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangeInput, deps: [{ token: i0.ChangeDetectorRef }, { token: i0.ElementRef }, { token: i2$1.ControlContainer, optional: true, self: true }, { token: i1$1.DateAdapter, optional: true }, { token: MAT_FORM_FIELD, optional: true }], target: i0.ɵɵFactoryTarget.Component }); }
  4226. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDateRangeInput, selector: "mat-date-range-input", inputs: { rangePicker: "rangePicker", required: "required", dateFilter: "dateFilter", min: "min", max: "max", disabled: "disabled", separator: "separator", comparisonStart: "comparisonStart", comparisonEnd: "comparisonEnd" }, host: { attributes: { "role": "group" }, properties: { "class.mat-date-range-input-hide-placeholders": "_shouldHidePlaceholders()", "class.mat-date-range-input-required": "required", "attr.id": "id", "attr.aria-labelledby": "_getAriaLabelledby()", "attr.aria-describedby": "_ariaDescribedBy", "attr.data-mat-calendar": "rangePicker ? rangePicker.id : null" }, classAttribute: "mat-date-range-input" }, providers: [
  4227. { provide: MatFormFieldControl, useExisting: MatDateRangeInput },
  4228. { provide: MAT_DATE_RANGE_INPUT_PARENT, useExisting: MatDateRangeInput },
  4229. ], queries: [{ propertyName: "_startInput", first: true, predicate: MatStartDate, descendants: true }, { propertyName: "_endInput", first: true, predicate: MatEndDate, descendants: true }], exportAs: ["matDateRangeInput"], usesOnChanges: true, ngImport: i0, template: "<div\n class=\"mat-date-range-input-container\"\n cdkMonitorSubtreeFocus\n (cdkFocusChange)=\"_updateFocus($event)\">\n <div class=\"mat-date-range-input-wrapper\">\n <ng-content select=\"input[matStartDate]\"></ng-content>\n <span\n class=\"mat-date-range-input-mirror\"\n aria-hidden=\"true\">{{_getInputMirrorValue('start')}}</span>\n </div>\n\n <span\n class=\"mat-date-range-input-separator\"\n [class.mat-date-range-input-separator-hidden]=\"_shouldHideSeparator()\">{{separator}}</span>\n\n <div class=\"mat-date-range-input-wrapper mat-date-range-input-end-wrapper\">\n <ng-content select=\"input[matEndDate]\"></ng-content>\n <span\n class=\"mat-date-range-input-mirror\"\n aria-hidden=\"true\">{{_getInputMirrorValue('end')}}</span>\n </div>\n</div>\n\n", styles: [".mat-date-range-input{display:block;width:100%}.mat-date-range-input-container{display:flex;align-items:center}.mat-date-range-input-separator{transition:opacity 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1);margin:0 4px}._mat-animation-noopable .mat-date-range-input-separator{transition:none}.mat-date-range-input-separator-hidden{-webkit-user-select:none;user-select:none;opacity:0;transition:none}.mat-date-range-input-wrapper{position:relative;overflow:hidden;max-width:calc(50% - 4px)}.mat-date-range-input-end-wrapper{flex-grow:1}.mat-date-range-input-inner{position:absolute;top:0;left:0;font:inherit;background:rgba(0,0,0,0);color:currentColor;border:none;outline:none;padding:0;margin:0;vertical-align:bottom;text-align:inherit;-webkit-appearance:none;width:100%;height:100%}.mat-date-range-input-inner:-moz-ui-invalid{box-shadow:none}.mat-date-range-input-inner::placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner::-moz-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner::-webkit-input-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner:-ms-input-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-date-range-input-inner::placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner::-moz-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-moz-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::-moz-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner::-webkit-input-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-webkit-input-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::-webkit-input-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner:-ms-input-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner:-ms-input-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner:-ms-input-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner:-ms-input-placeholder{opacity:0}._mat-animation-noopable .mat-date-range-input-inner::placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner::-moz-placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner::-webkit-input-placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner:-ms-input-placeholder{transition:none}.mat-date-range-input-mirror{-webkit-user-select:none;user-select:none;visibility:hidden;white-space:nowrap;display:inline-block;min-width:2px}.mat-mdc-form-field-type-mat-date-range-input .mat-mdc-form-field-infix{width:200px}"], dependencies: [{ kind: "directive", type: i5.CdkMonitorFocus, selector: "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", outputs: ["cdkFocusChange"], exportAs: ["cdkMonitorFocus"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  4230. }
  4231. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangeInput, decorators: [{
  4232. type: Component,
  4233. args: [{ selector: 'mat-date-range-input', exportAs: 'matDateRangeInput', host: {
  4234. 'class': 'mat-date-range-input',
  4235. '[class.mat-date-range-input-hide-placeholders]': '_shouldHidePlaceholders()',
  4236. '[class.mat-date-range-input-required]': 'required',
  4237. '[attr.id]': 'id',
  4238. 'role': 'group',
  4239. '[attr.aria-labelledby]': '_getAriaLabelledby()',
  4240. '[attr.aria-describedby]': '_ariaDescribedBy',
  4241. // Used by the test harness to tie this input to its calendar. We can't depend on
  4242. // `aria-owns` for this, because it's only defined while the calendar is open.
  4243. '[attr.data-mat-calendar]': 'rangePicker ? rangePicker.id : null',
  4244. }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [
  4245. { provide: MatFormFieldControl, useExisting: MatDateRangeInput },
  4246. { provide: MAT_DATE_RANGE_INPUT_PARENT, useExisting: MatDateRangeInput },
  4247. ], template: "<div\n class=\"mat-date-range-input-container\"\n cdkMonitorSubtreeFocus\n (cdkFocusChange)=\"_updateFocus($event)\">\n <div class=\"mat-date-range-input-wrapper\">\n <ng-content select=\"input[matStartDate]\"></ng-content>\n <span\n class=\"mat-date-range-input-mirror\"\n aria-hidden=\"true\">{{_getInputMirrorValue('start')}}</span>\n </div>\n\n <span\n class=\"mat-date-range-input-separator\"\n [class.mat-date-range-input-separator-hidden]=\"_shouldHideSeparator()\">{{separator}}</span>\n\n <div class=\"mat-date-range-input-wrapper mat-date-range-input-end-wrapper\">\n <ng-content select=\"input[matEndDate]\"></ng-content>\n <span\n class=\"mat-date-range-input-mirror\"\n aria-hidden=\"true\">{{_getInputMirrorValue('end')}}</span>\n </div>\n</div>\n\n", styles: [".mat-date-range-input{display:block;width:100%}.mat-date-range-input-container{display:flex;align-items:center}.mat-date-range-input-separator{transition:opacity 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1);margin:0 4px}._mat-animation-noopable .mat-date-range-input-separator{transition:none}.mat-date-range-input-separator-hidden{-webkit-user-select:none;user-select:none;opacity:0;transition:none}.mat-date-range-input-wrapper{position:relative;overflow:hidden;max-width:calc(50% - 4px)}.mat-date-range-input-end-wrapper{flex-grow:1}.mat-date-range-input-inner{position:absolute;top:0;left:0;font:inherit;background:rgba(0,0,0,0);color:currentColor;border:none;outline:none;padding:0;margin:0;vertical-align:bottom;text-align:inherit;-webkit-appearance:none;width:100%;height:100%}.mat-date-range-input-inner:-moz-ui-invalid{box-shadow:none}.mat-date-range-input-inner::placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner::-moz-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner::-webkit-input-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-date-range-input-inner:-ms-input-placeholder{transition:color 400ms 133.3333333333ms cubic-bezier(0.25, 0.8, 0.25, 1)}.mat-form-field-hide-placeholder .mat-date-range-input-inner::placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner::-moz-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-moz-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::-moz-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-moz-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner::-webkit-input-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-webkit-input-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner::-webkit-input-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner::-webkit-input-placeholder{opacity:0}.mat-form-field-hide-placeholder .mat-date-range-input-inner:-ms-input-placeholder,.mat-date-range-input-hide-placeholders .mat-date-range-input-inner:-ms-input-placeholder{-webkit-user-select:none;user-select:none;color:rgba(0,0,0,0) !important;-webkit-text-fill-color:rgba(0,0,0,0);transition:none}.cdk-high-contrast-active .mat-form-field-hide-placeholder .mat-date-range-input-inner:-ms-input-placeholder,.cdk-high-contrast-active .mat-date-range-input-hide-placeholders .mat-date-range-input-inner:-ms-input-placeholder{opacity:0}._mat-animation-noopable .mat-date-range-input-inner::placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner::-moz-placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner::-webkit-input-placeholder{transition:none}._mat-animation-noopable .mat-date-range-input-inner:-ms-input-placeholder{transition:none}.mat-date-range-input-mirror{-webkit-user-select:none;user-select:none;visibility:hidden;white-space:nowrap;display:inline-block;min-width:2px}.mat-mdc-form-field-type-mat-date-range-input .mat-mdc-form-field-infix{width:200px}"] }]
  4248. }], ctorParameters: function () { return [{ type: i0.ChangeDetectorRef }, { type: i0.ElementRef }, { type: i2$1.ControlContainer, decorators: [{
  4249. type: Optional
  4250. }, {
  4251. type: Self
  4252. }] }, { type: i1$1.DateAdapter, decorators: [{
  4253. type: Optional
  4254. }] }, { type: undefined, decorators: [{
  4255. type: Optional
  4256. }, {
  4257. type: Inject,
  4258. args: [MAT_FORM_FIELD]
  4259. }] }]; }, propDecorators: { rangePicker: [{
  4260. type: Input
  4261. }], required: [{
  4262. type: Input
  4263. }], dateFilter: [{
  4264. type: Input
  4265. }], min: [{
  4266. type: Input
  4267. }], max: [{
  4268. type: Input
  4269. }], disabled: [{
  4270. type: Input
  4271. }], separator: [{
  4272. type: Input
  4273. }], comparisonStart: [{
  4274. type: Input
  4275. }], comparisonEnd: [{
  4276. type: Input
  4277. }], _startInput: [{
  4278. type: ContentChild,
  4279. args: [MatStartDate]
  4280. }], _endInput: [{
  4281. type: ContentChild,
  4282. args: [MatEndDate]
  4283. }] } });
  4284. // TODO(mmalerba): We use a component instead of a directive here so the user can use implicit
  4285. // template reference variables (e.g. #d vs #d="matDateRangePicker"). We can change this to a
  4286. // directive if angular adds support for `exportAs: '$implicit'` on directives.
  4287. /** Component responsible for managing the date range picker popup/dialog. */
  4288. class MatDateRangePicker extends MatDatepickerBase {
  4289. _forwardContentValues(instance) {
  4290. super._forwardContentValues(instance);
  4291. const input = this.datepickerInput;
  4292. if (input) {
  4293. instance.comparisonStart = input.comparisonStart;
  4294. instance.comparisonEnd = input.comparisonEnd;
  4295. instance.startDateAccessibleName = input._getStartDateAccessibleName();
  4296. instance.endDateAccessibleName = input._getEndDateAccessibleName();
  4297. }
  4298. }
  4299. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangePicker, deps: null, target: i0.ɵɵFactoryTarget.Component }); }
  4300. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDateRangePicker, selector: "mat-date-range-picker", providers: [
  4301. MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER,
  4302. MAT_CALENDAR_RANGE_STRATEGY_PROVIDER,
  4303. { provide: MatDatepickerBase, useExisting: MatDateRangePicker },
  4304. ], exportAs: ["matDateRangePicker"], usesInheritance: true, ngImport: i0, template: '', isInline: true, changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  4305. }
  4306. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDateRangePicker, decorators: [{
  4307. type: Component,
  4308. args: [{
  4309. selector: 'mat-date-range-picker',
  4310. template: '',
  4311. exportAs: 'matDateRangePicker',
  4312. changeDetection: ChangeDetectionStrategy.OnPush,
  4313. encapsulation: ViewEncapsulation.None,
  4314. providers: [
  4315. MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER,
  4316. MAT_CALENDAR_RANGE_STRATEGY_PROVIDER,
  4317. { provide: MatDatepickerBase, useExisting: MatDateRangePicker },
  4318. ],
  4319. }]
  4320. }] });
  4321. /** Button that will close the datepicker and assign the current selection to the data model. */
  4322. class MatDatepickerApply {
  4323. constructor(_datepicker) {
  4324. this._datepicker = _datepicker;
  4325. }
  4326. _applySelection() {
  4327. this._datepicker._applyPendingSelection();
  4328. this._datepicker.close();
  4329. }
  4330. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerApply, deps: [{ token: MatDatepickerBase }], target: i0.ɵɵFactoryTarget.Directive }); }
  4331. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerApply, selector: "[matDatepickerApply], [matDateRangePickerApply]", host: { listeners: { "click": "_applySelection()" } }, ngImport: i0 }); }
  4332. }
  4333. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerApply, decorators: [{
  4334. type: Directive,
  4335. args: [{
  4336. selector: '[matDatepickerApply], [matDateRangePickerApply]',
  4337. host: { '(click)': '_applySelection()' },
  4338. }]
  4339. }], ctorParameters: function () { return [{ type: MatDatepickerBase }]; } });
  4340. /** Button that will close the datepicker and discard the current selection. */
  4341. class MatDatepickerCancel {
  4342. constructor(_datepicker) {
  4343. this._datepicker = _datepicker;
  4344. }
  4345. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerCancel, deps: [{ token: MatDatepickerBase }], target: i0.ɵɵFactoryTarget.Directive }); }
  4346. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerCancel, selector: "[matDatepickerCancel], [matDateRangePickerCancel]", host: { listeners: { "click": "_datepicker.close()" } }, ngImport: i0 }); }
  4347. }
  4348. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerCancel, decorators: [{
  4349. type: Directive,
  4350. args: [{
  4351. selector: '[matDatepickerCancel], [matDateRangePickerCancel]',
  4352. host: { '(click)': '_datepicker.close()' },
  4353. }]
  4354. }], ctorParameters: function () { return [{ type: MatDatepickerBase }]; } });
  4355. /**
  4356. * Container that can be used to project a row of action buttons
  4357. * to the bottom of a datepicker or date range picker.
  4358. */
  4359. class MatDatepickerActions {
  4360. constructor(_datepicker, _viewContainerRef) {
  4361. this._datepicker = _datepicker;
  4362. this._viewContainerRef = _viewContainerRef;
  4363. }
  4364. ngAfterViewInit() {
  4365. this._portal = new TemplatePortal(this._template, this._viewContainerRef);
  4366. this._datepicker.registerActions(this._portal);
  4367. }
  4368. ngOnDestroy() {
  4369. this._datepicker.removeActions(this._portal);
  4370. // Needs to be null checked since we initialize it in `ngAfterViewInit`.
  4371. if (this._portal && this._portal.isAttached) {
  4372. this._portal?.detach();
  4373. }
  4374. }
  4375. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerActions, deps: [{ token: MatDatepickerBase }, { token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Component }); }
  4376. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.0", type: MatDatepickerActions, selector: "mat-datepicker-actions, mat-date-range-picker-actions", viewQueries: [{ propertyName: "_template", first: true, predicate: TemplateRef, descendants: true }], ngImport: i0, template: `
  4377. <ng-template>
  4378. <div class="mat-datepicker-actions">
  4379. <ng-content></ng-content>
  4380. </div>
  4381. </ng-template>
  4382. `, isInline: true, styles: [".mat-datepicker-actions{display:flex;justify-content:flex-end;align-items:center;padding:0 8px 8px 8px}.mat-datepicker-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-datepicker-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); }
  4383. }
  4384. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerActions, decorators: [{
  4385. type: Component,
  4386. args: [{ selector: 'mat-datepicker-actions, mat-date-range-picker-actions', template: `
  4387. <ng-template>
  4388. <div class="mat-datepicker-actions">
  4389. <ng-content></ng-content>
  4390. </div>
  4391. </ng-template>
  4392. `, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, styles: [".mat-datepicker-actions{display:flex;justify-content:flex-end;align-items:center;padding:0 8px 8px 8px}.mat-datepicker-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:8px}[dir=rtl] .mat-datepicker-actions .mat-mdc-button-base+.mat-mdc-button-base{margin-left:0;margin-right:8px}"] }]
  4393. }], ctorParameters: function () { return [{ type: MatDatepickerBase }, { type: i0.ViewContainerRef }]; }, propDecorators: { _template: [{
  4394. type: ViewChild,
  4395. args: [TemplateRef]
  4396. }] } });
  4397. class MatDatepickerModule {
  4398. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
  4399. static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerModule, declarations: [MatCalendar,
  4400. MatCalendarBody,
  4401. MatDatepicker,
  4402. MatDatepickerContent,
  4403. MatDatepickerInput,
  4404. MatDatepickerToggle,
  4405. MatDatepickerToggleIcon,
  4406. MatMonthView,
  4407. MatYearView,
  4408. MatMultiYearView,
  4409. MatCalendarHeader,
  4410. MatDateRangeInput,
  4411. MatStartDate,
  4412. MatEndDate,
  4413. MatDateRangePicker,
  4414. MatDatepickerActions,
  4415. MatDatepickerCancel,
  4416. MatDatepickerApply], imports: [CommonModule,
  4417. MatButtonModule,
  4418. OverlayModule,
  4419. A11yModule,
  4420. PortalModule,
  4421. MatCommonModule], exports: [CdkScrollableModule,
  4422. MatCalendar,
  4423. MatCalendarBody,
  4424. MatDatepicker,
  4425. MatDatepickerContent,
  4426. MatDatepickerInput,
  4427. MatDatepickerToggle,
  4428. MatDatepickerToggleIcon,
  4429. MatMonthView,
  4430. MatYearView,
  4431. MatMultiYearView,
  4432. MatCalendarHeader,
  4433. MatDateRangeInput,
  4434. MatStartDate,
  4435. MatEndDate,
  4436. MatDateRangePicker,
  4437. MatDatepickerActions,
  4438. MatDatepickerCancel,
  4439. MatDatepickerApply] }); }
  4440. static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerModule, providers: [MatDatepickerIntl, MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER], imports: [CommonModule,
  4441. MatButtonModule,
  4442. OverlayModule,
  4443. A11yModule,
  4444. PortalModule,
  4445. MatCommonModule, CdkScrollableModule] }); }
  4446. }
  4447. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: MatDatepickerModule, decorators: [{
  4448. type: NgModule,
  4449. args: [{
  4450. imports: [
  4451. CommonModule,
  4452. MatButtonModule,
  4453. OverlayModule,
  4454. A11yModule,
  4455. PortalModule,
  4456. MatCommonModule,
  4457. ],
  4458. exports: [
  4459. CdkScrollableModule,
  4460. MatCalendar,
  4461. MatCalendarBody,
  4462. MatDatepicker,
  4463. MatDatepickerContent,
  4464. MatDatepickerInput,
  4465. MatDatepickerToggle,
  4466. MatDatepickerToggleIcon,
  4467. MatMonthView,
  4468. MatYearView,
  4469. MatMultiYearView,
  4470. MatCalendarHeader,
  4471. MatDateRangeInput,
  4472. MatStartDate,
  4473. MatEndDate,
  4474. MatDateRangePicker,
  4475. MatDatepickerActions,
  4476. MatDatepickerCancel,
  4477. MatDatepickerApply,
  4478. ],
  4479. declarations: [
  4480. MatCalendar,
  4481. MatCalendarBody,
  4482. MatDatepicker,
  4483. MatDatepickerContent,
  4484. MatDatepickerInput,
  4485. MatDatepickerToggle,
  4486. MatDatepickerToggleIcon,
  4487. MatMonthView,
  4488. MatYearView,
  4489. MatMultiYearView,
  4490. MatCalendarHeader,
  4491. MatDateRangeInput,
  4492. MatStartDate,
  4493. MatEndDate,
  4494. MatDateRangePicker,
  4495. MatDatepickerActions,
  4496. MatDatepickerCancel,
  4497. MatDatepickerApply,
  4498. ],
  4499. providers: [MatDatepickerIntl, MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER],
  4500. }]
  4501. }] });
  4502. /**
  4503. * Generated bundle index. Do not edit.
  4504. */
  4505. export { DateRange, DefaultMatCalendarRangeStrategy, MAT_DATEPICKER_SCROLL_STRATEGY, MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY, MAT_DATEPICKER_SCROLL_STRATEGY_FACTORY_PROVIDER, MAT_DATEPICKER_VALIDATORS, MAT_DATEPICKER_VALUE_ACCESSOR, MAT_DATE_RANGE_SELECTION_STRATEGY, MAT_RANGE_DATE_SELECTION_MODEL_FACTORY, MAT_RANGE_DATE_SELECTION_MODEL_PROVIDER, MAT_SINGLE_DATE_SELECTION_MODEL_FACTORY, MAT_SINGLE_DATE_SELECTION_MODEL_PROVIDER, MatCalendar, MatCalendarBody, MatCalendarCell, MatCalendarHeader, MatDateRangeInput, MatDateRangePicker, MatDateSelectionModel, MatDatepicker, MatDatepickerActions, MatDatepickerApply, MatDatepickerCancel, MatDatepickerContent, MatDatepickerInput, MatDatepickerInputEvent, MatDatepickerIntl, MatDatepickerModule, MatDatepickerToggle, MatDatepickerToggleIcon, MatEndDate, MatMonthView, MatMultiYearView, MatRangeDateSelectionModel, MatSingleDateSelectionModel, MatStartDate, MatYearView, matDatepickerAnimations, yearsPerPage, yearsPerRow };
  4506. //# sourceMappingURL=datepicker.mjs.map