Skip to content

Commit 9a114f5

Browse files
committed
refactor(overlay): use component to render backdrop
Uses an Angular component to render the backdrop, instead of managing a DOM element manually. This has the advantage of being able to leverage the animations API to transition in/out, as well as not having to worry about the cases where the backdrop animation is disabled. These changes also enable the backdrop transition for the dialog (previously it would be removed immediately on close).
1 parent 595cffd commit 9a114f5

File tree

9 files changed

+121
-109
lines changed

9 files changed

+121
-109
lines changed

src/cdk/overlay/_overlay.scss

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,9 @@ $backdrop-animation-timing-function: cubic-bezier(0.25, 0.8, 0.25, 1) !default;
6363
transition: opacity $backdrop-animation-duration $backdrop-animation-timing-function;
6464
opacity: 0;
6565

66-
&.cdk-overlay-backdrop-showing {
67-
opacity: 0.48;
66+
// Prevent the user from interacting while the backdrop is animating.
67+
&.ng-animating {
68+
pointer-events: none;
6869
}
6970
}
7071

src/cdk/overlay/backdrop.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* @license
3+
* Copyright Google Inc. All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import {
10+
Component,
11+
ViewEncapsulation,
12+
ChangeDetectionStrategy,
13+
OnDestroy,
14+
Renderer2,
15+
ElementRef,
16+
} from '@angular/core';
17+
import {animate, AnimationEvent, state, style, transition, trigger} from '@angular/animations';
18+
import {Subject} from 'rxjs/Subject';
19+
20+
/**
21+
* Semi-transparent backdrop that will be rendered behind an overlay.
22+
* @docs-private
23+
*/
24+
@Component({
25+
template: '',
26+
host: {
27+
'class': 'cdk-overlay-backdrop',
28+
'[@state]': '_animationState',
29+
'(@state.done)': '_animationStream.next($event)',
30+
'(click)': '_clickStream.next()',
31+
},
32+
animations: [
33+
trigger('state', [
34+
state('void', style({opacity: '0'})),
35+
state('visible', style({opacity: '0.48'})),
36+
transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
37+
])
38+
],
39+
changeDetection: ChangeDetectionStrategy.OnPush,
40+
encapsulation: ViewEncapsulation.None,
41+
})
42+
export class MdBackdrop implements OnDestroy {
43+
_animationState = 'visible';
44+
_clickStream = new Subject<void>();
45+
_animationStream = new Subject<AnimationEvent>();
46+
47+
constructor(private _element: ElementRef, private _renderer: Renderer2) {}
48+
49+
_setClass(cssClass: string) {
50+
this._renderer.addClass(this._element.nativeElement, cssClass);
51+
}
52+
53+
ngOnDestroy() {
54+
this._clickStream.complete();
55+
}
56+
}

