import { elementClosest } from './dom-manip' ; import { VUIEvent } from '../vdom' ; export function preventDefault ( ev ) { ev . preventDefault ( ) ; } export function buildDelegationHandler < EventType extends ( Event | VUIEvent ) > ( selector , handler ) { return ( ev ) => { let matchedChild = elementClosest ( ev . target as HTMLElement , selector ) ; if ( matchedChild ) { handler . call ( matchedChild , ev , matchedChild ) ; } } ; } export function listenBySelector ( container , eventType , selector , handler ) { let attachedHandler = buildDelegationHandler ( selector , handler ) ; container . addEventListener ( eventType , attachedHandler ) ; return ( ) => { container . removeEventListener ( eventType , attachedHandler ) ; } ; } export function listenToHoverBySelector ( container , selector , onMouseEnter , onMouseLeave ) { let currentMatchedChild ; return listenBySelector ( container , 'mouseover' , selector , ( mouseOverEv , matchedChild ) => { if ( matchedChild !== currentMatchedChild ) { currentMatchedChild = matchedChild ; onMouseEnter ( mouseOverEv , matchedChild ) ; let realOnMouseLeave = ( mouseLeaveEv ) => { currentMatchedChild = null ; onMouseLeave ( mouseLeaveEv , matchedChild ) ; matchedChild . removeEventListener ( 'mouseleave' , realOnMouseLeave ) ; } ; matchedChild . addEventListener ( 'mouseleave' , realOnMouseLeave ) ; } } ) ; } const transitionEventNames = [ 'webkitTransitionEnd' , 'otransitionend' , 'oTransitionEnd' , 'msTransitionEnd' , 'transitionend' , ] ; export function whenTransitionDone ( el , callback ) { let realCallback = ( ev ) => { callback ( ev ) ; transitionEventNames . forEach ( ( eventName ) => { el . removeEventListener ( eventName , realCallback ) ; } ) ; } ; transitionEventNames . forEach ( ( eventName ) => { el . addEventListener ( eventName , realCallback ) ; } ) ; } export function createAriaClickAttrs ( handler ) { return { onClick : handler , ... createAriaKeyboardAttrs ( handler ) , } ; } export function createAriaKeyboardAttrs ( handler ) { return { tabIndex : 0 , onKeyDown ( ev ) { if ( ev . key === 'Enter' || ev . key === ' ' ) { handler ( ev ) ; ev . preventDefault ( ) ; } } , } ; }