license import { DOCUMENT } from '@angular/common' ; import { Inject , Injectable } from '@angular/core' ; import { OverlayReference } from '../overlay-reference' ; import { BaseOverlayDispatcher } from './base-overlay-dispatcher' ; /**
 * Service for dispatching keyboard 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 class OverlayKeyboardDispatcher extends BaseOverlayDispatcher { constructor ( @ Inject ( DOCUMENT ) document ) { super ( document ) ; } /** Add a new overlay to the list of attached overlay refs. */ override add ( overlayRef ) { super . add ( overlayRef ) ; if ( ! this . _isAttached ) { this . _document . body . addEventListener ( 'keydown' , this . _keydownListener ) ; this . _isAttached = true ; } } /** Detaches the global keyboard event listener. */ protected detach ( ) { if ( this . _isAttached ) { this . _document . body . removeEventListener ( 'keydown' , this . _keydownListener ) ; this . _isAttached = false ; } } /** Keyboard event listener that will be attached to the body. */ private _keydownListener = ( event ) => { const overlays = this . _attachedOverlays ; for ( let i = overlays . length - 1 ; i > - 1 ; i -- ) { if ( overlays [ i ] . _keydownEvents . observers . length > 0 ) { overlays [ i ] . _keydownEvents . next ( event ) ; break ; } } } ; }