@@ -3,6 +3,7 @@ import {Observable} from 'rxjs/Observable';
3
3
import { Subject } from 'rxjs/Subject' ;
4
4
import { Overlay , OverlayRef , ComponentType , OverlayState , ComponentPortal } from '../core' ;
5
5
import { extendObject } from '../core/util/object-extend' ;
6
+ import { ESCAPE } from '../core/keyboard/keycodes' ;
6
7
import { DialogInjector } from './dialog-injector' ;
7
8
import { MdDialogConfig } from './dialog-config' ;
8
9
import { MdDialogRef } from './dialog-ref' ;
@@ -22,6 +23,7 @@ export class MdDialog {
22
23
private _openDialogsAtThisLevel : MdDialogRef < any > [ ] = [ ] ;
23
24
private _afterAllClosedAtThisLevel = new Subject < void > ( ) ;
24
25
private _afterOpenAtThisLevel = new Subject < MdDialogRef < any > > ( ) ;
26
+ private _boundKeydown = this . _handleKeydown . bind ( this ) ;
25
27
26
28
/** Keeps track of the currently-open dialogs. */
27
29
get _openDialogs ( ) : MdDialogRef < any > [ ] {
@@ -65,6 +67,10 @@ export class MdDialog {
65
67
let dialogRef =
66
68
this . _attachDialogContent ( componentOrTemplateRef , dialogContainer , overlayRef , config ) ;
67
69
70
+ if ( ! this . _openDialogs . length && ! this . _parentDialog ) {
71
+ document . addEventListener ( 'keydown' , this . _boundKeydown ) ;
72
+ }
73
+
68
74
this . _openDialogs . push ( dialogRef ) ;
69
75
dialogRef . afterClosed ( ) . subscribe ( ( ) => this . _removeOpenDialog ( dialogRef ) ) ;
70
76
this . _afterOpen . next ( dialogRef ) ;
@@ -129,7 +135,7 @@ export class MdDialog {
129
135
config ?: MdDialogConfig ) : MdDialogRef < T > {
130
136
// Create a reference to the dialog we're creating in order to give the user a handle
131
137
// to modify and close it.
132
- let dialogRef = < MdDialogRef < T > > new MdDialogRef ( overlayRef ) ;
138
+ let dialogRef = < MdDialogRef < T > > new MdDialogRef ( overlayRef , config ) ;
133
139
134
140
if ( ! config . disableClose ) {
135
141
// When the dialog backdrop is clicked, we want to close it.
@@ -199,9 +205,22 @@ export class MdDialog {
199
205
// no open dialogs are left, call next on afterAllClosed Subject
200
206
if ( ! this . _openDialogs . length ) {
201
207
this . _afterAllClosed . next ( ) ;
208
+ document . removeEventListener ( 'keydown' , this . _boundKeydown ) ;
202
209
}
203
210
}
204
211
}
212
+
213
+ /**
214
+ * Handles global key presses while there are open dialogs. Closes the
215
+ * top dialog when the user presses escape.
216
+ */
217
+ private _handleKeydown ( event : KeyboardEvent ) : void {
218
+ let topDialog = this . _openDialogs [ this . _openDialogs . length - 1 ] ;
219
+
220
+ if ( event . keyCode === ESCAPE && topDialog && ! topDialog . config . disableClose ) {
221
+ topDialog . close ( ) ;
222
+ }
223
+ }
205
224
}
206
225
207
226
/**
0 commit comments