import { EuiModal , EuiModalHeader } from '@elastic/eui' ; import constate from 'constate' ; import type { FunctionComponent } from 'react' ; import React , { useEffect , useRef , useState } from 'react' ; import { euiThemeVars } from '@kbn/ui-shared-deps-src/theme' ; import { useKibana } from './use_kibana' ; import { VerificationCodeForm } from './verification_code_form' ; export interface VerificationProps { defaultCode ? : string ; } const [ OuterVerificationProvider , useVerification ] = constate ( ( { defaultCode } ) => { const codeRef = useRef ( defaultCode ) ; const [ status , setStatus ] = useState < 'unknown' | 'unverified' | 'verified' > ( 'unknown' ) ; return { status , setStatus , getCode ( ) { return codeRef . current ; } , setCode ( code ) { codeRef . current = code ; } , } ; } ) ; const InnerVerificationProvider = ( { children } ) => { const { http } = useKibana ( ) ; const { status , setStatus , setCode } = useVerification ( ) ; useEffect ( ( ) => { return http . intercept ( { responseError : ( error ) => { if ( error . response ?. status === 403 ) { setStatus ( 'unverified' ) ; setCode ( undefined ) ; } } , } ) ; } , [ http ] ) ; return ( < > { status === 'unverified' && ( < EuiModal onClose = { ( ) => setStatus ( 'unknown' ) } maxWidth = { euiThemeVars . euiBreakpoints . s } > < EuiModalHeader > < VerificationCodeForm onSuccess = { ( values ) => { setStatus ( 'verified' ) ; setCode ( values . code ) ; } } /> < /EuiModalHeader> < /EuiModal>)} { children } < />); } ; export const VerificationProvider = ( { defaultCode , children , } ) => { return ( < OuterVerificationProvider defaultCode = { defaultCode } > < InnerVerificationProvider > { children } < /InnerVerificationProvider> < /OuterVerificationProvider>); } ; export { useVerification } ;