All files / src/component AutoCompleteItem.js

96.55% Statements 28/29
70% Branches 14/20
100% Functions 5/5
96.55% Lines 28/29
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                    2x                     2x 2x     2x       3x 3x       2x 2x       5x 5x   1x 1x 1x   1x 1x 1x   1x 1x     2x 2x     5x       10x 10x 10x     10x 10x 10x                             2x        
/* eslint-disable react/no-find-dom-node,jsx-a11y/no-noninteractive-element-interactions */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { findDOMNode } from 'react-dom';
import omit from 'lodash/omit';
import { focusNextItem, focusPreviousItem } from '../utils/moveFocus';
import getItemsAndActiveIndex from '../utils/getItemsAndActiveIndex';
import KEY_CODE from '../KEY_CODE';
 
const propTypes = {
  text: PropTypes.string,
  title: PropTypes.string,
  active: PropTypes.bool,
  onClick: PropTypes.func,
  onClose: PropTypes.func,
  onKeyDown: PropTypes.func
};
 
class AutoCompleteItem extends Component {
  getFocusAbleItems() {
    const node = findDOMNode(this);
    Iif (!node) {
      return [];
    }
    return Array.from(node.parentNode.querySelectorAll('.auto-complete-item'));
  }
 
  handleClick = (event) => {
    const { text, onClick } = this.props;
    onClick && onClick(text, event);
  };
 
  handleClose = (event) => {
    const { onClose } = this.props;
    onClose && onClose(event);
  };
 
  handleKeyDown = (event) => {
    const { onKeyDown } = this.props;
    switch (event.keyCode) {
      case KEY_CODE.DOWN:
        focusNextItem(getItemsAndActiveIndex(this.getFocusAbleItems()));
        event.preventDefault();
        break;
      case KEY_CODE.UP:
        focusPreviousItem(getItemsAndActiveIndex(this.getFocusAbleItems()));
        event.preventDefault();
        break;
      case KEY_CODE.ENTER:
        this.handleClick(event);
        break;
      case KEY_CODE.ESC:
      case KEY_CODE.TAB:
        this.handleClose(event);
        break;
      default:
    }
    onKeyDown && onKeyDown(event);
  };
 
  render() {
    const { active, text } = this.props;
    const props = omit(this.props, Object.keys(propTypes));
    const className = classnames('item auto-complete-item', {
      active
    });
    const children = this.props.children ? this.props.children : text;
    const title = !children ? (this.props.title || text) : '';
    return (
      <li
        title={title}
        className={className}
        onClick={this.handleClick}
        onKeyDown={this.handleKeyDown}
        tabIndex="-1"
        {...props}
      >
        <label className="text">{children}</label>
      </li>
    );
  }
}
 
AutoCompleteItem.propTypes = propTypes;
 
export default AutoCompleteItem;