import type * as d from '../declarations' ; import { BUILD } from '@app-data' ; import { doc , plt , consoleError , supportsListenerOptions , win } from '@platform' ; import { HOST_FLAGS , LISTENER_FLAGS } from '@utils' ; export const addHostEventListeners = ( elm , hostRef , listeners , attachParentListeners ) => { if ( BUILD . hostListener && listeners ) { if ( BUILD . hostListenerTargetParent ) { if ( attachParentListeners ) { listeners = listeners . filter ( ( [ flags ] ) => flags & LISTENER_FLAGS . TargetParent ) ; } else { listeners = listeners . filter ( ( [ flags ] ) => ! ( flags & LISTENER_FLAGS . TargetParent ) ) ; } } listeners . map ( ( [ flags , name , method ] ) => { const target = BUILD . hostListenerTarget ? getHostListenerTarget ( elm , flags ) : elm ; const handler = hostListenerProxy ( hostRef , method ) ; const opts = hostListenerOpts ( flags ) ; plt . ael ( target , name , handler , opts ) ; ( hostRef . $rmListeners$ = hostRef . $rmListeners$ || [ ] ) . push ( ( ) => plt . rel ( target , name , handler , opts ) ) ; } ) ; } } ; const hostListenerProxy = ( hostRef , methodName ) => ( ev ) => { try { if ( BUILD . lazyLoad ) { if ( hostRef . $flags$ & HOST_FLAGS . isListenReady ) { hostRef . $lazyInstance$ [ methodName ] ( ev ) ; } else { ( hostRef . $queuedListeners$ = hostRef . $queuedListeners$ || [ ] ) . push ( [ methodName , ev ] ) ; } } else { ( hostRef . $hostElement$ as any ) [ methodName ] ( ev ) ; } } catch ( e ) { consoleError ( e ) ; } } ; const getHostListenerTarget = ( elm , flags ) : EventTarget => { if ( BUILD . hostListenerTargetDocument && flags & LISTENER_FLAGS . TargetDocument ) return doc ; if ( BUILD . hostListenerTargetWindow && flags & LISTENER_FLAGS . TargetWindow ) return win ; if ( BUILD . hostListenerTargetBody && flags & LISTENER_FLAGS . TargetBody ) return doc . body ; if ( BUILD . hostListenerTargetParent && flags & LISTENER_FLAGS . TargetParent ) return elm . parentElement ; return elm ; } ; const hostListenerOpts = ( flags ) => supportsListenerOptions ? ( { passive : ( flags & LISTENER_FLAGS . Passive ) !== 0 , capture : ( flags & LISTENER_FLAGS . Capture ) !== 0 , } ) : ( flags & LISTENER_FLAGS . Capture ) !== 0 ;