2022-06-27 23:18:58 +00:00
|
|
|
import classNames from 'classnames';
|
2022-11-25 20:25:03 +00:00
|
|
|
import copy from 'copy-to-clipboard';
|
|
|
|
import type { MouseEvent, ReactNode } from 'react';
|
|
|
|
import { Children, cloneElement, isValidElement, useEffect, useState } from 'react';
|
|
|
|
|
|
|
|
import Portal from '@/components/elements/Portal';
|
|
|
|
import FadeTransition from '@/components/elements/transitions/FadeTransition';
|
2020-10-31 20:16:41 +00:00
|
|
|
|
2022-07-02 22:53:03 +00:00
|
|
|
interface CopyOnClickProps {
|
|
|
|
text: string | number | null | undefined;
|
|
|
|
showInNotification?: boolean;
|
2022-11-25 20:25:03 +00:00
|
|
|
children: ReactNode;
|
2022-07-02 22:53:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const CopyOnClick = ({ text, showInNotification = true, children }: CopyOnClickProps) => {
|
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-11-25 20:25:03 +00:00
|
|
|
if (!isValidElement(children)) {
|
2022-06-27 23:18:58 +00:00
|
|
|
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-11-25 20:25:03 +00:00
|
|
|
? Children.only(children)
|
|
|
|
: cloneElement(Children.only(children), {
|
|
|
|
// @ts-expect-error I don't know
|
2022-06-27 23:18:58 +00:00
|
|
|
className: classNames(children.props.className || '', 'cursor-pointer'),
|
2022-11-25 20:25:03 +00:00
|
|
|
onClick: (e: 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>
|
2022-11-25 20:25:03 +00:00
|
|
|
<FadeTransition show duration="duration-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">
|
2022-07-02 22:53:03 +00:00
|
|
|
<p>
|
|
|
|
{showInNotification
|
|
|
|
? `Copied "${String(text)}" to clipboard.`
|
|
|
|
: 'Copied text to clipboard.'}
|
|
|
|
</p>
|
2020-10-31 20:16:41 +00:00
|
|
|
</div>
|
2022-06-27 23:18:58 +00:00
|
|
|
</div>
|
2022-11-25 20:25:03 +00:00
|
|
|
</FadeTransition>
|
2022-06-27 23:18:58 +00:00
|
|
|
</Portal>
|
|
|
|
)}
|
|
|
|
{child}
|
2020-10-31 20:16:41 +00:00
|
|
|
</>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default CopyOnClick;
|