insomnia/app/ui/components/base/Editable.js

86 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-07-08 06:02:40 +00:00
import React, {Component, PropTypes} from 'react';
2016-11-10 21:03:12 +00:00
import * as misc from '../../../common/misc';
2016-07-08 06:02:40 +00:00
class Editable extends Component {
constructor (props) {
super(props);
this.state = {
editing: false
}
}
_handleEditStart () {
this.setState({editing: true});
setTimeout(() => {
this._input && this._input.focus();
this._input && this._input.select();
2016-07-08 06:02:40 +00:00
});
}
2016-11-10 21:03:12 +00:00
async _handleEditEnd () {
const value = this._input.value.trim();
if (!value) {
// Don't do anything if it's empty
return;
}
2016-11-10 21:03:12 +00:00
this.props.onSubmit(value);
// This timeout prevents the UI from showing the old value after submit.
// It should give the UI enough time to redraw the new value.
2016-11-10 21:03:12 +00:00
await misc.delay(100);
this.setState({editing: false});
2016-07-08 06:02:40 +00:00
}
_handleEditKeyDown (e) {
if (e.keyCode === 13) {
// Pressed Enter
this._handleEditEnd();
} else if (e.keyCode === 27) {
// Pressed Escape
2016-11-10 21:03:12 +00:00
// NOTE: This blur causes a save because we save on blur
// TODO: Make escape blur without saving
this._input && this._input.blur();
2016-07-08 06:02:40 +00:00
}
}
render () {
const {value, singleClick, ...extra} = this.props;
2016-07-08 06:02:40 +00:00
const {editing} = this.state;
if (editing) {
return (
<input
className="editable"
2016-07-08 06:02:40 +00:00
type="text"
ref={n => this._input = n}
2016-07-08 06:02:40 +00:00
defaultValue={value}
onKeyDown={e => this._handleEditKeyDown(e)}
onBlur={e => this._handleEditEnd()}
{...extra}
/>
)
} else {
return (
<div className="editable"
onClick={e => singleClick && this._handleEditStart()}
onDoubleClick={e => this._handleEditStart()} {...extra}>
{value}
</div>
2016-07-08 06:02:40 +00:00
)
}
}
}
Editable.propTypes = {
onSubmit: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
// Optional
singleClick: PropTypes.bool
};
2016-07-08 06:02:40 +00:00
export default Editable;