overlay.js 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844
  1. /**
  2. * @license
  3. * Copyright Google LLC All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. import { coerceCssPixelValue, coerceArray, coerceBooleanProperty } from '@angular/cdk/coercion';
  9. import { ScrollDispatcher, ViewportRuler, ScrollingModule, VIEWPORT_RULER_PROVIDER } from '@angular/cdk/scrolling';
  10. export { ViewportRuler, VIEWPORT_RULER_PROVIDER, CdkScrollable, ScrollDispatcher } from '@angular/cdk/scrolling';
  11. import { DOCUMENT, Location } from '@angular/common';
  12. import { Inject, Injectable, NgZone, Optional, NgModule, SkipSelf, ApplicationRef, ComponentFactoryResolver, Injector, ElementRef, Directive, EventEmitter, InjectionToken, Input, Output, TemplateRef, ViewContainerRef, ɵɵdefineInjectable, ɵɵinject } from '@angular/core';
  13. import { Observable, Subject, merge, Subscription } from 'rxjs';
  14. import { take, takeUntil } from 'rxjs/operators';
  15. import { Platform } from '@angular/cdk/platform';
  16. import { Directionality, BidiModule } from '@angular/cdk/bidi';
  17. import { DomPortalOutlet, TemplatePortal, PortalModule } from '@angular/cdk/portal';
  18. import { ESCAPE, hasModifierKey } from '@angular/cdk/keycodes';
  19. /**
  20. * @fileoverview added by tsickle
  21. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  22. */
  23. /**
  24. * Strategy that will prevent the user from scrolling while the overlay is visible.
  25. */
  26. class BlockScrollStrategy {
  27. /**
  28. * @param {?} _viewportRuler
  29. * @param {?} document
  30. */
  31. constructor(_viewportRuler, document) {
  32. this._viewportRuler = _viewportRuler;
  33. this._previousHTMLStyles = { top: '', left: '' };
  34. this._isEnabled = false;
  35. this._document = document;
  36. }
  37. /**
  38. * Attaches this scroll strategy to an overlay.
  39. * @return {?}
  40. */
  41. attach() { }
  42. /**
  43. * Blocks page-level scroll while the attached overlay is open.
  44. * @return {?}
  45. */
  46. enable() {
  47. if (this._canBeEnabled()) {
  48. /** @type {?} */
  49. const root = (/** @type {?} */ (this._document.documentElement));
  50. this._previousScrollPosition = this._viewportRuler.getViewportScrollPosition();
  51. // Cache the previous inline styles in case the user had set them.
  52. this._previousHTMLStyles.left = root.style.left || '';
  53. this._previousHTMLStyles.top = root.style.top || '';
  54. // Note: we're using the `html` node, instead of the `body`, because the `body` may
  55. // have the user agent margin, whereas the `html` is guaranteed not to have one.
  56. root.style.left = coerceCssPixelValue(-this._previousScrollPosition.left);
  57. root.style.top = coerceCssPixelValue(-this._previousScrollPosition.top);
  58. root.classList.add('cdk-global-scrollblock');
  59. this._isEnabled = true;
  60. }
  61. }
  62. /**
  63. * Unblocks page-level scroll while the attached overlay is open.
  64. * @return {?}
  65. */
  66. disable() {
  67. if (this._isEnabled) {
  68. /** @type {?} */
  69. const html = (/** @type {?} */ (this._document.documentElement));
  70. /** @type {?} */
  71. const body = (/** @type {?} */ (this._document.body));
  72. /** @type {?} */
  73. const htmlStyle = (/** @type {?} */ (html.style));
  74. /** @type {?} */
  75. const bodyStyle = (/** @type {?} */ (body.style));
  76. /** @type {?} */
  77. const previousHtmlScrollBehavior = htmlStyle.scrollBehavior || '';
  78. /** @type {?} */
  79. const previousBodyScrollBehavior = bodyStyle.scrollBehavior || '';
  80. this._isEnabled = false;
  81. htmlStyle.left = this._previousHTMLStyles.left;
  82. htmlStyle.top = this._previousHTMLStyles.top;
  83. html.classList.remove('cdk-global-scrollblock');
  84. // Disable user-defined smooth scrolling temporarily while we restore the scroll position.
  85. // See https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
  86. htmlStyle.scrollBehavior = bodyStyle.scrollBehavior = 'auto';
  87. window.scroll(this._previousScrollPosition.left, this._previousScrollPosition.top);
  88. htmlStyle.scrollBehavior = previousHtmlScrollBehavior;
  89. bodyStyle.scrollBehavior = previousBodyScrollBehavior;
  90. }
  91. }
  92. /**
  93. * @private
  94. * @return {?}
  95. */
  96. _canBeEnabled() {
  97. // Since the scroll strategies can't be singletons, we have to use a global CSS class
  98. // (`cdk-global-scrollblock`) to make sure that we don't try to disable global
  99. // scrolling multiple times.
  100. /** @type {?} */
  101. const html = (/** @type {?} */ (this._document.documentElement));
  102. if (html.classList.contains('cdk-global-scrollblock') || this._isEnabled) {
  103. return false;
  104. }
  105. /** @type {?} */
  106. const body = this._document.body;
  107. /** @type {?} */
  108. const viewport = this._viewportRuler.getViewportSize();
  109. return body.scrollHeight > viewport.height || body.scrollWidth > viewport.width;
  110. }
  111. }
  112. /**
  113. * @fileoverview added by tsickle
  114. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  115. */
  116. /**
  117. * Returns an error to be thrown when attempting to attach an already-attached scroll strategy.
  118. * @return {?}
  119. */
  120. function getMatScrollStrategyAlreadyAttachedError() {
  121. return Error(`Scroll strategy has already been attached.`);
  122. }
  123. /**
  124. * @fileoverview added by tsickle
  125. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  126. */
  127. /**
  128. * Strategy that will close the overlay as soon as the user starts scrolling.
  129. */
  130. class CloseScrollStrategy {
  131. /**
  132. * @param {?} _scrollDispatcher
  133. * @param {?} _ngZone
  134. * @param {?} _viewportRuler
  135. * @param {?=} _config
  136. */
  137. constructor(_scrollDispatcher, _ngZone, _viewportRuler, _config) {
  138. this._scrollDispatcher = _scrollDispatcher;
  139. this._ngZone = _ngZone;
  140. this._viewportRuler = _viewportRuler;
  141. this._config = _config;
  142. this._scrollSubscription = null;
  143. /**
  144. * Detaches the overlay ref and disables the scroll strategy.
  145. */
  146. this._detach = (/**
  147. * @return {?}
  148. */
  149. () => {
  150. this.disable();
  151. if (this._overlayRef.hasAttached()) {
  152. this._ngZone.run((/**
  153. * @return {?}
  154. */
  155. () => this._overlayRef.detach()));
  156. }
  157. });
  158. }
  159. /**
  160. * Attaches this scroll strategy to an overlay.
  161. * @param {?} overlayRef
  162. * @return {?}
  163. */
  164. attach(overlayRef) {
  165. if (this._overlayRef) {
  166. throw getMatScrollStrategyAlreadyAttachedError();
  167. }
  168. this._overlayRef = overlayRef;
  169. }
  170. /**
  171. * Enables the closing of the attached overlay on scroll.
  172. * @return {?}
  173. */
  174. enable() {
  175. if (this._scrollSubscription) {
  176. return;
  177. }
  178. /** @type {?} */
  179. const stream = this._scrollDispatcher.scrolled(0);
  180. if (this._config && this._config.threshold && this._config.threshold > 1) {
  181. this._initialScrollPosition = this._viewportRuler.getViewportScrollPosition().top;
  182. this._scrollSubscription = stream.subscribe((/**
  183. * @return {?}
  184. */
  185. () => {
  186. /** @type {?} */
  187. const scrollPosition = this._viewportRuler.getViewportScrollPosition().top;
  188. if (Math.abs(scrollPosition - this._initialScrollPosition) > (/** @type {?} */ ((/** @type {?} */ (this._config)).threshold))) {
  189. this._detach();
  190. }
  191. else {
  192. this._overlayRef.updatePosition();
  193. }
  194. }));
  195. }
  196. else {
  197. this._scrollSubscription = stream.subscribe(this._detach);
  198. }
  199. }
  200. /**
  201. * Disables the closing the attached overlay on scroll.
  202. * @return {?}
  203. */
  204. disable() {
  205. if (this._scrollSubscription) {
  206. this._scrollSubscription.unsubscribe();
  207. this._scrollSubscription = null;
  208. }
  209. }
  210. /**
  211. * @return {?}
  212. */
  213. detach() {
  214. this.disable();
  215. this._overlayRef = (/** @type {?} */ (null));
  216. }
  217. }
  218. /**
  219. * @fileoverview added by tsickle
  220. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  221. */
  222. /**
  223. * Scroll strategy that doesn't do anything.
  224. */
  225. class NoopScrollStrategy {
  226. /**
  227. * Does nothing, as this scroll strategy is a no-op.
  228. * @return {?}
  229. */
  230. enable() { }
  231. /**
  232. * Does nothing, as this scroll strategy is a no-op.
  233. * @return {?}
  234. */
  235. disable() { }
  236. /**
  237. * Does nothing, as this scroll strategy is a no-op.
  238. * @return {?}
  239. */
  240. attach() { }
  241. }
  242. /**
  243. * @fileoverview added by tsickle
  244. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  245. */
  246. // TODO(jelbourn): move this to live with the rest of the scrolling code
  247. // TODO(jelbourn): someday replace this with IntersectionObservers
  248. /**
  249. * Gets whether an element is scrolled outside of view by any of its parent scrolling containers.
  250. * \@docs-private
  251. * @param {?} element Dimensions of the element (from getBoundingClientRect)
  252. * @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
  253. * @return {?} Whether the element is scrolled out of view
  254. */
  255. function isElementScrolledOutsideView(element, scrollContainers) {
  256. return scrollContainers.some((/**
  257. * @param {?} containerBounds
  258. * @return {?}
  259. */
  260. containerBounds => {
  261. /** @type {?} */
  262. const outsideAbove = element.bottom < containerBounds.top;
  263. /** @type {?} */
  264. const outsideBelow = element.top > containerBounds.bottom;
  265. /** @type {?} */
  266. const outsideLeft = element.right < containerBounds.left;
  267. /** @type {?} */
  268. const outsideRight = element.left > containerBounds.right;
  269. return outsideAbove || outsideBelow || outsideLeft || outsideRight;
  270. }));
  271. }
  272. /**
  273. * Gets whether an element is clipped by any of its scrolling containers.
  274. * \@docs-private
  275. * @param {?} element Dimensions of the element (from getBoundingClientRect)
  276. * @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
  277. * @return {?} Whether the element is clipped
  278. */
  279. function isElementClippedByScrolling(element, scrollContainers) {
  280. return scrollContainers.some((/**
  281. * @param {?} scrollContainerRect
  282. * @return {?}
  283. */
  284. scrollContainerRect => {
  285. /** @type {?} */
  286. const clippedAbove = element.top < scrollContainerRect.top;
  287. /** @type {?} */
  288. const clippedBelow = element.bottom > scrollContainerRect.bottom;
  289. /** @type {?} */
  290. const clippedLeft = element.left < scrollContainerRect.left;
  291. /** @type {?} */
  292. const clippedRight = element.right > scrollContainerRect.right;
  293. return clippedAbove || clippedBelow || clippedLeft || clippedRight;
  294. }));
  295. }
  296. /**
  297. * @fileoverview added by tsickle
  298. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  299. */
  300. /**
  301. * Strategy that will update the element position as the user is scrolling.
  302. */
  303. class RepositionScrollStrategy {
  304. /**
  305. * @param {?} _scrollDispatcher
  306. * @param {?} _viewportRuler
  307. * @param {?} _ngZone
  308. * @param {?=} _config
  309. */
  310. constructor(_scrollDispatcher, _viewportRuler, _ngZone, _config) {
  311. this._scrollDispatcher = _scrollDispatcher;
  312. this._viewportRuler = _viewportRuler;
  313. this._ngZone = _ngZone;
  314. this._config = _config;
  315. this._scrollSubscription = null;
  316. }
  317. /**
  318. * Attaches this scroll strategy to an overlay.
  319. * @param {?} overlayRef
  320. * @return {?}
  321. */
  322. attach(overlayRef) {
  323. if (this._overlayRef) {
  324. throw getMatScrollStrategyAlreadyAttachedError();
  325. }
  326. this._overlayRef = overlayRef;
  327. }
  328. /**
  329. * Enables repositioning of the attached overlay on scroll.
  330. * @return {?}
  331. */
  332. enable() {
  333. if (!this._scrollSubscription) {
  334. /** @type {?} */
  335. const throttle = this._config ? this._config.scrollThrottle : 0;
  336. this._scrollSubscription = this._scrollDispatcher.scrolled(throttle).subscribe((/**
  337. * @return {?}
  338. */
  339. () => {
  340. this._overlayRef.updatePosition();
  341. // TODO(crisbeto): make `close` on by default once all components can handle it.
  342. if (this._config && this._config.autoClose) {
  343. /** @type {?} */
  344. const overlayRect = this._overlayRef.overlayElement.getBoundingClientRect();
  345. const { width, height } = this._viewportRuler.getViewportSize();
  346. // TODO(crisbeto): include all ancestor scroll containers here once
  347. // we have a way of exposing the trigger element to the scroll strategy.
  348. /** @type {?} */
  349. const parentRects = [{ width, height, bottom: height, right: width, top: 0, left: 0 }];
  350. if (isElementScrolledOutsideView(overlayRect, parentRects)) {
  351. this.disable();
  352. this._ngZone.run((/**
  353. * @return {?}
  354. */
  355. () => this._overlayRef.detach()));
  356. }
  357. }
  358. }));
  359. }
  360. }
  361. /**
  362. * Disables repositioning of the attached overlay on scroll.
  363. * @return {?}
  364. */
  365. disable() {
  366. if (this._scrollSubscription) {
  367. this._scrollSubscription.unsubscribe();
  368. this._scrollSubscription = null;
  369. }
  370. }
  371. /**
  372. * @return {?}
  373. */
  374. detach() {
  375. this.disable();
  376. this._overlayRef = (/** @type {?} */ (null));
  377. }
  378. }
  379. /**
  380. * @fileoverview added by tsickle
  381. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  382. */
  383. /**
  384. * Options for how an overlay will handle scrolling.
  385. *
  386. * Users can provide a custom value for `ScrollStrategyOptions` to replace the default
  387. * behaviors. This class primarily acts as a factory for ScrollStrategy instances.
  388. */
  389. class ScrollStrategyOptions {
  390. /**
  391. * @param {?} _scrollDispatcher
  392. * @param {?} _viewportRuler
  393. * @param {?} _ngZone
  394. * @param {?} document
  395. */
  396. constructor(_scrollDispatcher, _viewportRuler, _ngZone, document) {
  397. this._scrollDispatcher = _scrollDispatcher;
  398. this._viewportRuler = _viewportRuler;
  399. this._ngZone = _ngZone;
  400. /**
  401. * Do nothing on scroll.
  402. */
  403. this.noop = (/**
  404. * @return {?}
  405. */
  406. () => new NoopScrollStrategy());
  407. /**
  408. * Close the overlay as soon as the user scrolls.
  409. * @param config Configuration to be used inside the scroll strategy.
  410. */
  411. this.close = (/**
  412. * @param {?=} config
  413. * @return {?}
  414. */
  415. (config) => new CloseScrollStrategy(this._scrollDispatcher, this._ngZone, this._viewportRuler, config));
  416. /**
  417. * Block scrolling.
  418. */
  419. this.block = (/**
  420. * @return {?}
  421. */
  422. () => new BlockScrollStrategy(this._viewportRuler, this._document));
  423. /**
  424. * Update the overlay's position on scroll.
  425. * @param config Configuration to be used inside the scroll strategy.
  426. * Allows debouncing the reposition calls.
  427. */
  428. this.reposition = (/**
  429. * @param {?=} config
  430. * @return {?}
  431. */
  432. (config) => new RepositionScrollStrategy(this._scrollDispatcher, this._viewportRuler, this._ngZone, config));
  433. this._document = document;
  434. }
  435. }
  436. ScrollStrategyOptions.decorators = [
  437. { type: Injectable, args: [{ providedIn: 'root' },] },
  438. ];
  439. /** @nocollapse */
  440. ScrollStrategyOptions.ctorParameters = () => [
  441. { type: ScrollDispatcher },
  442. { type: ViewportRuler },
  443. { type: NgZone },
  444. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  445. ];
  446. /** @nocollapse */ ScrollStrategyOptions.ngInjectableDef = ɵɵdefineInjectable({ factory: function ScrollStrategyOptions_Factory() { return new ScrollStrategyOptions(ɵɵinject(ScrollDispatcher), ɵɵinject(ViewportRuler), ɵɵinject(NgZone), ɵɵinject(DOCUMENT)); }, token: ScrollStrategyOptions, providedIn: "root" });
  447. /**
  448. * @fileoverview added by tsickle
  449. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  450. */
  451. /**
  452. * @fileoverview added by tsickle
  453. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  454. */
  455. /**
  456. * Initial configuration used when creating an overlay.
  457. */
  458. class OverlayConfig {
  459. /**
  460. * @param {?=} config
  461. */
  462. constructor(config) {
  463. /**
  464. * Strategy to be used when handling scroll events while the overlay is open.
  465. */
  466. this.scrollStrategy = new NoopScrollStrategy();
  467. /**
  468. * Custom class to add to the overlay pane.
  469. */
  470. this.panelClass = '';
  471. /**
  472. * Whether the overlay has a backdrop.
  473. */
  474. this.hasBackdrop = false;
  475. /**
  476. * Custom class to add to the backdrop
  477. */
  478. this.backdropClass = 'cdk-overlay-dark-backdrop';
  479. /**
  480. * Whether the overlay should be disposed of when the user goes backwards/forwards in history.
  481. * Note that this usually doesn't include clicking on links (unless the user is using
  482. * the `HashLocationStrategy`).
  483. */
  484. this.disposeOnNavigation = false;
  485. if (config) {
  486. /** @type {?} */
  487. const configKeys = (/** @type {?} */ (Object.keys(config)));
  488. for (const key of configKeys) {
  489. if (config[key] !== undefined) {
  490. // TypeScript, as of version 3.5, sees the left-hand-side of this expression
  491. // as "I don't know *which* key this is, so the only valid value is the intersection
  492. // of all the posible values." In this case, that happens to be `undefined`. TypeScript
  493. // is not smart enough to see that the right-hand-side is actually an access of the same
  494. // exact type with the same exact key, meaning that the value type must be identical.
  495. // So we use `any` to work around this.
  496. this[key] = (/** @type {?} */ (config[key]));
  497. }
  498. }
  499. }
  500. }
  501. }
  502. /**
  503. * @fileoverview added by tsickle
  504. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  505. */
  506. /**
  507. * The points of the origin element and the overlay element to connect.
  508. */
  509. class ConnectionPositionPair {
  510. /**
  511. * @param {?} origin
  512. * @param {?} overlay
  513. * @param {?=} offsetX
  514. * @param {?=} offsetY
  515. * @param {?=} panelClass
  516. */
  517. constructor(origin, overlay, offsetX, offsetY, panelClass) {
  518. this.offsetX = offsetX;
  519. this.offsetY = offsetY;
  520. this.panelClass = panelClass;
  521. this.originX = origin.originX;
  522. this.originY = origin.originY;
  523. this.overlayX = overlay.overlayX;
  524. this.overlayY = overlay.overlayY;
  525. }
  526. }
  527. /**
  528. * Set of properties regarding the position of the origin and overlay relative to the viewport
  529. * with respect to the containing Scrollable elements.
  530. *
  531. * The overlay and origin are clipped if any part of their bounding client rectangle exceeds the
  532. * bounds of any one of the strategy's Scrollable's bounding client rectangle.
  533. *
  534. * The overlay and origin are outside view if there is no overlap between their bounding client
  535. * rectangle and any one of the strategy's Scrollable's bounding client rectangle.
  536. *
  537. * ----------- -----------
  538. * | outside | | clipped |
  539. * | view | --------------------------
  540. * | | | | | |
  541. * ---------- | ----------- |
  542. * -------------------------- | |
  543. * | | | Scrollable |
  544. * | | | |
  545. * | | --------------------------
  546. * | Scrollable |
  547. * | |
  548. * --------------------------
  549. *
  550. * \@docs-private
  551. */
  552. class ScrollingVisibility {
  553. }
  554. /**
  555. * The change event emitted by the strategy when a fallback position is used.
  556. */
  557. class ConnectedOverlayPositionChange {
  558. /**
  559. * @param {?} connectionPair
  560. * @param {?} scrollableViewProperties
  561. */
  562. constructor(connectionPair, scrollableViewProperties) {
  563. this.connectionPair = connectionPair;
  564. this.scrollableViewProperties = scrollableViewProperties;
  565. }
  566. }
  567. /** @nocollapse */
  568. ConnectedOverlayPositionChange.ctorParameters = () => [
  569. { type: ConnectionPositionPair },
  570. { type: ScrollingVisibility, decorators: [{ type: Optional }] }
  571. ];
  572. /**
  573. * Validates whether a vertical position property matches the expected values.
  574. * \@docs-private
  575. * @param {?} property Name of the property being validated.
  576. * @param {?} value Value of the property being validated.
  577. * @return {?}
  578. */
  579. function validateVerticalPosition(property, value) {
  580. if (value !== 'top' && value !== 'bottom' && value !== 'center') {
  581. throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
  582. `Expected "top", "bottom" or "center".`);
  583. }
  584. }
  585. /**
  586. * Validates whether a horizontal position property matches the expected values.
  587. * \@docs-private
  588. * @param {?} property Name of the property being validated.
  589. * @param {?} value Value of the property being validated.
  590. * @return {?}
  591. */
  592. function validateHorizontalPosition(property, value) {
  593. if (value !== 'start' && value !== 'end' && value !== 'center') {
  594. throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
  595. `Expected "start", "end" or "center".`);
  596. }
  597. }
  598. /**
  599. * @fileoverview added by tsickle
  600. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  601. */
  602. /**
  603. * Service for dispatching keyboard events that land on the body to appropriate overlay ref,
  604. * if any. It maintains a list of attached overlays to determine best suited overlay based
  605. * on event target and order of overlay opens.
  606. */
  607. class OverlayKeyboardDispatcher {
  608. /**
  609. * @param {?} document
  610. */
  611. constructor(document) {
  612. /**
  613. * Currently attached overlays in the order they were attached.
  614. */
  615. this._attachedOverlays = [];
  616. /**
  617. * Keyboard event listener that will be attached to the body.
  618. */
  619. this._keydownListener = (/**
  620. * @param {?} event
  621. * @return {?}
  622. */
  623. (event) => {
  624. /** @type {?} */
  625. const overlays = this._attachedOverlays;
  626. for (let i = overlays.length - 1; i > -1; i--) {
  627. // Dispatch the keydown event to the top overlay which has subscribers to its keydown events.
  628. // We want to target the most recent overlay, rather than trying to match where the event came
  629. // from, because some components might open an overlay, but keep focus on a trigger element
  630. // (e.g. for select and autocomplete). We skip overlays without keydown event subscriptions,
  631. // because we don't want overlays that don't handle keyboard events to block the ones below
  632. // them that do.
  633. if (overlays[i]._keydownEventSubscriptions > 0) {
  634. overlays[i]._keydownEvents.next(event);
  635. break;
  636. }
  637. }
  638. });
  639. this._document = document;
  640. }
  641. /**
  642. * @return {?}
  643. */
  644. ngOnDestroy() {
  645. this._detach();
  646. }
  647. /**
  648. * Add a new overlay to the list of attached overlay refs.
  649. * @param {?} overlayRef
  650. * @return {?}
  651. */
  652. add(overlayRef) {
  653. // Ensure that we don't get the same overlay multiple times.
  654. this.remove(overlayRef);
  655. // Lazily start dispatcher once first overlay is added
  656. if (!this._isAttached) {
  657. this._document.body.addEventListener('keydown', this._keydownListener);
  658. this._isAttached = true;
  659. }
  660. this._attachedOverlays.push(overlayRef);
  661. }
  662. /**
  663. * Remove an overlay from the list of attached overlay refs.
  664. * @param {?} overlayRef
  665. * @return {?}
  666. */
  667. remove(overlayRef) {
  668. /** @type {?} */
  669. const index = this._attachedOverlays.indexOf(overlayRef);
  670. if (index > -1) {
  671. this._attachedOverlays.splice(index, 1);
  672. }
  673. // Remove the global listener once there are no more overlays.
  674. if (this._attachedOverlays.length === 0) {
  675. this._detach();
  676. }
  677. }
  678. /**
  679. * Detaches the global keyboard event listener.
  680. * @private
  681. * @return {?}
  682. */
  683. _detach() {
  684. if (this._isAttached) {
  685. this._document.body.removeEventListener('keydown', this._keydownListener);
  686. this._isAttached = false;
  687. }
  688. }
  689. }
  690. OverlayKeyboardDispatcher.decorators = [
  691. { type: Injectable, args: [{ providedIn: 'root' },] },
  692. ];
  693. /** @nocollapse */
  694. OverlayKeyboardDispatcher.ctorParameters = () => [
  695. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  696. ];
  697. /** @nocollapse */ OverlayKeyboardDispatcher.ngInjectableDef = ɵɵdefineInjectable({ factory: function OverlayKeyboardDispatcher_Factory() { return new OverlayKeyboardDispatcher(ɵɵinject(DOCUMENT)); }, token: OverlayKeyboardDispatcher, providedIn: "root" });
  698. /**
  699. * \@docs-private \@deprecated \@breaking-change 8.0.0
  700. * @param {?} dispatcher
  701. * @param {?} _document
  702. * @return {?}
  703. */
  704. function OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY(dispatcher, _document) {
  705. return dispatcher || new OverlayKeyboardDispatcher(_document);
  706. }
  707. /**
  708. * \@docs-private \@deprecated \@breaking-change 8.0.0
  709. * @type {?}
  710. */
  711. const OVERLAY_KEYBOARD_DISPATCHER_PROVIDER = {
  712. // If there is already an OverlayKeyboardDispatcher available, use that.
  713. // Otherwise, provide a new one.
  714. provide: OverlayKeyboardDispatcher,
  715. deps: [
  716. [new Optional(), new SkipSelf(), OverlayKeyboardDispatcher],
  717. (/** @type {?} */ (
  718. // Coerce to `InjectionToken` so that the `deps` match the "shape"
  719. // of the type expected by Angular
  720. DOCUMENT))
  721. ],
  722. useFactory: OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY
  723. };
  724. /**
  725. * @fileoverview added by tsickle
  726. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  727. */
  728. /**
  729. * Container inside which all overlays will render.
  730. */
  731. class OverlayContainer {
  732. /**
  733. * @param {?} document
  734. */
  735. constructor(document) {
  736. this._document = document;
  737. }
  738. /**
  739. * @return {?}
  740. */
  741. ngOnDestroy() {
  742. if (this._containerElement && this._containerElement.parentNode) {
  743. this._containerElement.parentNode.removeChild(this._containerElement);
  744. }
  745. }
  746. /**
  747. * This method returns the overlay container element. It will lazily
  748. * create the element the first time it is called to facilitate using
  749. * the container in non-browser environments.
  750. * @return {?} the container element
  751. */
  752. getContainerElement() {
  753. if (!this._containerElement) {
  754. this._createContainer();
  755. }
  756. return this._containerElement;
  757. }
  758. /**
  759. * Create the overlay container element, which is simply a div
  760. * with the 'cdk-overlay-container' class on the document body.
  761. * @protected
  762. * @return {?}
  763. */
  764. _createContainer() {
  765. /** @type {?} */
  766. const containerClass = 'cdk-overlay-container';
  767. /** @type {?} */
  768. const previousContainers = this._document.getElementsByClassName(containerClass);
  769. // Remove any old containers. This can happen when transitioning from the server to the client.
  770. for (let i = 0; i < previousContainers.length; i++) {
  771. (/** @type {?} */ (previousContainers[i].parentNode)).removeChild(previousContainers[i]);
  772. }
  773. /** @type {?} */
  774. const container = this._document.createElement('div');
  775. container.classList.add(containerClass);
  776. this._document.body.appendChild(container);
  777. this._containerElement = container;
  778. }
  779. }
  780. OverlayContainer.decorators = [
  781. { type: Injectable, args: [{ providedIn: 'root' },] },
  782. ];
  783. /** @nocollapse */
  784. OverlayContainer.ctorParameters = () => [
  785. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  786. ];
  787. /** @nocollapse */ OverlayContainer.ngInjectableDef = ɵɵdefineInjectable({ factory: function OverlayContainer_Factory() { return new OverlayContainer(ɵɵinject(DOCUMENT)); }, token: OverlayContainer, providedIn: "root" });
  788. /**
  789. * \@docs-private \@deprecated \@breaking-change 8.0.0
  790. * @param {?} parentContainer
  791. * @param {?} _document
  792. * @return {?}
  793. */
  794. function OVERLAY_CONTAINER_PROVIDER_FACTORY(parentContainer, _document) {
  795. return parentContainer || new OverlayContainer(_document);
  796. }
  797. /**
  798. * \@docs-private \@deprecated \@breaking-change 8.0.0
  799. * @type {?}
  800. */
  801. const OVERLAY_CONTAINER_PROVIDER = {
  802. // If there is already an OverlayContainer available, use that. Otherwise, provide a new one.
  803. provide: OverlayContainer,
  804. deps: [
  805. [new Optional(), new SkipSelf(), OverlayContainer],
  806. (/** @type {?} */ (DOCUMENT))
  807. ],
  808. useFactory: OVERLAY_CONTAINER_PROVIDER_FACTORY
  809. };
  810. /**
  811. * @fileoverview added by tsickle
  812. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  813. */
  814. /**
  815. * Reference to an overlay that has been created with the Overlay service.
  816. * Used to manipulate or dispose of said overlay.
  817. */
  818. class OverlayRef {
  819. /**
  820. * @param {?} _portalOutlet
  821. * @param {?} _host
  822. * @param {?} _pane
  823. * @param {?} _config
  824. * @param {?} _ngZone
  825. * @param {?} _keyboardDispatcher
  826. * @param {?} _document
  827. * @param {?=} _location
  828. */
  829. constructor(_portalOutlet, _host, _pane, _config, _ngZone, _keyboardDispatcher, _document, _location) {
  830. this._portalOutlet = _portalOutlet;
  831. this._host = _host;
  832. this._pane = _pane;
  833. this._config = _config;
  834. this._ngZone = _ngZone;
  835. this._keyboardDispatcher = _keyboardDispatcher;
  836. this._document = _document;
  837. this._location = _location;
  838. this._backdropElement = null;
  839. this._backdropClick = new Subject();
  840. this._attachments = new Subject();
  841. this._detachments = new Subject();
  842. this._locationChanges = Subscription.EMPTY;
  843. this._backdropClickHandler = (/**
  844. * @param {?} event
  845. * @return {?}
  846. */
  847. (event) => this._backdropClick.next(event));
  848. this._keydownEventsObservable = new Observable((/**
  849. * @param {?} observer
  850. * @return {?}
  851. */
  852. (observer) => {
  853. /** @type {?} */
  854. const subscription = this._keydownEvents.subscribe(observer);
  855. this._keydownEventSubscriptions++;
  856. return (/**
  857. * @return {?}
  858. */
  859. () => {
  860. subscription.unsubscribe();
  861. this._keydownEventSubscriptions--;
  862. });
  863. }));
  864. /**
  865. * Stream of keydown events dispatched to this overlay.
  866. */
  867. this._keydownEvents = new Subject();
  868. /**
  869. * Amount of subscriptions to the keydown events.
  870. */
  871. this._keydownEventSubscriptions = 0;
  872. if (_config.scrollStrategy) {
  873. this._scrollStrategy = _config.scrollStrategy;
  874. this._scrollStrategy.attach(this);
  875. }
  876. this._positionStrategy = _config.positionStrategy;
  877. }
  878. /**
  879. * The overlay's HTML element
  880. * @return {?}
  881. */
  882. get overlayElement() {
  883. return this._pane;
  884. }
  885. /**
  886. * The overlay's backdrop HTML element.
  887. * @return {?}
  888. */
  889. get backdropElement() {
  890. return this._backdropElement;
  891. }
  892. /**
  893. * Wrapper around the panel element. Can be used for advanced
  894. * positioning where a wrapper with specific styling is
  895. * required around the overlay pane.
  896. * @return {?}
  897. */
  898. get hostElement() {
  899. return this._host;
  900. }
  901. /**
  902. * Attaches content, given via a Portal, to the overlay.
  903. * If the overlay is configured to have a backdrop, it will be created.
  904. *
  905. * @param {?} portal Portal instance to which to attach the overlay.
  906. * @return {?} The portal attachment result.
  907. */
  908. attach(portal) {
  909. /** @type {?} */
  910. let attachResult = this._portalOutlet.attach(portal);
  911. if (this._positionStrategy) {
  912. this._positionStrategy.attach(this);
  913. }
  914. // Update the pane element with the given configuration.
  915. if (!this._host.parentElement && this._previousHostParent) {
  916. this._previousHostParent.appendChild(this._host);
  917. }
  918. this._updateStackingOrder();
  919. this._updateElementSize();
  920. this._updateElementDirection();
  921. if (this._scrollStrategy) {
  922. this._scrollStrategy.enable();
  923. }
  924. // Update the position once the zone is stable so that the overlay will be fully rendered
  925. // before attempting to position it, as the position may depend on the size of the rendered
  926. // content.
  927. this._ngZone.onStable
  928. .asObservable()
  929. .pipe(take(1))
  930. .subscribe((/**
  931. * @return {?}
  932. */
  933. () => {
  934. // The overlay could've been detached before the zone has stabilized.
  935. if (this.hasAttached()) {
  936. this.updatePosition();
  937. }
  938. }));
  939. // Enable pointer events for the overlay pane element.
  940. this._togglePointerEvents(true);
  941. if (this._config.hasBackdrop) {
  942. this._attachBackdrop();
  943. }
  944. if (this._config.panelClass) {
  945. this._toggleClasses(this._pane, this._config.panelClass, true);
  946. }
  947. // Only emit the `attachments` event once all other setup is done.
  948. this._attachments.next();
  949. // Track this overlay by the keyboard dispatcher
  950. this._keyboardDispatcher.add(this);
  951. // @breaking-change 8.0.0 remove the null check for `_location`
  952. // once the constructor parameter is made required.
  953. if (this._config.disposeOnNavigation && this._location) {
  954. this._locationChanges = this._location.subscribe((/**
  955. * @return {?}
  956. */
  957. () => this.dispose()));
  958. }
  959. return attachResult;
  960. }
  961. /**
  962. * Detaches an overlay from a portal.
  963. * @return {?} The portal detachment result.
  964. */
  965. detach() {
  966. if (!this.hasAttached()) {
  967. return;
  968. }
  969. this.detachBackdrop();
  970. // When the overlay is detached, the pane element should disable pointer events.
  971. // This is necessary because otherwise the pane element will cover the page and disable
  972. // pointer events therefore. Depends on the position strategy and the applied pane boundaries.
  973. this._togglePointerEvents(false);
  974. if (this._positionStrategy && this._positionStrategy.detach) {
  975. this._positionStrategy.detach();
  976. }
  977. if (this._scrollStrategy) {
  978. this._scrollStrategy.disable();
  979. }
  980. /** @type {?} */
  981. const detachmentResult = this._portalOutlet.detach();
  982. // Only emit after everything is detached.
  983. this._detachments.next();
  984. // Remove this overlay from keyboard dispatcher tracking.
  985. this._keyboardDispatcher.remove(this);
  986. // Keeping the host element in DOM the can cause scroll jank, because it still gets
  987. // rendered, even though it's transparent and unclickable which is why we remove it.
  988. this._detachContentWhenStable();
  989. // Stop listening for location changes.
  990. this._locationChanges.unsubscribe();
  991. return detachmentResult;
  992. }
  993. /**
  994. * Cleans up the overlay from the DOM.
  995. * @return {?}
  996. */
  997. dispose() {
  998. /** @type {?} */
  999. const isAttached = this.hasAttached();
  1000. if (this._positionStrategy) {
  1001. this._positionStrategy.dispose();
  1002. }
  1003. this._disposeScrollStrategy();
  1004. this.detachBackdrop();
  1005. this._locationChanges.unsubscribe();
  1006. this._keyboardDispatcher.remove(this);
  1007. this._portalOutlet.dispose();
  1008. this._attachments.complete();
  1009. this._backdropClick.complete();
  1010. this._keydownEvents.complete();
  1011. if (this._host && this._host.parentNode) {
  1012. this._host.parentNode.removeChild(this._host);
  1013. this._host = (/** @type {?} */ (null));
  1014. }
  1015. this._previousHostParent = this._pane = (/** @type {?} */ (null));
  1016. if (isAttached) {
  1017. this._detachments.next();
  1018. }
  1019. this._detachments.complete();
  1020. }
  1021. /**
  1022. * Whether the overlay has attached content.
  1023. * @return {?}
  1024. */
  1025. hasAttached() {
  1026. return this._portalOutlet.hasAttached();
  1027. }
  1028. /**
  1029. * Gets an observable that emits when the backdrop has been clicked.
  1030. * @return {?}
  1031. */
  1032. backdropClick() {
  1033. return this._backdropClick.asObservable();
  1034. }
  1035. /**
  1036. * Gets an observable that emits when the overlay has been attached.
  1037. * @return {?}
  1038. */
  1039. attachments() {
  1040. return this._attachments.asObservable();
  1041. }
  1042. /**
  1043. * Gets an observable that emits when the overlay has been detached.
  1044. * @return {?}
  1045. */
  1046. detachments() {
  1047. return this._detachments.asObservable();
  1048. }
  1049. /**
  1050. * Gets an observable of keydown events targeted to this overlay.
  1051. * @return {?}
  1052. */
  1053. keydownEvents() {
  1054. return this._keydownEventsObservable;
  1055. }
  1056. /**
  1057. * Gets the current overlay configuration, which is immutable.
  1058. * @return {?}
  1059. */
  1060. getConfig() {
  1061. return this._config;
  1062. }
  1063. /**
  1064. * Updates the position of the overlay based on the position strategy.
  1065. * @return {?}
  1066. */
  1067. updatePosition() {
  1068. if (this._positionStrategy) {
  1069. this._positionStrategy.apply();
  1070. }
  1071. }
  1072. /**
  1073. * Switches to a new position strategy and updates the overlay position.
  1074. * @param {?} strategy
  1075. * @return {?}
  1076. */
  1077. updatePositionStrategy(strategy) {
  1078. if (strategy === this._positionStrategy) {
  1079. return;
  1080. }
  1081. if (this._positionStrategy) {
  1082. this._positionStrategy.dispose();
  1083. }
  1084. this._positionStrategy = strategy;
  1085. if (this.hasAttached()) {
  1086. strategy.attach(this);
  1087. this.updatePosition();
  1088. }
  1089. }
  1090. /**
  1091. * Update the size properties of the overlay.
  1092. * @param {?} sizeConfig
  1093. * @return {?}
  1094. */
  1095. updateSize(sizeConfig) {
  1096. this._config = Object.assign({}, this._config, sizeConfig);
  1097. this._updateElementSize();
  1098. }
  1099. /**
  1100. * Sets the LTR/RTL direction for the overlay.
  1101. * @param {?} dir
  1102. * @return {?}
  1103. */
  1104. setDirection(dir) {
  1105. this._config = Object.assign({}, this._config, { direction: dir });
  1106. this._updateElementDirection();
  1107. }
  1108. /**
  1109. * Add a CSS class or an array of classes to the overlay pane.
  1110. * @param {?} classes
  1111. * @return {?}
  1112. */
  1113. addPanelClass(classes) {
  1114. if (this._pane) {
  1115. this._toggleClasses(this._pane, classes, true);
  1116. }
  1117. }
  1118. /**
  1119. * Remove a CSS class or an array of classes from the overlay pane.
  1120. * @param {?} classes
  1121. * @return {?}
  1122. */
  1123. removePanelClass(classes) {
  1124. if (this._pane) {
  1125. this._toggleClasses(this._pane, classes, false);
  1126. }
  1127. }
  1128. /**
  1129. * Returns the layout direction of the overlay panel.
  1130. * @return {?}
  1131. */
  1132. getDirection() {
  1133. /** @type {?} */
  1134. const direction = this._config.direction;
  1135. if (!direction) {
  1136. return 'ltr';
  1137. }
  1138. return typeof direction === 'string' ? direction : direction.value;
  1139. }
  1140. /**
  1141. * Switches to a new scroll strategy.
  1142. * @param {?} strategy
  1143. * @return {?}
  1144. */
  1145. updateScrollStrategy(strategy) {
  1146. if (strategy === this._scrollStrategy) {
  1147. return;
  1148. }
  1149. this._disposeScrollStrategy();
  1150. this._scrollStrategy = strategy;
  1151. if (this.hasAttached()) {
  1152. strategy.attach(this);
  1153. strategy.enable();
  1154. }
  1155. }
  1156. /**
  1157. * Updates the text direction of the overlay panel.
  1158. * @private
  1159. * @return {?}
  1160. */
  1161. _updateElementDirection() {
  1162. this._host.setAttribute('dir', this.getDirection());
  1163. }
  1164. /**
  1165. * Updates the size of the overlay element based on the overlay config.
  1166. * @private
  1167. * @return {?}
  1168. */
  1169. _updateElementSize() {
  1170. if (!this._pane) {
  1171. return;
  1172. }
  1173. /** @type {?} */
  1174. const style = this._pane.style;
  1175. style.width = coerceCssPixelValue(this._config.width);
  1176. style.height = coerceCssPixelValue(this._config.height);
  1177. style.minWidth = coerceCssPixelValue(this._config.minWidth);
  1178. style.minHeight = coerceCssPixelValue(this._config.minHeight);
  1179. style.maxWidth = coerceCssPixelValue(this._config.maxWidth);
  1180. style.maxHeight = coerceCssPixelValue(this._config.maxHeight);
  1181. }
  1182. /**
  1183. * Toggles the pointer events for the overlay pane element.
  1184. * @private
  1185. * @param {?} enablePointer
  1186. * @return {?}
  1187. */
  1188. _togglePointerEvents(enablePointer) {
  1189. this._pane.style.pointerEvents = enablePointer ? 'auto' : 'none';
  1190. }
  1191. /**
  1192. * Attaches a backdrop for this overlay.
  1193. * @private
  1194. * @return {?}
  1195. */
  1196. _attachBackdrop() {
  1197. /** @type {?} */
  1198. const showingClass = 'cdk-overlay-backdrop-showing';
  1199. this._backdropElement = this._document.createElement('div');
  1200. this._backdropElement.classList.add('cdk-overlay-backdrop');
  1201. if (this._config.backdropClass) {
  1202. this._toggleClasses(this._backdropElement, this._config.backdropClass, true);
  1203. }
  1204. // Insert the backdrop before the pane in the DOM order,
  1205. // in order to handle stacked overlays properly.
  1206. (/** @type {?} */ (this._host.parentElement)).insertBefore(this._backdropElement, this._host);
  1207. // Forward backdrop clicks such that the consumer of the overlay can perform whatever
  1208. // action desired when such a click occurs (usually closing the overlay).
  1209. this._backdropElement.addEventListener('click', this._backdropClickHandler);
  1210. // Add class to fade-in the backdrop after one frame.
  1211. if (typeof requestAnimationFrame !== 'undefined') {
  1212. this._ngZone.runOutsideAngular((/**
  1213. * @return {?}
  1214. */
  1215. () => {
  1216. requestAnimationFrame((/**
  1217. * @return {?}
  1218. */
  1219. () => {
  1220. if (this._backdropElement) {
  1221. this._backdropElement.classList.add(showingClass);
  1222. }
  1223. }));
  1224. }));
  1225. }
  1226. else {
  1227. this._backdropElement.classList.add(showingClass);
  1228. }
  1229. }
  1230. /**
  1231. * Updates the stacking order of the element, moving it to the top if necessary.
  1232. * This is required in cases where one overlay was detached, while another one,
  1233. * that should be behind it, was destroyed. The next time both of them are opened,
  1234. * the stacking will be wrong, because the detached element's pane will still be
  1235. * in its original DOM position.
  1236. * @private
  1237. * @return {?}
  1238. */
  1239. _updateStackingOrder() {
  1240. if (this._host.nextSibling) {
  1241. (/** @type {?} */ (this._host.parentNode)).appendChild(this._host);
  1242. }
  1243. }
  1244. /**
  1245. * Detaches the backdrop (if any) associated with the overlay.
  1246. * @return {?}
  1247. */
  1248. detachBackdrop() {
  1249. /** @type {?} */
  1250. let backdropToDetach = this._backdropElement;
  1251. if (!backdropToDetach) {
  1252. return;
  1253. }
  1254. /** @type {?} */
  1255. let timeoutId;
  1256. /** @type {?} */
  1257. let finishDetach = (/**
  1258. * @return {?}
  1259. */
  1260. () => {
  1261. // It may not be attached to anything in certain cases (e.g. unit tests).
  1262. if (backdropToDetach) {
  1263. backdropToDetach.removeEventListener('click', this._backdropClickHandler);
  1264. backdropToDetach.removeEventListener('transitionend', finishDetach);
  1265. if (backdropToDetach.parentNode) {
  1266. backdropToDetach.parentNode.removeChild(backdropToDetach);
  1267. }
  1268. }
  1269. // It is possible that a new portal has been attached to this overlay since we started
  1270. // removing the backdrop. If that is the case, only clear the backdrop reference if it
  1271. // is still the same instance that we started to remove.
  1272. if (this._backdropElement == backdropToDetach) {
  1273. this._backdropElement = null;
  1274. }
  1275. if (this._config.backdropClass) {
  1276. this._toggleClasses((/** @type {?} */ (backdropToDetach)), this._config.backdropClass, false);
  1277. }
  1278. clearTimeout(timeoutId);
  1279. });
  1280. backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');
  1281. this._ngZone.runOutsideAngular((/**
  1282. * @return {?}
  1283. */
  1284. () => {
  1285. (/** @type {?} */ (backdropToDetach)).addEventListener('transitionend', finishDetach);
  1286. }));
  1287. // If the backdrop doesn't have a transition, the `transitionend` event won't fire.
  1288. // In this case we make it unclickable and we try to remove it after a delay.
  1289. backdropToDetach.style.pointerEvents = 'none';
  1290. // Run this outside the Angular zone because there's nothing that Angular cares about.
  1291. // If it were to run inside the Angular zone, every test that used Overlay would have to be
  1292. // either async or fakeAsync.
  1293. timeoutId = this._ngZone.runOutsideAngular((/**
  1294. * @return {?}
  1295. */
  1296. () => setTimeout(finishDetach, 500)));
  1297. }
  1298. /**
  1299. * Toggles a single CSS class or an array of classes on an element.
  1300. * @private
  1301. * @param {?} element
  1302. * @param {?} cssClasses
  1303. * @param {?} isAdd
  1304. * @return {?}
  1305. */
  1306. _toggleClasses(element, cssClasses, isAdd) {
  1307. /** @type {?} */
  1308. const classList = element.classList;
  1309. coerceArray(cssClasses).forEach((/**
  1310. * @param {?} cssClass
  1311. * @return {?}
  1312. */
  1313. cssClass => {
  1314. // We can't do a spread here, because IE doesn't support setting multiple classes.
  1315. // Also trying to add an empty string to a DOMTokenList will throw.
  1316. if (cssClass) {
  1317. isAdd ? classList.add(cssClass) : classList.remove(cssClass);
  1318. }
  1319. }));
  1320. }
  1321. /**
  1322. * Detaches the overlay content next time the zone stabilizes.
  1323. * @private
  1324. * @return {?}
  1325. */
  1326. _detachContentWhenStable() {
  1327. // Normally we wouldn't have to explicitly run this outside the `NgZone`, however
  1328. // if the consumer is using `zone-patch-rxjs`, the `Subscription.unsubscribe` call will
  1329. // be patched to run inside the zone, which will throw us into an infinite loop.
  1330. this._ngZone.runOutsideAngular((/**
  1331. * @return {?}
  1332. */
  1333. () => {
  1334. // We can't remove the host here immediately, because the overlay pane's content
  1335. // might still be animating. This stream helps us avoid interrupting the animation
  1336. // by waiting for the pane to become empty.
  1337. /** @type {?} */
  1338. const subscription = this._ngZone.onStable
  1339. .asObservable()
  1340. .pipe(takeUntil(merge(this._attachments, this._detachments)))
  1341. .subscribe((/**
  1342. * @return {?}
  1343. */
  1344. () => {
  1345. // Needs a couple of checks for the pane and host, because
  1346. // they may have been removed by the time the zone stabilizes.
  1347. if (!this._pane || !this._host || this._pane.children.length === 0) {
  1348. if (this._pane && this._config.panelClass) {
  1349. this._toggleClasses(this._pane, this._config.panelClass, false);
  1350. }
  1351. if (this._host && this._host.parentElement) {
  1352. this._previousHostParent = this._host.parentElement;
  1353. this._previousHostParent.removeChild(this._host);
  1354. }
  1355. subscription.unsubscribe();
  1356. }
  1357. }));
  1358. }));
  1359. }
  1360. /**
  1361. * Disposes of a scroll strategy.
  1362. * @private
  1363. * @return {?}
  1364. */
  1365. _disposeScrollStrategy() {
  1366. /** @type {?} */
  1367. const scrollStrategy = this._scrollStrategy;
  1368. if (scrollStrategy) {
  1369. scrollStrategy.disable();
  1370. if (scrollStrategy.detach) {
  1371. scrollStrategy.detach();
  1372. }
  1373. }
  1374. }
  1375. }
  1376. /**
  1377. * @fileoverview added by tsickle
  1378. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  1379. */
  1380. // TODO: refactor clipping detection into a separate thing (part of scrolling module)
  1381. // TODO: doesn't handle both flexible width and height when it has to scroll along both axis.
  1382. /**
  1383. * Class to be added to the overlay bounding box.
  1384. * @type {?}
  1385. */
  1386. const boundingBoxClass = 'cdk-overlay-connected-position-bounding-box';
  1387. /**
  1388. * A strategy for positioning overlays. Using this strategy, an overlay is given an
  1389. * implicit position relative some origin element. The relative position is defined in terms of
  1390. * a point on the origin element that is connected to a point on the overlay element. For example,
  1391. * a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
  1392. * of the overlay.
  1393. */
  1394. class FlexibleConnectedPositionStrategy {
  1395. /**
  1396. * @param {?} connectedTo
  1397. * @param {?} _viewportRuler
  1398. * @param {?} _document
  1399. * @param {?} _platform
  1400. * @param {?} _overlayContainer
  1401. */
  1402. constructor(connectedTo, _viewportRuler, _document, _platform, _overlayContainer) {
  1403. this._viewportRuler = _viewportRuler;
  1404. this._document = _document;
  1405. this._platform = _platform;
  1406. this._overlayContainer = _overlayContainer;
  1407. /**
  1408. * Last size used for the bounding box. Used to avoid resizing the overlay after open.
  1409. */
  1410. this._lastBoundingBoxSize = { width: 0, height: 0 };
  1411. /**
  1412. * Whether the overlay was pushed in a previous positioning.
  1413. */
  1414. this._isPushed = false;
  1415. /**
  1416. * Whether the overlay can be pushed on-screen on the initial open.
  1417. */
  1418. this._canPush = true;
  1419. /**
  1420. * Whether the overlay can grow via flexible width/height after the initial open.
  1421. */
  1422. this._growAfterOpen = false;
  1423. /**
  1424. * Whether the overlay's width and height can be constrained to fit within the viewport.
  1425. */
  1426. this._hasFlexibleDimensions = true;
  1427. /**
  1428. * Whether the overlay position is locked.
  1429. */
  1430. this._positionLocked = false;
  1431. /**
  1432. * Amount of space that must be maintained between the overlay and the edge of the viewport.
  1433. */
  1434. this._viewportMargin = 0;
  1435. /**
  1436. * The Scrollable containers used to check scrollable view properties on position change.
  1437. */
  1438. this._scrollables = [];
  1439. /**
  1440. * Ordered list of preferred positions, from most to least desirable.
  1441. */
  1442. this._preferredPositions = [];
  1443. /**
  1444. * Subject that emits whenever the position changes.
  1445. */
  1446. this._positionChanges = new Subject();
  1447. /**
  1448. * Subscription to viewport size changes.
  1449. */
  1450. this._resizeSubscription = Subscription.EMPTY;
  1451. /**
  1452. * Default offset for the overlay along the x axis.
  1453. */
  1454. this._offsetX = 0;
  1455. /**
  1456. * Default offset for the overlay along the y axis.
  1457. */
  1458. this._offsetY = 0;
  1459. /**
  1460. * Keeps track of the CSS classes that the position strategy has applied on the overlay panel.
  1461. */
  1462. this._appliedPanelClasses = [];
  1463. /**
  1464. * Observable sequence of position changes.
  1465. */
  1466. this.positionChanges = this._positionChanges.asObservable();
  1467. this.setOrigin(connectedTo);
  1468. }
  1469. /**
  1470. * Ordered list of preferred positions, from most to least desirable.
  1471. * @return {?}
  1472. */
  1473. get positions() {
  1474. return this._preferredPositions;
  1475. }
  1476. /**
  1477. * Attaches this position strategy to an overlay.
  1478. * @param {?} overlayRef
  1479. * @return {?}
  1480. */
  1481. attach(overlayRef) {
  1482. if (this._overlayRef && overlayRef !== this._overlayRef) {
  1483. throw Error('This position strategy is already attached to an overlay');
  1484. }
  1485. this._validatePositions();
  1486. overlayRef.hostElement.classList.add(boundingBoxClass);
  1487. this._overlayRef = overlayRef;
  1488. this._boundingBox = overlayRef.hostElement;
  1489. this._pane = overlayRef.overlayElement;
  1490. this._isDisposed = false;
  1491. this._isInitialRender = true;
  1492. this._lastPosition = null;
  1493. this._resizeSubscription.unsubscribe();
  1494. this._resizeSubscription = this._viewportRuler.change().subscribe((/**
  1495. * @return {?}
  1496. */
  1497. () => {
  1498. // When the window is resized, we want to trigger the next reposition as if it
  1499. // was an initial render, in order for the strategy to pick a new optimal position,
  1500. // otherwise position locking will cause it to stay at the old one.
  1501. this._isInitialRender = true;
  1502. this.apply();
  1503. }));
  1504. }
  1505. /**
  1506. * Updates the position of the overlay element, using whichever preferred position relative
  1507. * to the origin best fits on-screen.
  1508. *
  1509. * The selection of a position goes as follows:
  1510. * - If any positions fit completely within the viewport as-is,
  1511. * choose the first position that does so.
  1512. * - If flexible dimensions are enabled and at least one satifies the given minimum width/height,
  1513. * choose the position with the greatest available size modified by the positions' weight.
  1514. * - If pushing is enabled, take the position that went off-screen the least and push it
  1515. * on-screen.
  1516. * - If none of the previous criteria were met, use the position that goes off-screen the least.
  1517. * \@docs-private
  1518. * @return {?}
  1519. */
  1520. apply() {
  1521. // We shouldn't do anything if the strategy was disposed or we're on the server.
  1522. if (this._isDisposed || !this._platform.isBrowser) {
  1523. return;
  1524. }
  1525. // If the position has been applied already (e.g. when the overlay was opened) and the
  1526. // consumer opted into locking in the position, re-use the old position, in order to
  1527. // prevent the overlay from jumping around.
  1528. if (!this._isInitialRender && this._positionLocked && this._lastPosition) {
  1529. this.reapplyLastPosition();
  1530. return;
  1531. }
  1532. this._clearPanelClasses();
  1533. this._resetOverlayElementStyles();
  1534. this._resetBoundingBoxStyles();
  1535. // We need the bounding rects for the origin and the overlay to determine how to position
  1536. // the overlay relative to the origin.
  1537. // We use the viewport rect to determine whether a position would go off-screen.
  1538. this._viewportRect = this._getNarrowedViewportRect();
  1539. this._originRect = this._getOriginRect();
  1540. this._overlayRect = this._pane.getBoundingClientRect();
  1541. /** @type {?} */
  1542. const originRect = this._originRect;
  1543. /** @type {?} */
  1544. const overlayRect = this._overlayRect;
  1545. /** @type {?} */
  1546. const viewportRect = this._viewportRect;
  1547. // Positions where the overlay will fit with flexible dimensions.
  1548. /** @type {?} */
  1549. const flexibleFits = [];
  1550. // Fallback if none of the preferred positions fit within the viewport.
  1551. /** @type {?} */
  1552. let fallback;
  1553. // Go through each of the preferred positions looking for a good fit.
  1554. // If a good fit is found, it will be applied immediately.
  1555. for (let pos of this._preferredPositions) {
  1556. // Get the exact (x, y) coordinate for the point-of-origin on the origin element.
  1557. /** @type {?} */
  1558. let originPoint = this._getOriginPoint(originRect, pos);
  1559. // From that point-of-origin, get the exact (x, y) coordinate for the top-left corner of the
  1560. // overlay in this position. We use the top-left corner for calculations and later translate
  1561. // this into an appropriate (top, left, bottom, right) style.
  1562. /** @type {?} */
  1563. let overlayPoint = this._getOverlayPoint(originPoint, overlayRect, pos);
  1564. // Calculate how well the overlay would fit into the viewport with this point.
  1565. /** @type {?} */
  1566. let overlayFit = this._getOverlayFit(overlayPoint, overlayRect, viewportRect, pos);
  1567. // If the overlay, without any further work, fits into the viewport, use this position.
  1568. if (overlayFit.isCompletelyWithinViewport) {
  1569. this._isPushed = false;
  1570. this._applyPosition(pos, originPoint);
  1571. return;
  1572. }
  1573. // If the overlay has flexible dimensions, we can use this position
  1574. // so long as there's enough space for the minimum dimensions.
  1575. if (this._canFitWithFlexibleDimensions(overlayFit, overlayPoint, viewportRect)) {
  1576. // Save positions where the overlay will fit with flexible dimensions. We will use these
  1577. // if none of the positions fit *without* flexible dimensions.
  1578. flexibleFits.push({
  1579. position: pos,
  1580. origin: originPoint,
  1581. overlayRect,
  1582. boundingBoxRect: this._calculateBoundingBoxRect(originPoint, pos)
  1583. });
  1584. continue;
  1585. }
  1586. // If the current preferred position does not fit on the screen, remember the position
  1587. // if it has more visible area on-screen than we've seen and move onto the next preferred
  1588. // position.
  1589. if (!fallback || fallback.overlayFit.visibleArea < overlayFit.visibleArea) {
  1590. fallback = { overlayFit, overlayPoint, originPoint, position: pos, overlayRect };
  1591. }
  1592. }
  1593. // If there are any positions where the overlay would fit with flexible dimensions, choose the
  1594. // one that has the greatest area available modified by the position's weight
  1595. if (flexibleFits.length) {
  1596. /** @type {?} */
  1597. let bestFit = null;
  1598. /** @type {?} */
  1599. let bestScore = -1;
  1600. for (const fit of flexibleFits) {
  1601. /** @type {?} */
  1602. const score = fit.boundingBoxRect.width * fit.boundingBoxRect.height * (fit.position.weight || 1);
  1603. if (score > bestScore) {
  1604. bestScore = score;
  1605. bestFit = fit;
  1606. }
  1607. }
  1608. this._isPushed = false;
  1609. this._applyPosition((/** @type {?} */ (bestFit)).position, (/** @type {?} */ (bestFit)).origin);
  1610. return;
  1611. }
  1612. // When none of the preferred positions fit within the viewport, take the position
  1613. // that went off-screen the least and attempt to push it on-screen.
  1614. if (this._canPush) {
  1615. // TODO(jelbourn): after pushing, the opening "direction" of the overlay might not make sense.
  1616. this._isPushed = true;
  1617. this._applyPosition((/** @type {?} */ (fallback)).position, (/** @type {?} */ (fallback)).originPoint);
  1618. return;
  1619. }
  1620. // All options for getting the overlay within the viewport have been exhausted, so go with the
  1621. // position that went off-screen the least.
  1622. this._applyPosition((/** @type {?} */ (fallback)).position, (/** @type {?} */ (fallback)).originPoint);
  1623. }
  1624. /**
  1625. * @return {?}
  1626. */
  1627. detach() {
  1628. this._clearPanelClasses();
  1629. this._lastPosition = null;
  1630. this._previousPushAmount = null;
  1631. this._resizeSubscription.unsubscribe();
  1632. }
  1633. /**
  1634. * Cleanup after the element gets destroyed.
  1635. * @return {?}
  1636. */
  1637. dispose() {
  1638. if (this._isDisposed) {
  1639. return;
  1640. }
  1641. // We can't use `_resetBoundingBoxStyles` here, because it resets
  1642. // some properties to zero, rather than removing them.
  1643. if (this._boundingBox) {
  1644. extendStyles(this._boundingBox.style, (/** @type {?} */ ({
  1645. top: '',
  1646. left: '',
  1647. right: '',
  1648. bottom: '',
  1649. height: '',
  1650. width: '',
  1651. alignItems: '',
  1652. justifyContent: '',
  1653. })));
  1654. }
  1655. if (this._pane) {
  1656. this._resetOverlayElementStyles();
  1657. }
  1658. if (this._overlayRef) {
  1659. this._overlayRef.hostElement.classList.remove(boundingBoxClass);
  1660. }
  1661. this.detach();
  1662. this._positionChanges.complete();
  1663. this._overlayRef = this._boundingBox = (/** @type {?} */ (null));
  1664. this._isDisposed = true;
  1665. }
  1666. /**
  1667. * This re-aligns the overlay element with the trigger in its last calculated position,
  1668. * even if a position higher in the "preferred positions" list would now fit. This
  1669. * allows one to re-align the panel without changing the orientation of the panel.
  1670. * @return {?}
  1671. */
  1672. reapplyLastPosition() {
  1673. if (!this._isDisposed && (!this._platform || this._platform.isBrowser)) {
  1674. this._originRect = this._getOriginRect();
  1675. this._overlayRect = this._pane.getBoundingClientRect();
  1676. this._viewportRect = this._getNarrowedViewportRect();
  1677. /** @type {?} */
  1678. const lastPosition = this._lastPosition || this._preferredPositions[0];
  1679. /** @type {?} */
  1680. const originPoint = this._getOriginPoint(this._originRect, lastPosition);
  1681. this._applyPosition(lastPosition, originPoint);
  1682. }
  1683. }
  1684. /**
  1685. * Sets the list of Scrollable containers that host the origin element so that
  1686. * on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
  1687. * Scrollable must be an ancestor element of the strategy's origin element.
  1688. * @template THIS
  1689. * @this {THIS}
  1690. * @param {?} scrollables
  1691. * @return {THIS}
  1692. */
  1693. withScrollableContainers(scrollables) {
  1694. (/** @type {?} */ (this))._scrollables = scrollables;
  1695. return (/** @type {?} */ (this));
  1696. }
  1697. /**
  1698. * Adds new preferred positions.
  1699. * @template THIS
  1700. * @this {THIS}
  1701. * @param {?} positions List of positions options for this overlay.
  1702. * @return {THIS}
  1703. */
  1704. withPositions(positions) {
  1705. (/** @type {?} */ (this))._preferredPositions = positions;
  1706. // If the last calculated position object isn't part of the positions anymore, clear
  1707. // it in order to avoid it being picked up if the consumer tries to re-apply.
  1708. if (positions.indexOf((/** @type {?} */ ((/** @type {?} */ (this))._lastPosition))) === -1) {
  1709. (/** @type {?} */ (this))._lastPosition = null;
  1710. }
  1711. (/** @type {?} */ (this))._validatePositions();
  1712. return (/** @type {?} */ (this));
  1713. }
  1714. /**
  1715. * Sets a minimum distance the overlay may be positioned to the edge of the viewport.
  1716. * @template THIS
  1717. * @this {THIS}
  1718. * @param {?} margin Required margin between the overlay and the viewport edge in pixels.
  1719. * @return {THIS}
  1720. */
  1721. withViewportMargin(margin) {
  1722. (/** @type {?} */ (this))._viewportMargin = margin;
  1723. return (/** @type {?} */ (this));
  1724. }
  1725. /**
  1726. * Sets whether the overlay's width and height can be constrained to fit within the viewport.
  1727. * @template THIS
  1728. * @this {THIS}
  1729. * @param {?=} flexibleDimensions
  1730. * @return {THIS}
  1731. */
  1732. withFlexibleDimensions(flexibleDimensions = true) {
  1733. (/** @type {?} */ (this))._hasFlexibleDimensions = flexibleDimensions;
  1734. return (/** @type {?} */ (this));
  1735. }
  1736. /**
  1737. * Sets whether the overlay can grow after the initial open via flexible width/height.
  1738. * @template THIS
  1739. * @this {THIS}
  1740. * @param {?=} growAfterOpen
  1741. * @return {THIS}
  1742. */
  1743. withGrowAfterOpen(growAfterOpen = true) {
  1744. (/** @type {?} */ (this))._growAfterOpen = growAfterOpen;
  1745. return (/** @type {?} */ (this));
  1746. }
  1747. /**
  1748. * Sets whether the overlay can be pushed on-screen if none of the provided positions fit.
  1749. * @template THIS
  1750. * @this {THIS}
  1751. * @param {?=} canPush
  1752. * @return {THIS}
  1753. */
  1754. withPush(canPush = true) {
  1755. (/** @type {?} */ (this))._canPush = canPush;
  1756. return (/** @type {?} */ (this));
  1757. }
  1758. /**
  1759. * Sets whether the overlay's position should be locked in after it is positioned
  1760. * initially. When an overlay is locked in, it won't attempt to reposition itself
  1761. * when the position is re-applied (e.g. when the user scrolls away).
  1762. * @template THIS
  1763. * @this {THIS}
  1764. * @param {?=} isLocked Whether the overlay should locked in.
  1765. * @return {THIS}
  1766. */
  1767. withLockedPosition(isLocked = true) {
  1768. (/** @type {?} */ (this))._positionLocked = isLocked;
  1769. return (/** @type {?} */ (this));
  1770. }
  1771. /**
  1772. * Sets the origin, relative to which to position the overlay.
  1773. * Using an element origin is useful for building components that need to be positioned
  1774. * relatively to a trigger (e.g. dropdown menus or tooltips), whereas using a point can be
  1775. * used for cases like contextual menus which open relative to the user's pointer.
  1776. * @template THIS
  1777. * @this {THIS}
  1778. * @param {?} origin Reference to the new origin.
  1779. * @return {THIS}
  1780. */
  1781. setOrigin(origin) {
  1782. (/** @type {?} */ (this))._origin = origin;
  1783. return (/** @type {?} */ (this));
  1784. }
  1785. /**
  1786. * Sets the default offset for the overlay's connection point on the x-axis.
  1787. * @template THIS
  1788. * @this {THIS}
  1789. * @param {?} offset New offset in the X axis.
  1790. * @return {THIS}
  1791. */
  1792. withDefaultOffsetX(offset) {
  1793. (/** @type {?} */ (this))._offsetX = offset;
  1794. return (/** @type {?} */ (this));
  1795. }
  1796. /**
  1797. * Sets the default offset for the overlay's connection point on the y-axis.
  1798. * @template THIS
  1799. * @this {THIS}
  1800. * @param {?} offset New offset in the Y axis.
  1801. * @return {THIS}
  1802. */
  1803. withDefaultOffsetY(offset) {
  1804. (/** @type {?} */ (this))._offsetY = offset;
  1805. return (/** @type {?} */ (this));
  1806. }
  1807. /**
  1808. * Configures that the position strategy should set a `transform-origin` on some elements
  1809. * inside the overlay, depending on the current position that is being applied. This is
  1810. * useful for the cases where the origin of an animation can change depending on the
  1811. * alignment of the overlay.
  1812. * @template THIS
  1813. * @this {THIS}
  1814. * @param {?} selector CSS selector that will be used to find the target
  1815. * elements onto which to set the transform origin.
  1816. * @return {THIS}
  1817. */
  1818. withTransformOriginOn(selector) {
  1819. (/** @type {?} */ (this))._transformOriginSelector = selector;
  1820. return (/** @type {?} */ (this));
  1821. }
  1822. /**
  1823. * Gets the (x, y) coordinate of a connection point on the origin based on a relative position.
  1824. * @private
  1825. * @param {?} originRect
  1826. * @param {?} pos
  1827. * @return {?}
  1828. */
  1829. _getOriginPoint(originRect, pos) {
  1830. /** @type {?} */
  1831. let x;
  1832. if (pos.originX == 'center') {
  1833. // Note: when centering we should always use the `left`
  1834. // offset, otherwise the position will be wrong in RTL.
  1835. x = originRect.left + (originRect.width / 2);
  1836. }
  1837. else {
  1838. /** @type {?} */
  1839. const startX = this._isRtl() ? originRect.right : originRect.left;
  1840. /** @type {?} */
  1841. const endX = this._isRtl() ? originRect.left : originRect.right;
  1842. x = pos.originX == 'start' ? startX : endX;
  1843. }
  1844. /** @type {?} */
  1845. let y;
  1846. if (pos.originY == 'center') {
  1847. y = originRect.top + (originRect.height / 2);
  1848. }
  1849. else {
  1850. y = pos.originY == 'top' ? originRect.top : originRect.bottom;
  1851. }
  1852. return { x, y };
  1853. }
  1854. /**
  1855. * Gets the (x, y) coordinate of the top-left corner of the overlay given a given position and
  1856. * origin point to which the overlay should be connected.
  1857. * @private
  1858. * @param {?} originPoint
  1859. * @param {?} overlayRect
  1860. * @param {?} pos
  1861. * @return {?}
  1862. */
  1863. _getOverlayPoint(originPoint, overlayRect, pos) {
  1864. // Calculate the (overlayStartX, overlayStartY), the start of the
  1865. // potential overlay position relative to the origin point.
  1866. /** @type {?} */
  1867. let overlayStartX;
  1868. if (pos.overlayX == 'center') {
  1869. overlayStartX = -overlayRect.width / 2;
  1870. }
  1871. else if (pos.overlayX === 'start') {
  1872. overlayStartX = this._isRtl() ? -overlayRect.width : 0;
  1873. }
  1874. else {
  1875. overlayStartX = this._isRtl() ? 0 : -overlayRect.width;
  1876. }
  1877. /** @type {?} */
  1878. let overlayStartY;
  1879. if (pos.overlayY == 'center') {
  1880. overlayStartY = -overlayRect.height / 2;
  1881. }
  1882. else {
  1883. overlayStartY = pos.overlayY == 'top' ? 0 : -overlayRect.height;
  1884. }
  1885. // The (x, y) coordinates of the overlay.
  1886. return {
  1887. x: originPoint.x + overlayStartX,
  1888. y: originPoint.y + overlayStartY,
  1889. };
  1890. }
  1891. /**
  1892. * Gets how well an overlay at the given point will fit within the viewport.
  1893. * @private
  1894. * @param {?} point
  1895. * @param {?} overlay
  1896. * @param {?} viewport
  1897. * @param {?} position
  1898. * @return {?}
  1899. */
  1900. _getOverlayFit(point, overlay, viewport, position) {
  1901. let { x, y } = point;
  1902. /** @type {?} */
  1903. let offsetX = this._getOffset(position, 'x');
  1904. /** @type {?} */
  1905. let offsetY = this._getOffset(position, 'y');
  1906. // Account for the offsets since they could push the overlay out of the viewport.
  1907. if (offsetX) {
  1908. x += offsetX;
  1909. }
  1910. if (offsetY) {
  1911. y += offsetY;
  1912. }
  1913. // How much the overlay would overflow at this position, on each side.
  1914. /** @type {?} */
  1915. let leftOverflow = 0 - x;
  1916. /** @type {?} */
  1917. let rightOverflow = (x + overlay.width) - viewport.width;
  1918. /** @type {?} */
  1919. let topOverflow = 0 - y;
  1920. /** @type {?} */
  1921. let bottomOverflow = (y + overlay.height) - viewport.height;
  1922. // Visible parts of the element on each axis.
  1923. /** @type {?} */
  1924. let visibleWidth = this._subtractOverflows(overlay.width, leftOverflow, rightOverflow);
  1925. /** @type {?} */
  1926. let visibleHeight = this._subtractOverflows(overlay.height, topOverflow, bottomOverflow);
  1927. /** @type {?} */
  1928. let visibleArea = visibleWidth * visibleHeight;
  1929. return {
  1930. visibleArea,
  1931. isCompletelyWithinViewport: (overlay.width * overlay.height) === visibleArea,
  1932. fitsInViewportVertically: visibleHeight === overlay.height,
  1933. fitsInViewportHorizontally: visibleWidth == overlay.width,
  1934. };
  1935. }
  1936. /**
  1937. * Whether the overlay can fit within the viewport when it may resize either its width or height.
  1938. * @private
  1939. * @param {?} fit How well the overlay fits in the viewport at some position.
  1940. * @param {?} point The (x, y) coordinates of the overlat at some position.
  1941. * @param {?} viewport The geometry of the viewport.
  1942. * @return {?}
  1943. */
  1944. _canFitWithFlexibleDimensions(fit, point, viewport) {
  1945. if (this._hasFlexibleDimensions) {
  1946. /** @type {?} */
  1947. const availableHeight = viewport.bottom - point.y;
  1948. /** @type {?} */
  1949. const availableWidth = viewport.right - point.x;
  1950. /** @type {?} */
  1951. const minHeight = this._overlayRef.getConfig().minHeight;
  1952. /** @type {?} */
  1953. const minWidth = this._overlayRef.getConfig().minWidth;
  1954. /** @type {?} */
  1955. const verticalFit = fit.fitsInViewportVertically ||
  1956. (minHeight != null && minHeight <= availableHeight);
  1957. /** @type {?} */
  1958. const horizontalFit = fit.fitsInViewportHorizontally ||
  1959. (minWidth != null && minWidth <= availableWidth);
  1960. return verticalFit && horizontalFit;
  1961. }
  1962. return false;
  1963. }
  1964. /**
  1965. * Gets the point at which the overlay can be "pushed" on-screen. If the overlay is larger than
  1966. * the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
  1967. * right and bottom).
  1968. *
  1969. * @private
  1970. * @param {?} start Starting point from which the overlay is pushed.
  1971. * @param {?} overlay Dimensions of the overlay.
  1972. * @param {?} scrollPosition Current viewport scroll position.
  1973. * @return {?} The point at which to position the overlay after pushing. This is effectively a new
  1974. * originPoint.
  1975. */
  1976. _pushOverlayOnScreen(start, overlay, scrollPosition) {
  1977. // If the position is locked and we've pushed the overlay already, reuse the previous push
  1978. // amount, rather than pushing it again. If we were to continue pushing, the element would
  1979. // remain in the viewport, which goes against the expectations when position locking is enabled.
  1980. if (this._previousPushAmount && this._positionLocked) {
  1981. return {
  1982. x: start.x + this._previousPushAmount.x,
  1983. y: start.y + this._previousPushAmount.y
  1984. };
  1985. }
  1986. /** @type {?} */
  1987. const viewport = this._viewportRect;
  1988. // Determine how much the overlay goes outside the viewport on each
  1989. // side, which we'll use to decide which direction to push it.
  1990. /** @type {?} */
  1991. const overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
  1992. /** @type {?} */
  1993. const overflowBottom = Math.max(start.y + overlay.height - viewport.bottom, 0);
  1994. /** @type {?} */
  1995. const overflowTop = Math.max(viewport.top - scrollPosition.top - start.y, 0);
  1996. /** @type {?} */
  1997. const overflowLeft = Math.max(viewport.left - scrollPosition.left - start.x, 0);
  1998. // Amount by which to push the overlay in each axis such that it remains on-screen.
  1999. /** @type {?} */
  2000. let pushX = 0;
  2001. /** @type {?} */
  2002. let pushY = 0;
  2003. // If the overlay fits completely within the bounds of the viewport, push it from whichever
  2004. // direction is goes off-screen. Otherwise, push the top-left corner such that its in the
  2005. // viewport and allow for the trailing end of the overlay to go out of bounds.
  2006. if (overlay.width <= viewport.width) {
  2007. pushX = overflowLeft || -overflowRight;
  2008. }
  2009. else {
  2010. pushX = start.x < this._viewportMargin ? (viewport.left - scrollPosition.left) - start.x : 0;
  2011. }
  2012. if (overlay.height <= viewport.height) {
  2013. pushY = overflowTop || -overflowBottom;
  2014. }
  2015. else {
  2016. pushY = start.y < this._viewportMargin ? (viewport.top - scrollPosition.top) - start.y : 0;
  2017. }
  2018. this._previousPushAmount = { x: pushX, y: pushY };
  2019. return {
  2020. x: start.x + pushX,
  2021. y: start.y + pushY,
  2022. };
  2023. }
  2024. /**
  2025. * Applies a computed position to the overlay and emits a position change.
  2026. * @private
  2027. * @param {?} position The position preference
  2028. * @param {?} originPoint The point on the origin element where the overlay is connected.
  2029. * @return {?}
  2030. */
  2031. _applyPosition(position, originPoint) {
  2032. this._setTransformOrigin(position);
  2033. this._setOverlayElementStyles(originPoint, position);
  2034. this._setBoundingBoxStyles(originPoint, position);
  2035. if (position.panelClass) {
  2036. this._addPanelClasses(position.panelClass);
  2037. }
  2038. // Save the last connected position in case the position needs to be re-calculated.
  2039. this._lastPosition = position;
  2040. // Notify that the position has been changed along with its change properties.
  2041. // We only emit if we've got any subscriptions, because the scroll visibility
  2042. // calculcations can be somewhat expensive.
  2043. if (this._positionChanges.observers.length) {
  2044. /** @type {?} */
  2045. const scrollableViewProperties = this._getScrollVisibility();
  2046. /** @type {?} */
  2047. const changeEvent = new ConnectedOverlayPositionChange(position, scrollableViewProperties);
  2048. this._positionChanges.next(changeEvent);
  2049. }
  2050. this._isInitialRender = false;
  2051. }
  2052. /**
  2053. * Sets the transform origin based on the configured selector and the passed-in position.
  2054. * @private
  2055. * @param {?} position
  2056. * @return {?}
  2057. */
  2058. _setTransformOrigin(position) {
  2059. if (!this._transformOriginSelector) {
  2060. return;
  2061. }
  2062. /** @type {?} */
  2063. const elements = (/** @type {?} */ (this._boundingBox)).querySelectorAll(this._transformOriginSelector);
  2064. /** @type {?} */
  2065. let xOrigin;
  2066. /** @type {?} */
  2067. let yOrigin = position.overlayY;
  2068. if (position.overlayX === 'center') {
  2069. xOrigin = 'center';
  2070. }
  2071. else if (this._isRtl()) {
  2072. xOrigin = position.overlayX === 'start' ? 'right' : 'left';
  2073. }
  2074. else {
  2075. xOrigin = position.overlayX === 'start' ? 'left' : 'right';
  2076. }
  2077. for (let i = 0; i < elements.length; i++) {
  2078. elements[i].style.transformOrigin = `${xOrigin} ${yOrigin}`;
  2079. }
  2080. }
  2081. /**
  2082. * Gets the position and size of the overlay's sizing container.
  2083. *
  2084. * This method does no measuring and applies no styles so that we can cheaply compute the
  2085. * bounds for all positions and choose the best fit based on these results.
  2086. * @private
  2087. * @param {?} origin
  2088. * @param {?} position
  2089. * @return {?}
  2090. */
  2091. _calculateBoundingBoxRect(origin, position) {
  2092. /** @type {?} */
  2093. const viewport = this._viewportRect;
  2094. /** @type {?} */
  2095. const isRtl = this._isRtl();
  2096. /** @type {?} */
  2097. let height;
  2098. /** @type {?} */
  2099. let top;
  2100. /** @type {?} */
  2101. let bottom;
  2102. if (position.overlayY === 'top') {
  2103. // Overlay is opening "downward" and thus is bound by the bottom viewport edge.
  2104. top = origin.y;
  2105. height = viewport.height - top + this._viewportMargin;
  2106. }
  2107. else if (position.overlayY === 'bottom') {
  2108. // Overlay is opening "upward" and thus is bound by the top viewport edge. We need to add
  2109. // the viewport margin back in, because the viewport rect is narrowed down to remove the
  2110. // margin, whereas the `origin` position is calculated based on its `ClientRect`.
  2111. bottom = viewport.height - origin.y + this._viewportMargin * 2;
  2112. height = viewport.height - bottom + this._viewportMargin;
  2113. }
  2114. else {
  2115. // If neither top nor bottom, it means that the overlay is vertically centered on the
  2116. // origin point. Note that we want the position relative to the viewport, rather than
  2117. // the page, which is why we don't use something like `viewport.bottom - origin.y` and
  2118. // `origin.y - viewport.top`.
  2119. /** @type {?} */
  2120. const smallestDistanceToViewportEdge = Math.min(viewport.bottom - origin.y + viewport.top, origin.y);
  2121. /** @type {?} */
  2122. const previousHeight = this._lastBoundingBoxSize.height;
  2123. height = smallestDistanceToViewportEdge * 2;
  2124. top = origin.y - smallestDistanceToViewportEdge;
  2125. if (height > previousHeight && !this._isInitialRender && !this._growAfterOpen) {
  2126. top = origin.y - (previousHeight / 2);
  2127. }
  2128. }
  2129. // The overlay is opening 'right-ward' (the content flows to the right).
  2130. /** @type {?} */
  2131. const isBoundedByRightViewportEdge = (position.overlayX === 'start' && !isRtl) ||
  2132. (position.overlayX === 'end' && isRtl);
  2133. // The overlay is opening 'left-ward' (the content flows to the left).
  2134. /** @type {?} */
  2135. const isBoundedByLeftViewportEdge = (position.overlayX === 'end' && !isRtl) ||
  2136. (position.overlayX === 'start' && isRtl);
  2137. /** @type {?} */
  2138. let width;
  2139. /** @type {?} */
  2140. let left;
  2141. /** @type {?} */
  2142. let right;
  2143. if (isBoundedByLeftViewportEdge) {
  2144. right = viewport.width - origin.x + this._viewportMargin;
  2145. width = origin.x - this._viewportMargin;
  2146. }
  2147. else if (isBoundedByRightViewportEdge) {
  2148. left = origin.x;
  2149. width = viewport.right - origin.x;
  2150. }
  2151. else {
  2152. // If neither start nor end, it means that the overlay is horizontally centered on the
  2153. // origin point. Note that we want the position relative to the viewport, rather than
  2154. // the page, which is why we don't use something like `viewport.right - origin.x` and
  2155. // `origin.x - viewport.left`.
  2156. /** @type {?} */
  2157. const smallestDistanceToViewportEdge = Math.min(viewport.right - origin.x + viewport.left, origin.x);
  2158. /** @type {?} */
  2159. const previousWidth = this._lastBoundingBoxSize.width;
  2160. width = smallestDistanceToViewportEdge * 2;
  2161. left = origin.x - smallestDistanceToViewportEdge;
  2162. if (width > previousWidth && !this._isInitialRender && !this._growAfterOpen) {
  2163. left = origin.x - (previousWidth / 2);
  2164. }
  2165. }
  2166. return { top: (/** @type {?} */ (top)), left: (/** @type {?} */ (left)), bottom: (/** @type {?} */ (bottom)), right: (/** @type {?} */ (right)), width, height };
  2167. }
  2168. /**
  2169. * Sets the position and size of the overlay's sizing wrapper. The wrapper is positioned on the
  2170. * origin's connection point and stetches to the bounds of the viewport.
  2171. *
  2172. * @private
  2173. * @param {?} origin The point on the origin element where the overlay is connected.
  2174. * @param {?} position The position preference
  2175. * @return {?}
  2176. */
  2177. _setBoundingBoxStyles(origin, position) {
  2178. /** @type {?} */
  2179. const boundingBoxRect = this._calculateBoundingBoxRect(origin, position);
  2180. // It's weird if the overlay *grows* while scrolling, so we take the last size into account
  2181. // when applying a new size.
  2182. if (!this._isInitialRender && !this._growAfterOpen) {
  2183. boundingBoxRect.height = Math.min(boundingBoxRect.height, this._lastBoundingBoxSize.height);
  2184. boundingBoxRect.width = Math.min(boundingBoxRect.width, this._lastBoundingBoxSize.width);
  2185. }
  2186. /** @type {?} */
  2187. const styles = (/** @type {?} */ ({}));
  2188. if (this._hasExactPosition()) {
  2189. styles.top = styles.left = '0';
  2190. styles.bottom = styles.right = '';
  2191. styles.width = styles.height = '100%';
  2192. }
  2193. else {
  2194. /** @type {?} */
  2195. const maxHeight = this._overlayRef.getConfig().maxHeight;
  2196. /** @type {?} */
  2197. const maxWidth = this._overlayRef.getConfig().maxWidth;
  2198. styles.height = coerceCssPixelValue(boundingBoxRect.height);
  2199. styles.top = coerceCssPixelValue(boundingBoxRect.top);
  2200. styles.bottom = coerceCssPixelValue(boundingBoxRect.bottom);
  2201. styles.width = coerceCssPixelValue(boundingBoxRect.width);
  2202. styles.left = coerceCssPixelValue(boundingBoxRect.left);
  2203. styles.right = coerceCssPixelValue(boundingBoxRect.right);
  2204. // Push the pane content towards the proper direction.
  2205. if (position.overlayX === 'center') {
  2206. styles.alignItems = 'center';
  2207. }
  2208. else {
  2209. styles.alignItems = position.overlayX === 'end' ? 'flex-end' : 'flex-start';
  2210. }
  2211. if (position.overlayY === 'center') {
  2212. styles.justifyContent = 'center';
  2213. }
  2214. else {
  2215. styles.justifyContent = position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';
  2216. }
  2217. if (maxHeight) {
  2218. styles.maxHeight = coerceCssPixelValue(maxHeight);
  2219. }
  2220. if (maxWidth) {
  2221. styles.maxWidth = coerceCssPixelValue(maxWidth);
  2222. }
  2223. }
  2224. this._lastBoundingBoxSize = boundingBoxRect;
  2225. extendStyles((/** @type {?} */ (this._boundingBox)).style, styles);
  2226. }
  2227. /**
  2228. * Resets the styles for the bounding box so that a new positioning can be computed.
  2229. * @private
  2230. * @return {?}
  2231. */
  2232. _resetBoundingBoxStyles() {
  2233. extendStyles((/** @type {?} */ (this._boundingBox)).style, (/** @type {?} */ ({
  2234. top: '0',
  2235. left: '0',
  2236. right: '0',
  2237. bottom: '0',
  2238. height: '',
  2239. width: '',
  2240. alignItems: '',
  2241. justifyContent: '',
  2242. })));
  2243. }
  2244. /**
  2245. * Resets the styles for the overlay pane so that a new positioning can be computed.
  2246. * @private
  2247. * @return {?}
  2248. */
  2249. _resetOverlayElementStyles() {
  2250. extendStyles(this._pane.style, (/** @type {?} */ ({
  2251. top: '',
  2252. left: '',
  2253. bottom: '',
  2254. right: '',
  2255. position: '',
  2256. transform: '',
  2257. })));
  2258. }
  2259. /**
  2260. * Sets positioning styles to the overlay element.
  2261. * @private
  2262. * @param {?} originPoint
  2263. * @param {?} position
  2264. * @return {?}
  2265. */
  2266. _setOverlayElementStyles(originPoint, position) {
  2267. /** @type {?} */
  2268. const styles = (/** @type {?} */ ({}));
  2269. if (this._hasExactPosition()) {
  2270. /** @type {?} */
  2271. const scrollPosition = this._viewportRuler.getViewportScrollPosition();
  2272. extendStyles(styles, this._getExactOverlayY(position, originPoint, scrollPosition));
  2273. extendStyles(styles, this._getExactOverlayX(position, originPoint, scrollPosition));
  2274. }
  2275. else {
  2276. styles.position = 'static';
  2277. }
  2278. // Use a transform to apply the offsets. We do this because the `center` positions rely on
  2279. // being in the normal flex flow and setting a `top` / `left` at all will completely throw
  2280. // off the position. We also can't use margins, because they won't have an effect in some
  2281. // cases where the element doesn't have anything to "push off of". Finally, this works
  2282. // better both with flexible and non-flexible positioning.
  2283. /** @type {?} */
  2284. let transformString = '';
  2285. /** @type {?} */
  2286. let offsetX = this._getOffset(position, 'x');
  2287. /** @type {?} */
  2288. let offsetY = this._getOffset(position, 'y');
  2289. if (offsetX) {
  2290. transformString += `translateX(${offsetX}px) `;
  2291. }
  2292. if (offsetY) {
  2293. transformString += `translateY(${offsetY}px)`;
  2294. }
  2295. styles.transform = transformString.trim();
  2296. // If a maxWidth or maxHeight is specified on the overlay, we remove them. We do this because
  2297. // we need these values to both be set to "100%" for the automatic flexible sizing to work.
  2298. // The maxHeight and maxWidth are set on the boundingBox in order to enforce the constraint.
  2299. if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxHeight) {
  2300. styles.maxHeight = '';
  2301. }
  2302. if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxWidth) {
  2303. styles.maxWidth = '';
  2304. }
  2305. extendStyles(this._pane.style, styles);
  2306. }
  2307. /**
  2308. * Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing.
  2309. * @private
  2310. * @param {?} position
  2311. * @param {?} originPoint
  2312. * @param {?} scrollPosition
  2313. * @return {?}
  2314. */
  2315. _getExactOverlayY(position, originPoint, scrollPosition) {
  2316. // Reset any existing styles. This is necessary in case the
  2317. // preferred position has changed since the last `apply`.
  2318. /** @type {?} */
  2319. let styles = (/** @type {?} */ ({ top: null, bottom: null }));
  2320. /** @type {?} */
  2321. let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
  2322. if (this._isPushed) {
  2323. overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
  2324. }
  2325. /** @type {?} */
  2326. let virtualKeyboardOffset = this._overlayContainer.getContainerElement().getBoundingClientRect().top;
  2327. // Normally this would be zero, however when the overlay is attached to an input (e.g. in an
  2328. // autocomplete), mobile browsers will shift everything in order to put the input in the middle
  2329. // of the screen and to make space for the virtual keyboard. We need to account for this offset,
  2330. // otherwise our positioning will be thrown off.
  2331. overlayPoint.y -= virtualKeyboardOffset;
  2332. // We want to set either `top` or `bottom` based on whether the overlay wants to appear
  2333. // above or below the origin and the direction in which the element will expand.
  2334. if (position.overlayY === 'bottom') {
  2335. // When using `bottom`, we adjust the y position such that it is the distance
  2336. // from the bottom of the viewport rather than the top.
  2337. /** @type {?} */
  2338. const documentHeight = (/** @type {?} */ (this._document.documentElement)).clientHeight;
  2339. styles.bottom = `${documentHeight - (overlayPoint.y + this._overlayRect.height)}px`;
  2340. }
  2341. else {
  2342. styles.top = coerceCssPixelValue(overlayPoint.y);
  2343. }
  2344. return styles;
  2345. }
  2346. /**
  2347. * Gets the exact left/right for the overlay when not using flexible sizing or when pushing.
  2348. * @private
  2349. * @param {?} position
  2350. * @param {?} originPoint
  2351. * @param {?} scrollPosition
  2352. * @return {?}
  2353. */
  2354. _getExactOverlayX(position, originPoint, scrollPosition) {
  2355. // Reset any existing styles. This is necessary in case the preferred position has
  2356. // changed since the last `apply`.
  2357. /** @type {?} */
  2358. let styles = (/** @type {?} */ ({ left: null, right: null }));
  2359. /** @type {?} */
  2360. let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
  2361. if (this._isPushed) {
  2362. overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
  2363. }
  2364. // We want to set either `left` or `right` based on whether the overlay wants to appear "before"
  2365. // or "after" the origin, which determines the direction in which the element will expand.
  2366. // For the horizontal axis, the meaning of "before" and "after" change based on whether the
  2367. // page is in RTL or LTR.
  2368. /** @type {?} */
  2369. let horizontalStyleProperty;
  2370. if (this._isRtl()) {
  2371. horizontalStyleProperty = position.overlayX === 'end' ? 'left' : 'right';
  2372. }
  2373. else {
  2374. horizontalStyleProperty = position.overlayX === 'end' ? 'right' : 'left';
  2375. }
  2376. // When we're setting `right`, we adjust the x position such that it is the distance
  2377. // from the right edge of the viewport rather than the left edge.
  2378. if (horizontalStyleProperty === 'right') {
  2379. /** @type {?} */
  2380. const documentWidth = (/** @type {?} */ (this._document.documentElement)).clientWidth;
  2381. styles.right = `${documentWidth - (overlayPoint.x + this._overlayRect.width)}px`;
  2382. }
  2383. else {
  2384. styles.left = coerceCssPixelValue(overlayPoint.x);
  2385. }
  2386. return styles;
  2387. }
  2388. /**
  2389. * Gets the view properties of the trigger and overlay, including whether they are clipped
  2390. * or completely outside the view of any of the strategy's scrollables.
  2391. * @private
  2392. * @return {?}
  2393. */
  2394. _getScrollVisibility() {
  2395. // Note: needs fresh rects since the position could've changed.
  2396. /** @type {?} */
  2397. const originBounds = this._getOriginRect();
  2398. /** @type {?} */
  2399. const overlayBounds = this._pane.getBoundingClientRect();
  2400. // TODO(jelbourn): instead of needing all of the client rects for these scrolling containers
  2401. // every time, we should be able to use the scrollTop of the containers if the size of those
  2402. // containers hasn't changed.
  2403. /** @type {?} */
  2404. const scrollContainerBounds = this._scrollables.map((/**
  2405. * @param {?} scrollable
  2406. * @return {?}
  2407. */
  2408. scrollable => {
  2409. return scrollable.getElementRef().nativeElement.getBoundingClientRect();
  2410. }));
  2411. return {
  2412. isOriginClipped: isElementClippedByScrolling(originBounds, scrollContainerBounds),
  2413. isOriginOutsideView: isElementScrolledOutsideView(originBounds, scrollContainerBounds),
  2414. isOverlayClipped: isElementClippedByScrolling(overlayBounds, scrollContainerBounds),
  2415. isOverlayOutsideView: isElementScrolledOutsideView(overlayBounds, scrollContainerBounds),
  2416. };
  2417. }
  2418. /**
  2419. * Subtracts the amount that an element is overflowing on an axis from its length.
  2420. * @private
  2421. * @param {?} length
  2422. * @param {...?} overflows
  2423. * @return {?}
  2424. */
  2425. _subtractOverflows(length, ...overflows) {
  2426. return overflows.reduce((/**
  2427. * @param {?} currentValue
  2428. * @param {?} currentOverflow
  2429. * @return {?}
  2430. */
  2431. (currentValue, currentOverflow) => {
  2432. return currentValue - Math.max(currentOverflow, 0);
  2433. }), length);
  2434. }
  2435. /**
  2436. * Narrows the given viewport rect by the current _viewportMargin.
  2437. * @private
  2438. * @return {?}
  2439. */
  2440. _getNarrowedViewportRect() {
  2441. // We recalculate the viewport rect here ourselves, rather than using the ViewportRuler,
  2442. // because we want to use the `clientWidth` and `clientHeight` as the base. The difference
  2443. // being that the client properties don't include the scrollbar, as opposed to `innerWidth`
  2444. // and `innerHeight` that do. This is necessary, because the overlay container uses
  2445. // 100% `width` and `height` which don't include the scrollbar either.
  2446. /** @type {?} */
  2447. const width = (/** @type {?} */ (this._document.documentElement)).clientWidth;
  2448. /** @type {?} */
  2449. const height = (/** @type {?} */ (this._document.documentElement)).clientHeight;
  2450. /** @type {?} */
  2451. const scrollPosition = this._viewportRuler.getViewportScrollPosition();
  2452. return {
  2453. top: scrollPosition.top + this._viewportMargin,
  2454. left: scrollPosition.left + this._viewportMargin,
  2455. right: scrollPosition.left + width - this._viewportMargin,
  2456. bottom: scrollPosition.top + height - this._viewportMargin,
  2457. width: width - (2 * this._viewportMargin),
  2458. height: height - (2 * this._viewportMargin),
  2459. };
  2460. }
  2461. /**
  2462. * Whether the we're dealing with an RTL context
  2463. * @private
  2464. * @return {?}
  2465. */
  2466. _isRtl() {
  2467. return this._overlayRef.getDirection() === 'rtl';
  2468. }
  2469. /**
  2470. * Determines whether the overlay uses exact or flexible positioning.
  2471. * @private
  2472. * @return {?}
  2473. */
  2474. _hasExactPosition() {
  2475. return !this._hasFlexibleDimensions || this._isPushed;
  2476. }
  2477. /**
  2478. * Retrieves the offset of a position along the x or y axis.
  2479. * @private
  2480. * @param {?} position
  2481. * @param {?} axis
  2482. * @return {?}
  2483. */
  2484. _getOffset(position, axis) {
  2485. if (axis === 'x') {
  2486. // We don't do something like `position['offset' + axis]` in
  2487. // order to avoid breking minifiers that rename properties.
  2488. return position.offsetX == null ? this._offsetX : position.offsetX;
  2489. }
  2490. return position.offsetY == null ? this._offsetY : position.offsetY;
  2491. }
  2492. /**
  2493. * Validates that the current position match the expected values.
  2494. * @private
  2495. * @return {?}
  2496. */
  2497. _validatePositions() {
  2498. if (!this._preferredPositions.length) {
  2499. throw Error('FlexibleConnectedPositionStrategy: At least one position is required.');
  2500. }
  2501. // TODO(crisbeto): remove these once Angular's template type
  2502. // checking is advanced enough to catch these cases.
  2503. this._preferredPositions.forEach((/**
  2504. * @param {?} pair
  2505. * @return {?}
  2506. */
  2507. pair => {
  2508. validateHorizontalPosition('originX', pair.originX);
  2509. validateVerticalPosition('originY', pair.originY);
  2510. validateHorizontalPosition('overlayX', pair.overlayX);
  2511. validateVerticalPosition('overlayY', pair.overlayY);
  2512. }));
  2513. }
  2514. /**
  2515. * Adds a single CSS class or an array of classes on the overlay panel.
  2516. * @private
  2517. * @param {?} cssClasses
  2518. * @return {?}
  2519. */
  2520. _addPanelClasses(cssClasses) {
  2521. if (this._pane) {
  2522. coerceArray(cssClasses).forEach((/**
  2523. * @param {?} cssClass
  2524. * @return {?}
  2525. */
  2526. cssClass => {
  2527. if (cssClass !== '' && this._appliedPanelClasses.indexOf(cssClass) === -1) {
  2528. this._appliedPanelClasses.push(cssClass);
  2529. this._pane.classList.add(cssClass);
  2530. }
  2531. }));
  2532. }
  2533. }
  2534. /**
  2535. * Clears the classes that the position strategy has applied from the overlay panel.
  2536. * @private
  2537. * @return {?}
  2538. */
  2539. _clearPanelClasses() {
  2540. if (this._pane) {
  2541. this._appliedPanelClasses.forEach((/**
  2542. * @param {?} cssClass
  2543. * @return {?}
  2544. */
  2545. cssClass => {
  2546. this._pane.classList.remove(cssClass);
  2547. }));
  2548. this._appliedPanelClasses = [];
  2549. }
  2550. }
  2551. /**
  2552. * Returns the ClientRect of the current origin.
  2553. * @private
  2554. * @return {?}
  2555. */
  2556. _getOriginRect() {
  2557. /** @type {?} */
  2558. const origin = this._origin;
  2559. if (origin instanceof ElementRef) {
  2560. return origin.nativeElement.getBoundingClientRect();
  2561. }
  2562. if (origin instanceof HTMLElement) {
  2563. return origin.getBoundingClientRect();
  2564. }
  2565. /** @type {?} */
  2566. const width = origin.width || 0;
  2567. /** @type {?} */
  2568. const height = origin.height || 0;
  2569. // If the origin is a point, return a client rect as if it was a 0x0 element at the point.
  2570. return {
  2571. top: origin.y,
  2572. bottom: origin.y + height,
  2573. left: origin.x,
  2574. right: origin.x + width,
  2575. height,
  2576. width
  2577. };
  2578. }
  2579. }
  2580. /**
  2581. * Shallow-extends a stylesheet object with another stylesheet object.
  2582. * @param {?} dest
  2583. * @param {?} source
  2584. * @return {?}
  2585. */
  2586. function extendStyles(dest, source) {
  2587. for (let key in source) {
  2588. if (source.hasOwnProperty(key)) {
  2589. dest[key] = source[key];
  2590. }
  2591. }
  2592. return dest;
  2593. }
  2594. /**
  2595. * @fileoverview added by tsickle
  2596. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2597. */
  2598. /**
  2599. * A strategy for positioning overlays. Using this strategy, an overlay is given an
  2600. * implicit position relative to some origin element. The relative position is defined in terms of
  2601. * a point on the origin element that is connected to a point on the overlay element. For example,
  2602. * a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
  2603. * of the overlay.
  2604. * @deprecated Use `FlexibleConnectedPositionStrategy` instead.
  2605. * \@breaking-change 8.0.0
  2606. */
  2607. class ConnectedPositionStrategy {
  2608. /**
  2609. * @param {?} originPos
  2610. * @param {?} overlayPos
  2611. * @param {?} connectedTo
  2612. * @param {?} viewportRuler
  2613. * @param {?} document
  2614. * @param {?} platform
  2615. * @param {?} overlayContainer
  2616. */
  2617. constructor(originPos, overlayPos, connectedTo, viewportRuler, document, platform, overlayContainer) {
  2618. /**
  2619. * Ordered list of preferred positions, from most to least desirable.
  2620. */
  2621. this._preferredPositions = [];
  2622. // Since the `ConnectedPositionStrategy` is deprecated and we don't want to maintain
  2623. // the extra logic, we create an instance of the positioning strategy that has some
  2624. // defaults that make it behave as the old position strategy and to which we'll
  2625. // proxy all of the API calls.
  2626. this._positionStrategy = new FlexibleConnectedPositionStrategy(connectedTo, viewportRuler, document, platform, overlayContainer)
  2627. .withFlexibleDimensions(false)
  2628. .withPush(false)
  2629. .withViewportMargin(0);
  2630. this.withFallbackPosition(originPos, overlayPos);
  2631. }
  2632. /**
  2633. * Whether the we're dealing with an RTL context
  2634. * @return {?}
  2635. */
  2636. get _isRtl() {
  2637. return this._overlayRef.getDirection() === 'rtl';
  2638. }
  2639. /**
  2640. * Emits an event when the connection point changes.
  2641. * @return {?}
  2642. */
  2643. get onPositionChange() {
  2644. return this._positionStrategy.positionChanges;
  2645. }
  2646. /**
  2647. * Ordered list of preferred positions, from most to least desirable.
  2648. * @return {?}
  2649. */
  2650. get positions() {
  2651. return this._preferredPositions;
  2652. }
  2653. /**
  2654. * Attach this position strategy to an overlay.
  2655. * @param {?} overlayRef
  2656. * @return {?}
  2657. */
  2658. attach(overlayRef) {
  2659. this._overlayRef = overlayRef;
  2660. this._positionStrategy.attach(overlayRef);
  2661. if (this._direction) {
  2662. overlayRef.setDirection(this._direction);
  2663. this._direction = null;
  2664. }
  2665. }
  2666. /**
  2667. * Disposes all resources used by the position strategy.
  2668. * @return {?}
  2669. */
  2670. dispose() {
  2671. this._positionStrategy.dispose();
  2672. }
  2673. /**
  2674. * \@docs-private
  2675. * @return {?}
  2676. */
  2677. detach() {
  2678. this._positionStrategy.detach();
  2679. }
  2680. /**
  2681. * Updates the position of the overlay element, using whichever preferred position relative
  2682. * to the origin fits on-screen.
  2683. * \@docs-private
  2684. * @return {?}
  2685. */
  2686. apply() {
  2687. this._positionStrategy.apply();
  2688. }
  2689. /**
  2690. * Re-positions the overlay element with the trigger in its last calculated position,
  2691. * even if a position higher in the "preferred positions" list would now fit. This
  2692. * allows one to re-align the panel without changing the orientation of the panel.
  2693. * @return {?}
  2694. */
  2695. recalculateLastPosition() {
  2696. this._positionStrategy.reapplyLastPosition();
  2697. }
  2698. /**
  2699. * Sets the list of Scrollable containers that host the origin element so that
  2700. * on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
  2701. * Scrollable must be an ancestor element of the strategy's origin element.
  2702. * @param {?} scrollables
  2703. * @return {?}
  2704. */
  2705. withScrollableContainers(scrollables) {
  2706. this._positionStrategy.withScrollableContainers(scrollables);
  2707. }
  2708. /**
  2709. * Adds a new preferred fallback position.
  2710. * @template THIS
  2711. * @this {THIS}
  2712. * @param {?} originPos
  2713. * @param {?} overlayPos
  2714. * @param {?=} offsetX
  2715. * @param {?=} offsetY
  2716. * @return {THIS}
  2717. */
  2718. withFallbackPosition(originPos, overlayPos, offsetX, offsetY) {
  2719. /** @type {?} */
  2720. const position = new ConnectionPositionPair(originPos, overlayPos, offsetX, offsetY);
  2721. (/** @type {?} */ (this))._preferredPositions.push(position);
  2722. (/** @type {?} */ (this))._positionStrategy.withPositions((/** @type {?} */ (this))._preferredPositions);
  2723. return (/** @type {?} */ (this));
  2724. }
  2725. /**
  2726. * Sets the layout direction so the overlay's position can be adjusted to match.
  2727. * @template THIS
  2728. * @this {THIS}
  2729. * @param {?} dir New layout direction.
  2730. * @return {THIS}
  2731. */
  2732. withDirection(dir) {
  2733. // Since the direction might be declared before the strategy is attached,
  2734. // we save the value in a temporary property and we'll transfer it to the
  2735. // overlay ref on attachment.
  2736. if ((/** @type {?} */ (this))._overlayRef) {
  2737. (/** @type {?} */ (this))._overlayRef.setDirection(dir);
  2738. }
  2739. else {
  2740. (/** @type {?} */ (this))._direction = dir;
  2741. }
  2742. return (/** @type {?} */ (this));
  2743. }
  2744. /**
  2745. * Sets an offset for the overlay's connection point on the x-axis
  2746. * @template THIS
  2747. * @this {THIS}
  2748. * @param {?} offset New offset in the X axis.
  2749. * @return {THIS}
  2750. */
  2751. withOffsetX(offset) {
  2752. (/** @type {?} */ (this))._positionStrategy.withDefaultOffsetX(offset);
  2753. return (/** @type {?} */ (this));
  2754. }
  2755. /**
  2756. * Sets an offset for the overlay's connection point on the y-axis
  2757. * @template THIS
  2758. * @this {THIS}
  2759. * @param {?} offset New offset in the Y axis.
  2760. * @return {THIS}
  2761. */
  2762. withOffsetY(offset) {
  2763. (/** @type {?} */ (this))._positionStrategy.withDefaultOffsetY(offset);
  2764. return (/** @type {?} */ (this));
  2765. }
  2766. /**
  2767. * Sets whether the overlay's position should be locked in after it is positioned
  2768. * initially. When an overlay is locked in, it won't attempt to reposition itself
  2769. * when the position is re-applied (e.g. when the user scrolls away).
  2770. * @template THIS
  2771. * @this {THIS}
  2772. * @param {?} isLocked Whether the overlay should locked in.
  2773. * @return {THIS}
  2774. */
  2775. withLockedPosition(isLocked) {
  2776. (/** @type {?} */ (this))._positionStrategy.withLockedPosition(isLocked);
  2777. return (/** @type {?} */ (this));
  2778. }
  2779. /**
  2780. * Overwrites the current set of positions with an array of new ones.
  2781. * @template THIS
  2782. * @this {THIS}
  2783. * @param {?} positions Position pairs to be set on the strategy.
  2784. * @return {THIS}
  2785. */
  2786. withPositions(positions) {
  2787. (/** @type {?} */ (this))._preferredPositions = positions.slice();
  2788. (/** @type {?} */ (this))._positionStrategy.withPositions((/** @type {?} */ (this))._preferredPositions);
  2789. return (/** @type {?} */ (this));
  2790. }
  2791. /**
  2792. * Sets the origin element, relative to which to position the overlay.
  2793. * @template THIS
  2794. * @this {THIS}
  2795. * @param {?} origin Reference to the new origin element.
  2796. * @return {THIS}
  2797. */
  2798. setOrigin(origin) {
  2799. (/** @type {?} */ (this))._positionStrategy.setOrigin(origin);
  2800. return (/** @type {?} */ (this));
  2801. }
  2802. }
  2803. /**
  2804. * @fileoverview added by tsickle
  2805. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  2806. */
  2807. /**
  2808. * Class to be added to the overlay pane wrapper.
  2809. * @type {?}
  2810. */
  2811. const wrapperClass = 'cdk-global-overlay-wrapper';
  2812. /**
  2813. * A strategy for positioning overlays. Using this strategy, an overlay is given an
  2814. * explicit position relative to the browser's viewport. We use flexbox, instead of
  2815. * transforms, in order to avoid issues with subpixel rendering which can cause the
  2816. * element to become blurry.
  2817. */
  2818. class GlobalPositionStrategy {
  2819. constructor() {
  2820. this._cssPosition = 'static';
  2821. this._topOffset = '';
  2822. this._bottomOffset = '';
  2823. this._leftOffset = '';
  2824. this._rightOffset = '';
  2825. this._alignItems = '';
  2826. this._justifyContent = '';
  2827. this._width = '';
  2828. this._height = '';
  2829. }
  2830. /**
  2831. * @param {?} overlayRef
  2832. * @return {?}
  2833. */
  2834. attach(overlayRef) {
  2835. /** @type {?} */
  2836. const config = overlayRef.getConfig();
  2837. this._overlayRef = overlayRef;
  2838. if (this._width && !config.width) {
  2839. overlayRef.updateSize({ width: this._width });
  2840. }
  2841. if (this._height && !config.height) {
  2842. overlayRef.updateSize({ height: this._height });
  2843. }
  2844. overlayRef.hostElement.classList.add(wrapperClass);
  2845. this._isDisposed = false;
  2846. }
  2847. /**
  2848. * Sets the top position of the overlay. Clears any previously set vertical position.
  2849. * @template THIS
  2850. * @this {THIS}
  2851. * @param {?=} value New top offset.
  2852. * @return {THIS}
  2853. */
  2854. top(value = '') {
  2855. (/** @type {?} */ (this))._bottomOffset = '';
  2856. (/** @type {?} */ (this))._topOffset = value;
  2857. (/** @type {?} */ (this))._alignItems = 'flex-start';
  2858. return (/** @type {?} */ (this));
  2859. }
  2860. /**
  2861. * Sets the left position of the overlay. Clears any previously set horizontal position.
  2862. * @template THIS
  2863. * @this {THIS}
  2864. * @param {?=} value New left offset.
  2865. * @return {THIS}
  2866. */
  2867. left(value = '') {
  2868. (/** @type {?} */ (this))._rightOffset = '';
  2869. (/** @type {?} */ (this))._leftOffset = value;
  2870. (/** @type {?} */ (this))._justifyContent = 'flex-start';
  2871. return (/** @type {?} */ (this));
  2872. }
  2873. /**
  2874. * Sets the bottom position of the overlay. Clears any previously set vertical position.
  2875. * @template THIS
  2876. * @this {THIS}
  2877. * @param {?=} value New bottom offset.
  2878. * @return {THIS}
  2879. */
  2880. bottom(value = '') {
  2881. (/** @type {?} */ (this))._topOffset = '';
  2882. (/** @type {?} */ (this))._bottomOffset = value;
  2883. (/** @type {?} */ (this))._alignItems = 'flex-end';
  2884. return (/** @type {?} */ (this));
  2885. }
  2886. /**
  2887. * Sets the right position of the overlay. Clears any previously set horizontal position.
  2888. * @template THIS
  2889. * @this {THIS}
  2890. * @param {?=} value New right offset.
  2891. * @return {THIS}
  2892. */
  2893. right(value = '') {
  2894. (/** @type {?} */ (this))._leftOffset = '';
  2895. (/** @type {?} */ (this))._rightOffset = value;
  2896. (/** @type {?} */ (this))._justifyContent = 'flex-end';
  2897. return (/** @type {?} */ (this));
  2898. }
  2899. /**
  2900. * Sets the overlay width and clears any previously set width.
  2901. * @deprecated Pass the `width` through the `OverlayConfig`.
  2902. * \@breaking-change 8.0.0
  2903. * @template THIS
  2904. * @this {THIS}
  2905. * @param {?=} value New width for the overlay
  2906. * @return {THIS}
  2907. */
  2908. width(value = '') {
  2909. if ((/** @type {?} */ (this))._overlayRef) {
  2910. (/** @type {?} */ (this))._overlayRef.updateSize({ width: value });
  2911. }
  2912. else {
  2913. (/** @type {?} */ (this))._width = value;
  2914. }
  2915. return (/** @type {?} */ (this));
  2916. }
  2917. /**
  2918. * Sets the overlay height and clears any previously set height.
  2919. * @deprecated Pass the `height` through the `OverlayConfig`.
  2920. * \@breaking-change 8.0.0
  2921. * @template THIS
  2922. * @this {THIS}
  2923. * @param {?=} value New height for the overlay
  2924. * @return {THIS}
  2925. */
  2926. height(value = '') {
  2927. if ((/** @type {?} */ (this))._overlayRef) {
  2928. (/** @type {?} */ (this))._overlayRef.updateSize({ height: value });
  2929. }
  2930. else {
  2931. (/** @type {?} */ (this))._height = value;
  2932. }
  2933. return (/** @type {?} */ (this));
  2934. }
  2935. /**
  2936. * Centers the overlay horizontally with an optional offset.
  2937. * Clears any previously set horizontal position.
  2938. *
  2939. * @template THIS
  2940. * @this {THIS}
  2941. * @param {?=} offset Overlay offset from the horizontal center.
  2942. * @return {THIS}
  2943. */
  2944. centerHorizontally(offset = '') {
  2945. (/** @type {?} */ (this)).left(offset);
  2946. (/** @type {?} */ (this))._justifyContent = 'center';
  2947. return (/** @type {?} */ (this));
  2948. }
  2949. /**
  2950. * Centers the overlay vertically with an optional offset.
  2951. * Clears any previously set vertical position.
  2952. *
  2953. * @template THIS
  2954. * @this {THIS}
  2955. * @param {?=} offset Overlay offset from the vertical center.
  2956. * @return {THIS}
  2957. */
  2958. centerVertically(offset = '') {
  2959. (/** @type {?} */ (this)).top(offset);
  2960. (/** @type {?} */ (this))._alignItems = 'center';
  2961. return (/** @type {?} */ (this));
  2962. }
  2963. /**
  2964. * Apply the position to the element.
  2965. * \@docs-private
  2966. * @return {?}
  2967. */
  2968. apply() {
  2969. // Since the overlay ref applies the strategy asynchronously, it could
  2970. // have been disposed before it ends up being applied. If that is the
  2971. // case, we shouldn't do anything.
  2972. if (!this._overlayRef || !this._overlayRef.hasAttached()) {
  2973. return;
  2974. }
  2975. /** @type {?} */
  2976. const styles = this._overlayRef.overlayElement.style;
  2977. /** @type {?} */
  2978. const parentStyles = this._overlayRef.hostElement.style;
  2979. /** @type {?} */
  2980. const config = this._overlayRef.getConfig();
  2981. styles.position = this._cssPosition;
  2982. styles.marginLeft = config.width === '100%' ? '0' : this._leftOffset;
  2983. styles.marginTop = config.height === '100%' ? '0' : this._topOffset;
  2984. styles.marginBottom = this._bottomOffset;
  2985. styles.marginRight = this._rightOffset;
  2986. if (config.width === '100%') {
  2987. parentStyles.justifyContent = 'flex-start';
  2988. }
  2989. else if (this._justifyContent === 'center') {
  2990. parentStyles.justifyContent = 'center';
  2991. }
  2992. else if (this._overlayRef.getConfig().direction === 'rtl') {
  2993. // In RTL the browser will invert `flex-start` and `flex-end` automatically, but we
  2994. // don't want that because our positioning is explicitly `left` and `right`, hence
  2995. // why we do another inversion to ensure that the overlay stays in the same position.
  2996. // TODO: reconsider this if we add `start` and `end` methods.
  2997. if (this._justifyContent === 'flex-start') {
  2998. parentStyles.justifyContent = 'flex-end';
  2999. }
  3000. else if (this._justifyContent === 'flex-end') {
  3001. parentStyles.justifyContent = 'flex-start';
  3002. }
  3003. }
  3004. else {
  3005. parentStyles.justifyContent = this._justifyContent;
  3006. }
  3007. parentStyles.alignItems = config.height === '100%' ? 'flex-start' : this._alignItems;
  3008. }
  3009. /**
  3010. * Cleans up the DOM changes from the position strategy.
  3011. * \@docs-private
  3012. * @return {?}
  3013. */
  3014. dispose() {
  3015. if (this._isDisposed || !this._overlayRef) {
  3016. return;
  3017. }
  3018. /** @type {?} */
  3019. const styles = this._overlayRef.overlayElement.style;
  3020. /** @type {?} */
  3021. const parent = this._overlayRef.hostElement;
  3022. /** @type {?} */
  3023. const parentStyles = parent.style;
  3024. parent.classList.remove(wrapperClass);
  3025. parentStyles.justifyContent = parentStyles.alignItems = styles.marginTop =
  3026. styles.marginBottom = styles.marginLeft = styles.marginRight = styles.position = '';
  3027. this._overlayRef = (/** @type {?} */ (null));
  3028. this._isDisposed = true;
  3029. }
  3030. }
  3031. /**
  3032. * @fileoverview added by tsickle
  3033. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3034. */
  3035. /**
  3036. * Builder for overlay position strategy.
  3037. */
  3038. class OverlayPositionBuilder {
  3039. /**
  3040. * @param {?} _viewportRuler
  3041. * @param {?} _document
  3042. * @param {?} _platform
  3043. * @param {?} _overlayContainer
  3044. */
  3045. constructor(_viewportRuler, _document, _platform, _overlayContainer) {
  3046. this._viewportRuler = _viewportRuler;
  3047. this._document = _document;
  3048. this._platform = _platform;
  3049. this._overlayContainer = _overlayContainer;
  3050. }
  3051. /**
  3052. * Creates a global position strategy.
  3053. * @return {?}
  3054. */
  3055. global() {
  3056. return new GlobalPositionStrategy();
  3057. }
  3058. /**
  3059. * Creates a relative position strategy.
  3060. * @deprecated Use `flexibleConnectedTo` instead.
  3061. * \@breaking-change 8.0.0
  3062. * @param {?} elementRef
  3063. * @param {?} originPos
  3064. * @param {?} overlayPos
  3065. * @return {?}
  3066. */
  3067. connectedTo(elementRef, originPos, overlayPos) {
  3068. return new ConnectedPositionStrategy(originPos, overlayPos, elementRef, this._viewportRuler, this._document, this._platform, this._overlayContainer);
  3069. }
  3070. /**
  3071. * Creates a flexible position strategy.
  3072. * @param {?} origin Origin relative to which to position the overlay.
  3073. * @return {?}
  3074. */
  3075. flexibleConnectedTo(origin) {
  3076. return new FlexibleConnectedPositionStrategy(origin, this._viewportRuler, this._document, this._platform, this._overlayContainer);
  3077. }
  3078. }
  3079. OverlayPositionBuilder.decorators = [
  3080. { type: Injectable, args: [{ providedIn: 'root' },] },
  3081. ];
  3082. /** @nocollapse */
  3083. OverlayPositionBuilder.ctorParameters = () => [
  3084. { type: ViewportRuler },
  3085. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
  3086. { type: Platform },
  3087. { type: OverlayContainer }
  3088. ];
  3089. /** @nocollapse */ OverlayPositionBuilder.ngInjectableDef = ɵɵdefineInjectable({ factory: function OverlayPositionBuilder_Factory() { return new OverlayPositionBuilder(ɵɵinject(ViewportRuler), ɵɵinject(DOCUMENT), ɵɵinject(Platform), ɵɵinject(OverlayContainer)); }, token: OverlayPositionBuilder, providedIn: "root" });
  3090. /**
  3091. * @fileoverview added by tsickle
  3092. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3093. */
  3094. /**
  3095. * Next overlay unique ID.
  3096. * @type {?}
  3097. */
  3098. let nextUniqueId = 0;
  3099. // Note that Overlay is *not* scoped to the app root because the ComponentFactoryResolver
  3100. // it needs is different based on where OverlayModule is imported.
  3101. /**
  3102. * Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
  3103. * used as a low-level building block for other components. Dialogs, tooltips, menus,
  3104. * selects, etc. can all be built using overlays. The service should primarily be used by authors
  3105. * of re-usable components rather than developers building end-user applications.
  3106. *
  3107. * An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
  3108. */
  3109. class Overlay {
  3110. /**
  3111. * @param {?} scrollStrategies
  3112. * @param {?} _overlayContainer
  3113. * @param {?} _componentFactoryResolver
  3114. * @param {?} _positionBuilder
  3115. * @param {?} _keyboardDispatcher
  3116. * @param {?} _injector
  3117. * @param {?} _ngZone
  3118. * @param {?} _document
  3119. * @param {?} _directionality
  3120. * @param {?=} _location
  3121. */
  3122. constructor(scrollStrategies, _overlayContainer, _componentFactoryResolver, _positionBuilder, _keyboardDispatcher, _injector, _ngZone, _document, _directionality, _location) {
  3123. this.scrollStrategies = scrollStrategies;
  3124. this._overlayContainer = _overlayContainer;
  3125. this._componentFactoryResolver = _componentFactoryResolver;
  3126. this._positionBuilder = _positionBuilder;
  3127. this._keyboardDispatcher = _keyboardDispatcher;
  3128. this._injector = _injector;
  3129. this._ngZone = _ngZone;
  3130. this._document = _document;
  3131. this._directionality = _directionality;
  3132. this._location = _location;
  3133. }
  3134. /**
  3135. * Creates an overlay.
  3136. * @param {?=} config Configuration applied to the overlay.
  3137. * @return {?} Reference to the created overlay.
  3138. */
  3139. create(config) {
  3140. /** @type {?} */
  3141. const host = this._createHostElement();
  3142. /** @type {?} */
  3143. const pane = this._createPaneElement(host);
  3144. /** @type {?} */
  3145. const portalOutlet = this._createPortalOutlet(pane);
  3146. /** @type {?} */
  3147. const overlayConfig = new OverlayConfig(config);
  3148. overlayConfig.direction = overlayConfig.direction || this._directionality.value;
  3149. return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone, this._keyboardDispatcher, this._document, this._location);
  3150. }
  3151. /**
  3152. * Gets a position builder that can be used, via fluent API,
  3153. * to construct and configure a position strategy.
  3154. * @return {?} An overlay position builder.
  3155. */
  3156. position() {
  3157. return this._positionBuilder;
  3158. }
  3159. /**
  3160. * Creates the DOM element for an overlay and appends it to the overlay container.
  3161. * @private
  3162. * @param {?} host
  3163. * @return {?} Newly-created pane element
  3164. */
  3165. _createPaneElement(host) {
  3166. /** @type {?} */
  3167. const pane = this._document.createElement('div');
  3168. pane.id = `cdk-overlay-${nextUniqueId++}`;
  3169. pane.classList.add('cdk-overlay-pane');
  3170. host.appendChild(pane);
  3171. return pane;
  3172. }
  3173. /**
  3174. * Creates the host element that wraps around an overlay
  3175. * and can be used for advanced positioning.
  3176. * @private
  3177. * @return {?} Newly-create host element.
  3178. */
  3179. _createHostElement() {
  3180. /** @type {?} */
  3181. const host = this._document.createElement('div');
  3182. this._overlayContainer.getContainerElement().appendChild(host);
  3183. return host;
  3184. }
  3185. /**
  3186. * Create a DomPortalOutlet into which the overlay content can be loaded.
  3187. * @private
  3188. * @param {?} pane The DOM element to turn into a portal outlet.
  3189. * @return {?} A portal outlet for the given DOM element.
  3190. */
  3191. _createPortalOutlet(pane) {
  3192. // We have to resolve the ApplicationRef later in order to allow people
  3193. // to use overlay-based providers during app initialization.
  3194. if (!this._appRef) {
  3195. this._appRef = this._injector.get(ApplicationRef);
  3196. }
  3197. return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
  3198. }
  3199. }
  3200. Overlay.decorators = [
  3201. { type: Injectable },
  3202. ];
  3203. /** @nocollapse */
  3204. Overlay.ctorParameters = () => [
  3205. { type: ScrollStrategyOptions },
  3206. { type: OverlayContainer },
  3207. { type: ComponentFactoryResolver },
  3208. { type: OverlayPositionBuilder },
  3209. { type: OverlayKeyboardDispatcher },
  3210. { type: Injector },
  3211. { type: NgZone },
  3212. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
  3213. { type: Directionality },
  3214. { type: Location, decorators: [{ type: Optional }] }
  3215. ];
  3216. /**
  3217. * @fileoverview added by tsickle
  3218. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3219. */
  3220. /**
  3221. * Default set of positions for the overlay. Follows the behavior of a dropdown.
  3222. * @type {?}
  3223. */
  3224. const defaultPositionList = [
  3225. {
  3226. originX: 'start',
  3227. originY: 'bottom',
  3228. overlayX: 'start',
  3229. overlayY: 'top'
  3230. },
  3231. {
  3232. originX: 'start',
  3233. originY: 'top',
  3234. overlayX: 'start',
  3235. overlayY: 'bottom'
  3236. },
  3237. {
  3238. originX: 'end',
  3239. originY: 'top',
  3240. overlayX: 'end',
  3241. overlayY: 'bottom'
  3242. },
  3243. {
  3244. originX: 'end',
  3245. originY: 'bottom',
  3246. overlayX: 'end',
  3247. overlayY: 'top'
  3248. }
  3249. ];
  3250. /**
  3251. * Injection token that determines the scroll handling while the connected overlay is open.
  3252. * @type {?}
  3253. */
  3254. const CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY = new InjectionToken('cdk-connected-overlay-scroll-strategy');
  3255. /**
  3256. * Directive applied to an element to make it usable as an origin for an Overlay using a
  3257. * ConnectedPositionStrategy.
  3258. */
  3259. class CdkOverlayOrigin {
  3260. /**
  3261. * @param {?} elementRef
  3262. */
  3263. constructor(elementRef) {
  3264. this.elementRef = elementRef;
  3265. }
  3266. }
  3267. CdkOverlayOrigin.decorators = [
  3268. { type: Directive, args: [{
  3269. selector: '[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]',
  3270. exportAs: 'cdkOverlayOrigin',
  3271. },] },
  3272. ];
  3273. /** @nocollapse */
  3274. CdkOverlayOrigin.ctorParameters = () => [
  3275. { type: ElementRef }
  3276. ];
  3277. /**
  3278. * Directive to facilitate declarative creation of an
  3279. * Overlay using a FlexibleConnectedPositionStrategy.
  3280. */
  3281. class CdkConnectedOverlay {
  3282. // TODO(jelbourn): inputs for size, scroll behavior, animation, etc.
  3283. /**
  3284. * @param {?} _overlay
  3285. * @param {?} templateRef
  3286. * @param {?} viewContainerRef
  3287. * @param {?} scrollStrategyFactory
  3288. * @param {?} _dir
  3289. */
  3290. constructor(_overlay, templateRef, viewContainerRef, scrollStrategyFactory, _dir) {
  3291. this._overlay = _overlay;
  3292. this._dir = _dir;
  3293. this._hasBackdrop = false;
  3294. this._lockPosition = false;
  3295. this._growAfterOpen = false;
  3296. this._flexibleDimensions = false;
  3297. this._push = false;
  3298. this._backdropSubscription = Subscription.EMPTY;
  3299. /**
  3300. * Margin between the overlay and the viewport edges.
  3301. */
  3302. this.viewportMargin = 0;
  3303. /**
  3304. * Whether the overlay is open.
  3305. */
  3306. this.open = false;
  3307. /**
  3308. * Event emitted when the backdrop is clicked.
  3309. */
  3310. this.backdropClick = new EventEmitter();
  3311. /**
  3312. * Event emitted when the position has changed.
  3313. */
  3314. this.positionChange = new EventEmitter();
  3315. /**
  3316. * Event emitted when the overlay has been attached.
  3317. */
  3318. this.attach = new EventEmitter();
  3319. /**
  3320. * Event emitted when the overlay has been detached.
  3321. */
  3322. this.detach = new EventEmitter();
  3323. /**
  3324. * Emits when there are keyboard events that are targeted at the overlay.
  3325. */
  3326. this.overlayKeydown = new EventEmitter();
  3327. this._templatePortal = new TemplatePortal(templateRef, viewContainerRef);
  3328. this._scrollStrategyFactory = scrollStrategyFactory;
  3329. this.scrollStrategy = this._scrollStrategyFactory();
  3330. }
  3331. /**
  3332. * The offset in pixels for the overlay connection point on the x-axis
  3333. * @return {?}
  3334. */
  3335. get offsetX() { return this._offsetX; }
  3336. /**
  3337. * @param {?} offsetX
  3338. * @return {?}
  3339. */
  3340. set offsetX(offsetX) {
  3341. this._offsetX = offsetX;
  3342. if (this._position) {
  3343. this._updatePositionStrategy(this._position);
  3344. }
  3345. }
  3346. /**
  3347. * The offset in pixels for the overlay connection point on the y-axis
  3348. * @return {?}
  3349. */
  3350. get offsetY() { return this._offsetY; }
  3351. /**
  3352. * @param {?} offsetY
  3353. * @return {?}
  3354. */
  3355. set offsetY(offsetY) {
  3356. this._offsetY = offsetY;
  3357. if (this._position) {
  3358. this._updatePositionStrategy(this._position);
  3359. }
  3360. }
  3361. /**
  3362. * Whether or not the overlay should attach a backdrop.
  3363. * @return {?}
  3364. */
  3365. get hasBackdrop() { return this._hasBackdrop; }
  3366. /**
  3367. * @param {?} value
  3368. * @return {?}
  3369. */
  3370. set hasBackdrop(value) { this._hasBackdrop = coerceBooleanProperty(value); }
  3371. /**
  3372. * Whether or not the overlay should be locked when scrolling.
  3373. * @return {?}
  3374. */
  3375. get lockPosition() { return this._lockPosition; }
  3376. /**
  3377. * @param {?} value
  3378. * @return {?}
  3379. */
  3380. set lockPosition(value) { this._lockPosition = coerceBooleanProperty(value); }
  3381. /**
  3382. * Whether the overlay's width and height can be constrained to fit within the viewport.
  3383. * @return {?}
  3384. */
  3385. get flexibleDimensions() { return this._flexibleDimensions; }
  3386. /**
  3387. * @param {?} value
  3388. * @return {?}
  3389. */
  3390. set flexibleDimensions(value) {
  3391. this._flexibleDimensions = coerceBooleanProperty(value);
  3392. }
  3393. /**
  3394. * Whether the overlay can grow after the initial open when flexible positioning is turned on.
  3395. * @return {?}
  3396. */
  3397. get growAfterOpen() { return this._growAfterOpen; }
  3398. /**
  3399. * @param {?} value
  3400. * @return {?}
  3401. */
  3402. set growAfterOpen(value) { this._growAfterOpen = coerceBooleanProperty(value); }
  3403. /**
  3404. * Whether the overlay can be pushed on-screen if none of the provided positions fit.
  3405. * @return {?}
  3406. */
  3407. get push() { return this._push; }
  3408. /**
  3409. * @param {?} value
  3410. * @return {?}
  3411. */
  3412. set push(value) { this._push = coerceBooleanProperty(value); }
  3413. /**
  3414. * The associated overlay reference.
  3415. * @return {?}
  3416. */
  3417. get overlayRef() {
  3418. return this._overlayRef;
  3419. }
  3420. /**
  3421. * The element's layout direction.
  3422. * @return {?}
  3423. */
  3424. get dir() {
  3425. return this._dir ? this._dir.value : 'ltr';
  3426. }
  3427. /**
  3428. * @return {?}
  3429. */
  3430. ngOnDestroy() {
  3431. if (this._overlayRef) {
  3432. this._overlayRef.dispose();
  3433. }
  3434. this._backdropSubscription.unsubscribe();
  3435. }
  3436. /**
  3437. * @param {?} changes
  3438. * @return {?}
  3439. */
  3440. ngOnChanges(changes) {
  3441. if (this._position) {
  3442. this._updatePositionStrategy(this._position);
  3443. this._overlayRef.updateSize({
  3444. width: this.width,
  3445. minWidth: this.minWidth,
  3446. height: this.height,
  3447. minHeight: this.minHeight,
  3448. });
  3449. if (changes['origin'] && this.open) {
  3450. this._position.apply();
  3451. }
  3452. }
  3453. if (changes['open']) {
  3454. this.open ? this._attachOverlay() : this._detachOverlay();
  3455. }
  3456. }
  3457. /**
  3458. * Creates an overlay
  3459. * @private
  3460. * @return {?}
  3461. */
  3462. _createOverlay() {
  3463. if (!this.positions || !this.positions.length) {
  3464. this.positions = defaultPositionList;
  3465. }
  3466. this._overlayRef = this._overlay.create(this._buildConfig());
  3467. this._overlayRef.keydownEvents().subscribe((/**
  3468. * @param {?} event
  3469. * @return {?}
  3470. */
  3471. (event) => {
  3472. this.overlayKeydown.next(event);
  3473. if (event.keyCode === ESCAPE && !hasModifierKey(event)) {
  3474. event.preventDefault();
  3475. this._detachOverlay();
  3476. }
  3477. }));
  3478. }
  3479. /**
  3480. * Builds the overlay config based on the directive's inputs
  3481. * @private
  3482. * @return {?}
  3483. */
  3484. _buildConfig() {
  3485. /** @type {?} */
  3486. const positionStrategy = this._position = this._createPositionStrategy();
  3487. /** @type {?} */
  3488. const overlayConfig = new OverlayConfig({
  3489. direction: this._dir,
  3490. positionStrategy,
  3491. scrollStrategy: this.scrollStrategy,
  3492. hasBackdrop: this.hasBackdrop
  3493. });
  3494. if (this.width || this.width === 0) {
  3495. overlayConfig.width = this.width;
  3496. }
  3497. if (this.height || this.height === 0) {
  3498. overlayConfig.height = this.height;
  3499. }
  3500. if (this.minWidth || this.minWidth === 0) {
  3501. overlayConfig.minWidth = this.minWidth;
  3502. }
  3503. if (this.minHeight || this.minHeight === 0) {
  3504. overlayConfig.minHeight = this.minHeight;
  3505. }
  3506. if (this.backdropClass) {
  3507. overlayConfig.backdropClass = this.backdropClass;
  3508. }
  3509. if (this.panelClass) {
  3510. overlayConfig.panelClass = this.panelClass;
  3511. }
  3512. return overlayConfig;
  3513. }
  3514. /**
  3515. * Updates the state of a position strategy, based on the values of the directive inputs.
  3516. * @private
  3517. * @param {?} positionStrategy
  3518. * @return {?}
  3519. */
  3520. _updatePositionStrategy(positionStrategy) {
  3521. /** @type {?} */
  3522. const positions = this.positions.map((/**
  3523. * @param {?} currentPosition
  3524. * @return {?}
  3525. */
  3526. currentPosition => ({
  3527. originX: currentPosition.originX,
  3528. originY: currentPosition.originY,
  3529. overlayX: currentPosition.overlayX,
  3530. overlayY: currentPosition.overlayY,
  3531. offsetX: currentPosition.offsetX || this.offsetX,
  3532. offsetY: currentPosition.offsetY || this.offsetY,
  3533. panelClass: currentPosition.panelClass || undefined,
  3534. })));
  3535. return positionStrategy
  3536. .setOrigin(this.origin.elementRef)
  3537. .withPositions(positions)
  3538. .withFlexibleDimensions(this.flexibleDimensions)
  3539. .withPush(this.push)
  3540. .withGrowAfterOpen(this.growAfterOpen)
  3541. .withViewportMargin(this.viewportMargin)
  3542. .withLockedPosition(this.lockPosition);
  3543. }
  3544. /**
  3545. * Returns the position strategy of the overlay to be set on the overlay config
  3546. * @private
  3547. * @return {?}
  3548. */
  3549. _createPositionStrategy() {
  3550. /** @type {?} */
  3551. const strategy = this._overlay.position().flexibleConnectedTo(this.origin.elementRef);
  3552. this._updatePositionStrategy(strategy);
  3553. strategy.positionChanges.subscribe((/**
  3554. * @param {?} p
  3555. * @return {?}
  3556. */
  3557. p => this.positionChange.emit(p)));
  3558. return strategy;
  3559. }
  3560. /**
  3561. * Attaches the overlay and subscribes to backdrop clicks if backdrop exists
  3562. * @private
  3563. * @return {?}
  3564. */
  3565. _attachOverlay() {
  3566. if (!this._overlayRef) {
  3567. this._createOverlay();
  3568. }
  3569. else {
  3570. // Update the overlay size, in case the directive's inputs have changed
  3571. this._overlayRef.getConfig().hasBackdrop = this.hasBackdrop;
  3572. }
  3573. if (!this._overlayRef.hasAttached()) {
  3574. this._overlayRef.attach(this._templatePortal);
  3575. this.attach.emit();
  3576. }
  3577. if (this.hasBackdrop) {
  3578. this._backdropSubscription = this._overlayRef.backdropClick().subscribe((/**
  3579. * @param {?} event
  3580. * @return {?}
  3581. */
  3582. event => {
  3583. this.backdropClick.emit(event);
  3584. }));
  3585. }
  3586. else {
  3587. this._backdropSubscription.unsubscribe();
  3588. }
  3589. }
  3590. /**
  3591. * Detaches the overlay and unsubscribes to backdrop clicks if backdrop exists
  3592. * @private
  3593. * @return {?}
  3594. */
  3595. _detachOverlay() {
  3596. if (this._overlayRef) {
  3597. this._overlayRef.detach();
  3598. this.detach.emit();
  3599. }
  3600. this._backdropSubscription.unsubscribe();
  3601. }
  3602. }
  3603. CdkConnectedOverlay.decorators = [
  3604. { type: Directive, args: [{
  3605. selector: '[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]',
  3606. exportAs: 'cdkConnectedOverlay'
  3607. },] },
  3608. ];
  3609. /** @nocollapse */
  3610. CdkConnectedOverlay.ctorParameters = () => [
  3611. { type: Overlay },
  3612. { type: TemplateRef },
  3613. { type: ViewContainerRef },
  3614. { type: undefined, decorators: [{ type: Inject, args: [CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,] }] },
  3615. { type: Directionality, decorators: [{ type: Optional }] }
  3616. ];
  3617. CdkConnectedOverlay.propDecorators = {
  3618. origin: [{ type: Input, args: ['cdkConnectedOverlayOrigin',] }],
  3619. positions: [{ type: Input, args: ['cdkConnectedOverlayPositions',] }],
  3620. offsetX: [{ type: Input, args: ['cdkConnectedOverlayOffsetX',] }],
  3621. offsetY: [{ type: Input, args: ['cdkConnectedOverlayOffsetY',] }],
  3622. width: [{ type: Input, args: ['cdkConnectedOverlayWidth',] }],
  3623. height: [{ type: Input, args: ['cdkConnectedOverlayHeight',] }],
  3624. minWidth: [{ type: Input, args: ['cdkConnectedOverlayMinWidth',] }],
  3625. minHeight: [{ type: Input, args: ['cdkConnectedOverlayMinHeight',] }],
  3626. backdropClass: [{ type: Input, args: ['cdkConnectedOverlayBackdropClass',] }],
  3627. panelClass: [{ type: Input, args: ['cdkConnectedOverlayPanelClass',] }],
  3628. viewportMargin: [{ type: Input, args: ['cdkConnectedOverlayViewportMargin',] }],
  3629. scrollStrategy: [{ type: Input, args: ['cdkConnectedOverlayScrollStrategy',] }],
  3630. open: [{ type: Input, args: ['cdkConnectedOverlayOpen',] }],
  3631. hasBackdrop: [{ type: Input, args: ['cdkConnectedOverlayHasBackdrop',] }],
  3632. lockPosition: [{ type: Input, args: ['cdkConnectedOverlayLockPosition',] }],
  3633. flexibleDimensions: [{ type: Input, args: ['cdkConnectedOverlayFlexibleDimensions',] }],
  3634. growAfterOpen: [{ type: Input, args: ['cdkConnectedOverlayGrowAfterOpen',] }],
  3635. push: [{ type: Input, args: ['cdkConnectedOverlayPush',] }],
  3636. backdropClick: [{ type: Output }],
  3637. positionChange: [{ type: Output }],
  3638. attach: [{ type: Output }],
  3639. detach: [{ type: Output }],
  3640. overlayKeydown: [{ type: Output }]
  3641. };
  3642. /**
  3643. * \@docs-private
  3644. * @param {?} overlay
  3645. * @return {?}
  3646. */
  3647. function CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay) {
  3648. return (/**
  3649. * @return {?}
  3650. */
  3651. () => overlay.scrollStrategies.reposition());
  3652. }
  3653. /**
  3654. * \@docs-private
  3655. * @type {?}
  3656. */
  3657. const CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER = {
  3658. provide: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,
  3659. deps: [Overlay],
  3660. useFactory: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY,
  3661. };
  3662. /**
  3663. * @fileoverview added by tsickle
  3664. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3665. */
  3666. class OverlayModule {
  3667. }
  3668. OverlayModule.decorators = [
  3669. { type: NgModule, args: [{
  3670. imports: [BidiModule, PortalModule, ScrollingModule],
  3671. exports: [CdkConnectedOverlay, CdkOverlayOrigin, ScrollingModule],
  3672. declarations: [CdkConnectedOverlay, CdkOverlayOrigin],
  3673. providers: [
  3674. Overlay,
  3675. CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
  3676. ],
  3677. },] },
  3678. ];
  3679. /**
  3680. * @deprecated Use `OverlayModule` instead.
  3681. * \@breaking-change 8.0.0
  3682. * \@docs-private
  3683. * @type {?}
  3684. */
  3685. const OVERLAY_PROVIDERS = [
  3686. Overlay,
  3687. OverlayPositionBuilder,
  3688. OVERLAY_KEYBOARD_DISPATCHER_PROVIDER,
  3689. VIEWPORT_RULER_PROVIDER,
  3690. OVERLAY_CONTAINER_PROVIDER,
  3691. CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
  3692. ];
  3693. /**
  3694. * @fileoverview added by tsickle
  3695. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3696. */
  3697. /**
  3698. * Alternative to OverlayContainer that supports correct displaying of overlay elements in
  3699. * Fullscreen mode
  3700. * https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen
  3701. *
  3702. * Should be provided in the root component.
  3703. */
  3704. class FullscreenOverlayContainer extends OverlayContainer {
  3705. /**
  3706. * @param {?} _document
  3707. */
  3708. constructor(_document) {
  3709. super(_document);
  3710. }
  3711. /**
  3712. * @return {?}
  3713. */
  3714. ngOnDestroy() {
  3715. super.ngOnDestroy();
  3716. if (this._fullScreenEventName && this._fullScreenListener) {
  3717. this._document.removeEventListener(this._fullScreenEventName, this._fullScreenListener);
  3718. }
  3719. }
  3720. /**
  3721. * @protected
  3722. * @return {?}
  3723. */
  3724. _createContainer() {
  3725. super._createContainer();
  3726. this._adjustParentForFullscreenChange();
  3727. this._addFullscreenChangeListener((/**
  3728. * @return {?}
  3729. */
  3730. () => this._adjustParentForFullscreenChange()));
  3731. }
  3732. /**
  3733. * @private
  3734. * @return {?}
  3735. */
  3736. _adjustParentForFullscreenChange() {
  3737. if (!this._containerElement) {
  3738. return;
  3739. }
  3740. /** @type {?} */
  3741. const fullscreenElement = this.getFullscreenElement();
  3742. /** @type {?} */
  3743. const parent = fullscreenElement || this._document.body;
  3744. parent.appendChild(this._containerElement);
  3745. }
  3746. /**
  3747. * @private
  3748. * @param {?} fn
  3749. * @return {?}
  3750. */
  3751. _addFullscreenChangeListener(fn) {
  3752. /** @type {?} */
  3753. const eventName = this._getEventName();
  3754. if (eventName) {
  3755. if (this._fullScreenListener) {
  3756. this._document.removeEventListener(eventName, this._fullScreenListener);
  3757. }
  3758. this._document.addEventListener(eventName, fn);
  3759. this._fullScreenListener = fn;
  3760. }
  3761. }
  3762. /**
  3763. * @private
  3764. * @return {?}
  3765. */
  3766. _getEventName() {
  3767. if (!this._fullScreenEventName) {
  3768. /** @type {?} */
  3769. const _document = (/** @type {?} */ (this._document));
  3770. if (_document.fullscreenEnabled) {
  3771. this._fullScreenEventName = 'fullscreenchange';
  3772. }
  3773. else if (_document.webkitFullscreenEnabled) {
  3774. this._fullScreenEventName = 'webkitfullscreenchange';
  3775. }
  3776. else if (_document.mozFullScreenEnabled) {
  3777. this._fullScreenEventName = 'mozfullscreenchange';
  3778. }
  3779. else if (_document.msFullscreenEnabled) {
  3780. this._fullScreenEventName = 'MSFullscreenChange';
  3781. }
  3782. }
  3783. return this._fullScreenEventName;
  3784. }
  3785. /**
  3786. * When the page is put into fullscreen mode, a specific element is specified.
  3787. * Only that element and its children are visible when in fullscreen mode.
  3788. * @return {?}
  3789. */
  3790. getFullscreenElement() {
  3791. /** @type {?} */
  3792. const _document = (/** @type {?} */ (this._document));
  3793. return _document.fullscreenElement ||
  3794. _document.webkitFullscreenElement ||
  3795. _document.mozFullScreenElement ||
  3796. _document.msFullscreenElement ||
  3797. null;
  3798. }
  3799. }
  3800. FullscreenOverlayContainer.decorators = [
  3801. { type: Injectable, args: [{ providedIn: 'root' },] },
  3802. ];
  3803. /** @nocollapse */
  3804. FullscreenOverlayContainer.ctorParameters = () => [
  3805. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] }
  3806. ];
  3807. /** @nocollapse */ FullscreenOverlayContainer.ngInjectableDef = ɵɵdefineInjectable({ factory: function FullscreenOverlayContainer_Factory() { return new FullscreenOverlayContainer(ɵɵinject(DOCUMENT)); }, token: FullscreenOverlayContainer, providedIn: "root" });
  3808. /**
  3809. * @fileoverview added by tsickle
  3810. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3811. */
  3812. /**
  3813. * @fileoverview added by tsickle
  3814. * @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
  3815. */
  3816. export { Overlay, OverlayContainer, CdkOverlayOrigin, CdkConnectedOverlay, FullscreenOverlayContainer, OverlayRef, OverlayKeyboardDispatcher, OverlayPositionBuilder, GlobalPositionStrategy, ConnectedPositionStrategy, FlexibleConnectedPositionStrategy, OverlayConfig, validateVerticalPosition, validateHorizontalPosition, ConnectionPositionPair, ScrollingVisibility, ConnectedOverlayPositionChange, ScrollStrategyOptions, RepositionScrollStrategy, CloseScrollStrategy, NoopScrollStrategy, BlockScrollStrategy, OverlayModule, OVERLAY_PROVIDERS, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER as ɵg, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY as ɵf, OVERLAY_CONTAINER_PROVIDER as ɵb, OVERLAY_CONTAINER_PROVIDER_FACTORY as ɵa, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY as ɵc, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER as ɵe, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY as ɵd };
  3817. //# sourceMappingURL=overlay.js.map