all files / src/components/ OnPasteSelect.jsx

93.33% Statements 42/45
55.56% Branches 10/18
87.5% Functions 7/8
92.86% Lines 39/42
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           18× 21×       18× 18× 18×                                                                                  
import React from 'react';
import PropTypes from 'prop-types';
import Select from 'react-select';
 
export default class OnPasteSelect extends React.Component {
  onPaste(evt) {
    if (I!this.props.multi) {
      return;
    }
    evt.preventDefault();
    const clipboard = evt.clipboardData.getData('Text');
    if (I!clipboard) {
      return;
    }
    const regex = `[${this.props.separator}]+`;
    const values = clipboard.split(new RegExp(regex)).map(v => v.trim());
    const validator = this.props.isValidNewOption;
    const selected = this.props.value || [];
    const existingOptions = {};
    const existing = {};
    this.props.options.forEach((v) => {
      existingOptions[v[this.props.valueKey]] = 1;
    });
    let options = [];
    selected.forEach((v) => {
      options.push({ [this.props.labelKey]: v, [this.props.valueKey]: v });
      existing[v] = 1;
    });
    options = options.concat(values
      .filter((v) => {
        const notExists = !existing[v];
        existing[v] = 1;
        return notExists && (validator ? validator({ [this.props.labelKey]: v }) : !!v);
      })
      .map((v) => {
        const opt = { [this.props.labelKey]: v, [this.props.valueKey]: v };
        if (!existingOptions[v]) {
          this.props.options.unshift(opt);
        }
        return opt;
      }),
    );
    if (Eoptions.length) {
      if (Ethis.props.onChange) {
        this.props.onChange(options);
      }
    }
  }
  render() {
    const SelectComponent = this.props.selectWrap;
    const refFunc = (ref) => {
      if (this.props.refFunc) {
        this.props.refFunc(ref);
      }
      this.pasteInput = ref;
    };
    const inputProps = { onPaste: this.onPaste.bind(this) };
    return (
      <SelectComponent
        {...this.props}
        ref={refFunc}
        inputProps={inputProps}
      />
    );
  }
}
 
OnPasteSelect.propTypes = {
  separator: PropTypes.string.isRequired,
  selectWrap: PropTypes.func.isRequired,
  refFunc: PropTypes.func,
  onChange: PropTypes.func.isRequired,
  valueKey: PropTypes.string.isRequired,
  labelKey: PropTypes.string.isRequired,
  options: PropTypes.array,
  multi: PropTypes.bool.isRequired,
  value: PropTypes.any,
  isValidNewOption: PropTypes.func,
};
OnPasteSelect.defaultProps = {
  separator: ',',
  selectWrap: Select,
  valueKey: 'value',
  labelKey: 'label',
  options: [],
  multi: false,
};