All files / src/component AutoComplete.js

78.79% Statements 52/66
51.35% Branches 19/37
82.61% Functions 19/23
80% Lines 52/65
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                            1x                   1x           9x 9x               9x 9x                                             1x 1x       4x             19x 19x 4x 4x         4x               4x 1x 1x       3x       1x         8x 8x 8x 24x 24x   8x             5x 5x 5x       3x     3x 3x       1x 1x         1x       2x   1x 1x 1x     1x 1x 1x           1x                                   5x       19x 19x 19x 19x 19x 19x                                             1x 1x 1x      
/* eslint-disable react/no-find-dom-node */
import React, { cloneElement, Component } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import { FormControl } from 'rsuite';
import classnames from 'classnames';
import { on, off, contains } from 'dom-lib';
import _omit from 'lodash/omit';
 
import AutoCompleteItem from './AutoCompleteItem';
import { focusNextItem } from '../utils/moveFocus';
import getItemsAndActiveIndex from '../utils/getItemsAndActiveIndex';
import KEY_CODE from '../KEY_CODE';
 
const propTypes = {
  placeholder: PropTypes.string,
  dataSource: PropTypes.arrayOf(PropTypes.string),
  disabled: PropTypes.bool,
  onSelect: PropTypes.func,
  onChange: PropTypes.func,
  value: PropTypes.string,
  defaultValue: PropTypes.string,
};
 
const defaultProps = {
  dataSource: []
};
 
class AutoComplete extends Component {
  constructor(props) {
    super(props);
    this.state = {
      children: [],
      show: true,
      text: this.props.value || this.props.defaultValue || ''
    };
  }
 
  componentWillMount() {
    const { children } = this.props;
    Iif (children) {
      this.setState({
        children
      });
    }
  }
 
  componentWillReceiveProps(nextProps) {
    const { children, value } = nextProps;
    if (children && this.state.children !== children) {
      this.setState({
        children
      });
    }
 
    if (this.props.value !== value) {
      this.setState({
        value
      });
    }
  }
 
  getFocusableItems() {
    const node = findDOMNode(this);
    return Array.from(node.querySelectorAll('.auto-complete-item'));
  }
 
  getItemsProps(item) {
    return {
      onClick: this.getHandleCustomizedItemClick(item),
      onClose: this.handleClose
    };
  }
 
  getDefaltItems() {
    const { children, text } = this.state;
    return children.map((data, key) => {
      const active = text === data;
      const props = Object.assign({
        key,
        active,
        text: data
      }, this.getItemsProps());
      return <AutoCompleteItem {...props} />;
    });
  }
 
  getCustomizedItems() {
    return React.Children.map(this.state.children, item => cloneElement(item, this.getItemsProps(item)));
  }
 
  getHandleCustomizedItemClick = item => (...args) => {
    this.handleItemChange(...args);
    item && item.props && item.props.onClick && item.props.onClick(...args);
  };
 
  bindAutoClosePanelFunctionToDom() {
    on(document.body, 'click', this.handleDomClosePanel);
  }
 
  unBindAutoClosePanelFunctionToDom() {
    off(document.body, 'click', this.handleDomClosePanel);
  }
 
 
  handleSearchData = (value) => {
    const { dataSource } = this.props;
    const valueUpper = value.trim().toUpperCase();
    const children = valueUpper.length > 0 ? dataSource.filter((data) => {
      const text = data.toUpperCase();
      return text.indexOf(valueUpper) > -1;
    }) : [];
    this.setState({
      text: value,
      children
    });
  };
 
  handleChange = (value, ...args) => {
    const { onChange } = this.props;
    this.handleSearchData(value);
    onChange && onChange(value, ...args);
  };
 
  handleInputFocus = (e) => {
    this.setState({
      show: true
    });
    this.handleSearchData(e.target.value);
    this.bindAutoClosePanelFunctionToDom();
  };
 
  handleItemChange = (text, ...args) => {
    const { onSelect } = this.props;
    this.setState({
      text,
      children: [],
      show: false
    });
    onSelect && onSelect(text, ...args);
  };
 
  handleKeyDown = (event) => {
    switch (event.keyCode) {
      case KEY_CODE.DOWN:
        event.preventDefault();
        focusNextItem(getItemsAndActiveIndex(this.getFocusableItems()));
        break;
      case KEY_CODE.ESC:
      case KEY_CODE.TAB:
        this.handleClose(event);
        this.unBindAutoClosePanelFunctionToDom();
        break;
      default:
    }
  };
 
  handleClose = () => {
    this.setState({
      show: false,
      children: []
    });
  };
 
  handleDomClosePanel = (e) => {
    const node = findDOMNode(this);
    const input = findDOMNode(this.input);
    if (e.target !== node && !contains(node, e.target)) {
      this.handleClose();
    }
    if (e.target !== input) {
      this.unBindAutoClosePanelFunctionToDom();
    }
  };
 
  bindInput = (ref) => {
    this.input = ref;
  };
 
  render() {
    const { disabled, placeholder, className, children } = this.props;
    const props = _omit(this.props, [...Object.keys(propTypes), 'children']);
    const { text, show } = this.state;
    const childrenDoms = children ? this.getCustomizedItems() : this.getDefaltItems();
    const contentClassName = (classnames('auto-complete-content', { show: show && childrenDoms.length > 0 }));
    return (
      <div className={`${className || ''} auto-complete-wrap`}>
        <FormControl
          {...props}
          ref={this.bindInput}
          type="text"
          placeholder={placeholder}
          disabled={disabled}
          value={text}
          onFocus={this.handleInputFocus}
          onChange={this.handleChange}
          onKeyDown={this.handleKeyDown}
        />
        <div
          className={contentClassName}
        >
          <ul>{childrenDoms}</ul>
        </div>
      </div>
    );
  }
}
 
AutoComplete.propTypes = propTypes;
AutoComplete.defaultProps = defaultProps;
AutoComplete.Item = AutoCompleteItem;
 
export default AutoComplete;