import { useCallback , useLayoutEffect , useState } from 'react' ; import { PlayerProps , createDispatcher , usePlayerContext as useContext , findPlayer , WritableProps , } from '@vime/core' ; const noop = ( ) => { } ; /**
 * Returns the closest ancestor player to the given `ref`.
 */ export const usePlayer = ( ref ) => { const [ player , setPlayer ] = useState < HTMLVmPlayerElement | null > ( null ) ; useLayoutEffect ( ( ) => { async function find ( ) { setPlayer ( ref . current ? ( await findPlayer ( ref . current ) ) ?? null : null ) ; } find ( ) ; } , [ ref . current ] ) ; return player ; } ; export type PropBinding < P extends keyof PlayerProps > = [ value : PlayerProps [ P ] , setValue : P extends keyof WritableProps ? ( value : PlayerProps [ P ] ) => void : undefined ] ; param ref param prop param defaultValue export const usePlayerContext = < P extends keyof PlayerProps > ( ref , prop , defaultValue ) : PropBinding < P > => { const [ value , setValue ] = useState ( defaultValue ) ; const dispatch = useCallback ( ref . current === null ? noop : createDispatcher ( ref . current ) , [ ref . current ] ) ; const setter = useCallback ( ( value ) => { dispatch ( prop as any , value ) ; } , [ dispatch , prop ] ) ; useLayoutEffect ( ( ) => { if ( ref . current === null ) return undefined ; let cleanup ; async function connect ( ) { cleanup = await useContext ( ref . current ! , [ prop ] , ( _ , newValue ) => { setValue ( newValue as any ) ; } ) ; } connect ( ) ; return ( ) => { cleanup ?. ( ) ; } ; } , [ ref . current , prop ] ) ; return [ value , setter as any ] ; } ;