Lidarr/frontend/src/Components/Link/ClipboardButton.js

140 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-09-07 01:33:10 +00:00
import Clipboard from 'clipboard';
2017-09-04 02:20:56 +00:00
import PropTypes from 'prop-types';
import React, { Component } from 'react';
2020-09-07 01:33:10 +00:00
import FormInputButton from 'Components/Form/FormInputButton';
import Icon from 'Components/Icon';
2017-09-04 02:20:56 +00:00
import { icons, kinds } from 'Helpers/Props';
import getUniqueElememtId from 'Utilities/getUniqueElementId';
import styles from './ClipboardButton.css';
class ClipboardButton extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._id = getUniqueElememtId();
this._successTimeout = null;
this._testResultTimeout = null;
2017-09-04 02:20:56 +00:00
this.state = {
showSuccess: false,
showError: false
};
}
componentDidMount() {
this._clipboard = new Clipboard(`#${this._id}`, {
text: () => this.props.value,
container: document.getElementById(this._id)
2017-09-04 02:20:56 +00:00
});
this._clipboard.on('success', this.onSuccess);
}
componentDidUpdate() {
const {
showSuccess,
showError
} = this.state;
if (showSuccess || showError) {
this._testResultTimeout = setTimeout(this.resetState, 3000);
}
}
componentWillUnmount() {
if (this._clipboard) {
this._clipboard.destroy();
}
if (this._testResultTimeout) {
clearTimeout(this._testResultTimeout);
}
2017-09-04 02:20:56 +00:00
}
//
// Control
resetState = () => {
this.setState({
showSuccess: false,
showError: false
});
2021-12-24 18:18:14 +00:00
};
2017-09-04 02:20:56 +00:00
//
// Listeners
onSuccess = () => {
this.setState({
showSuccess: true
});
2021-12-24 18:18:14 +00:00
};
2017-09-04 02:20:56 +00:00
onError = () => {
this.setState({
showError: true
});
2021-12-24 18:18:14 +00:00
};
2017-09-04 02:20:56 +00:00
//
// Render
render() {
const {
value,
className,
2017-09-04 02:20:56 +00:00
...otherProps
} = this.props;
const {
showSuccess,
showError
} = this.state;
const showStateIcon = showSuccess || showError;
const iconName = showError ? icons.DANGER : icons.CHECK;
const iconKind = showError ? kinds.DANGER : kinds.SUCCESS;
return (
<FormInputButton
id={this._id}
className={className}
2017-09-04 02:20:56 +00:00
{...otherProps}
>
<span className={showStateIcon ? styles.showStateIcon : undefined}>
2017-09-04 02:20:56 +00:00
{
showSuccess &&
<span className={styles.stateIconContainer}>
<Icon
name={iconName}
kind={iconKind}
/>
</span>
}
{
<span className={styles.clipboardIconContainer}>
<Icon name={icons.CLIPBOARD} />
</span>
}
</span>
</FormInputButton>
);
}
}
ClipboardButton.propTypes = {
className: PropTypes.string.isRequired,
2017-09-04 02:20:56 +00:00
value: PropTypes.string.isRequired
};
ClipboardButton.defaultProps = {
className: styles.button
};
2017-09-04 02:20:56 +00:00
export default ClipboardButton;