import { useCallback , useEffect , useState } from 'react' ; import { useMlKibana } from './kibana_context' ; import { ML_APP_LOCATOR } from '../../../../common/constants/locator' ; import { MlLocatorParams } from '../../../../common/types/locator' ; import { useUrlState } from '../../util/url_state' ; import { LocatorGetUrlParams } from '../../../../../../../src/plugins/share/common/url_service' ; export const useMlLocator = ( ) => { const { services : { share } , } = useMlKibana ( ) ; return share . url . locators . get ( ML_APP_LOCATOR ) ; } ; export const useMlLink = ( params , getUrlParams ? ) : string => { const [ href , setHref ] = useState < string > ( params . page ) ; const mlLocator = useMlLocator ( ) ; useEffect ( ( ) => { let isCancelled = false ; const generateUrl = async ( _params ) => { if ( mlLocator ) { const url = await mlLocator . getUrl ( _params , getUrlParams ) ; if ( ! isCancelled ) { setHref ( url ) ; } } } ; generateUrl ( params ) ; return ( ) => { isCancelled = true ; } ; } , [ params , getUrlParams ] ) ; return href ; } ; export const useCreateAndNavigateToMlLink = ( page ) : ( ( ) => Promise < void > ) => { const mlLocator = useMlLocator ( ) ; const [ globalState ] = useUrlState ( '_g' ) ; const { services : { application : { navigateToUrl } , } , } = useMlKibana ( ) ; const redirectToMlPage = useCallback ( async ( _page ) => { const pageState = globalState ?. refreshInterval !== undefined ? { globalState : { refreshInterval : globalState . refreshInterval , } , } : undefined ; const url = await mlLocator . getUrl ( { page : _page , pageState } ) ; await navigateToUrl ( url ) ; } , [ mlLocator , navigateToUrl ] ) ; return useCallback ( ( ) => redirectToMlPage ( page ) , [ redirectToMlPage , page ] ) ; } ;