2017-02-28 21:32:23 +00:00
|
|
|
import React, {PureComponent, PropTypes} from 'react';
|
2017-03-03 01:44:07 +00:00
|
|
|
import autobind from 'autobind-decorator';
|
2016-11-29 20:55:31 +00:00
|
|
|
import {debounce} from '../../../common/misc';
|
2016-11-10 21:03:12 +00:00
|
|
|
|
2017-03-03 01:44:07 +00:00
|
|
|
@autobind
|
2017-02-28 21:32:23 +00:00
|
|
|
class DebouncedInput extends PureComponent {
|
2017-03-01 21:15:56 +00:00
|
|
|
constructor (props) {
|
|
|
|
super(props);
|
|
|
|
|
|
|
|
if (!props.delay) {
|
|
|
|
this._handleValueChange = props.onChange;
|
|
|
|
} else {
|
|
|
|
this._handleValueChange = debounce(props.onChange, props.delay || 500);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-03 01:44:07 +00:00
|
|
|
_handleChange (e) {
|
|
|
|
this._handleValueChange(e.target.value);
|
|
|
|
}
|
|
|
|
|
|
|
|
_setRef (n) {
|
|
|
|
this._input = n;
|
|
|
|
}
|
2017-03-01 21:15:56 +00:00
|
|
|
|
|
|
|
getSelectionStart () {
|
|
|
|
if (this._input) {
|
|
|
|
return this._input.selectionStart;
|
|
|
|
} else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getSelectionEnd () {
|
|
|
|
if (this._input) {
|
|
|
|
return this._input.selectionEnd;
|
|
|
|
} else {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
focus () {
|
|
|
|
if (this._input) {
|
|
|
|
this._input.focus();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
focusEnd () {
|
|
|
|
if (this._input) {
|
|
|
|
// Hack to focus the end (set value to current value);
|
|
|
|
this._input.value = this.getValue();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
blur () {
|
|
|
|
if (this._input) {
|
|
|
|
this._input.blur();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
getValue () {
|
|
|
|
if (this._input) {
|
|
|
|
return this._input.value;
|
|
|
|
} else {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
}
|
2016-11-10 21:03:12 +00:00
|
|
|
|
|
|
|
render () {
|
|
|
|
// NOTE: Strip out onChange because we're overriding it
|
2017-03-01 21:15:56 +00:00
|
|
|
const {onChange, delay, textarea, ...props} = this.props;
|
2016-11-29 20:55:31 +00:00
|
|
|
if (textarea) {
|
|
|
|
return (
|
2017-03-01 21:15:56 +00:00
|
|
|
<textarea ref={this._setRef} {...props} onChange={this._handleChange}/>
|
2016-11-29 20:55:31 +00:00
|
|
|
)
|
|
|
|
} else {
|
|
|
|
return (
|
2017-03-01 21:15:56 +00:00
|
|
|
<input ref={this._setRef} {...props} onChange={this._handleChange}/>
|
2016-11-29 20:55:31 +00:00
|
|
|
)
|
|
|
|
}
|
2016-11-10 21:03:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
DebouncedInput.propTypes = {
|
2016-11-29 20:55:31 +00:00
|
|
|
// Required
|
2016-11-10 21:03:12 +00:00
|
|
|
onChange: PropTypes.func.isRequired,
|
2016-11-29 20:55:31 +00:00
|
|
|
|
|
|
|
// Optional
|
|
|
|
textarea: PropTypes.bool,
|
2017-03-01 21:15:56 +00:00
|
|
|
delay: PropTypes.number,
|
2016-11-10 21:03:12 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export default DebouncedInput;
|