Skip to content

feat(overlay): detach on outside click #16611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/cdk/overlay/dispatchers/base-overlay-dispatcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {DOCUMENT} from '@angular/common';
import {Inject, Injectable, OnDestroy} from '@angular/core';
import {OverlayReference} from '../overlay-reference';


/**
* Service for dispatching events that land on the body to appropriate overlay ref,
* if any. It maintains a list of attached overlays to determine best suited overlay based
* on event target and order of overlay opens.
*/
@Injectable({providedIn: 'root'})
export abstract class BaseOverlayDispatcher implements OnDestroy {

/** Currently attached overlays in the order they were attached. */
_attachedOverlays: OverlayReference[] = [];

protected _document: Document;
protected _isAttached: boolean;

constructor(@Inject(DOCUMENT) document: any) {
this._document = document;
}

ngOnDestroy(): void {
this.detach();
}

/** Add a new overlay to the list of attached overlay refs. */
add(overlayRef: OverlayReference): void {
// Ensure that we don't get the same overlay multiple times.
this.remove(overlayRef);
this._attachedOverlays.push(overlayRef);
}

/** Remove an overlay from the list of attached overlay refs. */
remove(overlayRef: OverlayReference): void {
const index = this._attachedOverlays.indexOf(overlayRef);

if (index > -1) {
this._attachedOverlays.splice(index, 1);
}

// Remove the global listener once there are no more overlays.
if (this._attachedOverlays.length === 0) {
this.detach();
}
}

/** Detaches the global event listener. */
protected abstract detach(): void;
}
10 changes: 10 additions & 0 deletions src/cdk/overlay/dispatchers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

export {OverlayOutsideClickDispatcher} from './overlay-outside-click-dispatcher';
export {OverlayKeyboardDispatcher} from './overlay-keyboard-dispatcher';
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import {
Inject,
Injectable,
InjectionToken,
OnDestroy,
Optional,
SkipSelf,
} from '@angular/core';
import {OverlayReference} from '../overlay-reference';
import {BaseOverlayDispatcher} from './base-overlay-dispatcher';


