2022-06-27 23:18:58 +00:00
|
|
|
import React, { useEffect, useState } from 'react';
|
2020-10-31 20:16:41 +00:00
|
|
|
import Fade from '@/components/elements/Fade';
|
2022-06-27 23:18:58 +00:00
|
|
|
import Portal from '@/components/elements/Portal';
|
|
|
|
import copy from 'copy-to-clipboard';
|
|
|
|
import classNames from 'classnames';
|
2020-10-31 20:16:41 +00:00
|
|
|
|
2022-06-27 23:56:26 +00:00
|
|
|
const CopyOnClick: React.FC<{ text: string | number | null | undefined }> = ({ text, children }) => {
|
2022-06-26 19:13:52 +00:00
|
|
|
const [copied, setCopied] = useState(false);
|
2020-10-31 20:16:41 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!copied) return;
|
|
|
|
|
|
|
|
const timeout = setTimeout(() => {
|
|
|
|
setCopied(false);
|
|
|
|
}, 2500);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
clearTimeout(timeout);
|
|
|
|
};
|
2022-06-26 19:13:52 +00:00
|
|
|
}, [copied]);
|
2020-10-31 20:16:41 +00:00
|
|
|
|
2022-06-27 23:18:58 +00:00
|
|
|
if (!React.isValidElement(children)) {
|
|
|
|
throw new Error('Component passed to <CopyOnClick/> must be a valid React element.');
|
|
|
|
}
|
|
|
|
|
2022-06-27 23:56:26 +00:00
|
|
|
const child = !text
|
2022-06-27 23:18:58 +00:00
|
|
|
? React.Children.only(children)
|
|
|
|
: React.cloneElement(React.Children.only(children), {
|
|
|
|
className: classNames(children.props.className || '', 'cursor-pointer'),
|
|
|
|
onClick: (e: React.MouseEvent<HTMLElement>) => {
|
2022-06-27 23:56:26 +00:00
|
|
|
copy(String(text));
|
2022-06-27 23:18:58 +00:00
|
|
|
setCopied(true);
|
|
|
|
if (typeof children.props.onClick === 'function') {
|
|
|
|
children.props.onClick(e);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
});
|
2020-10-31 20:16:41 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
2022-06-27 23:18:58 +00:00
|
|
|
{copied && (
|
|
|
|
<Portal>
|
|
|
|
<Fade in appear timeout={250} key={copied ? 'visible' : 'invisible'}>
|
|
|
|
<div className={'fixed z-50 bottom-0 right-0 m-4'}>
|
|
|
|
<div className={'rounded-md py-3 px-4 text-gray-200 bg-neutral-600/95 shadow'}>
|
2020-10-31 20:16:41 +00:00
|
|
|
<p>Copied "{text}" to clipboard.</p>
|
|
|
|
</div>
|
2022-06-27 23:18:58 +00:00
|
|
|
</div>
|
|
|
|
</Fade>
|
|
|
|
</Portal>
|
|
|
|
)}
|
|
|
|
{child}
|
2020-10-31 20:16:41 +00:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default CopyOnClick;
|