UNPKG

140 kBJavaScriptView Raw
1import * as i1 from '@angular/cdk/scrolling';
2import { ScrollingModule } from '@angular/cdk/scrolling';
3export { CdkScrollable, ScrollDispatcher, ViewportRuler } from '@angular/cdk/scrolling';
4import * as i6 from '@angular/common';
5import { DOCUMENT } from '@angular/common';
6import * as i0 from '@angular/core';
7import { Injectable, Inject, Optional, ElementRef, ApplicationRef, ANIMATION_MODULE_TYPE, InjectionToken, Directive, EventEmitter, Input, Output, NgModule } from '@angular/core';
8import { coerceCssPixelValue, coerceArray, coerceBooleanProperty } from '@angular/cdk/coercion';
9import * as i1$1 from '@angular/cdk/platform';
10import { supportsScrollBehavior, _getEventTarget, _isTestEnvironment } from '@angular/cdk/platform';
11import { filter, take, takeUntil, takeWhile } from 'rxjs/operators';
12import * as i5 from '@angular/cdk/bidi';
13import { BidiModule } from '@angular/cdk/bidi';
14import { DomPortalOutlet, TemplatePortal, PortalModule } from '@angular/cdk/portal';
15import { Subject, Subscription, merge } from 'rxjs';
16import { ESCAPE, hasModifierKey } from '@angular/cdk/keycodes';
17
18const scrollBehaviorSupported = supportsScrollBehavior();
19/**
20 * Strategy that will prevent the user from scrolling while the overlay is visible.
21 */
22class BlockScrollStrategy {
23 constructor(_viewportRuler, document) {
24 this._viewportRuler = _viewportRuler;
25 this._previousHTMLStyles = { top: '', left: '' };
26 this._isEnabled = false;
27 this._document = document;
28 }
29 /** Attaches this scroll strategy to an overlay. */
30 attach() { }
31 /** Blocks page-level scroll while the attached overlay is open. */
32 enable() {
33 if (this._canBeEnabled()) {
34 const root = this._document.documentElement;
35 this._previousScrollPosition = this._viewportRuler.getViewportScrollPosition();
36 // Cache the previous inline styles in case the user had set them.
37 this._previousHTMLStyles.left = root.style.left || '';
38 this._previousHTMLStyles.top = root.style.top || '';
39 // Note: we're using the `html` node, instead of the `body`, because the `body` may
40 // have the user agent margin, whereas the `html` is guaranteed not to have one.
41 root.style.left = coerceCssPixelValue(-this._previousScrollPosition.left);
42 root.style.top = coerceCssPixelValue(-this._previousScrollPosition.top);
43 root.classList.add('cdk-global-scrollblock');
44 this._isEnabled = true;
45 }
46 }
47 /** Unblocks page-level scroll while the attached overlay is open. */
48 disable() {
49 if (this._isEnabled) {
50 const html = this._document.documentElement;
51 const body = this._document.body;
52 const htmlStyle = html.style;
53 const bodyStyle = body.style;
54 const previousHtmlScrollBehavior = htmlStyle.scrollBehavior || '';
55 const previousBodyScrollBehavior = bodyStyle.scrollBehavior || '';
56 this._isEnabled = false;
57 htmlStyle.left = this._previousHTMLStyles.left;
58 htmlStyle.top = this._previousHTMLStyles.top;
59 html.classList.remove('cdk-global-scrollblock');
60 // Disable user-defined smooth scrolling temporarily while we restore the scroll position.
61 // See https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
62 // Note that we don't mutate the property if the browser doesn't support `scroll-behavior`,
63 // because it can throw off feature detections in `supportsScrollBehavior` which
64 // checks for `'scrollBehavior' in documentElement.style`.
65 if (scrollBehaviorSupported) {
66 htmlStyle.scrollBehavior = bodyStyle.scrollBehavior = 'auto';
67 }
68 window.scroll(this._previousScrollPosition.left, this._previousScrollPosition.top);
69 if (scrollBehaviorSupported) {
70 htmlStyle.scrollBehavior = previousHtmlScrollBehavior;
71 bodyStyle.scrollBehavior = previousBodyScrollBehavior;
72 }
73 }
74 }
75 _canBeEnabled() {
76 // Since the scroll strategies can't be singletons, we have to use a global CSS class
77 // (`cdk-global-scrollblock`) to make sure that we don't try to disable global
78 // scrolling multiple times.
79 const html = this._document.documentElement;
80 if (html.classList.contains('cdk-global-scrollblock') || this._isEnabled) {
81 return false;
82 }
83 const body = this._document.body;
84 const viewport = this._viewportRuler.getViewportSize();
85 return body.scrollHeight > viewport.height || body.scrollWidth > viewport.width;
86 }
87}
88
89/**
90 * Returns an error to be thrown when attempting to attach an already-attached scroll strategy.
91 */
92function getMatScrollStrategyAlreadyAttachedError() {
93 return Error(`Scroll strategy has already been attached.`);
94}
95
96/**
97 * Strategy that will close the overlay as soon as the user starts scrolling.
98 */
99class CloseScrollStrategy {
100 constructor(_scrollDispatcher, _ngZone, _viewportRuler, _config) {
101 this._scrollDispatcher = _scrollDispatcher;
102 this._ngZone = _ngZone;
103 this._viewportRuler = _viewportRuler;
104 this._config = _config;
105 this._scrollSubscription = null;
106 /** Detaches the overlay ref and disables the scroll strategy. */
107 this._detach = () => {
108 this.disable();
109 if (this._overlayRef.hasAttached()) {
110 this._ngZone.run(() => this._overlayRef.detach());
111 }
112 };
113 }
114 /** Attaches this scroll strategy to an overlay. */
115 attach(overlayRef) {
116 if (this._overlayRef && (typeof ngDevMode === 'undefined' || ngDevMode)) {
117 throw getMatScrollStrategyAlreadyAttachedError();
118 }
119 this._overlayRef = overlayRef;
120 }
121 /** Enables the closing of the attached overlay on scroll. */
122 enable() {
123 if (this._scrollSubscription) {
124 return;
125 }
126 const stream = this._scrollDispatcher.scrolled(0).pipe(filter(scrollable => {
127 return (!scrollable ||
128 !this._overlayRef.overlayElement.contains(scrollable.getElementRef().nativeElement));
129 }));
130 if (this._config && this._config.threshold && this._config.threshold > 1) {
131 this._initialScrollPosition = this._viewportRuler.getViewportScrollPosition().top;
132 this._scrollSubscription = stream.subscribe(() => {
133 const scrollPosition = this._viewportRuler.getViewportScrollPosition().top;
134 if (Math.abs(scrollPosition - this._initialScrollPosition) > this._config.threshold) {
135 this._detach();
136 }
137 else {
138 this._overlayRef.updatePosition();
139 }
140 });
141 }
142 else {
143 this._scrollSubscription = stream.subscribe(this._detach);
144 }
145 }
146 /** Disables the closing the attached overlay on scroll. */
147 disable() {
148 if (this._scrollSubscription) {
149 this._scrollSubscription.unsubscribe();
150 this._scrollSubscription = null;
151 }
152 }
153 detach() {
154 this.disable();
155 this._overlayRef = null;
156 }
157}
158
159/** Scroll strategy that doesn't do anything. */
160class NoopScrollStrategy {
161 /** Does nothing, as this scroll strategy is a no-op. */
162 enable() { }
163 /** Does nothing, as this scroll strategy is a no-op. */
164 disable() { }
165 /** Does nothing, as this scroll strategy is a no-op. */
166 attach() { }
167}
168
169/**
170 * Gets whether an element is scrolled outside of view by any of its parent scrolling containers.
171 * @param element Dimensions of the element (from getBoundingClientRect)
172 * @param scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
173 * @returns Whether the element is scrolled out of view
174 * @docs-private
175 */
176function isElementScrolledOutsideView(element, scrollContainers) {
177 return scrollContainers.some(containerBounds => {
178 const outsideAbove = element.bottom < containerBounds.top;
179 const outsideBelow = element.top > containerBounds.bottom;
180 const outsideLeft = element.right < containerBounds.left;
181 const outsideRight = element.left > containerBounds.right;
182 return outsideAbove || outsideBelow || outsideLeft || outsideRight;
183 });
184}
185/**
186 * Gets whether an element is clipped by any of its scrolling containers.
187 * @param element Dimensions of the element (from getBoundingClientRect)
188 * @param scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
189 * @returns Whether the element is clipped
190 * @docs-private
191 */
192function isElementClippedByScrolling(element, scrollContainers) {
193 return scrollContainers.some(scrollContainerRect => {
194 const clippedAbove = element.top < scrollContainerRect.top;
195 const clippedBelow = element.bottom > scrollContainerRect.bottom;
196 const clippedLeft = element.left < scrollContainerRect.left;
197 const clippedRight = element.right > scrollContainerRect.right;
198 return clippedAbove || clippedBelow || clippedLeft || clippedRight;
199 });
200}
201
202/**
203 * Strategy that will update the element position as the user is scrolling.
204 */
205class RepositionScrollStrategy {
206 constructor(_scrollDispatcher, _viewportRuler, _ngZone, _config) {
207 this._scrollDispatcher = _scrollDispatcher;
208 this._viewportRuler = _viewportRuler;
209 this._ngZone = _ngZone;
210 this._config = _config;
211 this._scrollSubscription = null;
212 }
213 /** Attaches this scroll strategy to an overlay. */
214 attach(overlayRef) {
215 if (this._overlayRef && (typeof ngDevMode === 'undefined' || ngDevMode)) {
216 throw getMatScrollStrategyAlreadyAttachedError();
217 }
218 this._overlayRef = overlayRef;
219 }
220 /** Enables repositioning of the attached overlay on scroll. */
221 enable() {
222 if (!this._scrollSubscription) {
223 const throttle = this._config ? this._config.scrollThrottle : 0;
224 this._scrollSubscription = this._scrollDispatcher.scrolled(throttle).subscribe(() => {
225 this._overlayRef.updatePosition();
226 // TODO(crisbeto): make `close` on by default once all components can handle it.
227 if (this._config && this._config.autoClose) {
228 const overlayRect = this._overlayRef.overlayElement.getBoundingClientRect();
229 const { width, height } = this._viewportRuler.getViewportSize();
230 // TODO(crisbeto): include all ancestor scroll containers here once
231 // we have a way of exposing the trigger element to the scroll strategy.
232 const parentRects = [{ width, height, bottom: height, right: width, top: 0, left: 0 }];
233 if (isElementScrolledOutsideView(overlayRect, parentRects)) {
234 this.disable();
235 this._ngZone.run(() => this._overlayRef.detach());
236 }
237 }
238 });
239 }
240 }
241 /** Disables repositioning of the attached overlay on scroll. */
242 disable() {
243 if (this._scrollSubscription) {
244 this._scrollSubscription.unsubscribe();
245 this._scrollSubscription = null;
246 }
247 }
248 detach() {
249 this.disable();
250 this._overlayRef = null;
251 }
252}
253
254/**
255 * Options for how an overlay will handle scrolling.
256 *
257 * Users can provide a custom value for `ScrollStrategyOptions` to replace the default
258 * behaviors. This class primarily acts as a factory for ScrollStrategy instances.
259 */
260class ScrollStrategyOptions {
261 constructor(_scrollDispatcher, _viewportRuler, _ngZone, document) {
262 this._scrollDispatcher = _scrollDispatcher;
263 this._viewportRuler = _viewportRuler;
264 this._ngZone = _ngZone;
265 /** Do nothing on scroll. */
266 this.noop = () => new NoopScrollStrategy();
267 /**
268 * Close the overlay as soon as the user scrolls.
269 * @param config Configuration to be used inside the scroll strategy.
270 */
271 this.close = (config) => new CloseScrollStrategy(this._scrollDispatcher, this._ngZone, this._viewportRuler, config);
272 /** Block scrolling. */
273 this.block = () => new BlockScrollStrategy(this._viewportRuler, this._document);
274 /**
275 * Update the overlay's position on scroll.
276 * @param config Configuration to be used inside the scroll strategy.
277 * Allows debouncing the reposition calls.
278 */
279 this.reposition = (config) => new RepositionScrollStrategy(this._scrollDispatcher, this._viewportRuler, this._ngZone, config);
280 this._document = document;
281 }
282 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: ScrollStrategyOptions, deps: [{ token: i1.ScrollDispatcher }, { token: i1.ViewportRuler }, { token: i0.NgZone }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }
283 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: ScrollStrategyOptions, providedIn: 'root' }); }
284}
285i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: ScrollStrategyOptions, decorators: [{
286 type: Injectable,
287 args: [{ providedIn: 'root' }]
288 }], ctorParameters: function () { return [{ type: i1.ScrollDispatcher }, { type: i1.ViewportRuler }, { type: i0.NgZone }, { type: undefined, decorators: [{
289 type: Inject,
290 args: [DOCUMENT]
291 }] }]; } });
292
293/** Initial configuration used when creating an overlay. */
294class OverlayConfig {
295 constructor(config) {
296 /** Strategy to be used when handling scroll events while the overlay is open. */
297 this.scrollStrategy = new NoopScrollStrategy();
298 /** Custom class to add to the overlay pane. */
299 this.panelClass = '';
300 /** Whether the overlay has a backdrop. */
301 this.hasBackdrop = false;
302 /** Custom class to add to the backdrop */
303 this.backdropClass = 'cdk-overlay-dark-backdrop';
304 /**
305 * Whether the overlay should be disposed of when the user goes backwards/forwards in history.
306 * Note that this usually doesn't include clicking on links (unless the user is using
307 * the `HashLocationStrategy`).
308 */
309 this.disposeOnNavigation = false;
310 if (config) {
311 // Use `Iterable` instead of `Array` because TypeScript, as of 3.6.3,
312 // loses the array generic type in the `for of`. But we *also* have to use `Array` because
313 // typescript won't iterate over an `Iterable` unless you compile with `--downlevelIteration`
314 const configKeys = Object.keys(config);
315 for (const key of configKeys) {
316 if (config[key] !== undefined) {
317 // TypeScript, as of version 3.5, sees the left-hand-side of this expression
318 // as "I don't know *which* key this is, so the only valid value is the intersection
319 // of all the possible values." In this case, that happens to be `undefined`. TypeScript
320 // is not smart enough to see that the right-hand-side is actually an access of the same
321 // exact type with the same exact key, meaning that the value type must be identical.
322 // So we use `any` to work around this.
323 this[key] = config[key];
324 }
325 }
326 }
327 }
328}
329
330/** The points of the origin element and the overlay element to connect. */
331class ConnectionPositionPair {
332 constructor(origin, overlay,
333 /** Offset along the X axis. */
334 offsetX,
335 /** Offset along the Y axis. */
336 offsetY,
337 /** Class(es) to be applied to the panel while this position is active. */
338 panelClass) {
339 this.offsetX = offsetX;
340 this.offsetY = offsetY;
341 this.panelClass = panelClass;
342 this.originX = origin.originX;
343 this.originY = origin.originY;
344 this.overlayX = overlay.overlayX;
345 this.overlayY = overlay.overlayY;
346 }
347}
348/**
349 * Set of properties regarding the position of the origin and overlay relative to the viewport
350 * with respect to the containing Scrollable elements.
351 *
352 * The overlay and origin are clipped if any part of their bounding client rectangle exceeds the
353 * bounds of any one of the strategy's Scrollable's bounding client rectangle.
354 *
355 * The overlay and origin are outside view if there is no overlap between their bounding client
356 * rectangle and any one of the strategy's Scrollable's bounding client rectangle.
357 *
358 * ----------- -----------
359 * | outside | | clipped |
360 * | view | --------------------------
361 * | | | | | |
362 * ---------- | ----------- |
363 * -------------------------- | |
364 * | | | Scrollable |
365 * | | | |
366 * | | --------------------------
367 * | Scrollable |
368 * | |
369 * --------------------------
370 *
371 * @docs-private
372 */
373class ScrollingVisibility {
374}
375/** The change event emitted by the strategy when a fallback position is used. */
376class ConnectedOverlayPositionChange {
377 constructor(
378 /** The position used as a result of this change. */
379 connectionPair,
380 /** @docs-private */
381 scrollableViewProperties) {
382 this.connectionPair = connectionPair;
383 this.scrollableViewProperties = scrollableViewProperties;
384 }
385}
386/**
387 * Validates whether a vertical position property matches the expected values.
388 * @param property Name of the property being validated.
389 * @param value Value of the property being validated.
390 * @docs-private
391 */
392function validateVerticalPosition(property, value) {
393 if (value !== 'top' && value !== 'bottom' && value !== 'center') {
394 throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
395 `Expected "top", "bottom" or "center".`);
396 }
397}
398/**
399 * Validates whether a horizontal position property matches the expected values.
400 * @param property Name of the property being validated.
401 * @param value Value of the property being validated.
402 * @docs-private
403 */
404function validateHorizontalPosition(property, value) {
405 if (value !== 'start' && value !== 'end' && value !== 'center') {
406 throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
407 `Expected "start", "end" or "center".`);
408 }
409}
410
411/**
412 * Service for dispatching events that land on the body to appropriate overlay ref,
413 * if any. It maintains a list of attached overlays to determine best suited overlay based
414 * on event target and order of overlay opens.
415 */
416class BaseOverlayDispatcher {
417 constructor(document) {
418 /** Currently attached overlays in the order they were attached. */
419 this._attachedOverlays = [];
420 this._document = document;
421 }
422 ngOnDestroy() {
423 this.detach();
424 }
425 /** Add a new overlay to the list of attached overlay refs. */
426 add(overlayRef) {
427 // Ensure that we don't get the same overlay multiple times.
428 this.remove(overlayRef);
429 this._attachedOverlays.push(overlayRef);
430 }
431 /** Remove an overlay from the list of attached overlay refs. */
432 remove(overlayRef) {
433 const index = this._attachedOverlays.indexOf(overlayRef);
434 if (index > -1) {
435 this._attachedOverlays.splice(index, 1);
436 }
437 // Remove the global listener once there are no more overlays.
438 if (this._attachedOverlays.length === 0) {
439 this.detach();
440 }
441 }
442 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: BaseOverlayDispatcher, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }
443 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: BaseOverlayDispatcher, providedIn: 'root' }); }
444}
445i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: BaseOverlayDispatcher, decorators: [{
446 type: Injectable,
447 args: [{ providedIn: 'root' }]
448 }], ctorParameters: function () { return [{ type: undefined, decorators: [{
449 type: Inject,
450 args: [DOCUMENT]
451 }] }]; } });
452
453/**
454 * Service for dispatching keyboard events that land on the body to appropriate overlay ref,
455 * if any. It maintains a list of attached overlays to determine best suited overlay based
456 * on event target and order of overlay opens.
457 */
458class OverlayKeyboardDispatcher extends BaseOverlayDispatcher {
459 constructor(document,
460 /** @breaking-change 14.0.0 _ngZone will be required. */
461 _ngZone) {
462 super(document);
463 this._ngZone = _ngZone;
464 /** Keyboard event listener that will be attached to the body. */
465 this._keydownListener = (event) => {
466 const overlays = this._attachedOverlays;
467 for (let i = overlays.length - 1; i > -1; i--) {
468 // Dispatch the keydown event to the top overlay which has subscribers to its keydown events.
469 // We want to target the most recent overlay, rather than trying to match where the event came
470 // from, because some components might open an overlay, but keep focus on a trigger element
471 // (e.g. for select and autocomplete). We skip overlays without keydown event subscriptions,
472 // because we don't want overlays that don't handle keyboard events to block the ones below
473 // them that do.
474 if (overlays[i]._keydownEvents.observers.length > 0) {
475 const keydownEvents = overlays[i]._keydownEvents;
476 /** @breaking-change 14.0.0 _ngZone will be required. */
477 if (this._ngZone) {
478 this._ngZone.run(() => keydownEvents.next(event));
479 }
480 else {
481 keydownEvents.next(event);
482 }
483 break;
484 }
485 }
486 };
487 }
488 /** Add a new overlay to the list of attached overlay refs. */
489 add(overlayRef) {
490 super.add(overlayRef);
491 // Lazily start dispatcher once first overlay is added
492 if (!this._isAttached) {
493 /** @breaking-change 14.0.0 _ngZone will be required. */
494 if (this._ngZone) {
495 this._ngZone.runOutsideAngular(() => this._document.body.addEventListener('keydown', this._keydownListener));
496 }
497 else {
498 this._document.body.addEventListener('keydown', this._keydownListener);
499 }
500 this._isAttached = true;
501 }
502 }
503 /** Detaches the global keyboard event listener. */
504 detach() {
505 if (this._isAttached) {
506 this._document.body.removeEventListener('keydown', this._keydownListener);
507 this._isAttached = false;
508 }
509 }
510 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayKeyboardDispatcher, deps: [{ token: DOCUMENT }, { token: i0.NgZone, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
511 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayKeyboardDispatcher, providedIn: 'root' }); }
512}
513i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayKeyboardDispatcher, decorators: [{
514 type: Injectable,
515 args: [{ providedIn: 'root' }]
516 }], ctorParameters: function () { return [{ type: undefined, decorators: [{
517 type: Inject,
518 args: [DOCUMENT]
519 }] }, { type: i0.NgZone, decorators: [{
520 type: Optional
521 }] }]; } });
522
523/**
524 * Service for dispatching mouse click events that land on the body to appropriate overlay ref,
525 * if any. It maintains a list of attached overlays to determine best suited overlay based
526 * on event target and order of overlay opens.
527 */
528class OverlayOutsideClickDispatcher extends BaseOverlayDispatcher {
529 constructor(document, _platform,
530 /** @breaking-change 14.0.0 _ngZone will be required. */
531 _ngZone) {
532 super(document);
533 this._platform = _platform;
534 this._ngZone = _ngZone;
535 this._cursorStyleIsSet = false;
536 /** Store pointerdown event target to track origin of click. */
537 this._pointerDownListener = (event) => {
538 this._pointerDownEventTarget = _getEventTarget(event);
539 };
540 /** Click event listener that will be attached to the body propagate phase. */
541 this._clickListener = (event) => {
542 const target = _getEventTarget(event);
543 // In case of a click event, we want to check the origin of the click
544 // (e.g. in case where a user starts a click inside the overlay and
545 // releases the click outside of it).
546 // This is done by using the event target of the preceding pointerdown event.
547 // Every click event caused by a pointer device has a preceding pointerdown
548 // event, unless the click was programmatically triggered (e.g. in a unit test).
549 const origin = event.type === 'click' && this._pointerDownEventTarget
550 ? this._pointerDownEventTarget
551 : target;
552 // Reset the stored pointerdown event target, to avoid having it interfere
553 // in subsequent events.
554 this._pointerDownEventTarget = null;
555 // We copy the array because the original may be modified asynchronously if the
556 // outsidePointerEvents listener decides to detach overlays resulting in index errors inside
557 // the for loop.
558 const overlays = this._attachedOverlays.slice();
559 // Dispatch the mouse event to the top overlay which has subscribers to its mouse events.
560 // We want to target all overlays for which the click could be considered as outside click.
561 // As soon as we reach an overlay for which the click is not outside click we break off
562 // the loop.
563 for (let i = overlays.length - 1; i > -1; i--) {
564 const overlayRef = overlays[i];
565 if (overlayRef._outsidePointerEvents.observers.length < 1 || !overlayRef.hasAttached()) {
566 continue;
567 }
568 // If it's a click inside the overlay, just break - we should do nothing
569 // If it's an outside click (both origin and target of the click) dispatch the mouse event,
570 // and proceed with the next overlay
571 if (overlayRef.overlayElement.contains(target) ||
572 overlayRef.overlayElement.contains(origin)) {
573 break;
574 }
575 const outsidePointerEvents = overlayRef._outsidePointerEvents;
576 /** @breaking-change 14.0.0 _ngZone will be required. */
577 if (this._ngZone) {
578 this._ngZone.run(() => outsidePointerEvents.next(event));
579 }
580 else {
581 outsidePointerEvents.next(event);
582 }
583 }
584 };
585 }
586 /** Add a new overlay to the list of attached overlay refs. */
587 add(overlayRef) {
588 super.add(overlayRef);
589 // Safari on iOS does not generate click events for non-interactive
590 // elements. However, we want to receive a click for any element outside
591 // the overlay. We can force a "clickable" state by setting
592 // `cursor: pointer` on the document body. See:
593 // https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event#Safari_Mobile
594 // https://developer.apple.com/library/archive/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html
595 if (!this._isAttached) {
596 const body = this._document.body;
597 /** @breaking-change 14.0.0 _ngZone will be required. */
598 if (this._ngZone) {
599 this._ngZone.runOutsideAngular(() => this._addEventListeners(body));
600 }
601 else {
602 this._addEventListeners(body);
603 }
604 // click event is not fired on iOS. To make element "clickable" we are
605 // setting the cursor to pointer
606 if (this._platform.IOS && !this._cursorStyleIsSet) {
607 this._cursorOriginalValue = body.style.cursor;
608 body.style.cursor = 'pointer';
609 this._cursorStyleIsSet = true;
610 }
611 this._isAttached = true;
612 }
613 }
614 /** Detaches the global keyboard event listener. */
615 detach() {
616 if (this._isAttached) {
617 const body = this._document.body;
618 body.removeEventListener('pointerdown', this._pointerDownListener, true);
619 body.removeEventListener('click', this._clickListener, true);
620 body.removeEventListener('auxclick', this._clickListener, true);
621 body.removeEventListener('contextmenu', this._clickListener, true);
622 if (this._platform.IOS && this._cursorStyleIsSet) {
623 body.style.cursor = this._cursorOriginalValue;
624 this._cursorStyleIsSet = false;
625 }
626 this._isAttached = false;
627 }
628 }
629 _addEventListeners(body) {
630 body.addEventListener('pointerdown', this._pointerDownListener, true);
631 body.addEventListener('click', this._clickListener, true);
632 body.addEventListener('auxclick', this._clickListener, true);
633 body.addEventListener('contextmenu', this._clickListener, true);
634 }
635 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayOutsideClickDispatcher, deps: [{ token: DOCUMENT }, { token: i1$1.Platform }, { token: i0.NgZone, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
636 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayOutsideClickDispatcher, providedIn: 'root' }); }
637}
638i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayOutsideClickDispatcher, decorators: [{
639 type: Injectable,
640 args: [{ providedIn: 'root' }]
641 }], ctorParameters: function () { return [{ type: undefined, decorators: [{
642 type: Inject,
643 args: [DOCUMENT]
644 }] }, { type: i1$1.Platform }, { type: i0.NgZone, decorators: [{
645 type: Optional
646 }] }]; } });
647
648/** Container inside which all overlays will render. */
649class OverlayContainer {
650 constructor(document, _platform) {
651 this._platform = _platform;
652 this._document = document;
653 }
654 ngOnDestroy() {
655 this._containerElement?.remove();
656 }
657 /**
658 * This method returns the overlay container element. It will lazily
659 * create the element the first time it is called to facilitate using
660 * the container in non-browser environments.
661 * @returns the container element
662 */
663 getContainerElement() {
664 if (!this._containerElement) {
665 this._createContainer();
666 }
667 return this._containerElement;
668 }
669 /**
670 * Create the overlay container element, which is simply a div
671 * with the 'cdk-overlay-container' class on the document body.
672 */
673 _createContainer() {
674 const containerClass = 'cdk-overlay-container';
675 // TODO(crisbeto): remove the testing check once we have an overlay testing
676 // module or Angular starts tearing down the testing `NgModule`. See:
677 // https://github.com/angular/angular/issues/18831
678 if (this._platform.isBrowser || _isTestEnvironment()) {
679 const oppositePlatformContainers = this._document.querySelectorAll(`.${containerClass}[platform="server"], ` + `.${containerClass}[platform="test"]`);
680 // Remove any old containers from the opposite platform.
681 // This can happen when transitioning from the server to the client.
682 for (let i = 0; i < oppositePlatformContainers.length; i++) {
683 oppositePlatformContainers[i].remove();
684 }
685 }
686 const container = this._document.createElement('div');
687 container.classList.add(containerClass);
688 // A long time ago we kept adding new overlay containers whenever a new app was instantiated,
689 // but at some point we added logic which clears the duplicate ones in order to avoid leaks.
690 // The new logic was a little too aggressive since it was breaking some legitimate use cases.
691 // To mitigate the problem we made it so that only containers from a different platform are
692 // cleared, but the side-effect was that people started depending on the overly-aggressive
693 // logic to clean up their tests for them. Until we can introduce an overlay-specific testing
694 // module which does the cleanup, we try to detect that we're in a test environment and we
695 // always clear the container. See #17006.
696 // TODO(crisbeto): remove the test environment check once we have an overlay testing module.
697 if (_isTestEnvironment()) {
698 container.setAttribute('platform', 'test');
699 }
700 else if (!this._platform.isBrowser) {
701 container.setAttribute('platform', 'server');
702 }
703 this._document.body.appendChild(container);
704 this._containerElement = container;
705 }
706 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayContainer, deps: [{ token: DOCUMENT }, { token: i1$1.Platform }], target: i0.ɵɵFactoryTarget.Injectable }); }
707 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayContainer, providedIn: 'root' }); }
708}
709i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayContainer, decorators: [{
710 type: Injectable,
711 args: [{ providedIn: 'root' }]
712 }], ctorParameters: function () { return [{ type: undefined, decorators: [{
713 type: Inject,
714 args: [DOCUMENT]
715 }] }, { type: i1$1.Platform }]; } });
716
717/**
718 * Reference to an overlay that has been created with the Overlay service.
719 * Used to manipulate or dispose of said overlay.
720 */
721class OverlayRef {
722 constructor(_portalOutlet, _host, _pane, _config, _ngZone, _keyboardDispatcher, _document, _location, _outsideClickDispatcher, _animationsDisabled = false) {
723 this._portalOutlet = _portalOutlet;
724 this._host = _host;
725 this._pane = _pane;
726 this._config = _config;
727 this._ngZone = _ngZone;
728 this._keyboardDispatcher = _keyboardDispatcher;
729 this._document = _document;
730 this._location = _location;
731 this._outsideClickDispatcher = _outsideClickDispatcher;
732 this._animationsDisabled = _animationsDisabled;
733 this._backdropElement = null;
734 this._backdropClick = new Subject();
735 this._attachments = new Subject();
736 this._detachments = new Subject();
737 this._locationChanges = Subscription.EMPTY;
738 this._backdropClickHandler = (event) => this._backdropClick.next(event);
739 this._backdropTransitionendHandler = (event) => {
740 this._disposeBackdrop(event.target);
741 };
742 /** Stream of keydown events dispatched to this overlay. */
743 this._keydownEvents = new Subject();
744 /** Stream of mouse outside events dispatched to this overlay. */
745 this._outsidePointerEvents = new Subject();
746 if (_config.scrollStrategy) {
747 this._scrollStrategy = _config.scrollStrategy;
748 this._scrollStrategy.attach(this);
749 }
750 this._positionStrategy = _config.positionStrategy;
751 }
752 /** The overlay's HTML element */
753 get overlayElement() {
754 return this._pane;
755 }
756 /** The overlay's backdrop HTML element. */
757 get backdropElement() {
758 return this._backdropElement;
759 }
760 /**
761 * Wrapper around the panel element. Can be used for advanced
762 * positioning where a wrapper with specific styling is
763 * required around the overlay pane.
764 */
765 get hostElement() {
766 return this._host;
767 }
768 /**
769 * Attaches content, given via a Portal, to the overlay.
770 * If the overlay is configured to have a backdrop, it will be created.
771 *
772 * @param portal Portal instance to which to attach the overlay.
773 * @returns The portal attachment result.
774 */
775 attach(portal) {
776 // Insert the host into the DOM before attaching the portal, otherwise
777 // the animations module will skip animations on repeat attachments.
778 if (!this._host.parentElement && this._previousHostParent) {
779 this._previousHostParent.appendChild(this._host);
780 }
781 const attachResult = this._portalOutlet.attach(portal);
782 if (this._positionStrategy) {
783 this._positionStrategy.attach(this);
784 }
785 this._updateStackingOrder();
786 this._updateElementSize();
787 this._updateElementDirection();
788 if (this._scrollStrategy) {
789 this._scrollStrategy.enable();
790 }
791 // Update the position once the zone is stable so that the overlay will be fully rendered
792 // before attempting to position it, as the position may depend on the size of the rendered
793 // content.
794 this._ngZone.onStable.pipe(take(1)).subscribe(() => {
795 // The overlay could've been detached before the zone has stabilized.
796 if (this.hasAttached()) {
797 this.updatePosition();
798 }
799 });
800 // Enable pointer events for the overlay pane element.
801 this._togglePointerEvents(true);
802 if (this._config.hasBackdrop) {
803 this._attachBackdrop();
804 }
805 if (this._config.panelClass) {
806 this._toggleClasses(this._pane, this._config.panelClass, true);
807 }
808 // Only emit the `attachments` event once all other setup is done.
809 this._attachments.next();
810 // Track this overlay by the keyboard dispatcher
811 this._keyboardDispatcher.add(this);
812 if (this._config.disposeOnNavigation) {
813 this._locationChanges = this._location.subscribe(() => this.dispose());
814 }
815 this._outsideClickDispatcher.add(this);
816 // TODO(crisbeto): the null check is here, because the portal outlet returns `any`.
817 // We should be guaranteed for the result to be `ComponentRef | EmbeddedViewRef`, but
818 // `instanceof EmbeddedViewRef` doesn't appear to work at the moment.
819 if (typeof attachResult?.onDestroy === 'function') {
820 // In most cases we control the portal and we know when it is being detached so that
821 // we can finish the disposal process. The exception is if the user passes in a custom
822 // `ViewContainerRef` that isn't destroyed through the overlay API. Note that we use
823 // `detach` here instead of `dispose`, because we don't know if the user intends to
824 // reattach the overlay at a later point. It also has the advantage of waiting for animations.
825 attachResult.onDestroy(() => {
826 if (this.hasAttached()) {
827 // We have to delay the `detach` call, because detaching immediately prevents
828 // other destroy hooks from running. This is likely a framework bug similar to
829 // https://github.com/angular/angular/issues/46119
830 this._ngZone.runOutsideAngular(() => Promise.resolve().then(() => this.detach()));
831 }
832 });
833 }
834 return attachResult;
835 }
836 /**
837 * Detaches an overlay from a portal.
838 * @returns The portal detachment result.
839 */
840 detach() {
841 if (!this.hasAttached()) {
842 return;
843 }
844 this.detachBackdrop();
845 // When the overlay is detached, the pane element should disable pointer events.
846 // This is necessary because otherwise the pane element will cover the page and disable
847 // pointer events therefore. Depends on the position strategy and the applied pane boundaries.
848 this._togglePointerEvents(false);
849 if (this._positionStrategy && this._positionStrategy.detach) {
850 this._positionStrategy.detach();
851 }
852 if (this._scrollStrategy) {
853 this._scrollStrategy.disable();
854 }
855 const detachmentResult = this._portalOutlet.detach();
856 // Only emit after everything is detached.
857 this._detachments.next();
858 // Remove this overlay from keyboard dispatcher tracking.
859 this._keyboardDispatcher.remove(this);
860 // Keeping the host element in the DOM can cause scroll jank, because it still gets
861 // rendered, even though it's transparent and unclickable which is why we remove it.
862 this._detachContentWhenStable();
863 this._locationChanges.unsubscribe();
864 this._outsideClickDispatcher.remove(this);
865 return detachmentResult;
866 }
867 /** Cleans up the overlay from the DOM. */
868 dispose() {
869 const isAttached = this.hasAttached();
870 if (this._positionStrategy) {
871 this._positionStrategy.dispose();
872 }
873 this._disposeScrollStrategy();
874 this._disposeBackdrop(this._backdropElement);
875 this._locationChanges.unsubscribe();
876 this._keyboardDispatcher.remove(this);
877 this._portalOutlet.dispose();
878 this._attachments.complete();
879 this._backdropClick.complete();
880 this._keydownEvents.complete();
881 this._outsidePointerEvents.complete();
882 this._outsideClickDispatcher.remove(this);
883 this._host?.remove();
884 this._previousHostParent = this._pane = this._host = null;
885 if (isAttached) {
886 this._detachments.next();
887 }
888 this._detachments.complete();
889 }
890 /** Whether the overlay has attached content. */
891 hasAttached() {
892 return this._portalOutlet.hasAttached();
893 }
894 /** Gets an observable that emits when the backdrop has been clicked. */
895 backdropClick() {
896 return this._backdropClick;
897 }
898 /** Gets an observable that emits when the overlay has been attached. */
899 attachments() {
900 return this._attachments;
901 }
902 /** Gets an observable that emits when the overlay has been detached. */
903 detachments() {
904 return this._detachments;
905 }
906 /** Gets an observable of keydown events targeted to this overlay. */
907 keydownEvents() {
908 return this._keydownEvents;
909 }
910 /** Gets an observable of pointer events targeted outside this overlay. */
911 outsidePointerEvents() {
912 return this._outsidePointerEvents;
913 }
914 /** Gets the current overlay configuration, which is immutable. */
915 getConfig() {
916 return this._config;
917 }
918 /** Updates the position of the overlay based on the position strategy. */
919 updatePosition() {
920 if (this._positionStrategy) {
921 this._positionStrategy.apply();
922 }
923 }
924 /** Switches to a new position strategy and updates the overlay position. */
925 updatePositionStrategy(strategy) {
926 if (strategy === this._positionStrategy) {
927 return;
928 }
929 if (this._positionStrategy) {
930 this._positionStrategy.dispose();
931 }
932 this._positionStrategy = strategy;
933 if (this.hasAttached()) {
934 strategy.attach(this);
935 this.updatePosition();
936 }
937 }
938 /** Update the size properties of the overlay. */
939 updateSize(sizeConfig) {
940 this._config = { ...this._config, ...sizeConfig };
941 this._updateElementSize();
942 }
943 /** Sets the LTR/RTL direction for the overlay. */
944 setDirection(dir) {
945 this._config = { ...this._config, direction: dir };
946 this._updateElementDirection();
947 }
948 /** Add a CSS class or an array of classes to the overlay pane. */
949 addPanelClass(classes) {
950 if (this._pane) {
951 this._toggleClasses(this._pane, classes, true);
952 }
953 }
954 /** Remove a CSS class or an array of classes from the overlay pane. */
955 removePanelClass(classes) {
956 if (this._pane) {
957 this._toggleClasses(this._pane, classes, false);
958 }
959 }
960 /**
961 * Returns the layout direction of the overlay panel.
962 */
963 getDirection() {
964 const direction = this._config.direction;
965 if (!direction) {
966 return 'ltr';
967 }
968 return typeof direction === 'string' ? direction : direction.value;
969 }
970 /** Switches to a new scroll strategy. */
971 updateScrollStrategy(strategy) {
972 if (strategy === this._scrollStrategy) {
973 return;
974 }
975 this._disposeScrollStrategy();
976 this._scrollStrategy = strategy;
977 if (this.hasAttached()) {
978 strategy.attach(this);
979 strategy.enable();
980 }
981 }
982 /** Updates the text direction of the overlay panel. */
983 _updateElementDirection() {
984 this._host.setAttribute('dir', this.getDirection());
985 }
986 /** Updates the size of the overlay element based on the overlay config. */
987 _updateElementSize() {
988 if (!this._pane) {
989 return;
990 }
991 const style = this._pane.style;
992 style.width = coerceCssPixelValue(this._config.width);
993 style.height = coerceCssPixelValue(this._config.height);
994 style.minWidth = coerceCssPixelValue(this._config.minWidth);
995 style.minHeight = coerceCssPixelValue(this._config.minHeight);
996 style.maxWidth = coerceCssPixelValue(this._config.maxWidth);
997 style.maxHeight = coerceCssPixelValue(this._config.maxHeight);
998 }
999 /** Toggles the pointer events for the overlay pane element. */
1000 _togglePointerEvents(enablePointer) {
1001 this._pane.style.pointerEvents = enablePointer ? '' : 'none';
1002 }
1003 /** Attaches a backdrop for this overlay. */
1004 _attachBackdrop() {
1005 const showingClass = 'cdk-overlay-backdrop-showing';
1006 this._backdropElement = this._document.createElement('div');
1007 this._backdropElement.classList.add('cdk-overlay-backdrop');
1008 if (this._animationsDisabled) {
1009 this._backdropElement.classList.add('cdk-overlay-backdrop-noop-animation');
1010 }
1011 if (this._config.backdropClass) {
1012 this._toggleClasses(this._backdropElement, this._config.backdropClass, true);
1013 }
1014 // Insert the backdrop before the pane in the DOM order,
1015 // in order to handle stacked overlays properly.
1016 this._host.parentElement.insertBefore(this._backdropElement, this._host);
1017 // Forward backdrop clicks such that the consumer of the overlay can perform whatever
1018 // action desired when such a click occurs (usually closing the overlay).
1019 this._backdropElement.addEventListener('click', this._backdropClickHandler);
1020 // Add class to fade-in the backdrop after one frame.
1021 if (!this._animationsDisabled && typeof requestAnimationFrame !== 'undefined') {
1022 this._ngZone.runOutsideAngular(() => {
1023 requestAnimationFrame(() => {
1024 if (this._backdropElement) {
1025 this._backdropElement.classList.add(showingClass);
1026 }
1027 });
1028 });
1029 }
1030 else {
1031 this._backdropElement.classList.add(showingClass);
1032 }
1033 }
1034 /**
1035 * Updates the stacking order of the element, moving it to the top if necessary.
1036 * This is required in cases where one overlay was detached, while another one,
1037 * that should be behind it, was destroyed. The next time both of them are opened,
1038 * the stacking will be wrong, because the detached element's pane will still be
1039 * in its original DOM position.
1040 */
1041 _updateStackingOrder() {
1042 if (this._host.nextSibling) {
1043 this._host.parentNode.appendChild(this._host);
1044 }
1045 }
1046 /** Detaches the backdrop (if any) associated with the overlay. */
1047 detachBackdrop() {
1048 const backdropToDetach = this._backdropElement;
1049 if (!backdropToDetach) {
1050 return;
1051 }
1052 if (this._animationsDisabled) {
1053 this._disposeBackdrop(backdropToDetach);
1054 return;
1055 }
1056 backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');
1057 this._ngZone.runOutsideAngular(() => {
1058 backdropToDetach.addEventListener('transitionend', this._backdropTransitionendHandler);
1059 });
1060 // If the backdrop doesn't have a transition, the `transitionend` event won't fire.
1061 // In this case we make it unclickable and we try to remove it after a delay.
1062 backdropToDetach.style.pointerEvents = 'none';
1063 // Run this outside the Angular zone because there's nothing that Angular cares about.
1064 // If it were to run inside the Angular zone, every test that used Overlay would have to be
1065 // either async or fakeAsync.
1066 this._backdropTimeout = this._ngZone.runOutsideAngular(() => setTimeout(() => {
1067 this._disposeBackdrop(backdropToDetach);
1068 }, 500));
1069 }
1070 /** Toggles a single CSS class or an array of classes on an element. */
1071 _toggleClasses(element, cssClasses, isAdd) {
1072 const classes = coerceArray(cssClasses || []).filter(c => !!c);
1073 if (classes.length) {
1074 isAdd ? element.classList.add(...classes) : element.classList.remove(...classes);
1075 }
1076 }
1077 /** Detaches the overlay content next time the zone stabilizes. */
1078 _detachContentWhenStable() {
1079 // Normally we wouldn't have to explicitly run this outside the `NgZone`, however
1080 // if the consumer is using `zone-patch-rxjs`, the `Subscription.unsubscribe` call will
1081 // be patched to run inside the zone, which will throw us into an infinite loop.
1082 this._ngZone.runOutsideAngular(() => {
1083 // We can't remove the host here immediately, because the overlay pane's content
1084 // might still be animating. This stream helps us avoid interrupting the animation
1085 // by waiting for the pane to become empty.
1086 const subscription = this._ngZone.onStable
1087 .pipe(takeUntil(merge(this._attachments, this._detachments)))
1088 .subscribe(() => {
1089 // Needs a couple of checks for the pane and host, because
1090 // they may have been removed by the time the zone stabilizes.
1091 if (!this._pane || !this._host || this._pane.children.length === 0) {
1092 if (this._pane && this._config.panelClass) {
1093 this._toggleClasses(this._pane, this._config.panelClass, false);
1094 }
1095 if (this._host && this._host.parentElement) {
1096 this._previousHostParent = this._host.parentElement;
1097 this._host.remove();
1098 }
1099 subscription.unsubscribe();
1100 }
1101 });
1102 });
1103 }
1104 /** Disposes of a scroll strategy. */
1105 _disposeScrollStrategy() {
1106 const scrollStrategy = this._scrollStrategy;
1107 if (scrollStrategy) {
1108 scrollStrategy.disable();
1109 if (scrollStrategy.detach) {
1110 scrollStrategy.detach();
1111 }
1112 }
1113 }
1114 /** Removes a backdrop element from the DOM. */
1115 _disposeBackdrop(backdrop) {
1116 if (backdrop) {
1117 backdrop.removeEventListener('click', this._backdropClickHandler);
1118 backdrop.removeEventListener('transitionend', this._backdropTransitionendHandler);
1119 backdrop.remove();
1120 // It is possible that a new portal has been attached to this overlay since we started
1121 // removing the backdrop. If that is the case, only clear the backdrop reference if it
1122 // is still the same instance that we started to remove.
1123 if (this._backdropElement === backdrop) {
1124 this._backdropElement = null;
1125 }
1126 }
1127 if (this._backdropTimeout) {
1128 clearTimeout(this._backdropTimeout);
1129 this._backdropTimeout = undefined;
1130 }
1131 }
1132}
1133
1134// TODO: refactor clipping detection into a separate thing (part of scrolling module)
1135// TODO: doesn't handle both flexible width and height when it has to scroll along both axis.
1136/** Class to be added to the overlay bounding box. */
1137const boundingBoxClass = 'cdk-overlay-connected-position-bounding-box';
1138/** Regex used to split a string on its CSS units. */
1139const cssUnitPattern = /([A-Za-z%]+)$/;
1140/**
1141 * A strategy for positioning overlays. Using this strategy, an overlay is given an
1142 * implicit position relative some origin element. The relative position is defined in terms of
1143 * a point on the origin element that is connected to a point on the overlay element. For example,
1144 * a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
1145 * of the overlay.
1146 */
1147class FlexibleConnectedPositionStrategy {
1148 /** Ordered list of preferred positions, from most to least desirable. */
1149 get positions() {
1150 return this._preferredPositions;
1151 }
1152 constructor(connectedTo, _viewportRuler, _document, _platform, _overlayContainer) {
1153 this._viewportRuler = _viewportRuler;
1154 this._document = _document;
1155 this._platform = _platform;
1156 this._overlayContainer = _overlayContainer;
1157 /** Last size used for the bounding box. Used to avoid resizing the overlay after open. */
1158 this._lastBoundingBoxSize = { width: 0, height: 0 };
1159 /** Whether the overlay was pushed in a previous positioning. */
1160 this._isPushed = false;
1161 /** Whether the overlay can be pushed on-screen on the initial open. */
1162 this._canPush = true;
1163 /** Whether the overlay can grow via flexible width/height after the initial open. */
1164 this._growAfterOpen = false;
1165 /** Whether the overlay's width and height can be constrained to fit within the viewport. */
1166 this._hasFlexibleDimensions = true;
1167 /** Whether the overlay position is locked. */
1168 this._positionLocked = false;
1169 /** Amount of space that must be maintained between the overlay and the edge of the viewport. */
1170 this._viewportMargin = 0;
1171 /** The Scrollable containers used to check scrollable view properties on position change. */
1172 this._scrollables = [];
1173 /** Ordered list of preferred positions, from most to least desirable. */
1174 this._preferredPositions = [];
1175 /** Subject that emits whenever the position changes. */
1176 this._positionChanges = new Subject();
1177 /** Subscription to viewport size changes. */
1178 this._resizeSubscription = Subscription.EMPTY;
1179 /** Default offset for the overlay along the x axis. */
1180 this._offsetX = 0;
1181 /** Default offset for the overlay along the y axis. */
1182 this._offsetY = 0;
1183 /** Keeps track of the CSS classes that the position strategy has applied on the overlay panel. */
1184 this._appliedPanelClasses = [];
1185 /** Observable sequence of position changes. */
1186 this.positionChanges = this._positionChanges;
1187 this.setOrigin(connectedTo);
1188 }
1189 /** Attaches this position strategy to an overlay. */
1190 attach(overlayRef) {
1191 if (this._overlayRef &&
1192 overlayRef !== this._overlayRef &&
1193 (typeof ngDevMode === 'undefined' || ngDevMode)) {
1194 throw Error('This position strategy is already attached to an overlay');
1195 }
1196 this._validatePositions();
1197 overlayRef.hostElement.classList.add(boundingBoxClass);
1198 this._overlayRef = overlayRef;
1199 this._boundingBox = overlayRef.hostElement;
1200 this._pane = overlayRef.overlayElement;
1201 this._isDisposed = false;
1202 this._isInitialRender = true;
1203 this._lastPosition = null;
1204 this._resizeSubscription.unsubscribe();
1205 this._resizeSubscription = this._viewportRuler.change().subscribe(() => {
1206 // When the window is resized, we want to trigger the next reposition as if it
1207 // was an initial render, in order for the strategy to pick a new optimal position,
1208 // otherwise position locking will cause it to stay at the old one.
1209 this._isInitialRender = true;
1210 this.apply();
1211 });
1212 }
1213 /**
1214 * Updates the position of the overlay element, using whichever preferred position relative
1215 * to the origin best fits on-screen.
1216 *
1217 * The selection of a position goes as follows:
1218 * - If any positions fit completely within the viewport as-is,
1219 * choose the first position that does so.
1220 * - If flexible dimensions are enabled and at least one satisfies the given minimum width/height,
1221 * choose the position with the greatest available size modified by the positions' weight.
1222 * - If pushing is enabled, take the position that went off-screen the least and push it
1223 * on-screen.
1224 * - If none of the previous criteria were met, use the position that goes off-screen the least.
1225 * @docs-private
1226 */
1227 apply() {
1228 // We shouldn't do anything if the strategy was disposed or we're on the server.
1229 if (this._isDisposed || !this._platform.isBrowser) {
1230 return;
1231 }
1232 // If the position has been applied already (e.g. when the overlay was opened) and the
1233 // consumer opted into locking in the position, re-use the old position, in order to
1234 // prevent the overlay from jumping around.
1235 if (!this._isInitialRender && this._positionLocked && this._lastPosition) {
1236 this.reapplyLastPosition();
1237 return;
1238 }
1239 this._clearPanelClasses();
1240 this._resetOverlayElementStyles();
1241 this._resetBoundingBoxStyles();
1242 // We need the bounding rects for the origin, the overlay and the container to determine how to position
1243 // the overlay relative to the origin.
1244 // We use the viewport rect to determine whether a position would go off-screen.
1245 this._viewportRect = this._getNarrowedViewportRect();
1246 this._originRect = this._getOriginRect();
1247 this._overlayRect = this._pane.getBoundingClientRect();
1248 this._containerRect = this._overlayContainer.getContainerElement().getBoundingClientRect();
1249 const originRect = this._originRect;
1250 const overlayRect = this._overlayRect;
1251 const viewportRect = this._viewportRect;
1252 const containerRect = this._containerRect;
1253 // Positions where the overlay will fit with flexible dimensions.
1254 const flexibleFits = [];
1255 // Fallback if none of the preferred positions fit within the viewport.
1256 let fallback;
1257 // Go through each of the preferred positions looking for a good fit.
1258 // If a good fit is found, it will be applied immediately.
1259 for (let pos of this._preferredPositions) {
1260 // Get the exact (x, y) coordinate for the point-of-origin on the origin element.
1261 let originPoint = this._getOriginPoint(originRect, containerRect, pos);
1262 // From that point-of-origin, get the exact (x, y) coordinate for the top-left corner of the
1263 // overlay in this position. We use the top-left corner for calculations and later translate
1264 // this into an appropriate (top, left, bottom, right) style.
1265 let overlayPoint = this._getOverlayPoint(originPoint, overlayRect, pos);
1266 // Calculate how well the overlay would fit into the viewport with this point.
1267 let overlayFit = this._getOverlayFit(overlayPoint, overlayRect, viewportRect, pos);
1268 // If the overlay, without any further work, fits into the viewport, use this position.
1269 if (overlayFit.isCompletelyWithinViewport) {
1270 this._isPushed = false;
1271 this._applyPosition(pos, originPoint);
1272 return;
1273 }
1274 // If the overlay has flexible dimensions, we can use this position
1275 // so long as there's enough space for the minimum dimensions.
1276 if (this._canFitWithFlexibleDimensions(overlayFit, overlayPoint, viewportRect)) {
1277 // Save positions where the overlay will fit with flexible dimensions. We will use these
1278 // if none of the positions fit *without* flexible dimensions.
1279 flexibleFits.push({
1280 position: pos,
1281 origin: originPoint,
1282 overlayRect,
1283 boundingBoxRect: this._calculateBoundingBoxRect(originPoint, pos),
1284 });
1285 continue;
1286 }
1287 // If the current preferred position does not fit on the screen, remember the position
1288 // if it has more visible area on-screen than we've seen and move onto the next preferred
1289 // position.
1290 if (!fallback || fallback.overlayFit.visibleArea < overlayFit.visibleArea) {
1291 fallback = { overlayFit, overlayPoint, originPoint, position: pos, overlayRect };
1292 }
1293 }
1294 // If there are any positions where the overlay would fit with flexible dimensions, choose the
1295 // one that has the greatest area available modified by the position's weight
1296 if (flexibleFits.length) {
1297 let bestFit = null;
1298 let bestScore = -1;
1299 for (const fit of flexibleFits) {
1300 const score = fit.boundingBoxRect.width * fit.boundingBoxRect.height * (fit.position.weight || 1);
1301 if (score > bestScore) {
1302 bestScore = score;
1303 bestFit = fit;
1304 }
1305 }
1306 this._isPushed = false;
1307 this._applyPosition(bestFit.position, bestFit.origin);
1308 return;
1309 }
1310 // When none of the preferred positions fit within the viewport, take the position
1311 // that went off-screen the least and attempt to push it on-screen.
1312 if (this._canPush) {
1313 // TODO(jelbourn): after pushing, the opening "direction" of the overlay might not make sense.
1314 this._isPushed = true;
1315 this._applyPosition(fallback.position, fallback.originPoint);
1316 return;
1317 }
1318 // All options for getting the overlay within the viewport have been exhausted, so go with the
1319 // position that went off-screen the least.
1320 this._applyPosition(fallback.position, fallback.originPoint);
1321 }
1322 detach() {
1323 this._clearPanelClasses();
1324 this._lastPosition = null;
1325 this._previousPushAmount = null;
1326 this._resizeSubscription.unsubscribe();
1327 }
1328 /** Cleanup after the element gets destroyed. */
1329 dispose() {
1330 if (this._isDisposed) {
1331 return;
1332 }
1333 // We can't use `_resetBoundingBoxStyles` here, because it resets
1334 // some properties to zero, rather than removing them.
1335 if (this._boundingBox) {
1336 extendStyles(this._boundingBox.style, {
1337 top: '',
1338 left: '',
1339 right: '',
1340 bottom: '',
1341 height: '',
1342 width: '',
1343 alignItems: '',
1344 justifyContent: '',
1345 });
1346 }
1347 if (this._pane) {
1348 this._resetOverlayElementStyles();
1349 }
1350 if (this._overlayRef) {
1351 this._overlayRef.hostElement.classList.remove(boundingBoxClass);
1352 }
1353 this.detach();
1354 this._positionChanges.complete();
1355 this._overlayRef = this._boundingBox = null;
1356 this._isDisposed = true;
1357 }
1358 /**
1359 * This re-aligns the overlay element with the trigger in its last calculated position,
1360 * even if a position higher in the "preferred positions" list would now fit. This
1361 * allows one to re-align the panel without changing the orientation of the panel.
1362 */
1363 reapplyLastPosition() {
1364 if (this._isDisposed || !this._platform.isBrowser) {
1365 return;
1366 }
1367 const lastPosition = this._lastPosition;
1368 if (lastPosition) {
1369 this._originRect = this._getOriginRect();
1370 this._overlayRect = this._pane.getBoundingClientRect();
1371 this._viewportRect = this._getNarrowedViewportRect();
1372 this._containerRect = this._overlayContainer.getContainerElement().getBoundingClientRect();
1373 const originPoint = this._getOriginPoint(this._originRect, this._containerRect, lastPosition);
1374 this._applyPosition(lastPosition, originPoint);
1375 }
1376 else {
1377 this.apply();
1378 }
1379 }
1380 /**
1381 * Sets the list of Scrollable containers that host the origin element so that
1382 * on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
1383 * Scrollable must be an ancestor element of the strategy's origin element.
1384 */
1385 withScrollableContainers(scrollables) {
1386 this._scrollables = scrollables;
1387 return this;
1388 }
1389 /**
1390 * Adds new preferred positions.
1391 * @param positions List of positions options for this overlay.
1392 */
1393 withPositions(positions) {
1394 this._preferredPositions = positions;
1395 // If the last calculated position object isn't part of the positions anymore, clear
1396 // it in order to avoid it being picked up if the consumer tries to re-apply.
1397 if (positions.indexOf(this._lastPosition) === -1) {
1398 this._lastPosition = null;
1399 }
1400 this._validatePositions();
1401 return this;
1402 }
1403 /**
1404 * Sets a minimum distance the overlay may be positioned to the edge of the viewport.
1405 * @param margin Required margin between the overlay and the viewport edge in pixels.
1406 */
1407 withViewportMargin(margin) {
1408 this._viewportMargin = margin;
1409 return this;
1410 }
1411 /** Sets whether the overlay's width and height can be constrained to fit within the viewport. */
1412 withFlexibleDimensions(flexibleDimensions = true) {
1413 this._hasFlexibleDimensions = flexibleDimensions;
1414 return this;
1415 }
1416 /** Sets whether the overlay can grow after the initial open via flexible width/height. */
1417 withGrowAfterOpen(growAfterOpen = true) {
1418 this._growAfterOpen = growAfterOpen;
1419 return this;
1420 }
1421 /** Sets whether the overlay can be pushed on-screen if none of the provided positions fit. */
1422 withPush(canPush = true) {
1423 this._canPush = canPush;
1424 return this;
1425 }
1426 /**
1427 * Sets whether the overlay's position should be locked in after it is positioned
1428 * initially. When an overlay is locked in, it won't attempt to reposition itself
1429 * when the position is re-applied (e.g. when the user scrolls away).
1430 * @param isLocked Whether the overlay should locked in.
1431 */
1432 withLockedPosition(isLocked = true) {
1433 this._positionLocked = isLocked;
1434 return this;
1435 }
1436 /**
1437 * Sets the origin, relative to which to position the overlay.
1438 * Using an element origin is useful for building components that need to be positioned
1439 * relatively to a trigger (e.g. dropdown menus or tooltips), whereas using a point can be
1440 * used for cases like contextual menus which open relative to the user's pointer.
1441 * @param origin Reference to the new origin.
1442 */
1443 setOrigin(origin) {
1444 this._origin = origin;
1445 return this;
1446 }
1447 /**
1448 * Sets the default offset for the overlay's connection point on the x-axis.
1449 * @param offset New offset in the X axis.
1450 */
1451 withDefaultOffsetX(offset) {
1452 this._offsetX = offset;
1453 return this;
1454 }
1455 /**
1456 * Sets the default offset for the overlay's connection point on the y-axis.
1457 * @param offset New offset in the Y axis.
1458 */
1459 withDefaultOffsetY(offset) {
1460 this._offsetY = offset;
1461 return this;
1462 }
1463 /**
1464 * Configures that the position strategy should set a `transform-origin` on some elements
1465 * inside the overlay, depending on the current position that is being applied. This is
1466 * useful for the cases where the origin of an animation can change depending on the
1467 * alignment of the overlay.
1468 * @param selector CSS selector that will be used to find the target
1469 * elements onto which to set the transform origin.
1470 */
1471 withTransformOriginOn(selector) {
1472 this._transformOriginSelector = selector;
1473 return this;
1474 }
1475 /**
1476 * Gets the (x, y) coordinate of a connection point on the origin based on a relative position.
1477 */
1478 _getOriginPoint(originRect, containerRect, pos) {
1479 let x;
1480 if (pos.originX == 'center') {
1481 // Note: when centering we should always use the `left`
1482 // offset, otherwise the position will be wrong in RTL.
1483 x = originRect.left + originRect.width / 2;
1484 }
1485 else {
1486 const startX = this._isRtl() ? originRect.right : originRect.left;
1487 const endX = this._isRtl() ? originRect.left : originRect.right;
1488 x = pos.originX == 'start' ? startX : endX;
1489 }
1490 // When zooming in Safari the container rectangle contains negative values for the position
1491 // and we need to re-add them to the calculated coordinates.
1492 if (containerRect.left < 0) {
1493 x -= containerRect.left;
1494 }
1495 let y;
1496 if (pos.originY == 'center') {
1497 y = originRect.top + originRect.height / 2;
1498 }
1499 else {
1500 y = pos.originY == 'top' ? originRect.top : originRect.bottom;
1501 }
1502 // Normally the containerRect's top value would be zero, however when the overlay is attached to an input
1503 // (e.g. in an autocomplete), mobile browsers will shift everything in order to put the input in the middle
1504 // of the screen and to make space for the virtual keyboard. We need to account for this offset,
1505 // otherwise our positioning will be thrown off.
1506 // Additionally, when zooming in Safari this fixes the vertical position.
1507 if (containerRect.top < 0) {
1508 y -= containerRect.top;
1509 }
1510 return { x, y };
1511 }
1512 /**
1513 * Gets the (x, y) coordinate of the top-left corner of the overlay given a given position and
1514 * origin point to which the overlay should be connected.
1515 */
1516 _getOverlayPoint(originPoint, overlayRect, pos) {
1517 // Calculate the (overlayStartX, overlayStartY), the start of the
1518 // potential overlay position relative to the origin point.
1519 let overlayStartX;
1520 if (pos.overlayX == 'center') {
1521 overlayStartX = -overlayRect.width / 2;
1522 }
1523 else if (pos.overlayX === 'start') {
1524 overlayStartX = this._isRtl() ? -overlayRect.width : 0;
1525 }
1526 else {
1527 overlayStartX = this._isRtl() ? 0 : -overlayRect.width;
1528 }
1529 let overlayStartY;
1530 if (pos.overlayY == 'center') {
1531 overlayStartY = -overlayRect.height / 2;
1532 }
1533 else {
1534 overlayStartY = pos.overlayY == 'top' ? 0 : -overlayRect.height;
1535 }
1536 // The (x, y) coordinates of the overlay.
1537 return {
1538 x: originPoint.x + overlayStartX,
1539 y: originPoint.y + overlayStartY,
1540 };
1541 }
1542 /** Gets how well an overlay at the given point will fit within the viewport. */
1543 _getOverlayFit(point, rawOverlayRect, viewport, position) {
1544 // Round the overlay rect when comparing against the
1545 // viewport, because the viewport is always rounded.
1546 const overlay = getRoundedBoundingClientRect(rawOverlayRect);
1547 let { x, y } = point;
1548 let offsetX = this._getOffset(position, 'x');
1549 let offsetY = this._getOffset(position, 'y');
1550 // Account for the offsets since they could push the overlay out of the viewport.
1551 if (offsetX) {
1552 x += offsetX;
1553 }
1554 if (offsetY) {
1555 y += offsetY;
1556 }
1557 // How much the overlay would overflow at this position, on each side.
1558 let leftOverflow = 0 - x;
1559 let rightOverflow = x + overlay.width - viewport.width;
1560 let topOverflow = 0 - y;
1561 let bottomOverflow = y + overlay.height - viewport.height;
1562 // Visible parts of the element on each axis.
1563 let visibleWidth = this._subtractOverflows(overlay.width, leftOverflow, rightOverflow);
1564 let visibleHeight = this._subtractOverflows(overlay.height, topOverflow, bottomOverflow);
1565 let visibleArea = visibleWidth * visibleHeight;
1566 return {
1567 visibleArea,
1568 isCompletelyWithinViewport: overlay.width * overlay.height === visibleArea,
1569 fitsInViewportVertically: visibleHeight === overlay.height,
1570 fitsInViewportHorizontally: visibleWidth == overlay.width,
1571 };
1572 }
1573 /**
1574 * Whether the overlay can fit within the viewport when it may resize either its width or height.
1575 * @param fit How well the overlay fits in the viewport at some position.
1576 * @param point The (x, y) coordinates of the overlay at some position.
1577 * @param viewport The geometry of the viewport.
1578 */
1579 _canFitWithFlexibleDimensions(fit, point, viewport) {
1580 if (this._hasFlexibleDimensions) {
1581 const availableHeight = viewport.bottom - point.y;
1582 const availableWidth = viewport.right - point.x;
1583 const minHeight = getPixelValue(this._overlayRef.getConfig().minHeight);
1584 const minWidth = getPixelValue(this._overlayRef.getConfig().minWidth);
1585 const verticalFit = fit.fitsInViewportVertically || (minHeight != null && minHeight <= availableHeight);
1586 const horizontalFit = fit.fitsInViewportHorizontally || (minWidth != null && minWidth <= availableWidth);
1587 return verticalFit && horizontalFit;
1588 }
1589 return false;
1590 }
1591 /**
1592 * Gets the point at which the overlay can be "pushed" on-screen. If the overlay is larger than
1593 * the viewport, the top-left corner will be pushed on-screen (with overflow occurring on the
1594 * right and bottom).
1595 *
1596 * @param start Starting point from which the overlay is pushed.
1597 * @param rawOverlayRect Dimensions of the overlay.
1598 * @param scrollPosition Current viewport scroll position.
1599 * @returns The point at which to position the overlay after pushing. This is effectively a new
1600 * originPoint.
1601 */
1602 _pushOverlayOnScreen(start, rawOverlayRect, scrollPosition) {
1603 // If the position is locked and we've pushed the overlay already, reuse the previous push
1604 // amount, rather than pushing it again. If we were to continue pushing, the element would
1605 // remain in the viewport, which goes against the expectations when position locking is enabled.
1606 if (this._previousPushAmount && this._positionLocked) {
1607 return {
1608 x: start.x + this._previousPushAmount.x,
1609 y: start.y + this._previousPushAmount.y,
1610 };
1611 }
1612 // Round the overlay rect when comparing against the
1613 // viewport, because the viewport is always rounded.
1614 const overlay = getRoundedBoundingClientRect(rawOverlayRect);
1615 const viewport = this._viewportRect;
1616 // Determine how much the overlay goes outside the viewport on each
1617 // side, which we'll use to decide which direction to push it.
1618 const overflowRight = Math.max(start.x + overlay.width - viewport.width, 0);
1619 const overflowBottom = Math.max(start.y + overlay.height - viewport.height, 0);
1620 const overflowTop = Math.max(viewport.top - scrollPosition.top - start.y, 0);
1621 const overflowLeft = Math.max(viewport.left - scrollPosition.left - start.x, 0);
1622 // Amount by which to push the overlay in each axis such that it remains on-screen.
1623 let pushX = 0;
1624 let pushY = 0;
1625 // If the overlay fits completely within the bounds of the viewport, push it from whichever
1626 // direction is goes off-screen. Otherwise, push the top-left corner such that its in the
1627 // viewport and allow for the trailing end of the overlay to go out of bounds.
1628 if (overlay.width <= viewport.width) {
1629 pushX = overflowLeft || -overflowRight;
1630 }
1631 else {
1632 pushX = start.x < this._viewportMargin ? viewport.left - scrollPosition.left - start.x : 0;
1633 }
1634 if (overlay.height <= viewport.height) {
1635 pushY = overflowTop || -overflowBottom;
1636 }
1637 else {
1638 pushY = start.y < this._viewportMargin ? viewport.top - scrollPosition.top - start.y : 0;
1639 }
1640 this._previousPushAmount = { x: pushX, y: pushY };
1641 return {
1642 x: start.x + pushX,
1643 y: start.y + pushY,
1644 };
1645 }
1646 /**
1647 * Applies a computed position to the overlay and emits a position change.
1648 * @param position The position preference
1649 * @param originPoint The point on the origin element where the overlay is connected.
1650 */
1651 _applyPosition(position, originPoint) {
1652 this._setTransformOrigin(position);
1653 this._setOverlayElementStyles(originPoint, position);
1654 this._setBoundingBoxStyles(originPoint, position);
1655 if (position.panelClass) {
1656 this._addPanelClasses(position.panelClass);
1657 }
1658 // Save the last connected position in case the position needs to be re-calculated.
1659 this._lastPosition = position;
1660 // Notify that the position has been changed along with its change properties.
1661 // We only emit if we've got any subscriptions, because the scroll visibility
1662 // calculations can be somewhat expensive.
1663 if (this._positionChanges.observers.length) {
1664 const scrollableViewProperties = this._getScrollVisibility();
1665 const changeEvent = new ConnectedOverlayPositionChange(position, scrollableViewProperties);
1666 this._positionChanges.next(changeEvent);
1667 }
1668 this._isInitialRender = false;
1669 }
1670 /** Sets the transform origin based on the configured selector and the passed-in position. */
1671 _setTransformOrigin(position) {
1672 if (!this._transformOriginSelector) {
1673 return;
1674 }
1675 const elements = this._boundingBox.querySelectorAll(this._transformOriginSelector);
1676 let xOrigin;
1677 let yOrigin = position.overlayY;
1678 if (position.overlayX === 'center') {
1679 xOrigin = 'center';
1680 }
1681 else if (this._isRtl()) {
1682 xOrigin = position.overlayX === 'start' ? 'right' : 'left';
1683 }
1684 else {
1685 xOrigin = position.overlayX === 'start' ? 'left' : 'right';
1686 }
1687 for (let i = 0; i < elements.length; i++) {
1688 elements[i].style.transformOrigin = `${xOrigin} ${yOrigin}`;
1689 }
1690 }
1691 /**
1692 * Gets the position and size of the overlay's sizing container.
1693 *
1694 * This method does no measuring and applies no styles so that we can cheaply compute the
1695 * bounds for all positions and choose the best fit based on these results.
1696 */
1697 _calculateBoundingBoxRect(origin, position) {
1698 const viewport = this._viewportRect;
1699 const isRtl = this._isRtl();
1700 let height, top, bottom;
1701 if (position.overlayY === 'top') {
1702 // Overlay is opening "downward" and thus is bound by the bottom viewport edge.
1703 top = origin.y;
1704 height = viewport.height - top + this._viewportMargin;
1705 }
1706 else if (position.overlayY === 'bottom') {
1707 // Overlay is opening "upward" and thus is bound by the top viewport edge. We need to add
1708 // the viewport margin back in, because the viewport rect is narrowed down to remove the
1709 // margin, whereas the `origin` position is calculated based on its `ClientRect`.
1710 bottom = viewport.height - origin.y + this._viewportMargin * 2;
1711 height = viewport.height - bottom + this._viewportMargin;
1712 }
1713 else {
1714 // If neither top nor bottom, it means that the overlay is vertically centered on the
1715 // origin point. Note that we want the position relative to the viewport, rather than
1716 // the page, which is why we don't use something like `viewport.bottom - origin.y` and
1717 // `origin.y - viewport.top`.
1718 const smallestDistanceToViewportEdge = Math.min(viewport.bottom - origin.y + viewport.top, origin.y);
1719 const previousHeight = this._lastBoundingBoxSize.height;
1720 height = smallestDistanceToViewportEdge * 2;
1721 top = origin.y - smallestDistanceToViewportEdge;
1722 if (height > previousHeight && !this._isInitialRender && !this._growAfterOpen) {
1723 top = origin.y - previousHeight / 2;
1724 }
1725 }
1726 // The overlay is opening 'right-ward' (the content flows to the right).
1727 const isBoundedByRightViewportEdge = (position.overlayX === 'start' && !isRtl) || (position.overlayX === 'end' && isRtl);
1728 // The overlay is opening 'left-ward' (the content flows to the left).
1729 const isBoundedByLeftViewportEdge = (position.overlayX === 'end' && !isRtl) || (position.overlayX === 'start' && isRtl);
1730 let width, left, right;
1731 if (isBoundedByLeftViewportEdge) {
1732 right = viewport.width - origin.x + this._viewportMargin;
1733 width = origin.x - this._viewportMargin;
1734 }
1735 else if (isBoundedByRightViewportEdge) {
1736 left = origin.x;
1737 width = viewport.right - origin.x;
1738 }
1739 else {
1740 // If neither start nor end, it means that the overlay is horizontally centered on the
1741 // origin point. Note that we want the position relative to the viewport, rather than
1742 // the page, which is why we don't use something like `viewport.right - origin.x` and
1743 // `origin.x - viewport.left`.
1744 const smallestDistanceToViewportEdge = Math.min(viewport.right - origin.x + viewport.left, origin.x);
1745 const previousWidth = this._lastBoundingBoxSize.width;
1746 width = smallestDistanceToViewportEdge * 2;
1747 left = origin.x - smallestDistanceToViewportEdge;
1748 if (width > previousWidth && !this._isInitialRender && !this._growAfterOpen) {
1749 left = origin.x - previousWidth / 2;
1750 }
1751 }
1752 return { top: top, left: left, bottom: bottom, right: right, width, height };
1753 }
1754 /**
1755 * Sets the position and size of the overlay's sizing wrapper. The wrapper is positioned on the
1756 * origin's connection point and stretches to the bounds of the viewport.
1757 *
1758 * @param origin The point on the origin element where the overlay is connected.
1759 * @param position The position preference
1760 */
1761 _setBoundingBoxStyles(origin, position) {
1762 const boundingBoxRect = this._calculateBoundingBoxRect(origin, position);
1763 // It's weird if the overlay *grows* while scrolling, so we take the last size into account
1764 // when applying a new size.
1765 if (!this._isInitialRender && !this._growAfterOpen) {
1766 boundingBoxRect.height = Math.min(boundingBoxRect.height, this._lastBoundingBoxSize.height);
1767 boundingBoxRect.width = Math.min(boundingBoxRect.width, this._lastBoundingBoxSize.width);
1768 }
1769 const styles = {};
1770 if (this._hasExactPosition()) {
1771 styles.top = styles.left = '0';
1772 styles.bottom = styles.right = styles.maxHeight = styles.maxWidth = '';
1773 styles.width = styles.height = '100%';
1774 }
1775 else {
1776 const maxHeight = this._overlayRef.getConfig().maxHeight;
1777 const maxWidth = this._overlayRef.getConfig().maxWidth;
1778 styles.height = coerceCssPixelValue(boundingBoxRect.height);
1779 styles.top = coerceCssPixelValue(boundingBoxRect.top);
1780 styles.bottom = coerceCssPixelValue(boundingBoxRect.bottom);
1781 styles.width = coerceCssPixelValue(boundingBoxRect.width);
1782 styles.left = coerceCssPixelValue(boundingBoxRect.left);
1783 styles.right = coerceCssPixelValue(boundingBoxRect.right);
1784 // Push the pane content towards the proper direction.
1785 if (position.overlayX === 'center') {
1786 styles.alignItems = 'center';
1787 }
1788 else {
1789 styles.alignItems = position.overlayX === 'end' ? 'flex-end' : 'flex-start';
1790 }
1791 if (position.overlayY === 'center') {
1792 styles.justifyContent = 'center';
1793 }
1794 else {
1795 styles.justifyContent = position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';
1796 }
1797 if (maxHeight) {
1798 styles.maxHeight = coerceCssPixelValue(maxHeight);
1799 }
1800 if (maxWidth) {
1801 styles.maxWidth = coerceCssPixelValue(maxWidth);
1802 }
1803 }
1804 this._lastBoundingBoxSize = boundingBoxRect;
1805 extendStyles(this._boundingBox.style, styles);
1806 }
1807 /** Resets the styles for the bounding box so that a new positioning can be computed. */
1808 _resetBoundingBoxStyles() {
1809 extendStyles(this._boundingBox.style, {
1810 top: '0',
1811 left: '0',
1812 right: '0',
1813 bottom: '0',
1814 height: '',
1815 width: '',
1816 alignItems: '',
1817 justifyContent: '',
1818 });
1819 }
1820 /** Resets the styles for the overlay pane so that a new positioning can be computed. */
1821 _resetOverlayElementStyles() {
1822 extendStyles(this._pane.style, {
1823 top: '',
1824 left: '',
1825 bottom: '',
1826 right: '',
1827 position: '',
1828 transform: '',
1829 });
1830 }
1831 /** Sets positioning styles to the overlay element. */
1832 _setOverlayElementStyles(originPoint, position) {
1833 const styles = {};
1834 const hasExactPosition = this._hasExactPosition();
1835 const hasFlexibleDimensions = this._hasFlexibleDimensions;
1836 const config = this._overlayRef.getConfig();
1837 if (hasExactPosition) {
1838 const scrollPosition = this._viewportRuler.getViewportScrollPosition();
1839 extendStyles(styles, this._getExactOverlayY(position, originPoint, scrollPosition));
1840 extendStyles(styles, this._getExactOverlayX(position, originPoint, scrollPosition));
1841 }
1842 else {
1843 styles.position = 'static';
1844 }
1845 // Use a transform to apply the offsets. We do this because the `center` positions rely on
1846 // being in the normal flex flow and setting a `top` / `left` at all will completely throw
1847 // off the position. We also can't use margins, because they won't have an effect in some
1848 // cases where the element doesn't have anything to "push off of". Finally, this works
1849 // better both with flexible and non-flexible positioning.
1850 let transformString = '';
1851 let offsetX = this._getOffset(position, 'x');
1852 let offsetY = this._getOffset(position, 'y');
1853 if (offsetX) {
1854 transformString += `translateX(${offsetX}px) `;
1855 }
1856 if (offsetY) {
1857 transformString += `translateY(${offsetY}px)`;
1858 }
1859 styles.transform = transformString.trim();
1860 // If a maxWidth or maxHeight is specified on the overlay, we remove them. We do this because
1861 // we need these values to both be set to "100%" for the automatic flexible sizing to work.
1862 // The maxHeight and maxWidth are set on the boundingBox in order to enforce the constraint.
1863 // Note that this doesn't apply when we have an exact position, in which case we do want to
1864 // apply them because they'll be cleared from the bounding box.
1865 if (config.maxHeight) {
1866 if (hasExactPosition) {
1867 styles.maxHeight = coerceCssPixelValue(config.maxHeight);
1868 }
1869 else if (hasFlexibleDimensions) {
1870 styles.maxHeight = '';
1871 }
1872 }
1873 if (config.maxWidth) {
1874 if (hasExactPosition) {
1875 styles.maxWidth = coerceCssPixelValue(config.maxWidth);
1876 }
1877 else if (hasFlexibleDimensions) {
1878 styles.maxWidth = '';
1879 }
1880 }
1881 extendStyles(this._pane.style, styles);
1882 }
1883 /** Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing. */
1884 _getExactOverlayY(position, originPoint, scrollPosition) {
1885 // Reset any existing styles. This is necessary in case the
1886 // preferred position has changed since the last `apply`.
1887 let styles = { top: '', bottom: '' };
1888 let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
1889 if (this._isPushed) {
1890 overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
1891 }
1892 // We want to set either `top` or `bottom` based on whether the overlay wants to appear
1893 // above or below the origin and the direction in which the element will expand.
1894 if (position.overlayY === 'bottom') {
1895 // When using `bottom`, we adjust the y position such that it is the distance
1896 // from the bottom of the viewport rather than the top.
1897 const documentHeight = this._document.documentElement.clientHeight;
1898 styles.bottom = `${documentHeight - (overlayPoint.y + this._overlayRect.height)}px`;
1899 }
1900 else {
1901 styles.top = coerceCssPixelValue(overlayPoint.y);
1902 }
1903 return styles;
1904 }
1905 /** Gets the exact left/right for the overlay when not using flexible sizing or when pushing. */
1906 _getExactOverlayX(position, originPoint, scrollPosition) {
1907 // Reset any existing styles. This is necessary in case the preferred position has
1908 // changed since the last `apply`.
1909 let styles = { left: '', right: '' };
1910 let overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
1911 if (this._isPushed) {
1912 overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect, scrollPosition);
1913 }
1914 // We want to set either `left` or `right` based on whether the overlay wants to appear "before"
1915 // or "after" the origin, which determines the direction in which the element will expand.
1916 // For the horizontal axis, the meaning of "before" and "after" change based on whether the
1917 // page is in RTL or LTR.
1918 let horizontalStyleProperty;
1919 if (this._isRtl()) {
1920 horizontalStyleProperty = position.overlayX === 'end' ? 'left' : 'right';
1921 }
1922 else {
1923 horizontalStyleProperty = position.overlayX === 'end' ? 'right' : 'left';
1924 }
1925 // When we're setting `right`, we adjust the x position such that it is the distance
1926 // from the right edge of the viewport rather than the left edge.
1927 if (horizontalStyleProperty === 'right') {
1928 const documentWidth = this._document.documentElement.clientWidth;
1929 styles.right = `${documentWidth - (overlayPoint.x + this._overlayRect.width)}px`;
1930 }
1931 else {
1932 styles.left = coerceCssPixelValue(overlayPoint.x);
1933 }
1934 return styles;
1935 }
1936 /**
1937 * Gets the view properties of the trigger and overlay, including whether they are clipped
1938 * or completely outside the view of any of the strategy's scrollables.
1939 */
1940 _getScrollVisibility() {
1941 // Note: needs fresh rects since the position could've changed.
1942 const originBounds = this._getOriginRect();
1943 const overlayBounds = this._pane.getBoundingClientRect();
1944 // TODO(jelbourn): instead of needing all of the client rects for these scrolling containers
1945 // every time, we should be able to use the scrollTop of the containers if the size of those
1946 // containers hasn't changed.
1947 const scrollContainerBounds = this._scrollables.map(scrollable => {
1948 return scrollable.getElementRef().nativeElement.getBoundingClientRect();
1949 });
1950 return {
1951 isOriginClipped: isElementClippedByScrolling(originBounds, scrollContainerBounds),
1952 isOriginOutsideView: isElementScrolledOutsideView(originBounds, scrollContainerBounds),
1953 isOverlayClipped: isElementClippedByScrolling(overlayBounds, scrollContainerBounds),
1954 isOverlayOutsideView: isElementScrolledOutsideView(overlayBounds, scrollContainerBounds),
1955 };
1956 }
1957 /** Subtracts the amount that an element is overflowing on an axis from its length. */
1958 _subtractOverflows(length, ...overflows) {
1959 return overflows.reduce((currentValue, currentOverflow) => {
1960 return currentValue - Math.max(currentOverflow, 0);
1961 }, length);
1962 }
1963 /** Narrows the given viewport rect by the current _viewportMargin. */
1964 _getNarrowedViewportRect() {
1965 // We recalculate the viewport rect here ourselves, rather than using the ViewportRuler,
1966 // because we want to use the `clientWidth` and `clientHeight` as the base. The difference
1967 // being that the client properties don't include the scrollbar, as opposed to `innerWidth`
1968 // and `innerHeight` that do. This is necessary, because the overlay container uses
1969 // 100% `width` and `height` which don't include the scrollbar either.
1970 const width = this._document.documentElement.clientWidth;
1971 const height = this._document.documentElement.clientHeight;
1972 const scrollPosition = this._viewportRuler.getViewportScrollPosition();
1973 return {
1974 top: scrollPosition.top + this._viewportMargin,
1975 left: scrollPosition.left + this._viewportMargin,
1976 right: scrollPosition.left + width - this._viewportMargin,
1977 bottom: scrollPosition.top + height - this._viewportMargin,
1978 width: width - 2 * this._viewportMargin,
1979 height: height - 2 * this._viewportMargin,
1980 };
1981 }
1982 /** Whether the we're dealing with an RTL context */
1983 _isRtl() {
1984 return this._overlayRef.getDirection() === 'rtl';
1985 }
1986 /** Determines whether the overlay uses exact or flexible positioning. */
1987 _hasExactPosition() {
1988 return !this._hasFlexibleDimensions || this._isPushed;
1989 }
1990 /** Retrieves the offset of a position along the x or y axis. */
1991 _getOffset(position, axis) {
1992 if (axis === 'x') {
1993 // We don't do something like `position['offset' + axis]` in
1994 // order to avoid breaking minifiers that rename properties.
1995 return position.offsetX == null ? this._offsetX : position.offsetX;
1996 }
1997 return position.offsetY == null ? this._offsetY : position.offsetY;
1998 }
1999 /** Validates that the current position match the expected values. */
2000 _validatePositions() {
2001 if (typeof ngDevMode === 'undefined' || ngDevMode) {
2002 if (!this._preferredPositions.length) {
2003 throw Error('FlexibleConnectedPositionStrategy: At least one position is required.');
2004 }
2005 // TODO(crisbeto): remove these once Angular's template type
2006 // checking is advanced enough to catch these cases.
2007 this._preferredPositions.forEach(pair => {
2008 validateHorizontalPosition('originX', pair.originX);
2009 validateVerticalPosition('originY', pair.originY);
2010 validateHorizontalPosition('overlayX', pair.overlayX);
2011 validateVerticalPosition('overlayY', pair.overlayY);
2012 });
2013 }
2014 }
2015 /** Adds a single CSS class or an array of classes on the overlay panel. */
2016 _addPanelClasses(cssClasses) {
2017 if (this._pane) {
2018 coerceArray(cssClasses).forEach(cssClass => {
2019 if (cssClass !== '' && this._appliedPanelClasses.indexOf(cssClass) === -1) {
2020 this._appliedPanelClasses.push(cssClass);
2021 this._pane.classList.add(cssClass);
2022 }
2023 });
2024 }
2025 }
2026 /** Clears the classes that the position strategy has applied from the overlay panel. */
2027 _clearPanelClasses() {
2028 if (this._pane) {
2029 this._appliedPanelClasses.forEach(cssClass => {
2030 this._pane.classList.remove(cssClass);
2031 });
2032 this._appliedPanelClasses = [];
2033 }
2034 }
2035 /** Returns the ClientRect of the current origin. */
2036 _getOriginRect() {
2037 const origin = this._origin;
2038 if (origin instanceof ElementRef) {
2039 return origin.nativeElement.getBoundingClientRect();
2040 }
2041 // Check for Element so SVG elements are also supported.
2042 if (origin instanceof Element) {
2043 return origin.getBoundingClientRect();
2044 }
2045 const width = origin.width || 0;
2046 const height = origin.height || 0;
2047 // If the origin is a point, return a client rect as if it was a 0x0 element at the point.
2048 return {
2049 top: origin.y,
2050 bottom: origin.y + height,
2051 left: origin.x,
2052 right: origin.x + width,
2053 height,
2054 width,
2055 };
2056 }
2057}
2058/** Shallow-extends a stylesheet object with another stylesheet object. */
2059function extendStyles(destination, source) {
2060 for (let key in source) {
2061 if (source.hasOwnProperty(key)) {
2062 destination[key] = source[key];
2063 }
2064 }
2065 return destination;
2066}
2067/**
2068 * Extracts the pixel value as a number from a value, if it's a number
2069 * or a CSS pixel string (e.g. `1337px`). Otherwise returns null.
2070 */
2071function getPixelValue(input) {
2072 if (typeof input !== 'number' && input != null) {
2073 const [value, units] = input.split(cssUnitPattern);
2074 return !units || units === 'px' ? parseFloat(value) : null;
2075 }
2076 return input || null;
2077}
2078/**
2079 * Gets a version of an element's bounding `ClientRect` where all the values are rounded down to
2080 * the nearest pixel. This allows us to account for the cases where there may be sub-pixel
2081 * deviations in the `ClientRect` returned by the browser (e.g. when zoomed in with a percentage
2082 * size, see #21350).
2083 */
2084function getRoundedBoundingClientRect(clientRect) {
2085 return {
2086 top: Math.floor(clientRect.top),
2087 right: Math.floor(clientRect.right),
2088 bottom: Math.floor(clientRect.bottom),
2089 left: Math.floor(clientRect.left),
2090 width: Math.floor(clientRect.width),
2091 height: Math.floor(clientRect.height),
2092 };
2093}
2094const STANDARD_DROPDOWN_BELOW_POSITIONS = [
2095 { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top' },
2096 { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom' },
2097 { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top' },
2098 { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom' },
2099];
2100const STANDARD_DROPDOWN_ADJACENT_POSITIONS = [
2101 { originX: 'end', originY: 'top', overlayX: 'start', overlayY: 'top' },
2102 { originX: 'end', originY: 'bottom', overlayX: 'start', overlayY: 'bottom' },
2103 { originX: 'start', originY: 'top', overlayX: 'end', overlayY: 'top' },
2104 { originX: 'start', originY: 'bottom', overlayX: 'end', overlayY: 'bottom' },
2105];
2106
2107/** Class to be added to the overlay pane wrapper. */
2108const wrapperClass = 'cdk-global-overlay-wrapper';
2109/**
2110 * A strategy for positioning overlays. Using this strategy, an overlay is given an
2111 * explicit position relative to the browser's viewport. We use flexbox, instead of
2112 * transforms, in order to avoid issues with subpixel rendering which can cause the
2113 * element to become blurry.
2114 */
2115class GlobalPositionStrategy {
2116 constructor() {
2117 this._cssPosition = 'static';
2118 this._topOffset = '';
2119 this._bottomOffset = '';
2120 this._alignItems = '';
2121 this._xPosition = '';
2122 this._xOffset = '';
2123 this._width = '';
2124 this._height = '';
2125 this._isDisposed = false;
2126 }
2127 attach(overlayRef) {
2128 const config = overlayRef.getConfig();
2129 this._overlayRef = overlayRef;
2130 if (this._width && !config.width) {
2131 overlayRef.updateSize({ width: this._width });
2132 }
2133 if (this._height && !config.height) {
2134 overlayRef.updateSize({ height: this._height });
2135 }
2136 overlayRef.hostElement.classList.add(wrapperClass);
2137 this._isDisposed = false;
2138 }
2139 /**
2140 * Sets the top position of the overlay. Clears any previously set vertical position.
2141 * @param value New top offset.
2142 */
2143 top(value = '') {
2144 this._bottomOffset = '';
2145 this._topOffset = value;
2146 this._alignItems = 'flex-start';
2147 return this;
2148 }
2149 /**
2150 * Sets the left position of the overlay. Clears any previously set horizontal position.
2151 * @param value New left offset.
2152 */
2153 left(value = '') {
2154 this._xOffset = value;
2155 this._xPosition = 'left';
2156 return this;
2157 }
2158 /**
2159 * Sets the bottom position of the overlay. Clears any previously set vertical position.
2160 * @param value New bottom offset.
2161 */
2162 bottom(value = '') {
2163 this._topOffset = '';
2164 this._bottomOffset = value;
2165 this._alignItems = 'flex-end';
2166 return this;
2167 }
2168 /**
2169 * Sets the right position of the overlay. Clears any previously set horizontal position.
2170 * @param value New right offset.
2171 */
2172 right(value = '') {
2173 this._xOffset = value;
2174 this._xPosition = 'right';
2175 return this;
2176 }
2177 /**
2178 * Sets the overlay to the start of the viewport, depending on the overlay direction.
2179 * This will be to the left in LTR layouts and to the right in RTL.
2180 * @param offset Offset from the edge of the screen.
2181 */
2182 start(value = '') {
2183 this._xOffset = value;
2184 this._xPosition = 'start';
2185 return this;
2186 }
2187 /**
2188 * Sets the overlay to the end of the viewport, depending on the overlay direction.
2189 * This will be to the right in LTR layouts and to the left in RTL.
2190 * @param offset Offset from the edge of the screen.
2191 */
2192 end(value = '') {
2193 this._xOffset = value;
2194 this._xPosition = 'end';
2195 return this;
2196 }
2197 /**
2198 * Sets the overlay width and clears any previously set width.
2199 * @param value New width for the overlay
2200 * @deprecated Pass the `width` through the `OverlayConfig`.
2201 * @breaking-change 8.0.0
2202 */
2203 width(value = '') {
2204 if (this._overlayRef) {
2205 this._overlayRef.updateSize({ width: value });
2206 }
2207 else {
2208 this._width = value;
2209 }
2210 return this;
2211 }
2212 /**
2213 * Sets the overlay height and clears any previously set height.
2214 * @param value New height for the overlay
2215 * @deprecated Pass the `height` through the `OverlayConfig`.
2216 * @breaking-change 8.0.0
2217 */
2218 height(value = '') {
2219 if (this._overlayRef) {
2220 this._overlayRef.updateSize({ height: value });
2221 }
2222 else {
2223 this._height = value;
2224 }
2225 return this;
2226 }
2227 /**
2228 * Centers the overlay horizontally with an optional offset.
2229 * Clears any previously set horizontal position.
2230 *
2231 * @param offset Overlay offset from the horizontal center.
2232 */
2233 centerHorizontally(offset = '') {
2234 this.left(offset);
2235 this._xPosition = 'center';
2236 return this;
2237 }
2238 /**
2239 * Centers the overlay vertically with an optional offset.
2240 * Clears any previously set vertical position.
2241 *
2242 * @param offset Overlay offset from the vertical center.
2243 */
2244 centerVertically(offset = '') {
2245 this.top(offset);
2246 this._alignItems = 'center';
2247 return this;
2248 }
2249 /**
2250 * Apply the position to the element.
2251 * @docs-private
2252 */
2253 apply() {
2254 // Since the overlay ref applies the strategy asynchronously, it could
2255 // have been disposed before it ends up being applied. If that is the
2256 // case, we shouldn't do anything.
2257 if (!this._overlayRef || !this._overlayRef.hasAttached()) {
2258 return;
2259 }
2260 const styles = this._overlayRef.overlayElement.style;
2261 const parentStyles = this._overlayRef.hostElement.style;
2262 const config = this._overlayRef.getConfig();
2263 const { width, height, maxWidth, maxHeight } = config;
2264 const shouldBeFlushHorizontally = (width === '100%' || width === '100vw') &&
2265 (!maxWidth || maxWidth === '100%' || maxWidth === '100vw');
2266 const shouldBeFlushVertically = (height === '100%' || height === '100vh') &&
2267 (!maxHeight || maxHeight === '100%' || maxHeight === '100vh');
2268 const xPosition = this._xPosition;
2269 const xOffset = this._xOffset;
2270 const isRtl = this._overlayRef.getConfig().direction === 'rtl';
2271 let marginLeft = '';
2272 let marginRight = '';
2273 let justifyContent = '';
2274 if (shouldBeFlushHorizontally) {
2275 justifyContent = 'flex-start';
2276 }
2277 else if (xPosition === 'center') {
2278 justifyContent = 'center';
2279 if (isRtl) {
2280 marginRight = xOffset;
2281 }
2282 else {
2283 marginLeft = xOffset;
2284 }
2285 }
2286 else if (isRtl) {
2287 if (xPosition === 'left' || xPosition === 'end') {
2288 justifyContent = 'flex-end';
2289 marginLeft = xOffset;
2290 }
2291 else if (xPosition === 'right' || xPosition === 'start') {
2292 justifyContent = 'flex-start';
2293 marginRight = xOffset;
2294 }
2295 }
2296 else if (xPosition === 'left' || xPosition === 'start') {
2297 justifyContent = 'flex-start';
2298 marginLeft = xOffset;
2299 }
2300 else if (xPosition === 'right' || xPosition === 'end') {
2301 justifyContent = 'flex-end';
2302 marginRight = xOffset;
2303 }
2304 styles.position = this._cssPosition;
2305 styles.marginLeft = shouldBeFlushHorizontally ? '0' : marginLeft;
2306 styles.marginTop = shouldBeFlushVertically ? '0' : this._topOffset;
2307 styles.marginBottom = this._bottomOffset;
2308 styles.marginRight = shouldBeFlushHorizontally ? '0' : marginRight;
2309 parentStyles.justifyContent = justifyContent;
2310 parentStyles.alignItems = shouldBeFlushVertically ? 'flex-start' : this._alignItems;
2311 }
2312 /**
2313 * Cleans up the DOM changes from the position strategy.
2314 * @docs-private
2315 */
2316 dispose() {
2317 if (this._isDisposed || !this._overlayRef) {
2318 return;
2319 }
2320 const styles = this._overlayRef.overlayElement.style;
2321 const parent = this._overlayRef.hostElement;
2322 const parentStyles = parent.style;
2323 parent.classList.remove(wrapperClass);
2324 parentStyles.justifyContent =
2325 parentStyles.alignItems =
2326 styles.marginTop =
2327 styles.marginBottom =
2328 styles.marginLeft =
2329 styles.marginRight =
2330 styles.position =
2331 '';
2332 this._overlayRef = null;
2333 this._isDisposed = true;
2334 }
2335}
2336
2337/** Builder for overlay position strategy. */
2338class OverlayPositionBuilder {
2339 constructor(_viewportRuler, _document, _platform, _overlayContainer) {
2340 this._viewportRuler = _viewportRuler;
2341 this._document = _document;
2342 this._platform = _platform;
2343 this._overlayContainer = _overlayContainer;
2344 }
2345 /**
2346 * Creates a global position strategy.
2347 */
2348 global() {
2349 return new GlobalPositionStrategy();
2350 }
2351 /**
2352 * Creates a flexible position strategy.
2353 * @param origin Origin relative to which to position the overlay.
2354 */
2355 flexibleConnectedTo(origin) {
2356 return new FlexibleConnectedPositionStrategy(origin, this._viewportRuler, this._document, this._platform, this._overlayContainer);
2357 }
2358 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayPositionBuilder, deps: [{ token: i1.ViewportRuler }, { token: DOCUMENT }, { token: i1$1.Platform }, { token: OverlayContainer }], target: i0.ɵɵFactoryTarget.Injectable }); }
2359 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayPositionBuilder, providedIn: 'root' }); }
2360}
2361i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayPositionBuilder, decorators: [{
2362 type: Injectable,
2363 args: [{ providedIn: 'root' }]
2364 }], ctorParameters: function () { return [{ type: i1.ViewportRuler }, { type: undefined, decorators: [{
2365 type: Inject,
2366 args: [DOCUMENT]
2367 }] }, { type: i1$1.Platform }, { type: OverlayContainer }]; } });
2368
2369/** Next overlay unique ID. */
2370let nextUniqueId = 0;
2371// Note that Overlay is *not* scoped to the app root because of the ComponentFactoryResolver
2372// which needs to be different depending on where OverlayModule is imported.
2373/**
2374 * Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
2375 * used as a low-level building block for other components. Dialogs, tooltips, menus,
2376 * selects, etc. can all be built using overlays. The service should primarily be used by authors
2377 * of re-usable components rather than developers building end-user applications.
2378 *
2379 * An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
2380 */
2381class Overlay {
2382 constructor(
2383 /** Scrolling strategies that can be used when creating an overlay. */
2384 scrollStrategies, _overlayContainer, _componentFactoryResolver, _positionBuilder, _keyboardDispatcher, _injector, _ngZone, _document, _directionality, _location, _outsideClickDispatcher, _animationsModuleType) {
2385 this.scrollStrategies = scrollStrategies;
2386 this._overlayContainer = _overlayContainer;
2387 this._componentFactoryResolver = _componentFactoryResolver;
2388 this._positionBuilder = _positionBuilder;
2389 this._keyboardDispatcher = _keyboardDispatcher;
2390 this._injector = _injector;
2391 this._ngZone = _ngZone;
2392 this._document = _document;
2393 this._directionality = _directionality;
2394 this._location = _location;
2395 this._outsideClickDispatcher = _outsideClickDispatcher;
2396 this._animationsModuleType = _animationsModuleType;
2397 }
2398 /**
2399 * Creates an overlay.
2400 * @param config Configuration applied to the overlay.
2401 * @returns Reference to the created overlay.
2402 */
2403 create(config) {
2404 const host = this._createHostElement();
2405 const pane = this._createPaneElement(host);
2406 const portalOutlet = this._createPortalOutlet(pane);
2407 const overlayConfig = new OverlayConfig(config);
2408 overlayConfig.direction = overlayConfig.direction || this._directionality.value;
2409 return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone, this._keyboardDispatcher, this._document, this._location, this._outsideClickDispatcher, this._animationsModuleType === 'NoopAnimations');
2410 }
2411 /**
2412 * Gets a position builder that can be used, via fluent API,
2413 * to construct and configure a position strategy.
2414 * @returns An overlay position builder.
2415 */
2416 position() {
2417 return this._positionBuilder;
2418 }
2419 /**
2420 * Creates the DOM element for an overlay and appends it to the overlay container.
2421 * @returns Newly-created pane element
2422 */
2423 _createPaneElement(host) {
2424 const pane = this._document.createElement('div');
2425 pane.id = `cdk-overlay-${nextUniqueId++}`;
2426 pane.classList.add('cdk-overlay-pane');
2427 host.appendChild(pane);
2428 return pane;
2429 }
2430 /**
2431 * Creates the host element that wraps around an overlay
2432 * and can be used for advanced positioning.
2433 * @returns Newly-create host element.
2434 */
2435 _createHostElement() {
2436 const host = this._document.createElement('div');
2437 this._overlayContainer.getContainerElement().appendChild(host);
2438 return host;
2439 }
2440 /**
2441 * Create a DomPortalOutlet into which the overlay content can be loaded.
2442 * @param pane The DOM element to turn into a portal outlet.
2443 * @returns A portal outlet for the given DOM element.
2444 */
2445 _createPortalOutlet(pane) {
2446 // We have to resolve the ApplicationRef later in order to allow people
2447 // to use overlay-based providers during app initialization.
2448 if (!this._appRef) {
2449 this._appRef = this._injector.get(ApplicationRef);
2450 }
2451 return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector, this._document);
2452 }
2453 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: Overlay, deps: [{ token: ScrollStrategyOptions }, { token: OverlayContainer }, { token: i0.ComponentFactoryResolver }, { token: OverlayPositionBuilder }, { token: OverlayKeyboardDispatcher }, { token: i0.Injector }, { token: i0.NgZone }, { token: DOCUMENT }, { token: i5.Directionality }, { token: i6.Location }, { token: OverlayOutsideClickDispatcher }, { token: ANIMATION_MODULE_TYPE, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
2454 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: Overlay, providedIn: 'root' }); }
2455}
2456i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: Overlay, decorators: [{
2457 type: Injectable,
2458 args: [{ providedIn: 'root' }]
2459 }], ctorParameters: function () { return [{ type: ScrollStrategyOptions }, { type: OverlayContainer }, { type: i0.ComponentFactoryResolver }, { type: OverlayPositionBuilder }, { type: OverlayKeyboardDispatcher }, { type: i0.Injector }, { type: i0.NgZone }, { type: undefined, decorators: [{
2460 type: Inject,
2461 args: [DOCUMENT]
2462 }] }, { type: i5.Directionality }, { type: i6.Location }, { type: OverlayOutsideClickDispatcher }, { type: undefined, decorators: [{
2463 type: Inject,
2464 args: [ANIMATION_MODULE_TYPE]
2465 }, {
2466 type: Optional
2467 }] }]; } });
2468
2469/** Default set of positions for the overlay. Follows the behavior of a dropdown. */
2470const defaultPositionList = [
2471 {
2472 originX: 'start',
2473 originY: 'bottom',
2474 overlayX: 'start',
2475 overlayY: 'top',
2476 },
2477 {
2478 originX: 'start',
2479 originY: 'top',
2480 overlayX: 'start',
2481 overlayY: 'bottom',
2482 },
2483 {
2484 originX: 'end',
2485 originY: 'top',
2486 overlayX: 'end',
2487 overlayY: 'bottom',
2488 },
2489 {
2490 originX: 'end',
2491 originY: 'bottom',
2492 overlayX: 'end',
2493 overlayY: 'top',
2494 },
2495];
2496/** Injection token that determines the scroll handling while the connected overlay is open. */
2497const CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY = new InjectionToken('cdk-connected-overlay-scroll-strategy');
2498/**
2499 * Directive applied to an element to make it usable as an origin for an Overlay using a
2500 * ConnectedPositionStrategy.
2501 */
2502class CdkOverlayOrigin {
2503 constructor(
2504 /** Reference to the element on which the directive is applied. */
2505 elementRef) {
2506 this.elementRef = elementRef;
2507 }
2508 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkOverlayOrigin, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive }); }
2509 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkOverlayOrigin, isStandalone: true, selector: "[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]", exportAs: ["cdkOverlayOrigin"], ngImport: i0 }); }
2510}
2511i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkOverlayOrigin, decorators: [{
2512 type: Directive,
2513 args: [{
2514 selector: '[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]',
2515 exportAs: 'cdkOverlayOrigin',
2516 standalone: true,
2517 }]
2518 }], ctorParameters: function () { return [{ type: i0.ElementRef }]; } });
2519/**
2520 * Directive to facilitate declarative creation of an
2521 * Overlay using a FlexibleConnectedPositionStrategy.
2522 */
2523class CdkConnectedOverlay {
2524 /** The offset in pixels for the overlay connection point on the x-axis */
2525 get offsetX() {
2526 return this._offsetX;
2527 }
2528 set offsetX(offsetX) {
2529 this._offsetX = offsetX;
2530 if (this._position) {
2531 this._updatePositionStrategy(this._position);
2532 }
2533 }
2534 /** The offset in pixels for the overlay connection point on the y-axis */
2535 get offsetY() {
2536 return this._offsetY;
2537 }
2538 set offsetY(offsetY) {
2539 this._offsetY = offsetY;
2540 if (this._position) {
2541 this._updatePositionStrategy(this._position);
2542 }
2543 }
2544 /** Whether or not the overlay should attach a backdrop. */
2545 get hasBackdrop() {
2546 return this._hasBackdrop;
2547 }
2548 set hasBackdrop(value) {
2549 this._hasBackdrop = coerceBooleanProperty(value);
2550 }
2551 /** Whether or not the overlay should be locked when scrolling. */
2552 get lockPosition() {
2553 return this._lockPosition;
2554 }
2555 set lockPosition(value) {
2556 this._lockPosition = coerceBooleanProperty(value);
2557 }
2558 /** Whether the overlay's width and height can be constrained to fit within the viewport. */
2559 get flexibleDimensions() {
2560 return this._flexibleDimensions;
2561 }
2562 set flexibleDimensions(value) {
2563 this._flexibleDimensions = coerceBooleanProperty(value);
2564 }
2565 /** Whether the overlay can grow after the initial open when flexible positioning is turned on. */
2566 get growAfterOpen() {
2567 return this._growAfterOpen;
2568 }
2569 set growAfterOpen(value) {
2570 this._growAfterOpen = coerceBooleanProperty(value);
2571 }
2572 /** Whether the overlay can be pushed on-screen if none of the provided positions fit. */
2573 get push() {
2574 return this._push;
2575 }
2576 set push(value) {
2577 this._push = coerceBooleanProperty(value);
2578 }
2579 // TODO(jelbourn): inputs for size, scroll behavior, animation, etc.
2580 constructor(_overlay, templateRef, viewContainerRef, scrollStrategyFactory, _dir) {
2581 this._overlay = _overlay;
2582 this._dir = _dir;
2583 this._hasBackdrop = false;
2584 this._lockPosition = false;
2585 this._growAfterOpen = false;
2586 this._flexibleDimensions = false;
2587 this._push = false;
2588 this._backdropSubscription = Subscription.EMPTY;
2589 this._attachSubscription = Subscription.EMPTY;
2590 this._detachSubscription = Subscription.EMPTY;
2591 this._positionSubscription = Subscription.EMPTY;
2592 /** Margin between the overlay and the viewport edges. */
2593 this.viewportMargin = 0;
2594 /** Whether the overlay is open. */
2595 this.open = false;
2596 /** Whether the overlay can be closed by user interaction. */
2597 this.disableClose = false;
2598 /** Event emitted when the backdrop is clicked. */
2599 this.backdropClick = new EventEmitter();
2600 /** Event emitted when the position has changed. */
2601 this.positionChange = new EventEmitter();
2602 /** Event emitted when the overlay has been attached. */
2603 this.attach = new EventEmitter();
2604 /** Event emitted when the overlay has been detached. */
2605 this.detach = new EventEmitter();
2606 /** Emits when there are keyboard events that are targeted at the overlay. */
2607 this.overlayKeydown = new EventEmitter();
2608 /** Emits when there are mouse outside click events that are targeted at the overlay. */
2609 this.overlayOutsideClick = new EventEmitter();
2610 this._templatePortal = new TemplatePortal(templateRef, viewContainerRef);
2611 this._scrollStrategyFactory = scrollStrategyFactory;
2612 this.scrollStrategy = this._scrollStrategyFactory();
2613 }
2614 /** The associated overlay reference. */
2615 get overlayRef() {
2616 return this._overlayRef;
2617 }
2618 /** The element's layout direction. */
2619 get dir() {
2620 return this._dir ? this._dir.value : 'ltr';
2621 }
2622 ngOnDestroy() {
2623 this._attachSubscription.unsubscribe();
2624 this._detachSubscription.unsubscribe();
2625 this._backdropSubscription.unsubscribe();
2626 this._positionSubscription.unsubscribe();
2627 if (this._overlayRef) {
2628 this._overlayRef.dispose();
2629 }
2630 }
2631 ngOnChanges(changes) {
2632 if (this._position) {
2633 this._updatePositionStrategy(this._position);
2634 this._overlayRef.updateSize({
2635 width: this.width,
2636 minWidth: this.minWidth,
2637 height: this.height,
2638 minHeight: this.minHeight,
2639 });
2640 if (changes['origin'] && this.open) {
2641 this._position.apply();
2642 }
2643 }
2644 if (changes['open']) {
2645 this.open ? this._attachOverlay() : this._detachOverlay();
2646 }
2647 }
2648 /** Creates an overlay */
2649 _createOverlay() {
2650 if (!this.positions || !this.positions.length) {
2651 this.positions = defaultPositionList;
2652 }
2653 const overlayRef = (this._overlayRef = this._overlay.create(this._buildConfig()));
2654 this._attachSubscription = overlayRef.attachments().subscribe(() => this.attach.emit());
2655 this._detachSubscription = overlayRef.detachments().subscribe(() => this.detach.emit());
2656 overlayRef.keydownEvents().subscribe((event) => {
2657 this.overlayKeydown.next(event);
2658 if (event.keyCode === ESCAPE && !this.disableClose && !hasModifierKey(event)) {
2659 event.preventDefault();
2660 this._detachOverlay();
2661 }
2662 });
2663 this._overlayRef.outsidePointerEvents().subscribe((event) => {
2664 this.overlayOutsideClick.next(event);
2665 });
2666 }
2667 /** Builds the overlay config based on the directive's inputs */
2668 _buildConfig() {
2669 const positionStrategy = (this._position =
2670 this.positionStrategy || this._createPositionStrategy());
2671 const overlayConfig = new OverlayConfig({
2672 direction: this._dir,
2673 positionStrategy,
2674 scrollStrategy: this.scrollStrategy,
2675 hasBackdrop: this.hasBackdrop,
2676 });
2677 if (this.width || this.width === 0) {
2678 overlayConfig.width = this.width;
2679 }
2680 if (this.height || this.height === 0) {
2681 overlayConfig.height = this.height;
2682 }
2683 if (this.minWidth || this.minWidth === 0) {
2684 overlayConfig.minWidth = this.minWidth;
2685 }
2686 if (this.minHeight || this.minHeight === 0) {
2687 overlayConfig.minHeight = this.minHeight;
2688 }
2689 if (this.backdropClass) {
2690 overlayConfig.backdropClass = this.backdropClass;
2691 }
2692 if (this.panelClass) {
2693 overlayConfig.panelClass = this.panelClass;
2694 }
2695 return overlayConfig;
2696 }
2697 /** Updates the state of a position strategy, based on the values of the directive inputs. */
2698 _updatePositionStrategy(positionStrategy) {
2699 const positions = this.positions.map(currentPosition => ({
2700 originX: currentPosition.originX,
2701 originY: currentPosition.originY,
2702 overlayX: currentPosition.overlayX,
2703 overlayY: currentPosition.overlayY,
2704 offsetX: currentPosition.offsetX || this.offsetX,
2705 offsetY: currentPosition.offsetY || this.offsetY,
2706 panelClass: currentPosition.panelClass || undefined,
2707 }));
2708 return positionStrategy
2709 .setOrigin(this._getFlexibleConnectedPositionStrategyOrigin())
2710 .withPositions(positions)
2711 .withFlexibleDimensions(this.flexibleDimensions)
2712 .withPush(this.push)
2713 .withGrowAfterOpen(this.growAfterOpen)
2714 .withViewportMargin(this.viewportMargin)
2715 .withLockedPosition(this.lockPosition)
2716 .withTransformOriginOn(this.transformOriginSelector);
2717 }
2718 /** Returns the position strategy of the overlay to be set on the overlay config */
2719 _createPositionStrategy() {
2720 const strategy = this._overlay
2721 .position()
2722 .flexibleConnectedTo(this._getFlexibleConnectedPositionStrategyOrigin());
2723 this._updatePositionStrategy(strategy);
2724 return strategy;
2725 }
2726 _getFlexibleConnectedPositionStrategyOrigin() {
2727 if (this.origin instanceof CdkOverlayOrigin) {
2728 return this.origin.elementRef;
2729 }
2730 else {
2731 return this.origin;
2732 }
2733 }
2734 /** Attaches the overlay and subscribes to backdrop clicks if backdrop exists */
2735 _attachOverlay() {
2736 if (!this._overlayRef) {
2737 this._createOverlay();
2738 }
2739 else {
2740 // Update the overlay size, in case the directive's inputs have changed
2741 this._overlayRef.getConfig().hasBackdrop = this.hasBackdrop;
2742 }
2743 if (!this._overlayRef.hasAttached()) {
2744 this._overlayRef.attach(this._templatePortal);
2745 }
2746 if (this.hasBackdrop) {
2747 this._backdropSubscription = this._overlayRef.backdropClick().subscribe(event => {
2748 this.backdropClick.emit(event);
2749 });
2750 }
2751 else {
2752 this._backdropSubscription.unsubscribe();
2753 }
2754 this._positionSubscription.unsubscribe();
2755 // Only subscribe to `positionChanges` if requested, because putting
2756 // together all the information for it can be expensive.
2757 if (this.positionChange.observers.length > 0) {
2758 this._positionSubscription = this._position.positionChanges
2759 .pipe(takeWhile(() => this.positionChange.observers.length > 0))
2760 .subscribe(position => {
2761 this.positionChange.emit(position);
2762 if (this.positionChange.observers.length === 0) {
2763 this._positionSubscription.unsubscribe();
2764 }
2765 });
2766 }
2767 }
2768 /** Detaches the overlay and unsubscribes to backdrop clicks if backdrop exists */
2769 _detachOverlay() {
2770 if (this._overlayRef) {
2771 this._overlayRef.detach();
2772 }
2773 this._backdropSubscription.unsubscribe();
2774 this._positionSubscription.unsubscribe();
2775 }
2776 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkConnectedOverlay, deps: [{ token: Overlay }, { token: i0.TemplateRef }, { token: i0.ViewContainerRef }, { token: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY }, { token: i5.Directionality, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
2777 static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.0", type: CdkConnectedOverlay, isStandalone: true, selector: "[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]", inputs: { origin: ["cdkConnectedOverlayOrigin", "origin"], positions: ["cdkConnectedOverlayPositions", "positions"], positionStrategy: ["cdkConnectedOverlayPositionStrategy", "positionStrategy"], offsetX: ["cdkConnectedOverlayOffsetX", "offsetX"], offsetY: ["cdkConnectedOverlayOffsetY", "offsetY"], width: ["cdkConnectedOverlayWidth", "width"], height: ["cdkConnectedOverlayHeight", "height"], minWidth: ["cdkConnectedOverlayMinWidth", "minWidth"], minHeight: ["cdkConnectedOverlayMinHeight", "minHeight"], backdropClass: ["cdkConnectedOverlayBackdropClass", "backdropClass"], panelClass: ["cdkConnectedOverlayPanelClass", "panelClass"], viewportMargin: ["cdkConnectedOverlayViewportMargin", "viewportMargin"], scrollStrategy: ["cdkConnectedOverlayScrollStrategy", "scrollStrategy"], open: ["cdkConnectedOverlayOpen", "open"], disableClose: ["cdkConnectedOverlayDisableClose", "disableClose"], transformOriginSelector: ["cdkConnectedOverlayTransformOriginOn", "transformOriginSelector"], hasBackdrop: ["cdkConnectedOverlayHasBackdrop", "hasBackdrop"], lockPosition: ["cdkConnectedOverlayLockPosition", "lockPosition"], flexibleDimensions: ["cdkConnectedOverlayFlexibleDimensions", "flexibleDimensions"], growAfterOpen: ["cdkConnectedOverlayGrowAfterOpen", "growAfterOpen"], push: ["cdkConnectedOverlayPush", "push"] }, outputs: { backdropClick: "backdropClick", positionChange: "positionChange", attach: "attach", detach: "detach", overlayKeydown: "overlayKeydown", overlayOutsideClick: "overlayOutsideClick" }, exportAs: ["cdkConnectedOverlay"], usesOnChanges: true, ngImport: i0 }); }
2778}
2779i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: CdkConnectedOverlay, decorators: [{
2780 type: Directive,
2781 args: [{
2782 selector: '[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]',
2783 exportAs: 'cdkConnectedOverlay',
2784 standalone: true,
2785 }]
2786 }], ctorParameters: function () { return [{ type: Overlay }, { type: i0.TemplateRef }, { type: i0.ViewContainerRef }, { type: undefined, decorators: [{
2787 type: Inject,
2788 args: [CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY]
2789 }] }, { type: i5.Directionality, decorators: [{
2790 type: Optional
2791 }] }]; }, propDecorators: { origin: [{
2792 type: Input,
2793 args: ['cdkConnectedOverlayOrigin']
2794 }], positions: [{
2795 type: Input,
2796 args: ['cdkConnectedOverlayPositions']
2797 }], positionStrategy: [{
2798 type: Input,
2799 args: ['cdkConnectedOverlayPositionStrategy']
2800 }], offsetX: [{
2801 type: Input,
2802 args: ['cdkConnectedOverlayOffsetX']
2803 }], offsetY: [{
2804 type: Input,
2805 args: ['cdkConnectedOverlayOffsetY']
2806 }], width: [{
2807 type: Input,
2808 args: ['cdkConnectedOverlayWidth']
2809 }], height: [{
2810 type: Input,
2811 args: ['cdkConnectedOverlayHeight']
2812 }], minWidth: [{
2813 type: Input,
2814 args: ['cdkConnectedOverlayMinWidth']
2815 }], minHeight: [{
2816 type: Input,
2817 args: ['cdkConnectedOverlayMinHeight']
2818 }], backdropClass: [{
2819 type: Input,
2820 args: ['cdkConnectedOverlayBackdropClass']
2821 }], panelClass: [{
2822 type: Input,
2823 args: ['cdkConnectedOverlayPanelClass']
2824 }], viewportMargin: [{
2825 type: Input,
2826 args: ['cdkConnectedOverlayViewportMargin']
2827 }], scrollStrategy: [{
2828 type: Input,
2829 args: ['cdkConnectedOverlayScrollStrategy']
2830 }], open: [{
2831 type: Input,
2832 args: ['cdkConnectedOverlayOpen']
2833 }], disableClose: [{
2834 type: Input,
2835 args: ['cdkConnectedOverlayDisableClose']
2836 }], transformOriginSelector: [{
2837 type: Input,
2838 args: ['cdkConnectedOverlayTransformOriginOn']
2839 }], hasBackdrop: [{
2840 type: Input,
2841 args: ['cdkConnectedOverlayHasBackdrop']
2842 }], lockPosition: [{
2843 type: Input,
2844 args: ['cdkConnectedOverlayLockPosition']
2845 }], flexibleDimensions: [{
2846 type: Input,
2847 args: ['cdkConnectedOverlayFlexibleDimensions']
2848 }], growAfterOpen: [{
2849 type: Input,
2850 args: ['cdkConnectedOverlayGrowAfterOpen']
2851 }], push: [{
2852 type: Input,
2853 args: ['cdkConnectedOverlayPush']
2854 }], backdropClick: [{
2855 type: Output
2856 }], positionChange: [{
2857 type: Output
2858 }], attach: [{
2859 type: Output
2860 }], detach: [{
2861 type: Output
2862 }], overlayKeydown: [{
2863 type: Output
2864 }], overlayOutsideClick: [{
2865 type: Output
2866 }] } });
2867/** @docs-private */
2868function CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay) {
2869 return () => overlay.scrollStrategies.reposition();
2870}
2871/** @docs-private */
2872const CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER = {
2873 provide: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,
2874 deps: [Overlay],
2875 useFactory: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY,
2876};
2877
2878class OverlayModule {
2879 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
2880 static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.0", ngImport: i0, type: OverlayModule, imports: [BidiModule, PortalModule, ScrollingModule, CdkConnectedOverlay, CdkOverlayOrigin], exports: [CdkConnectedOverlay, CdkOverlayOrigin, ScrollingModule] }); }
2881 static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayModule, providers: [Overlay, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER], imports: [BidiModule, PortalModule, ScrollingModule, ScrollingModule] }); }
2882}
2883i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: OverlayModule, decorators: [{
2884 type: NgModule,
2885 args: [{
2886 imports: [BidiModule, PortalModule, ScrollingModule, CdkConnectedOverlay, CdkOverlayOrigin],
2887 exports: [CdkConnectedOverlay, CdkOverlayOrigin, ScrollingModule],
2888 providers: [Overlay, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER],
2889 }]
2890 }] });
2891
2892/**
2893 * Alternative to OverlayContainer that supports correct displaying of overlay elements in
2894 * Fullscreen mode
2895 * https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen
2896 *
2897 * Should be provided in the root component.
2898 */
2899class FullscreenOverlayContainer extends OverlayContainer {
2900 constructor(_document, platform) {
2901 super(_document, platform);
2902 }
2903 ngOnDestroy() {
2904 super.ngOnDestroy();
2905 if (this._fullScreenEventName && this._fullScreenListener) {
2906 this._document.removeEventListener(this._fullScreenEventName, this._fullScreenListener);
2907 }
2908 }
2909 _createContainer() {
2910 super._createContainer();
2911 this._adjustParentForFullscreenChange();
2912 this._addFullscreenChangeListener(() => this._adjustParentForFullscreenChange());
2913 }
2914 _adjustParentForFullscreenChange() {
2915 if (!this._containerElement) {
2916 return;
2917 }
2918 const fullscreenElement = this.getFullscreenElement();
2919 const parent = fullscreenElement || this._document.body;
2920 parent.appendChild(this._containerElement);
2921 }
2922 _addFullscreenChangeListener(fn) {
2923 const eventName = this._getEventName();
2924 if (eventName) {
2925 if (this._fullScreenListener) {
2926 this._document.removeEventListener(eventName, this._fullScreenListener);
2927 }
2928 this._document.addEventListener(eventName, fn);
2929 this._fullScreenListener = fn;
2930 }
2931 }
2932 _getEventName() {
2933 if (!this._fullScreenEventName) {
2934 const _document = this._document;
2935 if (_document.fullscreenEnabled) {
2936 this._fullScreenEventName = 'fullscreenchange';
2937 }
2938 else if (_document.webkitFullscreenEnabled) {
2939 this._fullScreenEventName = 'webkitfullscreenchange';
2940 }
2941 else if (_document.mozFullScreenEnabled) {
2942 this._fullScreenEventName = 'mozfullscreenchange';
2943 }
2944 else if (_document.msFullscreenEnabled) {
2945 this._fullScreenEventName = 'MSFullscreenChange';
2946 }
2947 }
2948 return this._fullScreenEventName;
2949 }
2950 /**
2951 * When the page is put into fullscreen mode, a specific element is specified.
2952 * Only that element and its children are visible when in fullscreen mode.
2953 */
2954 getFullscreenElement() {
2955 const _document = this._document;
2956 return (_document.fullscreenElement ||
2957 _document.webkitFullscreenElement ||
2958 _document.mozFullScreenElement ||
2959 _document.msFullscreenElement ||
2960 null);
2961 }
2962 static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: FullscreenOverlayContainer, deps: [{ token: DOCUMENT }, { token: i1$1.Platform }], target: i0.ɵɵFactoryTarget.Injectable }); }
2963 static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: FullscreenOverlayContainer, providedIn: 'root' }); }
2964}
2965i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.0", ngImport: i0, type: FullscreenOverlayContainer, decorators: [{
2966 type: Injectable,
2967 args: [{ providedIn: 'root' }]
2968 }], ctorParameters: function () { return [{ type: undefined, decorators: [{
2969 type: Inject,
2970 args: [DOCUMENT]
2971 }] }, { type: i1$1.Platform }]; } });
2972
2973/**
2974 * Generated bundle index. Do not edit.
2975 */
2976
2977export { BlockScrollStrategy, CdkConnectedOverlay, CdkOverlayOrigin, CloseScrollStrategy, ConnectedOverlayPositionChange, ConnectionPositionPair, FlexibleConnectedPositionStrategy, FullscreenOverlayContainer, GlobalPositionStrategy, NoopScrollStrategy, Overlay, OverlayConfig, OverlayContainer, OverlayKeyboardDispatcher, OverlayModule, OverlayOutsideClickDispatcher, OverlayPositionBuilder, OverlayRef, RepositionScrollStrategy, STANDARD_DROPDOWN_ADJACENT_POSITIONS, STANDARD_DROPDOWN_BELOW_POSITIONS, ScrollStrategyOptions, ScrollingVisibility, validateHorizontalPosition, validateVerticalPosition };
2978//# sourceMappingURL=overlay.mjs.map