/* 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;
|