-
Notifications
You must be signed in to change notification settings - Fork 378
Expand file tree
/
Copy pathCopyButton.tsx
More file actions
60 lines (51 loc) · 1.28 KB
/
CopyButton.tsx
File metadata and controls
60 lines (51 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import React, { useState } from 'react'
import { Button, type ButtonProps } from '@/components/Button/Button'
type TimerID = ReturnType<typeof setTimeout>
export interface CopyButtonProps extends Omit<ButtonProps, 'children'> {
text: string
delay?: number
children: (copied: boolean) => React.ReactNode
}
export const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
(
{
text,
title = 'Copy to clipboard',
variant = 'secondary',
size = 'xs',
delay = 2000,
disabled = false,
children,
onClick,
...props
},
ref,
) => {
const [copied, setCopied] = useState<TimerID | null>(null)
const copy = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault()
e.stopPropagation()
if (copied) {
clearTimeout(copied)
}
navigator.clipboard.writeText(text).then(() => {
setCopied(setTimeout(() => setCopied(null), delay))
})
onClick?.(e)
}
return (
<Button
ref={ref}
title={title}
size={size}
variant={variant}
onClick={copy}
disabled={disabled || !!copied}
{...props}
>
{children(copied != null)}
</Button>
)
},
)
CopyButton.displayName = 'CopyButton'