All files / src/Control Base.jsx

97.78% Statements 88/90
90% Branches 27/30
96.55% Functions 28/29
97.67% Lines 84/86
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          7x 200x 498x               40x   40x                 40x 40x 40x 40x 40x 40x   40x 40x           14x                                     40x 40x 40x     2x     20x 6x 6x 6x           163x     9x 9x 9x         97x       40x       3x       3x 3x       12x     6x 6x 6x 1x       5x 5x 5x 5x 1x       14x 14x 14x 14x 14x 14x 14x 14x 3x       9x 9x     1x 1x     64x     64x 64x 64x     102x 102x 91x 84x     102x     98x 98x   98x 98x   98x 98x 5x     5x 5x 1x   5x           98x 98x 1078x       98x 98x 98x 98x 98x 98x   98x                                        
import * as React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import uuid from 'uuid';
 
let opositeProperty = function(obj, key, targetKey) {
  Object.defineProperty(obj, key, {
    get: () => !obj[targetKey],
    set: val => obj[targetKey] = !val,
    enumerable: true
  });
}
 
class Base extends React.Component {
  constructor(props) {
    super(props);
 
    this.initialControlState = {
      focus: false,
      touched: false,
      dirty: false,
      invalid: false,
      pending: false,
      empty: true,
    }
 
    this.controlState = {...this.initialControlState};
    opositeProperty(this.controlState, 'blur', 'focus');
    opositeProperty(this.controlState, 'untouched', 'touched');
    opositeProperty(this.controlState, 'pristine', 'dirty');
    opositeProperty(this.controlState, 'valid', 'invalid');
    opositeProperty(this.controlState, 'with-value', 'empty');
 
    this._errors = [];
    this._value = props.hasOwnProperty('value') ? props.value : props.initialValue;
  }
 
  _externalErrors = [];
 
  static defaultProps = {
    isEmpty: v => !Boolean(v),
    validators: [],
    showErrorOn: ['touched'],
    multipleErrors: false,
    initialValue: ''
  }
 
  static contextTypes = {
    onControlMount: PropTypes.func,
    onControlUnmount: PropTypes.func,
    onControlChangeID: PropTypes.func,
    onControlChange: PropTypes.func,
  }
 
  static propTypes = {
    cid: PropTypes.string
  }
 
  componentDidMount() {
    this._id = this.props.cid || uuid.v4();
    this.context.onControlMount(this._id, this, this.value);
    this.validate();
  }
  componentWillUnmount() {
    this.context.onControlUnmount(this._id, this);
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.cid != this.props.cid) {
      this._id = nextProps.cid;
      Eif (this.context.onControlChangeID) {
        this.context.onControlChangeID(this.props.cid, nextProps.cid, this);
      }
    }
  }
 
  get value() {
    return this.props.hasOwnProperty('value') ? this.props.value : this._value;
  }
  setValue(val) {
    return new Promise(resolve => {
      this._value = val;
      this.forceUpdate(resolve);
    });
  }
 
  get name() {
    return this.props.name;
  }
 
  setForm(f) {
    this._form = f;
  }
 
  reset() {
    this.controlState = {
      ...this.controlState,
      ...this.initialControlState
    };
    this._showErrors = false;
    this.setValue(this.props.initialValue);
  }
 
  getControlState() {
    return this.controlState;
  }
  handleFocus(e) {
    this.controlState.focus = true;
    this.forceUpdate();
    if (this.props.onFocus) {
      this.props.onFocus(e);
    }
  }
  handleBlur(e) {
    this.controlState.focus = false;
    this.controlState.touched = true;
    this.forceUpdate();
    if (this.props.onBlur) {
      this.props.onBlur(e);
    }
  }
  handleChange(e, val) {
    val = val === undefined ? e.target.value : val;
    this.controlState.dirty = true;
    this.controlState.empty = this.props.isEmpty(val);
    this._value = val;
    this.context.onControlChange(this._id, val);
    this.validate();
    this.forceUpdate();
    if (this.props.onChange) {
      this.props.onChange(e);
    }
  }
  showErrors() {
    this._showErrors = true;
    this.forceUpdate();
  }
  setError(msg) {
    this._externalErrors.push(msg);
    this.forceUpdate();
  }
  validate() {
    Iif (!this._form) {
      return [];
    }
    let data = this._form.value;
    this._errors = this.props.validators.filter(v => !v.f(this.value, data));
    return this._errors;
  }
  getVisibleErrors() {
    let errors = this._errors;
    if (!this._showErrors) {
      if (this.props.showErrorOn.find(s => !this.controlState[s])) {
        errors = [];
      }
    }
    return errors.concat(this._externalErrors.map(e => ({msg: e})));
  }
  render() {
    let props = {...this.props};
    let errors = this.getVisibleErrors();
  
    Eif (!props.multipleErrors) {
      errors = errors.slice(0, 1);
    }
    let errElement = null;
    if (errors.length) {
      errElement = (
        <div className='form-group__errors'>
          {errors.map((e, i) => {
            let msg = e.msg;
            if (typeof msg == 'function') {
              msg = msg(this.value, this._form.value);
            }
            return <div className='form-group-error' key={i}>{msg}</div>;
          })}
        </div>
      );
    }
 
    let baseCls = 'form-group';
    let classes = classnames(['form-group', 
      ...Object.entries(this.controlState).filter(v => v[1]).map(v => v[0]),
      {[`${baseCls}_has-error`]: errors.length > 0}
    ]);
 
    delete props['validators'];
    delete props['component'];
    delete props['showErrorOn'];
    delete props['isEmpty'];
    delete props['multipleErrors'];
    delete props['initialValue'];
    
    return (
      <div className={classes}>
        {this.props.component({
          state: this.controlState,
          errors,
          controlProps: {
            ...props,
            value: this.value,
            onChange: ::this.handleChange,
            onBlur: ::this.handleBlur,
            onFocus: ::this.handleFocus,
          }
        })}
        {errElement}
      </div>
    );
  }
}
 
export default Base;