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

77 lines
1.8 KiB
TypeScript
Raw Normal View History

import { autoBindMethodsForReact } from 'class-autobind-decorator';
2021-07-22 23:04:56 +00:00
import { clipboard } from 'electron';
import { Button, ButtonProps } from 'insomnia-components';
2021-07-22 23:04:56 +00:00
import React, { PureComponent, ReactNode } from 'react';
import { AUTOBIND_CFG } from '../../../common/constants';
interface Props extends ButtonProps {
content: string | Function;
children?: ReactNode;
title?: string;
confirmMessage?: string;
}
interface State {
showConfirmation: boolean;
}
@autoBindMethodsForReact(AUTOBIND_CFG)
export class CopyButton extends PureComponent<Props, State> {
state: State = {
showConfirmation: false,
};
2016-11-26 08:29:16 +00:00
_triggerTimeout: NodeJS.Timeout | null = null;
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);
}
this.setState({
showConfirmation: true,
});
this._triggerTimeout = setTimeout(() => {
this.setState({
showConfirmation: false,
});
}, 2000);
}
componentWillUnmount() {
if (this._triggerTimeout === null) {
return;
}
clearTimeout(this._triggerTimeout);
}
2018-06-25 17:42:50 +00:00
render() {
const {
content,
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';
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>
);
}
}