lbry-desktop/src/ui/component/copyableText/view.jsx

69 lines
1.6 KiB
React
Raw Normal View History

2018-10-04 15:39:14 +02:00
// @flow
2018-11-26 02:21:25 +01:00
import * as ICONS from 'constants/icons';
2018-10-04 15:39:14 +02:00
import * as React from 'react';
2019-02-13 17:27:20 +01:00
import { FormField } from 'component/common/form';
2018-10-04 15:39:14 +02:00
import Button from 'component/button';
2018-10-04 15:39:14 +02:00
type Props = {
copyable: string,
2019-01-22 21:36:28 +01:00
snackMessage: ?string,
doToast: ({ message: string }) => void,
2019-02-20 17:18:59 +01:00
label?: string,
2018-10-04 15:39:14 +02:00
};
export default class CopyableText extends React.PureComponent<Props> {
constructor() {
super();
2019-02-20 17:18:59 +01:00
this.input = React.createRef();
(this: any).onFocus = this.onFocus.bind(this);
(this: any).copyToClipboard = this.copyToClipboard.bind(this);
2018-10-04 15:39:14 +02:00
}
2019-02-20 17:18:59 +01:00
input: { current: React.ElementRef<any> };
copyToClipboard() {
const topRef = this.input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
}
document.execCommand('copy');
}
2019-02-20 17:18:59 +01:00
onFocus() {
// We have to go a layer deep since the input is inside the form component
const topRef = this.input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
}
}
2018-10-04 15:39:14 +02:00
render() {
2019-02-20 17:18:59 +01:00
const { copyable, doToast, snackMessage, label } = this.props;
2018-10-04 15:39:14 +02:00
return (
2019-02-13 17:27:20 +01:00
<FormField
type="text"
className="form-field--copyable"
readOnly
2019-02-20 17:18:59 +01:00
label={label}
2019-02-13 17:27:20 +01:00
value={copyable || ''}
2019-02-20 17:18:59 +01:00
ref={this.input}
onFocus={this.onFocus}
2019-02-13 17:27:20 +01:00
inputButton={
<Button
2019-06-17 22:32:38 +02:00
button="inverse"
icon={ICONS.COPY}
2019-02-13 17:27:20 +01:00
onClick={() => {
this.copyToClipboard();
2019-02-13 17:27:20 +01:00
doToast({
message: snackMessage || __('Text copied'),
});
}}
/>
}
/>
2018-10-04 15:39:14 +02:00
);
}
}