import { ProviderInterface } from '@polkadot/rpc-provider/types' ; import { Header , Health } from '@polkadot/types/interfaces' ; import React , { useContext , useEffect , useState } from 'react' ; import { SystemContext } from './SystemContext' ; /**
 * Period, in ms, after which we consider we're syncing
 */ const SYNCING_THRESHOLD = 2000 ; export interface HealthContextType { /**
     * Best block
     */ best : number ; /**
     * Node has peers
     */ hasPeers : boolean ; /**
     * Able to connect to the node
     */ isNodeConnected : boolean ; /**
     * Node is syncing (major or minor)
     */ isSyncing : boolean ; } param header param health function getNodeStatus ( provider ? , header ? , health ? ) { let best = 0 ; let isNodeConnected = false ; let hasPeers = false ; if ( provider && provider . isConnected ( ) && health && header ) { isNodeConnected = true ; best = header . number . toNumber ( ) ; if ( health . peers . gten ( 1 ) ) { hasPeers = true ; } } return { best , hasPeers , isNodeConnected , } ; } export const HealthContext = React . createContext ( { } as HealthContextType ) ; export interface HealthContextProviderProps { children ? : React . ReactElement ; provider ? : ProviderInterface ; } let wasSyncing = true ; export function HealthContextProvider ( props ) { const { children = null , provider } = props ; const { header , health } = useContext ( SystemContext ) ; const [ isSyncing , setIsSyncing ] = useState ( true ) ; useEffect ( ( ) => { wasSyncing = true ; setIsSyncing ( true ) ; } , [ provider ] ) ; useEffect ( ( ) => { let timer ; if ( ! health ) { return ; } if ( ! wasSyncing && health . isSyncing . eq ( true ) ) { wasSyncing = true ; timer = setTimeout ( ( ) => { setIsSyncing ( true ) ; } , SYNCING_THRESHOLD ) ; } else if ( wasSyncing && health . isSyncing . eq ( false ) ) { wasSyncing = false ; setIsSyncing ( false ) ; timer && clearTimeout ( timer ) ; } return ( ) : void => { timer && clearTimeout ( timer ) ; } ; } , [ health , setIsSyncing ] ) ; const status = { ... getNodeStatus ( provider , header , health ) , isSyncing , } ; return ( < HealthContext . Provider value = { status } > { children } < /HealthContext.Provider>); }