All files / src Veasy.jsx

96.15% Statements 25/26
83.33% Branches 10/12
100% Functions 8/8
96% Lines 24/25
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                1x 1x 1x     1x   1x     31x   22x     9x 9x 7x   2x       7x 7x               32x 31x 31x 7x     24x 24x   24x 24x           8x               1x       1x            
/* eslint-disable react/forbid-prop-types,import/no-extraneous-dependencies */
import is from 'is_js';
import PropTypes from 'prop-types';
import React from 'react';
import * as lib from './helpers';
 
export default class Veasy extends React.Component {
  triggerValidation = e => {
    e.preventDefault();
    const { schema, allState, update } = this.props;
    lib.startValidating(e.target, schema, update, allState);
  };
 
  handleOnChange = e => this.triggerValidation(e);
 
  handleBlur = e => this.triggerValidation(e);
 
  isRegisteredComponent = (child, childName) => {
    if (is.string(child.type)) {
      // Skip HTML element
      Eif (is.lowerCase(child.type[0])) return false;
    }
 
    const names = Object.keys(this.props.schema);
    if (React.isValidElement(child) && names.includes(childName)) {
      return true;
    }
    return false;
  };
 
  cloneElement = (child, childName) => {
    const childProp = this.props.allState[childName];
    return React.cloneElement(child, {
      status: childProp.status,
      errorText: childProp.errorText,
      value: childProp.value
    });
  };
 
  recursiveCloneChildren = children =>
    React.Children.map(children, child => {
      const childName = child.props.name;
      if (this.isRegisteredComponent(child, childName)) {
        return this.cloneElement(child, childName);
      }
 
      const childProps = {};
      Eif (child.props) {
        // String has no Prop
        childProps.children = this.recursiveCloneChildren(child.props.children);
        return React.cloneElement(child, childProps);
      }
      return child;
    });
 
  render() {
    return (
      <section onChange={this.handleOnChange} onBlur={this.handleBlur}>
        {this.recursiveCloneChildren(this.props.children)}
      </section>
    );
  }
}
 
Veasy.defaultProps = {
  allState: undefined
};
 
Veasy.propTypes = {
  schema: PropTypes.object.isRequired,
  allState: PropTypes.object,
  update: PropTypes.func.isRequired,
  children: PropTypes.any.isRequired
};