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

97 lines
2.3 KiB
JavaScript
Raw Normal View History

2016-09-09 18:28:57 +00:00
import React, {Component, PropTypes} from 'react';
const STATE_DEFAULT = 'default';
const STATE_ASK = 'ask';
const STATE_DONE = 'done';
2016-09-09 18:28:57 +00:00
class PromptButton extends Component {
constructor (props) {
super(props);
this.state = {state: STATE_DEFAULT}
2016-09-09 18:28:57 +00:00
}
_confirm (e) {
// Clear existing timeouts
clearTimeout(this._askTimeout);
2016-09-09 18:28:57 +00:00
// Fire the click handler
this.props.onClick(e);
// Set the state to done (but delay a bit to not alarm user)
this._doneTimeout = setTimeout(() => {
this.setState({state: STATE_DONE});
}, 100);
// Set a timeout to hide the confirmation
this._askTimeout = setTimeout(() => {
this.setState({state: STATE_DEFAULT});
}, 2000);
2016-09-09 18:28:57 +00:00
}
_ask (e) {
2016-09-09 18:28:57 +00:00
// Prevent events (ex. won't close dropdown if it's in one)
e.preventDefault();
e.stopPropagation();
// Toggle the confirmation notice
this.setState({state: STATE_ASK});
2016-09-09 18:28:57 +00:00
// Set a timeout to hide the confirmation
this._askTimeout = setTimeout(() => {
this.setState({state: STATE_DEFAULT});
2016-09-09 18:28:57 +00:00
}, 2000);
}
_handleClick (e) {
const {state} = this.state;
if (state === STATE_ASK) {
2016-09-09 18:28:57 +00:00
this._confirm(e)
} else if (state === STATE_DEFAULT) {
this._ask(e)
2016-09-09 18:28:57 +00:00
} else {
// Do nothing
2016-09-09 18:28:57 +00:00
}
}
componentWillUnmount () {
clearTimeout(this._askTimeout);
clearTimeout(this._doneTimeout);
2016-09-09 18:28:57 +00:00
}
render () {
const {children, onClick, addIcon, confirmMessage, doneMessage, ...other} = this.props;
const {state} = this.state;
2016-09-09 18:28:57 +00:00
2016-09-21 20:32:45 +00:00
const CONFIRM_MESSAGE = confirmMessage || 'Click to confirm';
const DONE_MESSAGE = doneMessage || 'Done';
2016-09-09 18:28:57 +00:00
let innerMsg;
if (state === STATE_ASK && addIcon) {
2016-09-09 18:28:57 +00:00
innerMsg = (
<span className="danger">
<i className="fa fa-exclamation-circle"></i> {CONFIRM_MESSAGE}
</span>
)
} else if (state === STATE_ASK) {
2016-09-09 18:28:57 +00:00
innerMsg = <span className="danger">{CONFIRM_MESSAGE}</span>
} else if (state === STATE_DONE) {
innerMsg = DONE_MESSAGE
2016-09-09 18:28:57 +00:00
} else {
innerMsg = children
}
return (
<button onClick={this._handleClick.bind(this)} {...other}>
{innerMsg}
</button>
)
}
}
PromptButton.propTypes = {
2016-09-21 20:32:45 +00:00
addIcon: PropTypes.bool,
confirmMessage: PropTypes.string
2016-09-09 18:28:57 +00:00
};
export default PromptButton;