1- import { RefObject , useEffect , useMemo , useState } from "react" ;
2- import flowplayer from "@flowplayer/player" ;
3- import type { Plugin } from "@flowplayer/player" ;
4- /**
5- * Hook to use Flowplayer API in an async way - tries to solve the chicken/egg problem
6- */
1+ import { RefObject , useEffect , useState } from "react" ;
2+ import flowplayer , { type Player } from "@flowplayer/player" ;
3+
74export const useFlowplayer = ( ref : RefObject < HTMLDivElement > ) => {
8- // Store flowplayer instances to a state value in order to force re-renders when new instances are available
9- const [ flowplayerInstances , setFlowplayerInstances ] = useState ( flowplayer . instances . slice ( ) ) ;
105
11- const ReactFlowplayerDetectExtension = useMemo (
12- ( ) =>
13- class implements Plugin {
14- init ( ) {
15- setFlowplayerInstances ( flowplayer . instances . slice ( ) ) ;
16- }
17- } ,
18- [ ] ,
19- ) ;
6+ const [ player , setPlayer ] = useState < Player > ( ) ;
207
21- // Detect new flowplayer instances to keep up to date
228 useEffect ( ( ) => {
23- // If API is already created we don't need the extension
24- if (
25- ref ?. current &&
26- ( flowplayer . instances as any [ ] ) . some ( ( instance ) => instance . root == ref ?. current )
27- ) {
28- setFlowplayerInstances ( flowplayer . instances . slice ( ) ) ;
29- return ( ) => { } ;
9+ if ( ref . current ) {
10+ const newPlayer = flowplayer ( ref . current ) ;
11+ setPlayer ( newPlayer ) ;
3012 }
31- flowplayer ( ReactFlowplayerDetectExtension ) ;
32- return ( ) => {
33- ( flowplayer . extensions as any [ ] ) . filter ( ( ext ) => ext !== ReactFlowplayerDetectExtension ) ;
34- } ;
35- } , [ ] ) ;
13+ } , [ ref ] ) ;
3614
37- return useMemo ( ( ) => {
38- return ref ?. current ? flowplayer ( ref . current ) : null ;
39- } , [ flowplayerInstances ] ) ;
15+ return player ;
4016} ;
0 commit comments