11import React from 'react' ;
22import PropTypes from 'prop-types' ;
33import { isEmpty as lodashIsEmpty } from 'lodash' ;
4- import { Field } from 'react-final-form' ;
4+ import { FormSpy } from 'react-final-form' ;
55
66const isEmptyValue = ( value ) => typeof value === 'number' || value === true ? false : lodashIsEmpty ( value ) ;
77
8- const Condition = ( { when , is , isNotEmpty , isEmpty , children, pattern , notMatch } ) => {
9- const shouldRender = value => {
8+ const Condition = ( { condition , children } ) => {
9+ const fieldCondition = ( value , { is , isNotEmpty , isEmpty , pattern , notMatch } ) => {
1010 if ( isNotEmpty ) {
1111 return ! isEmptyValue ( value ) ;
1212 }
@@ -24,14 +24,33 @@ const Condition = ({ when, is, isNotEmpty, isEmpty, children, pattern, notMatch
2424 return notMatch ? ! isMatched : isMatched ;
2525 } ;
2626
27+ const shouldRender = ( values , conditionItem ) => {
28+ if ( typeof conditionItem . when === 'string' ) {
29+ return fieldCondition ( values [ conditionItem . when ] , conditionItem ) ;
30+ }
31+
32+ if ( Array . isArray ( conditionItem . when ) ) {
33+ return conditionItem . when . map ( fieldName => fieldCondition ( values [ fieldName ] , conditionItem ) ) . find ( condition => ! ! condition ) ;
34+ }
35+
36+ return false ;
37+ } ;
38+
2739 return (
28- < Field name = { when } subscription = { { value : true } } >
29- { ( { input : { value } } ) => ( shouldRender ( value ) ? children : null ) }
30- </ Field >
40+ < FormSpy >
41+ { ( { values } ) => {
42+ const visible = Array . isArray ( condition )
43+ ? ! condition . map ( conditionItem => ! ! shouldRender ( values , conditionItem ) ) . some ( result => result === false )
44+ : shouldRender ( values , condition ) ;
45+
46+ return visible ? children : null ;
47+ } }
48+ </ FormSpy >
3149 ) ;
50+
3251} ;
3352
34- Condition . propTypes = {
53+ const conditionProps = {
3554 when : PropTypes . string . isRequired ,
3655 is : PropTypes . oneOfType ( [
3756 PropTypes . array ,
@@ -53,4 +72,15 @@ Condition.propTypes = {
5372 notMatch : PropTypes . any ,
5473} ;
5574
75+ Condition . propTypes = {
76+ condition : PropTypes . oneOfType ( [
77+ PropTypes . shape ( conditionProps ) ,
78+ PropTypes . arrayOf ( PropTypes . shape ( conditionProps ) ) ,
79+ ] ) ,
80+ children : PropTypes . oneOf ( [
81+ PropTypes . node ,
82+ PropTypes . arrayOf ( PropTypes . node ) ,
83+ ] ) . isRequired ,
84+ } ;
85+
5686export default Condition ;
0 commit comments