All files ReactCodeInput.js

94.9% Statements 93/98
80.6% Branches 54/67
100% Functions 15/15
94.9% Lines 93/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284          1x 1x 1x 1x 1x       19x   19x   19x                                           19x 113x 112x 112x       19x   19x       1x               3x       14x   14x                   4x   4x 3x     4x   4x 3x   3x 2x 12x 12x   12x     1x     3x 15x 15x   15x     3x   3x 3x 3x     3x   3x     4x 3x     4x       7x 7x 7x       7x   1x 1x 1x 1x 1x   1x 1x 1x         1x     1x 1x 1x 1x   1x     1x 1x 1x 1x   1x     1x 1x     1x 1x     2x     7x 1x     7x       24x 24x 24x         24x       24x 23x               24x 23x               24x 1x               24x     134x     132x                         3x 3x 4x 7x                     1x                 1x                                      
import React, { Component } from 'react';
import PropTypes            from 'prop-types';
import classNames           from 'classnames';
import { uuidv4 }           from './utils';
 
const BACKSPACE_KEY = 8;
const LEFT_ARROW_KEY = 37;
const UP_ARROW_KEY = 38;
const RIGHT_ARROW_KEY = 39;
const DOWN_ARROW_KEY = 40;
 
class ReactCodeInput extends Component {
  constructor(props) {
    super(props);
 
    const { value, fields, type, isValid, disabled } = props;
 
    this.state = {
      value,
      fields,
      type,
      input: [],
      isValid,
      disabled,
      defaultInputStyle: {
        fontFamily: 'monospace',
        MozAppearance: 'textfield',
        borderRadius: '6px',
        border: '1px solid',
        boxShadow: '0px 0px 10px 0px rgba(0,0,0,.10)',
        margin: '4px',
        paddingLeft: '8px',
        width: '36px',
        height: '42px',
        fontSize: '32px',
        boxSizing: 'border-box'
      }
    };
 
    for (let i = 0; i < Number(this.state.fields); i += 1) {
      if (i < 32) {
        const value = this.state.value[i] || '';
        this.state.input.push(value)
      }
    }
 
    this.textInput = [];
 
    this.uuid = uuidv4();
  }
 
  componentWillReceiveProps(nextProps) {
    this.setState({
      isValid:  nextProps.isValid,
      value:    nextProps.value,
      disabled: nextProps.disabled,
    });
  }
 
  handleBlur(e) {
    this.handleTouch(e.target.value);
  }
 
  handleTouch(value) {
    const { touch, untouch, name } = this.props;
 
    Iif (typeof touch === 'function' && typeof untouch === 'function') {
      if (value === '') {
        touch(name);
      } else {
        untouch(name);
      }
    }
  }
 
  handleChange(e) {
    let value = String(e.target.value);
 
    if (this.state.type === 'number') {
      value = value.replace(/[^\d]/g, '');
    }
 
    let fullValue = value;
 
    if (value !== '') {
      const input = this.state.input.slice();
 
      if (value.length > 1) {
        value.split('').map((chart, i) => {
          Eif (Number(e.target.dataset.id) + i < this.props.fields) {
            input[Number(e.target.dataset.id) + i] = chart;
          }
          return false;
        });
      } else {
        input[Number(e.target.dataset.id)] = value;
      }
 
      input.map((s, i) => {
        Eif (this.textInput[i]) {
          this.textInput[i].value = s;
        }
        return false;
      });
 
      const newTarget = this.textInput[e.target.dataset.id < input.length ? Number(e.target.dataset.id) + 1 : e.target.dataset.id];
 
      Eif (newTarget) {
        newTarget.focus();
        newTarget.select();
      }
 
      fullValue = input.join('');
 
      this.setState({ value: input.join(''), input });
    }
 
    if (this.props.onChange && fullValue) {
      this.props.onChange(fullValue);
    }
 
    this.handleTouch(fullValue);
  }
 
