import React from 'react' ; import Logger from '../../libs/logger' ; import { isObject } from 'lodash' ; const logger = Logger . create ( 'validation' ) ; export default class Validator { valid = true ; constructor ( ) { this . _subs = [ ] ; } subscribe ( cb ) { this . _subs . push ( cb ) ; } unsubscribe ( cb ) { const index = this . _subs . indexOf ( cb ) ; if ( index > - 1 ) { this . _subs . splice ( index , 1 ) ; } } addResult ( result ) { let isValid = false ; if ( isObject ( result ) ) { isValid = result . valid ; } else { logger . error ( `rule should return a valid object` ) ; } this . valid = this . valid && Boolean ( isValid ) ; } reset ( ) { this . valid = true ; this . validating = false ; } validate ( ) { this . reset ( ) ; this . validating = true ; this . _subs . forEach ( cb => { try { cb ( ) ; } catch ( err ) { logger . error ( err ) ; } } ) ; return this . valid ; } } const ValidationContext = React . createContext ( { } ) ; export function Validation ( props ) { const [ validator ] = React . useState ( ( ) => new Validator ( ) ) ; const children = typeof props . children === 'function' ? props . children ( { validator } ) : props . children ; return ( < ValidationContext . Provider value = { validator } > { children } < /ValidationContext.Provider>); } export function useValidation ( ) { const value = React . useContext ( ValidationContext ) ; if ( ! ( value instanceof Validator ) ) { logger . warn ( 'Missing Validation Context declaration' ) ; } return value ; }