/**
Expand All @@ -24,52 +24,25 @@ import {OverlayReference} from '../overlay-reference';
* on event target and order of overlay opens.
*/
@Injectable({providedIn: 'root'})
export class OverlayKeyboardDispatcher implements OnDestroy {

/** Currently attached overlays in the order they were attached. */
_attachedOverlays: OverlayReference[] = [];

private _document: Document;
private _isAttached: boolean;
export class OverlayKeyboardDispatcher extends BaseOverlayDispatcher {

constructor(@Inject(DOCUMENT) document: any) {
this._document = document;
}

ngOnDestroy() {
this._detach();
super(document);
}

/** Add a new overlay to the list of attached overlay refs. */
add(overlayRef: OverlayReference): void {
// Ensure that we don't get the same overlay multiple times.
this.remove(overlayRef);
super.add(overlayRef);

// Lazily start dispatcher once first overlay is added
if (!this._isAttached) {
this._document.body.addEventListener('keydown', this._keydownListener);
this._isAttached = true;
}

this._attachedOverlays.push(overlayRef);
}

/** Remove an overlay from the list of attached overlay refs. */
remove(overlayRef: OverlayReference): void {
const index = this._attachedOverlays.indexOf(overlayRef);

if (index > -1) {
this._attachedOverlays.splice(index, 1);
}

// Remove the global listener once there are no more overlays.
if (this._attachedOverlays.length === 0) {
this._detach();
}
}

/** Detaches the global keyboard event listener. */
private _detach() {
protected detach() {
if (this._isAttached) {
this._document.body.removeEventListener('keydown', this._keydownListener);
this._isAttached = false;
Expand Down
166 changes: 166 additions & 0 deletions src/cdk/overlay/dispatchers/overlay-outside-click-dispatcher.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import {TestBed, inject} from '@angular/core/testing';
import {Component, NgModule} from '@angular/core';
import {OverlayModule, OverlayContainer, Overlay} from '../index';
import {OverlayOutsideClickDispatcher} from './overlay-outside-click-dispatcher';
import {ComponentPortal} from '@angular/cdk/portal';


describe('OverlayOutsideClickDispatcher', () => {
let outsideClickDispatcher: OverlayOutsideClickDispatcher;
let overlay: Overlay;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [OverlayModule, TestComponentModule],
});

inject([OverlayOutsideClickDispatcher, Overlay],
(ocd: OverlayOutsideClickDispatcher, o: Overlay) => {
outsideClickDispatcher = ocd;
overlay = o;
})();
});

afterEach(inject([OverlayContainer], (overlayContainer: OverlayContainer) => {
overlayContainer.ngOnDestroy();
}));

it('should track overlays in order as they are attached and detached', () => {
const overlayOne = overlay.create();
const overlayTwo = overlay.create();

outsideClickDispatcher.add(overlayOne);
outsideClickDispatcher.add(overlayTwo);

expect(outsideClickDispatcher._attachedOverlays.length)
.toBe(2, 'Expected both overlays to be tracked.');
expect(outsideClickDispatcher._attachedOverlays[0])
.toBe(overlayOne, 'Expected one to be first.');
expect(outsideClickDispatcher._attachedOverlays[1])
.toBe(overlayTwo, 'Expected two to be last.');

outsideClickDispatcher.remove(overlayOne);
outsideClickDispatcher.add(overlayOne);

expect(outsideClickDispatcher._attachedOverlays[0])
.toBe(overlayTwo, 'Expected two to now be first.');
expect(outsideClickDispatcher._attachedOverlays[1])
.toBe(overlayOne, 'Expected one to now be last.');

overlayOne.dispose();
overlayTwo.dispose();
});

it(
'should dispatch mouse click events to the attached overlays',
() => {
const overlayOne = overlay.create();
const overlayTwo = overlay.create();
const overlayOneSpy = jasmine.createSpy('overlayOne mouse click event spy');
const overlayTwoSpy = jasmine.createSpy('overlayTwo mouse click event spy');

overlayOne.outsidePointerEvents().subscribe(overlayOneSpy);
overlayTwo.outsidePointerEvents().subscribe(overlayTwoSpy);

outsideClickDispatcher.add(overlayOne);
outsideClickDispatcher.add(overlayTwo);

const button = document.createElement('button');
document.body.appendChild(button);
button.click();

expect(overlayOneSpy).toHaveBeenCalled();
expect(overlayTwoSpy).toHaveBeenCalled();

button.parentNode!.removeChild(button);
overlayOne.dispose();
overlayTwo.dispose();
});

it(
'should dispatch mouse click events to the attached overlays even when propagation is stopped',
() => {
const overlayRef = overlay.create();
const spy = jasmine.createSpy('overlay mouse click event spy');
overlayRef.outsidePointerEvents().subscribe(spy);

outsideClickDispatcher.add(overlayRef);

const button = document.createElement('button');
document.body.appendChild(button);
button.addEventListener('click', event => event.stopPropagation());
button.click();

expect(spy).toHaveBeenCalled();

button.parentNode!.removeChild(button);
overlayRef.dispose();
});

it('should dispose of the global click event handler correctly', () => {
const overlayRef = overlay.create();
const body = document.body;

spyOn(body, 'addEventListener');
spyOn(body, 'removeEventListener');

outsideClickDispatcher.add(overlayRef);
expect(body.addEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), true);

overlayRef.dispose();
expect(body.removeEventListener).toHaveBeenCalledWith('click', jasmine.any(Function), true);
});

it('should not add the same overlay to the stack multiple times', () => {
const overlayOne = overlay.create();
const overlayTwo = overlay.create();

outsideClickDispatcher.add(overlayOne);
outsideClickDispatcher.add(overlayTwo);
outsideClickDispatcher.add(overlayOne);

expect(outsideClickDispatcher._attachedOverlays).toEqual([overlayTwo, overlayOne]);

overlayOne.dispose();
overlayTwo.dispose();
});

it(`should not dispatch click event when click on element
included in excludeFromOutsideClick array`, () => {
const overlayRef = overlay.create();
const spy = jasmine.createSpy('overlay mouse click event spy');
overlayRef.outsidePointerEvents().subscribe(spy);

const overlayConfig = overlayRef.getConfig();
expect(overlayConfig.excludeFromOutsideClick).toBeDefined();
expect(overlayConfig.excludeFromOutsideClick!.length).toBe(0);

overlayRef.attach(new ComponentPortal(TestComponent));

const buttonShouldNotDetach = document.createElement('button');
document.body.appendChild(buttonShouldNotDetach);
overlayConfig.excludeFromOutsideClick!.push(buttonShouldNotDetach);
buttonShouldNotDetach.click();

expect(spy).not.toHaveBeenCalled();

buttonShouldNotDetach.parentNode!.removeChild(buttonShouldNotDetach);
overlayRef.dispose();
});
});


@Component({
template: 'Hello'
})
class TestComponent { }


// Create a real (non-test) NgModule as a workaround for
// https://github.com/angular/angular/issues/10760
@NgModule({
exports: [TestComponent],
declarations: [TestComponent],
entryComponents: [TestComponent],
})
class TestComponentModule { }
Loading