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

94 lines
2.2 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 {
2016-11-26 08:29:16 +00:00
state = {state: STATE_DEFAULT};
2016-09-09 18:28:57 +00:00
_confirm (e) {
// Clear existing timeouts
clearTimeout(this._triggerTimeout);
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._triggerTimeout = 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._triggerTimeout = 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
}
};
2016-09-09 18:28:57 +00:00
componentWillUnmount () {
clearTimeout(this._triggerTimeout);
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"/> {CONFIRM_MESSAGE}
2016-09-09 18:28:57 +00:00
</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} {...other}>
2016-09-09 18:28:57 +00:00
{innerMsg}
</button>
)
}
}
PromptButton.propTypes = {
2016-09-21 20:32:45 +00:00
addIcon: PropTypes.bool,
confirmMessage: PropTypes.any,
2016-09-09 18:28:57 +00:00
};
export default PromptButton;