1 "use client"
2
3 import { Tooltip } from "@/components/tooltip"
4 import { clx } from "@/utils/clx"
5 import {
6 CheckCircleMiniSolid,
7 CheckCircleSolid,
8 SquareTwoStack,
9 SquareTwoStackMini,
10 } from "@medusajs/icons"
11 import copy from "copy-to-clipboard"
12 import { Slot } from "radix-ui"
13 import React, { useState } from "react"
14
15 type CopyProps = React.HTMLAttributes<HTMLButtonElement> & {
16 content: string
17 variant?: "mini" | "default" | null
18 asChild?: boolean
19 }
20
21 /**
22 * This component is based on the `button` element and supports all of its props
23 */
24 const Copy = React.forwardRef<HTMLButtonElement, CopyProps>(
25 (
26 {
27 children,
28 className,
29 /**
30 * The content to copy.
31 */
32 content,
33 /**
34 * The variant of the copy button.
35 */
36 variant = "default",
37 /**
38 * Whether to remove the wrapper `button` element and use the
39 * passed child element instead.
40 */
41 asChild = false,
42 ...props
43 }: CopyProps,
44 ref
45 ) => {
46 const [done, setDone] = useState(false)
47 const [open, setOpen] = useState(false)
48 const [text, setText] = useState("Copy")
49
50 const copyToClipboard = (
51 e:
52 | React.MouseEvent<HTMLElement, MouseEvent>
53 | React.MouseEvent<HTMLButtonElement, MouseEvent>
54 ) => {
55 e.stopPropagation()
56
57 setDone(true)
58 copy(content)
59
60 setTimeout(() => {
61 setDone(false)
62 }, 2000)
63 }
64
65 React.useEffect(() => {
66 if (done) {
67 setText("Copied")
68 return
69 }
70
71 setTimeout(() => {
72 setText("Copy")
73 }, 500)
74 }, [done])
75
76 const isDefaultVariant = (
77 variant?: string | null
78 ): variant is "default" => {
79 return variant === "default"
80 }
81
82 const isDefault = isDefaultVariant(variant)
83
84 const Component = asChild ? Slot.Root : "button"
85
86 return (
87 <Tooltip content={text} open={done || open} onOpenChange={setOpen}>
88 <Component
89 ref={ref}
90 aria-label="Copy code snippet"
91 type="button"
92 className={clx(
93 "h-fit w-fit",
94 className
95 )}
96 onClick={copyToClipboard}
97 {...props}
98 >
99 {children ? (
100 children
101 ) : done ? (
102 isDefault ? (
103 <CheckCircleSolid className="text-ui-fg-subtle" />
104 ) : (
105 <CheckCircleMiniSolid className="text-ui-fg-subtle" />
106 )
107 ) : isDefault ? (
108 <SquareTwoStack className="text-ui-fg-subtle" />
109 ) : (
110 <SquareTwoStackMini className="text-ui-fg-subtle" />
111 )}
112 </Component>
113 </Tooltip>
114 )
115 }
116 )
117 Copy.displayName = "Copy"
118
119 export { Copy }