react-toolbox/components/autocomplete/Autocomplete.js

272 lines
7.9 KiB
JavaScript
Raw Normal View History

2016-01-06 14:56:30 +03:00
import React from 'react';
import ReactDOM from 'react-dom';
2016-05-21 20:48:53 +03:00
import classnames from 'classnames';
import { themr } from 'react-css-themr';
2016-01-06 14:56:30 +03:00
import Input from '../input';
import events from '../utils/events';
import Chip from '../chip';
2016-01-06 14:56:30 +03:00
const POSITION = {
AUTO: 'auto',
DOWN: 'down',
UP: 'up'
};
class Autocomplete extends React.Component {
static propTypes = {
className: React.PropTypes.string,
direction: React.PropTypes.oneOf(['auto', 'up', 'down']),
disabled: React.PropTypes.bool,
error: React.PropTypes.string,
label: React.PropTypes.string,
multiple: React.PropTypes.bool,
onChange: React.PropTypes.func,
selectedPosition: React.PropTypes.oneOf(['above', 'below']),
showSuggestionsWhenValueIsSet: React.PropTypes.bool,
2016-01-06 14:56:30 +03:00
source: React.PropTypes.any,
2016-05-21 20:48:53 +03:00
theme: React.PropTypes.shape({
active: React.PropTypes.string.isRequired,
autocomplete: React.PropTypes.string.isRequired,
focus: React.PropTypes.string.isRequired,
input: React.PropTypes.string.isRequired,
label: React.PropTypes.string.isRequired,
suggestion: React.PropTypes.string.isRequired,
suggestions: React.PropTypes.string.isRequired,
up: React.PropTypes.string.isRequired,
value: React.PropTypes.string.isRequired,
values: React.PropTypes.string.isRequired
}),
2016-01-06 14:56:30 +03:00
value: React.PropTypes.any
};
static defaultProps = {
className: '',
direction: 'auto',
selectedPosition: 'above',
2016-01-06 14:56:30 +03:00
multiple: true,
showSuggestionsWhenValueIsSet: false,
2016-01-06 14:56:30 +03:00
source: {}
};
state = {
direction: this.props.direction,
focus: false,
showAllSuggestions: this.props.showSuggestionsWhenValueIsSet,
2016-01-06 14:56:30 +03:00
query: this.query(this.props.value)
};
componentWillReceiveProps (nextProps) {
if (!this.props.multiple) {
this.setState({query: nextProps.value});
2016-01-06 14:56:30 +03:00
}
}
shouldComponentUpdate (nextProps, nextState) {
if (!this.state.focus && nextState.focus && this.props.direction === POSITION.AUTO) {
const direction = this.calculateDirection();
if (this.state.direction !== direction) {
this.setState({ direction });
return false;
}
}
return true;
}
handleChange = (keys, event) => {
const key = this.props.multiple ? keys : keys[0];
const query = this.query(key);
if (this.props.onChange) this.props.onChange(key, event);
this.setState(
{focus: false, query, showAllSuggestions: this.props.showSuggestionsWhenValueIsSet},
2016-05-21 20:48:53 +03:00
() => { ReactDOM.findDOMNode(this).querySelector('input').blur(); }
);
2016-01-06 14:56:30 +03:00
};
handleQueryBlur = () => {
if (this.state.focus) this.setState({focus: false});
};
handleQueryChange = (value) => {
this.setState({query: value, showAllSuggestions: false});
2016-01-06 14:56:30 +03:00
};
handleQueryFocus = () => {
this.refs.suggestions.scrollTop = 0;
this.setState({active: '', focus: true});
};
handleQueryKeyDown = (event) => {
// Clear query when pressing backspace and showing all suggestions.
const shouldClearQuery = (
event.which === 8
&& this.props.showSuggestionsWhenValueIsSet
&& this.state.showAllSuggestions
);
if (shouldClearQuery) {
this.setState({query: ''});
}
};
2016-01-06 14:56:30 +03:00
handleQueryKeyUp = (event) => {
if (event.which === 13 && this.state.active) this.select(this.state.active, event);
2016-05-21 20:48:53 +03:00
if (event.which === 27) ReactDOM.findDOMNode(this).querySelector('input').blur();
2016-01-06 14:56:30 +03:00
if ([40, 38].indexOf(event.which) !== -1) {
const suggestionsKeys = [...this.suggestions().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]});
}
};
handleSuggestionHover = (key) => {
this.setState({active: key});
};
calculateDirection () {
if (this.props.direction === 'auto') {
const client = ReactDOM.findDOMNode(this.refs.input).getBoundingClientRect();
const screen_height = window.innerHeight || document.documentElement.offsetHeight;
const up = client.top > ((screen_height / 2) + client.height);
return up ? 'up' : 'down';
} else {
return this.props.direction;
}
}
query (key) {
return !this.props.multiple && key ? this.source().get(key) : '';
2016-01-06 14:56:30 +03:00
}
suggestions () {
let suggest = new Map();
2016-01-06 14:56:30 +03:00
const query = this.state.query.toLowerCase().trim() || '';
const values = this.values();
const source = this.source();
// Suggest any non-set value which matches the query
if (this.props.multiple) {
for (const [key, value] of source) {
if (!values.has(key) && value.toLowerCase().trim().startsWith(query)) {
suggest.set(key, value);
}
2016-01-06 14:56:30 +03:00
}
// When multiple is false, suggest any value which matches the query if showAllSuggestions is false
} else if (query && !this.state.showAllSuggestions) {
for (const [key, value] of source) {
if (value.toLowerCase().trim().startsWith(query)) {
suggest.set(key, value);
}
}
// When multiple is false, suggest all values when showAllSuggestions is true
} else {
suggest = source;
2016-01-06 14:56:30 +03:00
}
2016-01-06 14:56:30 +03:00
return suggest;
}
source () {
const { source: src } = this.props;
if (src.hasOwnProperty('length')) {
return new Map(src.map((item) => Array.isArray(item) ? [...item] : [item, item]));
2016-01-06 14:56:30 +03:00
} else {
return new Map(Object.keys(src).map((key) => [key, src[key]]));
}
}
values () {
const valueMap = new Map();
const vals = this.props.multiple ? this.props.value : [this.props.value];
for (const [k, v] of this.source()) {
if (vals.indexOf(k) !== -1) valueMap.set(k, v);
}
return valueMap;
}
select (key, event) {
events.pauseEvent(event);
const values = this.values(this.props.value);
this.handleChange([key, ...values.keys()], event);
}
unselect (key, event) {
2016-03-09 19:52:36 +03:00
if (!this.props.disabled) {
const values = this.values(this.props.value);
values.delete(key);
this.handleChange([...values.keys()], event);
}
2016-01-06 14:56:30 +03:00
}
renderSelected () {
if (this.props.multiple) {
const selectedItems = [...this.values()].map(([key, value]) => {
return (
<Chip
key={key}
2016-05-21 20:48:53 +03:00
className={this.props.theme.value}
deletable
onDeleteClick={this.unselect.bind(this, key)}
>
{value}
</Chip>
);
2016-01-06 14:56:30 +03:00
});
2016-05-21 20:48:53 +03:00
return <ul className={this.props.theme.values}>{selectedItems}</ul>;
2016-01-06 14:56:30 +03:00
}
}
renderSuggestions () {
2016-05-21 20:48:53 +03:00
const { theme } = this.props;
2016-01-06 14:56:30 +03:00
const suggestions = [...this.suggestions()].map(([key, value]) => {
2016-05-21 20:48:53 +03:00
const className = classnames(theme.suggestion, {[theme.active]: this.state.active === key});
2016-01-06 14:56:30 +03:00
return (
<li
key={key}
className={className}
onMouseDown={this.select.bind(this, key)}
onMouseOver={this.handleSuggestionHover.bind(this, key)}
>
{value}
</li>
);
});
2016-05-21 20:48:53 +03:00
const className = classnames(theme.suggestions, {[theme.up]: this.state.direction === 'up'});
2016-01-06 14:56:30 +03:00
return <ul ref='suggestions' className={className}>{suggestions}</ul>;
}
render () {
2016-05-21 20:48:53 +03:00
const {error, label, theme, ...other} = this.props;
const className = classnames(theme.autocomplete, {
[theme.focus]: this.state.focus
2016-01-06 14:56:30 +03:00
}, this.props.className);
return (
<div data-react-toolbox='autocomplete' className={className}>
{this.props.selectedPosition === 'above' ? this.renderSelected() : null}
2016-01-06 14:56:30 +03:00
<Input
{...other}
ref='input'
2016-05-21 20:48:53 +03:00
className={theme.input}
2016-01-06 14:56:30 +03:00
error={error}
label={label}
onBlur={this.handleQueryBlur}
onChange={this.handleQueryChange}
onFocus={this.handleQueryFocus}
onKeyDown={this.handleQueryKeyDown}
2016-01-06 14:56:30 +03:00
onKeyUp={this.handleQueryKeyUp}
value={this.state.query}
/>
{this.renderSuggestions()}
{this.props.selectedPosition === 'below' ? this.renderSelected() : null}
2016-01-06 14:56:30 +03:00
</div>
);
}
}
2016-05-21 20:48:53 +03:00
export default themr('ToolboxAutocomplete')(Autocomplete);