react-auto-suggest
Version:
React auto-suggest component
128 lines (110 loc) • 3.44 kB
JavaScript
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var React = _interopRequire(require("react"));
var SearchBox = _interopRequire(require("./SearchBox"));
var DropDown = _interopRequire(require("./DropDown"));
var AutoSuggest = React.createClass({
displayName: "AutoSuggest",
propTypes: {
suggestions: React.PropTypes.func.isRequired,
onSuggestion: React.PropTypes.func.isRequired
},
getInitialState: function getInitialState() {
return {
suggestions: [],
displayDropDown: false,
index: -1
};
},
handleTerm: function handleTerm(value) {
this.setState({
term: value,
value: value
});
this.props.suggestions(value, this.onResponse);
},
onResponse: function onResponse(suggestions) {
this.setState({
index: -1,
displayDropDown: true,
suggestions: suggestions
});
},
onClick: function onClick(term) {
this.setState({
index: -1,
term: term,
displayDropDown: false
});
this.triggerSuggestion(term);
},
triggerSuggestion: function triggerSuggestion(suggestion) {
this.props.onSuggestion(suggestion);
},
handleSpecial: function handleSpecial(code) {
var suggestions = this.state.suggestions;
var length = suggestions.length;
var index = this.state.index;
var displayDropDown = true;
var term = undefined;
if (code === 13) {
// enter
displayDropDown = false;
this.triggerSuggestion(this.state.term);
} else if (code === 27) {
// esc
index = -1;
displayDropDown = false;
} else if (code === 38) {
// up
if (index === -1) {
index = length - 1;
} else {
index--;
}
} else if (code === 39) {} else if (code === 40) {
// down
if (index === length - 1) {
index = -1;
} else {
index++;
}
}
if (index === -1) {
term = this.state.value;
} else {
var suggestion = suggestions[index];
if (this.props.onSelect) {
term = this.props.onSelect(suggestion);
} else {
term = suggestion;
}
}
this.setState({
index: index,
term: term,
displayDropDown: displayDropDown
});
},
render: function render() {
var renderer = this.props.children;
return React.createElement(
"div",
{ className: this.constructor.displayName },
React.createElement(SearchBox, {
handleTerm: this.handleTerm,
handleSpecial: this.handleSpecial,
value: this.state.term
}),
React.createElement(DropDown, { key: "dropdown",
onClick: this.onClick,
suggestions: this.state.suggestions,
display: this.state.displayDropDown,
renderer: renderer,
index: this.state.index
})
);
}
});
module.exports = AutoSuggest;
// right