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-29 18:23:53 +01:00
|
|
|
|
2018-10-04 15:39:14 +02:00
|
|
|
type Props = {
|
|
|
|
copyable: string,
|
2019-01-22 21:36:28 +01:00
|
|
|
snackMessage: ?string,
|
2018-10-29 18:23:53 +01:00
|
|
|
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,
|
2018-10-04 15:39:14 +02:00
|
|
|
};
|
|
|
|
|
2019-10-29 17:23:56 +01:00
|
|
|
export default function CopyableText(props: Props) {
|
2021-03-15 15:58:21 +01:00
|
|
|
const { copyable, doToast, snackMessage, label, primaryButton = false, name } = 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;
|
2019-08-23 03:32:09 +02:00
|
|
|
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
|
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
|
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
|
|
|
}
|