import { getElement } from '@stencil/core' ; import { fireEventAndRetry , listen } from '../../../utils/dom' ; import { deferredPromise } from '../../../utils/promise' ; import { createStencilHook } from '../../../utils/stencil' ; import { isInstanceOf } from '../../../utils/unit' ; import { MediaPlayer } from './MediaPlayer' ; export const FIND_PLAYER_EVENT = 'vmFindPlayer' ; export type FoundPlayerCallback = ( player : HTMLVmPlayerElement ) => void ; export function withFindPlayer ( player ) { const el = getElement ( player ) as HTMLVmPlayerElement ; let off ; createStencilHook ( player , ( ) => { off = listen ( el , FIND_PLAYER_EVENT , ( event ) => { event . stopPropagation ( ) ; event . detail ( el ) ; } ) ; } , ( ) => { off ?. ( ) ; } ) ; } param ref param interval param maxRetries export const findPlayer = ( ref , interval = 300 , maxRetries = 10 ) : Promise < HTMLVmPlayerElement | undefined > => { const el = ( isInstanceOf ( ref , HTMLElement ) ? ref : getElement ( ref ) ) as HTMLElement ; const search = deferredPromise < HTMLVmPlayerElement > ( ) ; let stopFiring ; const event = new CustomEvent < FoundPlayerCallback > ( FIND_PLAYER_EVENT , { bubbles : true , composed : true , detail : player => { search . resolve ( player ) ; stopFiring ( ) ; } , } ) ; stopFiring = fireEventAndRetry ( el , event , ( ) => { search . reject ( `Could not find player for ${ el . nodeName }` ) ; } , interval , maxRetries ) ; return search . promise ; } ;