src/cdk/overlay/overlay-directives.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {Component, ViewChild} from '@angular/core';
22
import {By} from '@angular/platform-browser';
33
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
4+
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
45
import {Directionality} from '@angular/cdk/bidi';
56
import {dispatchKeyboardEvent} from '@angular/cdk/testing';
67
import {ESCAPE} from '@angular/cdk/keycodes';
@@ -17,7 +18,7 @@ describe('Overlay directives', () => {
1718

1819
beforeEach(() => {
1920
TestBed.configureTestingModule({
20-
imports: [OverlayModule],
21+
imports: [OverlayModule, NoopAnimationsModule],
2122
declarations: [ConnectedOverlayDirectiveTest, ConnectedOverlayPropertyInitOrder],
2223
providers: [
2324
{provide: OverlayContainer, useFactory: () => {

src/cdk/overlay/overlay-ref.ts

Lines changed: 30 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,30 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {NgZone} from '@angular/core';
109
import {PortalHost, Portal} from '@angular/cdk/portal';
1110
import {OverlayState} from './overlay-state';
1211
import {Observable} from 'rxjs/Observable';
1312
import {Subject} from 'rxjs/Subject';
13+
import {MdBackdrop} from './backdrop';
14+
import {ComponentPortal} from '@angular/cdk/portal';
15+
import {first} from '@angular/cdk/rxjs';
16+
import {empty} from 'rxjs/observable/empty';
1417

1518

1619
/**
1720
* Reference to an overlay that has been created with the Overlay service.
1821
* Used to manipulate or dispose of said overlay.
1922
*/
2023
export class OverlayRef implements PortalHost {
21-
private _backdropElement: HTMLElement | null = null;
22-
private _backdropClick: Subject<any> = new Subject();
2324
private _attachments = new Subject<void>();
2425
private _detachments = new Subject<void>();
26+
private _backdropInstance: MdBackdrop | null;
2527

2628
constructor(
2729
private _portalHost: PortalHost,
2830
private _pane: HTMLElement,
29-
private _state: OverlayState,
30-
private _ngZone: NgZone) {
31+
private _backdropHost: PortalHost | null,
32+
private _state: OverlayState) {
3133

3234
_state.scrollStrategy.attach(this);
3335
}
@@ -43,7 +45,7 @@ export class OverlayRef implements PortalHost {
4345
* @returns The portal attachment result.
4446
*/
4547
attach(portal: Portal<any>): any {
46-
let attachResult = this._portalHost.attach(portal);
48+
const attachResult = this._portalHost.attach(portal);
4749

4850
if (this._state.positionStrategy) {
4951
this._state.positionStrategy.attach(this);
@@ -59,14 +61,15 @@ export class OverlayRef implements PortalHost {
5961
// Enable pointer events for the overlay pane element.
6062
this._togglePointerEvents(true);
6163

62-
if (this._state.hasBackdrop) {
63-
this._attachBackdrop();
64+
if (this._backdropHost) {
65+
this._backdropInstance = this._backdropHost.attach(new ComponentPortal(MdBackdrop)).instance;
66+
this._backdropInstance!._setClass(this._state.backdropClass!);
6467
}
6568

6669
if (this._state.panelClass) {
6770
// We can't do a spread here, because IE doesn't support setting multiple classes.
6871
if (Array.isArray(this._state.panelClass)) {
69-
this._state.panelClass.forEach(cls => this._pane.classList.add(cls));
72+
this._state.panelClass.forEach(cssClass => this._pane.classList.add(cssClass));
7073
} else {
7174
this._pane.classList.add(this._state.panelClass);
7275
}
@@ -83,15 +86,17 @@ export class OverlayRef implements PortalHost {
8386
* @returns Resolves when the overlay has been detached.
8487
*/
8588
detach(): Promise<any> {
86-
this.detachBackdrop();
89+
if (this._backdropHost && this._backdropHost.hasAttached()) {
90+
this._backdropHost.detach();
91+
}
8792

8893
// When the overlay is detached, the pane element should disable pointer events.
8994
// This is necessary because otherwise the pane element will cover the page and disable
9095
// pointer events therefore. Depends on the position strategy and the applied pane boundaries.
9196
this._togglePointerEvents(false);
9297
this._state.scrollStrategy.disable();
9398

94-
let detachmentResult = this._portalHost.detach();
99+
const detachmentResult = this._portalHost.detach();
95100

96101
// Only emit after everything is detached.
97102
this._detachments.next();
@@ -108,10 +113,9 @@ export class OverlayRef implements PortalHost {
108113
}
109114

110115
this._state.scrollStrategy.disable();
111-
this.detachBackdrop();
116+
this.disposeBackdrop();
112117
this._portalHost.dispose();
113118
this._attachments.complete();
114-
this._backdropClick.complete();
115119
this._detachments.next();
116120
this._detachments.complete();
117121
}
@@ -127,7 +131,7 @@ export class OverlayRef implements PortalHost {
127131
* Returns an observable that emits when the backdrop has been clicked.
128132
*/
129133
backdropClick(): Observable<void> {
130-
return this._backdropClick.asObservable();
134+
return this._backdropInstance ? this._backdropInstance._clickStream : empty<void>();
131135
}
132136

133137
/** Returns an observable that emits when the overlay has been attached. */
@@ -191,31 +195,6 @@ export class OverlayRef implements PortalHost {
191195
this._pane.style.pointerEvents = enablePointer ? 'auto' : 'none';
192196
}
193197

194-
/** Attaches a backdrop for this overlay. */
195-
private _attachBackdrop() {
196-
this._backdropElement = document.createElement('div');
197-
this._backdropElement.classList.add('cdk-overlay-backdrop');
198-
199-
if (this._state.backdropClass) {
200-
this._backdropElement.classList.add(this._state.backdropClass);
201-
}
202-
203-
// Insert the backdrop before the pane in the DOM order,
204-
// in order to handle stacked overlays properly.
205-
this._pane.parentElement!.insertBefore(this._backdropElement, this._pane);
206-
207-
// Forward backdrop clicks such that the consumer of the overlay can perform whatever
208-
// action desired when such a click occurs (usually closing the overlay).
209-
this._backdropElement.addEventListener('click', () => this._backdropClick.next(null));
210-
211-
// Add class to fade-in the backdrop after one frame.
212-
requestAnimationFrame(() => {
213-
if (this._backdropElement) {
214-
this._backdropElement.classList.add('cdk-overlay-backdrop-showing');
215-
}
216-
});
217-
}
218-
219198
/**
220199
* Updates the stacking order of the element, moving it to the top if necessary.
221200
* This is required in cases where one overlay was detached, while another one,
@@ -229,43 +208,19 @@ export class OverlayRef implements PortalHost {
229208
}
230209
}
231210

232-
/** Detaches the backdrop (if any) associated with the overlay. */
233-
detachBackdrop(): void {
234-
let backdropToDetach = this._backdropElement;
235-
236-
if (backdropToDetach) {
237-
let finishDetach = () => {
238-
// It may not be attached to anything in certain cases (e.g. unit tests).
239-
if (backdropToDetach && backdropToDetach.parentNode) {
240-
backdropToDetach.parentNode.removeChild(backdropToDetach);
241-
}
242-
243-
// It is possible that a new portal has been attached to this overlay since we started
244-
// removing the backdrop. If that is the case, only clear the backdrop reference if it
245-
// is still the same instance that we started to remove.
246-
if (this._backdropElement == backdropToDetach) {
247-
this._backdropElement = null;
248-
}
249-
};
250-
251-
backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');
252-
253-
if (this._state.backdropClass) {
254-
backdropToDetach.classList.remove(this._state.backdropClass);
255-
}
256-
257-
backdropToDetach.addEventListener('transitionend', finishDetach);
211+
/** Animates out and disposes of the backdrop. */
212+
disposeBackdrop(): void {
213+
if (this._backdropHost) {
214+
if (this._backdropHost.hasAttached()) {
215+
this._backdropHost.detach();
258216

259-
// If the backdrop doesn't have a transition, the `transitionend` event won't fire.
260-
// In this case we make it unclickable and we try to remove it after a delay.
261-
backdropToDetach.style.pointerEvents = 'none';
262-
263-
// Run this outside the Angular zone because there's nothing that Angular cares about.
264-
// If it were to run inside the Angular zone, every test that used Overlay would have to be
265-
// either async or fakeAsync.
266-
this._ngZone.runOutsideAngular(() => {
267-
setTimeout(finishDetach, 500);
268-
});
217+
first.call(this._backdropInstance!._animationStream).subscribe(() => {
218+
this._backdropHost!.dispose();
219+
this._backdropHost = this._backdropInstance = null;
220+
});
221+
} else {
222+
this._backdropHost.dispose();
223+
}
269224
}
270225
}
271226
}

src/cdk/overlay/overlay.spec.ts

Lines changed: 6 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing';
22
import {Component, NgModule, ViewChild, ViewContainerRef} from '@angular/core';
3+
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
34
import {
45
ComponentPortal,
56
PortalModule,
@@ -26,7 +27,7 @@ describe('Overlay', () => {
2627

2728
beforeEach(async(() => {
2829
TestBed.configureTestingModule({
29-
imports: [OverlayModule, PortalModule, OverlayTestModule],
30+
imports: [OverlayModule, PortalModule, OverlayTestModule, NoopAnimationsModule],
3031
providers: [{
3132
provide: OverlayContainer,
3233
useFactory: () => {
@@ -81,6 +82,7 @@ describe('Overlay', () => {
8182
.toBe('auto', 'Expected the overlay pane to enable pointerEvents when attached.');
8283

8384
overlayRef.detach();
85+
viewContainerFixture.detectChanges();
8486

8587
expect(paneElement.childNodes.length).toBe(0);
8688
expect(paneElement.style.pointerEvents)
@@ -185,6 +187,8 @@ describe('Overlay', () => {
185187
let overlayRef = overlay.create();
186188

187189
overlayRef.detachments().subscribe(() => {
190+
viewContainerFixture.detectChanges();
191+
188192
expect(overlayContainerElement.querySelector('pizza'))
189193
.toBeFalsy('Expected the overlay to have been detached.');
190194
});
@@ -338,7 +342,6 @@ describe('Overlay', () => {
338342
viewContainerFixture.detectChanges();
339343
let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
340344
expect(backdrop).toBeTruthy();
341-
expect(backdrop.classList).not.toContain('cdk-overlay-backdrop-showing');
342345

343346
let backdropClickHandler = jasmine.createSpy('backdropClickHander');
344347
overlayRef.backdropClick().subscribe(backdropClickHandler);
@@ -381,27 +384,13 @@ describe('Overlay', () => {
381384
expect(backdrop.classList).toContain('cdk-overlay-transparent-backdrop');
382385
});
383386

384-
it('should disable the pointer events of a backdrop that is being removed', () => {
385-
let overlayRef = overlay.create(config);
386-
overlayRef.attach(componentPortal);
387-
388-
viewContainerFixture.detectChanges();
389-
let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
390-
391-
expect(backdrop.style.pointerEvents).toBeFalsy();
392-
393-
overlayRef.detach();
394-
395-
expect(backdrop.style.pointerEvents).toBe('none');
396-
});
397-
398387
it('should insert the backdrop before the overlay pane in the DOM order', () => {
399388
let overlayRef = overlay.create(config);
400389
overlayRef.attach(componentPortal);
401390

402391
viewContainerFixture.detectChanges();
403392

404-
let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop');
393+
let backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop')!.parentNode;
405394
let pane = overlayContainerElement.querySelector('.cdk-overlay-pane');
406395
let children = Array.prototype.slice.call(overlayContainerElement.children);
407396

0 commit comments

Comments
 (0)