insomnia/packages/insomnia-app/app/ui/components/base/copy-button.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2018-06-25 17:42:50 +00:00
import React, { PureComponent } from 'react';
2017-08-10 01:56:27 +00:00
import PropTypes from 'prop-types';
import autobind from 'autobind-decorator';
2018-06-25 17:42:50 +00:00
const { clipboard } = require('electron');
@autobind
class CopyButton extends PureComponent {
2018-06-25 17:42:50 +00:00
constructor(props) {
super(props);
this.state = {
showConfirmation: false,
};
}
2016-11-26 08:29:16 +00:00
2018-06-25 17:42:50 +00:00
async _handleClick(e) {
e.preventDefault();
e.stopPropagation();
2018-06-25 17:42:50 +00:00
const content =
2018-10-17 16:42:33 +00:00
typeof this.props.content === 'string' ? this.props.content : await this.props.content();
if (content) {
clipboard.writeText(content);
}
2018-06-25 17:42:50 +00:00
this.setState({ showConfirmation: true });
this._triggerTimeout = setTimeout(() => {
2018-06-25 17:42:50 +00:00
this.setState({ showConfirmation: false });
}, 2000);
}
2018-06-25 17:42:50 +00:00
componentWillUnmount() {
clearTimeout(this._triggerTimeout);
}
2018-06-25 17:42:50 +00:00
render() {
const {
content, // eslint-disable-line no-unused-vars
children,
title,
2017-06-01 23:53:10 +00:00
confirmMessage,
...other
} = this.props;
2018-06-25 17:42:50 +00:00
const { showConfirmation } = this.state;
2018-10-17 16:42:33 +00:00
const confirm = typeof confirmMessage === 'string' ? confirmMessage : 'Copied';
2017-06-01 23:53:10 +00:00
return (
<button {...other} title={title} onClick={this._handleClick}>
2018-06-25 17:42:50 +00:00
{showConfirmation ? (
<span>
{confirm} <i className="fa fa-check-circle-o" />
</span>
) : (
children || 'Copy to Clipboard'
)}
</button>
);
}
}
CopyButton.propTypes = {
// Required
2018-10-17 16:42:33 +00:00
content: PropTypes.oneOfType([PropTypes.string.isRequired, PropTypes.func.isRequired]).isRequired,
// Optional
children: PropTypes.node,
2017-06-01 23:53:10 +00:00
title: PropTypes.string,
confirmMessage: PropTypes.string,
};
export default CopyButton;