  handleKeyDown(e) {
    const target = Number(e.target.dataset.id),
          nextTarget = this.textInput[target + 1],
          prevTarget = this.textInput[target - 1];
 
    let input, value;
 
    switch (e.keyCode) {
      case BACKSPACE_KEY:
        e.preventDefault();
        this.textInput[target].value = '';
        input = this.state.input.slice();
        input[target] = '';
        value = input.join('');
 
        this.setState({ value, input });
        Eif (this.textInput[target].value === '') {
          Iif (prevTarget) {
            prevTarget.focus();
            prevTarget.select();
          }
        }
        break;
 
      case LEFT_ARROW_KEY:
        e.preventDefault();
        Eif (prevTarget) {
          prevTarget.focus();
          prevTarget.select();
        }
        break;
 
      case RIGHT_ARROW_KEY:
        e.preventDefault();
        Eif (nextTarget) {
          nextTarget.focus();
          nextTarget.select();
        }
        break;
 
      case UP_ARROW_KEY:
        e.preventDefault();
        break;
 
      case DOWN_ARROW_KEY:
        e.preventDefault();
        break;
 
      default:
        break;
    }
 
    if (this.props.onChange && value) {
      this.props.onChange(value);
    }
 
    this.handleTouch(value);
  }
 
  render() {
    const { className, style = {}, inputStyle = {}, inputStyleInvalid = {}, type, autoFocus } = this.props,
    { disabled, input, isValid, defaultInputStyle } = this.state,
    styles = {
      container: style,
      input:     isValid ? inputStyle : inputStyleInvalid,
    };
 
    Object.assign(styles.container, {
      display: 'inline-block',
    });
 
    if (!className && Object.keys(inputStyle).length === 0) {
      Object.assign(inputStyle, {
        ...defaultInputStyle,
        color:           'black',
        backgroundColor: 'white',
        borderColor:     'lightgrey',
      });
    }
 
    if (!className && Object.keys(inputStyleInvalid).length === 0) {
      Object.assign(inputStyleInvalid, {
        ...defaultInputStyle,
        color:           '#b94a48',
        backgroundColor: '#f2dede',
        borderColor:     '#eed3d7',
      });
    }
 
    if (disabled) {
      Object.assign(styles.input, {
        cursor:          'not-allowed',
        color:           'lightgrey',
        borderColor:     'lightgrey',
        backgroundColor: '#efeff1',
      });
    }
 
    return (
      <div className={classNames(className, 'react-code-input')} style={styles.container}>
        {input.map((value, i) => {
          return (
            <input
              ref={(ref) => {
                this.textInput[i] = ref;
              }}
              id={`${this.uuid}-${i}`}
              data-id={i}
              autoFocus={autoFocus && (i === 0) ? 'autoFocus' : ''}
              defaultValue={value}
              key={`input_${i}`}
              type={type}
              min={0}
              max={9}
              maxLength={input.length === i + 1 ? 1 : input.length}
              style={styles.input}
              autoComplete="off"
              onFocus={(e) => e.target.select(e)}
              onBlur={(e) => this.handleBlur(e)}
              onChange={(e) => this.handleChange(e)}
              onKeyDown={(e) => this.handleKeyDown(e)}
              disabled={disabled}
              data-valid={isValid}
            />
          );
        })}
      </div>
    )
  }
}
 
ReactCodeInput.defaultProps = {
  autoFocus: true,
  isValid: true,
  disabled: false,
  fields: 4,
  value: '',
  type: 'text',
};
 
ReactCodeInput.propTypes = {
  options: PropTypes.object,
  type: PropTypes.oneOf(['text', 'number', 'password', 'tel']),
  fields: PropTypes.number,
  value: PropTypes.string,
  onChange: PropTypes.func,
  name: PropTypes.string,
  touch: PropTypes.func,
  untouch: PropTypes.func,
  className: PropTypes.string,
  isValid: PropTypes.bool,
  disabled: PropTypes.bool,
  style: PropTypes.object,
  inputStyle: PropTypes.object,
  inputStyleInvalid: PropTypes.object,
  autoFocus: PropTypes.bool,
};
 
export default ReactCodeInput;