1 "use client"
2
3 import React, { useState } from "react"
4 import clsx from "clsx"
5 import { Tooltip } from "@/components/Tooltip"
6 import { useCopy } from "../../hooks/use-copy"
7
8 export type CopyButtonChildFn = (props: {
9 isCopied: boolean
10 }) => React.ReactNode
11
12 export type CopyButtonProps = {
13 text: string
14 buttonClassName?: string
15 tooltipClassName?: string
16 tooltipInnerClassName?: string
17 tooltipText?: string
18 onCopy?: (
19 e:
20 | React.MouseEvent<HTMLSpanElement, MouseEvent>
21 | React.TouchEvent<HTMLSpanElement>
22 ) => void
23 handleTouch?: boolean
24 children?: React.ReactNode | CopyButtonChildFn
25 } & Omit<React.HTMLAttributes<HTMLDivElement>, "onCopy" | "children">
26
27 export const CopyButton = ({
28 text,
29 buttonClassName = "",
30 tooltipClassName = "",
31 tooltipText = "Copy to Clipboard",
32 children,
33 className,
34 onCopy,
35 handleTouch,
36 tooltipInnerClassName,
37 }: CopyButtonProps) => {
38 const { isCopied, handleCopy } = useCopy(text)
39 const [touchCount, setTouchCount] = useState(0)
40
41 return (
42 <Tooltip
43 text={isCopied ? `Copied!` : tooltipText}
44 tooltipClassName={clsx(tooltipClassName, handleTouch && "!block")}
45 className={className}
46 innerClassName={tooltipInnerClassName}
47 >
48 <span
49 className={clsx("cursor-pointer", buttonClassName)}
50 onClick={(e) => {
51 if (touchCount > 0) {
52 // prevent the on-click event from triggering if a touch event occurred.
53 return
54 }
55 onCopy?.(e)
56 handleCopy()
57 }}
58 onTouchEnd={(e) => {
59 if (!handleTouch) {
60 return
61 }
62
63 if (touchCount === 0) {
64 setTouchCount(touchCount + 1)
65 } else {
66 onCopy?.(e)
67 handleCopy()
68 setTouchCount(0)
69 }
70 }}
71 data-testid="copy-button"
72 >
73 {typeof children === "function" ? children({ isCopied }) : children}
74 </span>
75 </Tooltip>
76 )
77 }