Skip to content

fix(dialog): escape key not working once element loses focus #3082

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
Feb 15, 2017
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
10 changes: 10 additions & 0 deletions e2e/components/dialog/dialog.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ describe('dialog', () => {
});
});

it('should close by pressing escape when the first tabbable element has lost focus', () => {
element(by.id('default')).click();

waitForDialog().then(() => {
clickElementAtPoint('md-dialog-container', { x: 0, y: 0 });
pressKeys(Key.ESCAPE);
expectToExist('md-dialog-container', false);
});
});

it('should close by clicking on the "close" button', () => {
element(by.id('default')).click();

Expand Down
11 changes: 0 additions & 11 deletions src/lib/dialog/dialog-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import 'rxjs/add/operator/first';
host: {
'[class.mat-dialog-container]': 'true',
'[attr.role]': 'dialogConfig?.role',
'(keydown.escape)': 'handleEscapeKey()',
},
encapsulation: ViewEncapsulation.None,
})
Expand Down Expand Up @@ -93,16 +92,6 @@ export class MdDialogContainer extends BasePortalHost implements OnDestroy {
});
}

/**
* Handles the user pressing the Escape key.
* @docs-private
*/
handleEscapeKey() {
if (!this.dialogConfig.disableClose) {
this.dialogRef.close();
}
}

ngOnDestroy() {
// When the dialog is destroyed, return focus to the element that originally had it before
// the dialog was opened. Wait for the DOM to finish settling before changing the focus so
Expand Down
3 changes: 2 additions & 1 deletion src/lib/dialog/dialog-ref.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {OverlayRef} from '../core';
import {MdDialogConfig} from './dialog-config';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';

Expand All @@ -17,7 +18,7 @@ export class MdDialogRef<T> {
/** Subject for notifying the user that the dialog has finished closing. */
private _afterClosed: Subject<any> = new Subject();

constructor(private _overlayRef: OverlayRef) { }
constructor(private _overlayRef: OverlayRef, public config: MdDialogConfig) { }

/**
* Close the dialog.
Expand Down
27 changes: 15 additions & 12 deletions src/lib/dialog/dialog.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@ import {NgModule,
Injector,
Inject,
} from '@angular/core';
import {By} from '@angular/platform-browser';
import {MdDialogModule} from './index';
import {MdDialog} from './dialog';
import {OverlayContainer} from '../core';
import {MdDialogRef} from './dialog-ref';
import {MdDialogContainer} from './dialog-container';
import {MD_DIALOG_DATA} from './dialog-injector';
import {ESCAPE} from '../core/keyboard/keycodes';


describe('MdDialog', () => {
Expand Down Expand Up @@ -136,11 +135,7 @@ describe('MdDialog', () => {

viewContainerFixture.detectChanges();

let dialogContainer: MdDialogContainer =
viewContainerFixture.debugElement.query(By.directive(MdDialogContainer)).componentInstance;

// Fake the user pressing the escape key by calling the handler directly.
dialogContainer.handleEscapeKey();
dispatchKeydownEvent(document, ESCAPE);

expect(overlayContainerElement.querySelector('md-dialog-container')).toBeNull();
});
Expand Down Expand Up @@ -324,11 +319,7 @@ describe('MdDialog', () => {

viewContainerFixture.detectChanges();

let dialogContainer: MdDialogContainer = viewContainerFixture.debugElement.query(
By.directive(MdDialogContainer)).componentInstance;

// Fake the user pressing the escape key by calling the handler directly.
dialogContainer.handleEscapeKey();
dispatchKeydownEvent(document, ESCAPE);

expect(overlayContainerElement.querySelector('md-dialog-container')).toBeTruthy();
});
Expand Down Expand Up @@ -565,3 +556,15 @@ const TEST_DIRECTIVES = [
],
})
class DialogTestModule { }


// TODO(crisbeto): switch to using function from common testing utils once #2943 is merged.
function dispatchKeydownEvent(element: Node, keyCode: number) {
let event: any = document.createEvent('KeyboardEvent');
(event.initKeyEvent || event.initKeyboardEvent).bind(event)(
'keydown', true, true, window, 0, 0, 0, 0, 0, keyCode);
Object.defineProperty(event, 'keyCode', {
get: function() { return keyCode; }
});
element.dispatchEvent(event);
}
21 changes: 20 additions & 1 deletion src/lib/dialog/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {Overlay, OverlayRef, ComponentType, OverlayState, ComponentPortal} from '../core';
import {extendObject} from '../core/util/object-extend';
import {ESCAPE} from '../core/keyboard/keycodes';
import {DialogInjector} from './dialog-injector';
import {MdDialogConfig} from './dialog-config';
import {MdDialogRef} from './dialog-ref';
Expand All @@ -22,6 +23,7 @@ export class MdDialog {
private _openDialogsAtThisLevel: MdDialogRef<any>[] = [];
private _afterAllClosedAtThisLevel = new Subject<void>();
private _afterOpenAtThisLevel = new Subject<MdDialogRef<any>>();
private _boundKeydown = this._handleKeydown.bind(this);

/** Keeps track of the currently-open dialogs. */
get _openDialogs(): MdDialogRef<any>[] {
Expand Down Expand Up @@ -65,6 +67,10 @@ export class MdDialog {
let dialogRef =
this._attachDialogContent(componentOrTemplateRef, dialogContainer, overlayRef, config);

if (!this._openDialogs.length && !this._parentDialog) {
document.addEventListener('keydown', this._boundKeydown);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we don't have access to a Renerer we can use to do this at this point in the code?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't. Angular only injects the renderer in components.

}

this._openDialogs.push(dialogRef);
dialogRef.afterClosed().subscribe(() => this._removeOpenDialog(dialogRef));
this._afterOpen.next(dialogRef);
Expand Down Expand Up @@ -129,7 +135,7 @@ export class MdDialog {
config?: MdDialogConfig): MdDialogRef<T> {
// Create a reference to the dialog we're creating in order to give the user a handle
// to modify and close it.
let dialogRef = <MdDialogRef<T>> new MdDialogRef(overlayRef);
let dialogRef = <MdDialogRef<T>> new MdDialogRef(overlayRef, config);

if (!config.disableClose) {
// When the dialog backdrop is clicked, we want to close it.
Expand Down Expand Up @@ -199,9 +205,22 @@ export class MdDialog {
// no open dialogs are left, call next on afterAllClosed Subject
if (!this._openDialogs.length) {
this._afterAllClosed.next();
document.removeEventListener('keydown', this._boundKeydown);
}
}
}

/**
* Handles global key presses while there are open dialogs. Closes the
* top dialog when the user presses escape.
*/
private _handleKeydown(event: KeyboardEvent): void {
let topDialog = this._openDialogs[this._openDialogs.length - 1];

if (event.keyCode === ESCAPE && topDialog && !topDialog.config.disableClose) {
topDialog.close();
}
}
}

/**
Expand Down