Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/resources/scripts/components/elements/CopyOnClick.tsx
7461 views
1
import React, { useEffect, useState } from 'react';
2
import Fade from '@/components/elements/Fade';
3
import Portal from '@/components/elements/Portal';
4
import copy from 'copy-to-clipboard';
5
import classNames from 'classnames';
6
7
interface CopyOnClickProps {
8
text: string | number | null | undefined;
9
showInNotification?: boolean;
10
children: React.ReactNode;
11
}
12
13
const CopyOnClick = ({ text, showInNotification = true, children }: CopyOnClickProps) => {
14
const [copied, setCopied] = useState(false);
15
16
useEffect(() => {
17
if (!copied) return;
18
19
const timeout = setTimeout(() => {
20
setCopied(false);
21
}, 2500);
22
23
return () => {
24
clearTimeout(timeout);
25
};
26
}, [copied]);
27
28
if (!React.isValidElement(children)) {
29
throw new Error('Component passed to <CopyOnClick/> must be a valid React element.');
30
}
31
32
const child = !text
33
? React.Children.only(children)
34
: React.cloneElement(React.Children.only(children), {
35
className: classNames(children.props.className || '', 'cursor-pointer'),
36
onClick: (e: React.MouseEvent<HTMLElement>) => {
37
copy(String(text));
38
setCopied(true);
39
if (typeof children.props.onClick === 'function') {
40
children.props.onClick(e);
41
}
42
},
43
});
44
45
return (
46
<>
47
{copied && (
48
<Portal>
49
<Fade in appear timeout={250} key={copied ? 'visible' : 'invisible'}>
50
<div className={'fixed z-50 bottom-0 right-0 m-4'}>
51
<div className={'rounded-md py-3 px-4 text-gray-200 bg-neutral-600/95 shadow'}>
52
<p>
53
{showInNotification
54
? `Copied "${String(text)}" to clipboard.`
55
: 'Copied text to clipboard.'}
56
</p>
57
</div>
58
</div>
59
</Fade>
60
</Portal>
61
)}
62
{child}
63
</>
64
);
65
};
66
67
export default CopyOnClick;
68
69