react-predictive-text
Version:
A React component that finishes users' words.
125 lines (114 loc) • 3.06 kB
JSX
import React from "react";
import Trie from "./Trie.js";
import PTextItem from "./react-predictive-text-item.jsx";
import propTypes from "prop-types"
class PText extends React.Component {
constructor(props) {
super(props);
this.uniqueId = 0;
this.state = {
value: "",
predictions: [],
cache: [],
width: 100
};
this._trie = new Trie();
this.props.options.forEach((opt) => {
this._trie.add(opt);
})
this.handleOptionSelect = this.handleOptionSelect.bind(this)
}
handleTextInput(e) {
let fragment = e.target.value;
var newPredictions = this._trie.retrieve(e.target.value);
this.setState({
value: e.target.value,
predictions: newPredictions
})
}
handleOptionSelect(option) {
this.setState({
value: option,
predictions: []
}, this.props.onSelect(option))
}
handleResize(e) {
let bbox = e.target.getBoundingClientRect();
this.setState({width: bbox.width});
}
handleBlur(e) {
this.setState({
cache: this.state.predictions,
predictions: []
})
}
handleFocus(e) {
this.setState({
predictions: this.state.cache
})
}
render() {
return (
<div
onBlur={this.handleBlur.bind(this)}
onFocus={this.handleFocus.bind(this)}
style={this.props.wrapperStyles}
>
<textarea
style={this.props.textStyles}
id={this.props.options.id}
value={this.state.value}
onChange={this.handleTextInput.bind(this)}
onMouseUp={this.handleResize.bind(this)}
/>
<div style={{
width: this.state.width,
maxHeight: "10em",
overflow: "scroll",
position: "absolute",
zIndex: 99
}}>
{
this.state.predictions.map((pred) =>
<PTextItem
style={this.props.optionStyles}
key={this.uniqueId++}
color={this.props.optionColor}
onSelect={this.handleOptionSelect}
value={pred}
/>
)
}
</div>
</div>
);
}
}
PText.propTypes = {
options: propTypes.array
optionStyles: propTypes.object,
optionColor: propTypes.string,
textStyles: propTypes.object,
wrapperStyles: propTypes.object,
onSelect: propTypes.func
}
PText.defaultProps = {
options: []
optionStyles: {
border: '1px solid lightgrey',
fontSize: '0.25em',
padding: '0.25em'
},
optionColor: '#E6E6FA',
textStyles: {},
wrapperStyles: {},
onSelect: () => {}
}
// props:
// options -- an array of strings that may be used to auto-complete.
// optionStyles -- a style object for every item in the recommendation list.
// textStyles -- a style object for the textarea element.
// wrapperStyles -- a style object for the wrapper div.
// optionColor -- a string representing the color a hovered item will be colored.
// onSelect -- a function to be called when an item is selected.
export default PText