2016-03-20 23:20:00 +00:00
|
|
|
import React, {Component, PropTypes} from 'react';
|
|
|
|
|
|
|
|
const DEFAULT_DEBOUNCE_MILLIS = 300;
|
|
|
|
|
2016-03-23 05:26:27 +00:00
|
|
|
/**
|
|
|
|
* Input that only fire onChange() after the user stops typing
|
|
|
|
*/
|
|
|
|
class DebouncingInput extends Component {
|
2016-04-09 18:47:51 +00:00
|
|
|
_valueChanged (e) {
|
2016-03-20 23:20:00 +00:00
|
|
|
if (!this.props.onChange) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Surround in closure because callback may change before debounce
|
|
|
|
clearTimeout(this._timeout);
|
|
|
|
((value, cb, debounceMillis = DEFAULT_DEBOUNCE_MILLIS) => {
|
|
|
|
this._timeout = setTimeout(() => cb(value), debounceMillis);
|
|
|
|
})(e.target.value, this.props.onChange, this.props.debounceMillis);
|
|
|
|
}
|
|
|
|
|
2016-04-09 18:47:51 +00:00
|
|
|
_updateValueFromProps () {
|
2016-03-20 23:20:00 +00:00
|
|
|
this.refs.input.value = this.props.initialValue || this.props.value || '';
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidMount () {
|
2016-04-09 18:47:51 +00:00
|
|
|
this._updateValueFromProps()
|
2016-03-20 23:20:00 +00:00
|
|
|
}
|
2016-04-09 18:47:51 +00:00
|
|
|
|
2016-03-20 23:20:00 +00:00
|
|
|
componentDidUpdate () {
|
2016-04-09 18:47:51 +00:00
|
|
|
this._updateValueFromProps()
|
|
|
|
}
|
|
|
|
|
|
|
|
focus () {
|
|
|
|
this.refs.input.focus();
|
2016-03-20 23:20:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
render () {
|
2016-04-09 18:47:51 +00:00
|
|
|
const {value, ...other} = this.props;
|
2016-03-20 23:20:00 +00:00
|
|
|
return (
|
|
|
|
<input
|
2016-04-09 01:14:25 +00:00
|
|
|
{...other}
|
2016-03-20 23:20:00 +00:00
|
|
|
ref="input"
|
2016-04-09 18:47:51 +00:00
|
|
|
onChange={this._valueChanged.bind(this)}
|
2016-03-20 23:20:00 +00:00
|
|
|
/>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-23 05:26:27 +00:00
|
|
|
DebouncingInput.propTypes = {
|
2016-03-20 23:20:00 +00:00
|
|
|
onChange: PropTypes.func.isRequired,
|
2016-04-09 18:47:51 +00:00
|
|
|
value: PropTypes.string.isRequired,
|
|
|
|
debounceMillis: PropTypes.number
|
2016-03-20 23:20:00 +00:00
|
|
|
};
|
|
|
|
|
2016-03-23 05:26:27 +00:00
|
|
|
export default DebouncingInput;
|