import { useEffect , useRef } from 'react' ; interface GamepadRef { [ key ] : Gamepad ; } export default function useGamepads ( callback ) { const gamepads = useRef < GamepadRef > ( [ ] ) ; const requestRef = useRef < number > ( ) ; var haveEvents = 'ongamepadconnected' in window ; const addGamepad = ( gamepad ) => { gamepads . current = { ... gamepads . current , [ gamepad . index ] : gamepad } ; callback ( gamepads . current ) ; } ; param { object } e const connectGamepadHandler = ( e ) => { addGamepad ( ( e as GamepadEvent ) . gamepad ) ; } ; /**
     * Finds all gamepads and adds them to context
     */ const scanGamepads = ( ) => { var detectedGamepads = navigator . getGamepads ? navigator . getGamepads ( ) : navigator . webkitGetGamepads ? navigator . webkitGetGamepads ( ) : [ ] ; for ( var i = 0 ; i < detectedGamepads . length ; i ++ ) { const newGamepads = detectedGamepads [ i ] ; if ( newGamepads && newGamepads !== null ) addGamepad ( newGamepads ) ; } } ; useEffect ( ( ) => { window . addEventListener ( 'gamepadconnected' , connectGamepadHandler ) ; return window . removeEventListener ( 'gamepadconnected' , connectGamepadHandler ) ; } ) ; const animate = ( ) => { if ( ! haveEvents ) scanGamepads ( ) ; requestRef . current = requestAnimationFrame ( animate ) ; } ; useEffect ( ( ) => { requestRef . current = requestAnimationFrame ( animate ) ; return ( ) => cancelAnimationFrame ( requestRef . current ! ) ; } ) ; return gamepads . current ; }