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

78 lines
2.2 KiB
React
Raw Permalink 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,
2021-03-15 15:58:21 +01:00
name?: string,
onCopy?: (string) => string,
enableInputMask?: 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, name, onCopy, enableInputMask } = props;
const [maskInput, setMaskInput] = React.useState(enableInputMask);
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
function handleCopyText() {
if (enableInputMask) {
navigator.clipboard
.writeText(copyable)
.then(() => {
doToast({ message: snackMessage || __('Text copied') });
})
.catch(() => {
doToast({ message: __('Failed to copy.'), isError: true });
});
} else {
const topRef = input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
if (onCopy) {
// Allow clients to change the selection before making the copy.
onCopy(topRef.input.current);
}
}
document.execCommand('copy');
doToast({ message: snackMessage || __('Text copied') });
}
}
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={maskInput ? 'password' : 'text'}
2019-10-29 17:23:56 +01:00
className="form-field--copyable"
readOnly
2021-03-15 15:58:21 +01:00
name={name}
2019-10-29 17:23:56 +01:00
label={label}
value={copyable || ''}
ref={input}
onFocus={onFocus}
inputButton={
<Button button={primaryButton ? 'primary' : 'secondary'} icon={ICONS.COPY} onClick={handleCopyText} />
}
helper={
enableInputMask && (
<Button button="link" onClick={() => setMaskInput(!maskInput)} label={maskInput ? __('Show') : __('Hide')} />
)
2019-10-29 17:23:56 +01:00
}
/>
);
2018-10-04 15:39:14 +02:00
}