all files / src/ createHigherOrderComponent.js

95.05% Statements 192/202
89.01% Branches 81/91
83.87% Functions 26/31
87.01% Lines 67/77
17 statements, 1 function, 18 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241                       54×   54×   54×     54× 54× 54×       54×   54× 25×         100× 97×   99×                   13×   13× 13×                       15×   15×       15×             153× 153×             153×                                                   153× 153×           54× 54× 54×                                                                           54×         147×       54×                     54×                                   158× 158×     158×             54×          
import * as importedActions from './actions';
import getDisplayName from './getDisplayName';
import {initialState} from './reducer';
import deepEqual from 'deep-equal';
import bindActionData from './bindActionData';
import getValues from './getValues';
import isValid from './isValid';
import readFields from './readFields';
import handleSubmit from './handleSubmit';
import asyncValidation from './asyncValidation';
import silenceEvents from './events/silenceEvents';
import silenceEvent from './events/silenceEvent';
import wrapMapDispatchToProps from './wrapMapDispatchToProps';
import wrapMapStateToProps from './wrapMapStateToProps';
 
/**
 * Creates a HOC that knows how to create redux-connected sub-components.
 */
const createHigherOrderComponent = (config,
                                    isReactNative,
                                    React,
                                    connect,
                                    WrappedComponent,
                                    mapStateToProps,
                                    mapDispatchToProps,
                                    mergeProps,
                                    options) => {
  const {Component, PropTypes} = React;
  return (reduxMountPoint, formName, formKey, getFormState) => {
    class ReduxForm extends Component {
      constructor(props) {
        super(props);
        // bind functions
        this.asyncValidate = this.asyncValidate.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.fields = readFields(props, {}, {}, this.asyncValidate, isReactNative);
        const {submitPassback} = this.props;
        submitPassback(() => this.handleSubmit());  // wrapped in function to disallow params
      }
 
      componentWillMount() {
        const {fields, form, initialize, initialValues} = this.props;
        if (initialValues && !form._initialized) {
          initialize(initialValues, fields);
        }
      }
 
      componentWillReceiveProps(nextProps) {
        if (!deepEqual(this.props.fields, nextProps.fields) || !deepEqual(this.props.form, nextProps.form, {strict: true})) {
          this.fields = readFields(nextProps, this.props, this.fields, this.asyncValidate, isReactNative);
        }
        if (!deepEqual(this.props.initialValues, nextProps.initialValues)) {
          this.props.initialize(nextProps.initialValues,
            nextProps.fields,
            this.props.overwriteOnInitialValuesChange || !this.props.form._initialized);
        }
      }
 
      componentWillUnmount() {
        if (config.destroyOnUnmount) {
          this.props.destroy();
        }
      }
 
      asyncValidate(name, value) {
        const {alwaysAsyncValidate, asyncValidate, dispatch, fields, form, startAsyncValidation, stopAsyncValidation, validate} = this.props;
        const isSubmitting = !name;
        if (asyncValidate) {
          const values = getValues(fields, form);
          if (name) {
            values[name] = value;
          }
          const syncErrors = validate(values, this.props);
          const {allPristine} = this.fields._meta;
          const initialized = form._initialized;
 
          // if blur validating, only run async validate if sync validation passes
          // and submitting (not blur validation) or form is dirty or form was never initialized
          // unless alwaysAsyncValidate is true
          const syncValidationPasses = isSubmitting || isValid(syncErrors[name]);
          if (alwaysAsyncValidate || (syncValidationPasses && (isSubmitting || !allPristine || !initialized))) {
            return asyncValidation(() =>
              asyncValidate(values, dispatch, this.props), startAsyncValidation, stopAsyncValidation, name);
          }
        }
      }
 
      handleSubmit(submitOrEvent) {
        const {onSubmit, fields, form} = this.props;
        const check = submit => {
          Iif (!submit || typeof submit !== 'function') {
            throw new Error('You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop');
          }
          return submit;
        };
        return !submitOrEvent || silenceEvent(submitOrEvent) ?
          // submitOrEvent is an event: fire submit
          handleSubmit(check(onSubmit), getValues(fields, form), this.props, this.asyncValidate) :
          // submitOrEvent is the submit function: return deferred submit thunk
          silenceEvents(() =>
            handleSubmit(check(submitOrEvent), getValues(fields, form), this.props, this.asyncValidate));
      }
 
      render() {
        const allFields = this.fields;
        const {addArrayValue, asyncBlurFields, autofill, blur, change, destroy, focus, fields, form, initialValues, initialize,
          onSubmit, propNamespace, reset, removeArrayValue, returnRejectedSubmitPromise, startAsyncValidation,
          startSubmit, stopAsyncValidation, stopSubmit, submitFailed, swapArrayValues, touch, untouch, validate,
          ...passableProps} = this.props; // eslint-disable-line no-redeclare
        const {allPristine, allValid, errors, formError, values} = allFields._meta;
 
        const props = {
          // State:
          active: form._active,
          asyncValidating: form._asyncValidating,
          dirty: !allPristine,
          error: formError,
          errors,
          fields: allFields,
          formKey,
          invalid: !allValid,
          pristine: allPristine,
          submitting: form._submitting,
          submitFailed: form._submitFailed,
          valid: allValid,
          values,
 
          // Actions:
          asyncValidate: silenceEvents(() => this.asyncValidate()),
          // ^ doesn't just pass this.asyncValidate to disallow values passing
          destroyForm: silenceEvents(destroy),
          handleSubmit: this.handleSubmit,
          initializeForm: silenceEvents(initValues => initialize(initValues, fields)),
          resetForm: silenceEvents(reset),
          touch: silenceEvents((...touchFields) => touch(...touchFields)),
          touchAll: silenceEvents(() => touch(...fields)),
          untouch: silenceEvents((...untouchFields) => untouch(...untouchFields)),
          untouchAll: silenceEvents(() => untouch(...fields))
        };
        const passedProps = propNamespace ? {[propNamespace]: props} : props;
        return (<WrappedComponent {...{
          ...passableProps, // contains dispatch
          ...passedProps
        }}/>);
      }
    }
    ReduxForm.displayName = `ReduxForm(${getDisplayName(WrappedComponent)})`;
    ReduxForm.WrappedComponent = WrappedComponent;
    ReduxForm.propTypes = {
      // props:
      alwaysAsyncValidate: PropTypes.bool,
      asyncBlurFields: PropTypes.arrayOf(PropTypes.string),
      asyncValidate: PropTypes.func,
      dispatch: PropTypes.func.isRequired,
      fields: PropTypes.arrayOf(PropTypes.string).isRequired,
      form: PropTypes.object,
      initialValues: PropTypes.any,
      onSubmit: PropTypes.func,
      onSubmitSuccess: PropTypes.func,
      onSubmitFail: PropTypes.func,
      overwriteOnInitialValuesChange: PropTypes.bool.isRequired,
      propNamespace: PropTypes.string,
      readonly: PropTypes.bool,
      returnRejectedSubmitPromise: PropTypes.bool,
      submitPassback: PropTypes.func.isRequired,
      validate: PropTypes.func,
 
      // actions:
      addArrayValue: PropTypes.func.isRequired,
      autofill: PropTypes.func.isRequired,
      blur: PropTypes.func.isRequired,
      change: PropTypes.func.isRequired,
      destroy: PropTypes.func.isRequired,
      focus: PropTypes.func.isRequired,
      initialize: PropTypes.func.isRequired,
      removeArrayValue: PropTypes.func.isRequired,
      reset: PropTypes.func.isRequired,
      startAsyncValidation: PropTypes.func.isRequired,
      startSubmit: PropTypes.func.isRequired,
      stopAsyncValidation: PropTypes.func.isRequired,
      stopSubmit: PropTypes.func.isRequired,
      submitFailed: PropTypes.func.isRequired,
      swapArrayValues: PropTypes.func.isRequired,
      touch: PropTypes.func.isRequired,
      untouch: PropTypes.func.isRequired
    };
    ReduxForm.defaultProps = {
      asyncBlurFields: [],
      form: initialState,
      readonly: false,
      returnRejectedSubmitPromise: false,
      validate: () => ({})
    };
 
    // bind touch flags to blur and change
    const unboundActions = {
      ...importedActions,
      blur: bindActionData(importedActions.blur, {
        touch: !!config.touchOnBlur
      }),
      change: bindActionData(importedActions.change, {
        touch: !!config.touchOnChange
      })
    };
 
    // make redux connector with or without form key
    const decorate = formKey !== undefined && formKey !== null ?
      connect(
        wrapMapStateToProps(mapStateToProps, state => {
          const formState = getFormState(state, reduxMountPoint);
          if (!formState) {
            throw new Error(`You need to mount the redux-form reducer at "${reduxMountPoint}"`);
          }
          return formState && formState[formName] && formState[formName][formKey];
        }),
        wrapMapDispatchToProps(mapDispatchToProps, bindActionData(unboundActions, {
          form: formName,
          key: formKey
        })),
        mergeProps,
        options
      ) :
      connect(
        wrapMapStateToProps(mapStateToProps, state => {
          const formState = getFormState(state, reduxMountPoint);
          Iif (!formState) {
            throw new Error(`You need to mount the redux-form reducer at "${reduxMountPoint}"`);
          }
          return formState && formState[formName];
        }),
        wrapMapDispatchToProps(mapDispatchToProps, bindActionData(unboundActions, {form: formName})),
        mergeProps,
        options
      );
 
    return decorate(ReduxForm);
  };
};
 
export default createHigherOrderComponent;