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

60 lines
1.4 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';
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';
2019-10-29 17:23:56 +01:00
import React, { useRef } from 'react';
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,
2019-11-22 22:13:00 +01:00
primaryButton?: boolean,
2018-10-04 15:39:14 +02:00
};
2019-10-29 17:23:56 +01:00
export default function CopyableText(props: Props) {
const { copyable, doToast, snackMessage, label, primaryButton = false } = props;
2018-10-04 15:39:14 +02:00
2019-10-29 17:23:56 +01:00
const input = useRef();
2019-02-20 17:18:59 +01:00
2019-10-29 17:23:56 +01:00
function copyToClipboard() {
const topRef = input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
}
document.execCommand('copy');
}
2019-10-29 17:23:56 +01:00
function onFocus() {
2019-02-20 17:18:59 +01:00
// We have to go a layer deep since the input is inside the form component
2019-10-29 17:23:56 +01:00
const topRef = input.current;
2019-02-20 17:18:59 +01:00
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
}
}
2018-10-04 15:39:14 +02:00
2019-10-29 17:23:56 +01:00
return (
<FormField
type="text"
className="form-field--copyable"
readOnly
label={label}
value={copyable || ''}
ref={input}
onFocus={onFocus}
inputButton={
<Button
2019-11-22 22:13:00 +01:00
button={primaryButton ? 'primary' : 'secondary'}
2019-10-29 17:23:56 +01:00
icon={ICONS.COPY}
onClick={() => {
copyToClipboard();
doToast({
message: snackMessage || __('Text copied'),
});
}}
/>
}
/>
);
2018-10-04 15:39:14 +02:00
}