All files / src/components/Form/Field index.jsx

94.12% Statements 16/17
90% Branches 9/10
100% Functions 5/5
94.12% Lines 16/17
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              4x 30x     30x 17x     13x     30x                           30x 24x     6x           30x 6x     24x 5x         6x       6x       4x                            
import styles from './style.postcss';
 
import React from 'react';
import pure from 'recompose/pure';
import classnames from 'classnames';
import PropTypes from 'prop-types';
 
export const Field = (props) => {
  const classes = classnames(styles.Field, props.className, getValidationClasses(), {
    [styles.__stackedHorizontally]: props.neighborStackMode === 'horizontal',
  });
  if (props.useLabel === true) {
    return <label className={classes}>{renderInner()}</label>;
  }
 
  return <div className={classes}>{renderInner()}</div>;
 
  function renderInner() {
    return <div className={classnames(styles.Field_wrap, {
      [styles.__stackedVertically]: props.innerStackMode === 'vertical',
    })}>
      <span className={classnames(styles.Field_wrap_label, props.labelTextClassName)}>
        {props.label}
      </span>
      <div className={styles.Field_wrap_inputContainer}>
        {props.children}
        {renderError()}
      </div>
    </div>;
  }
 
  function renderError() {
    if (! props.showError()) {
      return;
    }
 
    return <span className={styles.Field_wrap_inputContainer_validationError}>
      {getErrorMessage()}
    </span>;
  }
 
  function getValidationClasses() {
    if (props.showError()) {
      return styles.__error;
    }
 
    if (props.showRequired()) {
      return styles.__required;
    }
  }
 
  function getErrorMessage() {
    Iif (props.showRequired()) {
      return 'This field is required';
    }
 
    return props.getErrorMessage();
  }
};
 
Field.propTypes = {
  className: PropTypes.string,
  labelTextClassName: PropTypes.string,
  label: PropTypes.string,
  showError: PropTypes.func.isRequired,
  showRequired: PropTypes.func.isRequired,
  getErrorMessage: PropTypes.func.isRequired,
  children: PropTypes.node,
  useLabel: PropTypes.bool,
  neighborStackMode: PropTypes.oneOf(['default', 'horizontal']),
  innerStackMode: PropTypes.oneOf(['horizontal', 'vertical']),  // default: horizontal
};
 
export default pure(Field);