import React from 'react'; import ReactDOM from 'react-dom'; import Input from '../input'; import style from './style'; import utils from '../utils'; class Autocomplete extends React.Component { static propTypes = { className: React.PropTypes.string, dataSource: React.PropTypes.any, disabled: React.PropTypes.bool, error: React.PropTypes.string, label: React.PropTypes.string, multiple: React.PropTypes.bool, onChange: React.PropTypes.func, required: React.PropTypes.bool, value: React.PropTypes.any }; static defaultProps = { className: '', dataSource: {}, multiple: true }; state = { dataSource: this._indexDataSource(this.props.dataSource), focus: false, query: '', up: false, values: new Map(), width: undefined }; componentDidMount () { if (this.props.value) this.setValue(this.props.value); this.setState({ width: ReactDOM.findDOMNode(this).getBoundingClientRect().width }); } componentWillReceiveProps (props) { if (props.dataSource) { this.setState({dataSource: this._indexDataSource(props.dataSource)}); } } componentWillUpdate (props, state) { this.refs.input.setValue(state.query); } handleQueryChange = () => { const query = this.refs.input.getValue(); if (this.state.query !== query) { this.setState({query}); } }; handleKeyPress = (event) => { if (event.which === 13 && this.state.active) { this._selectOption(this.state.active); } if ([40, 38].indexOf(event.which) !== -1) { const suggestionsKeys = [...this._getSuggestions().keys()]; let index = suggestionsKeys.indexOf(this.state.active) + (event.which === 40 ? +1 : -1); if (index < 0) index = suggestionsKeys.length - 1; if (index >= suggestionsKeys.length) index = 0; this.setState({active: suggestionsKeys[index]}); } }; handleFocus = () => { const client = event.target.getBoundingClientRect(); const screen_height = window.innerHeight || document.documentElement.offsetHeight; this.refs.suggestions.scrollTop = 0; this.setState({ active: '', up: client.top > ((screen_height / 2) + client.height), focus: true }); }; handleBlur = () => { if (this.state.focus) this.setState({focus: false}); }; handleHover = (event) => { this.setState({active: event.target.getAttribute('id')}); }; handleSelect = (event) => { utils.events.pauseEvent(event); this._selectOption(event.target.getAttribute('id')); }; handleUnselect = (event) => { this._unselectOption(event.target.getAttribute('id')); }; renderSelected () { if (this.props.multiple) { return (