Skip to content

Commit 3db5164

Browse files
committed
export hooks
1 parent e9cf88f commit 3db5164

File tree

3 files changed

+28
-22
lines changed

3 files changed

+28
-22
lines changed

web/common/src/components/CopyButton/CopyButton.tsx

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import React, { useState } from 'react'
1+
import React from 'react'
22

33
import { Button, type ButtonProps } from '@/components/Button/Button'
4-
5-
type TimerID = ReturnType<typeof setTimeout>
4+
import { useCopyClipboard } from '@/hooks/useCopyClipboard'
65

76
export interface CopyButtonProps extends Omit<ButtonProps, 'children'> {
87
text: string
@@ -25,22 +24,7 @@ export const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
2524
},
2625
ref,
2726
) => {
28-
const [copied, setCopied] = useState<TimerID | null>(null)
29-
30-
const copy = (e: React.MouseEvent<HTMLButtonElement>) => {
31-
e.preventDefault()
32-
e.stopPropagation()
33-
34-
if (copied) {
35-
clearTimeout(copied)
36-
}
37-
38-
navigator.clipboard.writeText(text).then(() => {
39-
setCopied(setTimeout(() => setCopied(null), delay))
40-
})
41-
42-
onClick?.(e)
43-
}
27+
const [copyToClipboard, isCopied] = useCopyClipboard(delay)
4428

4529
return (
4630
<Button
@@ -49,11 +33,14 @@ export const CopyButton = React.forwardRef<HTMLButtonElement, CopyButtonProps>(
4933
title={title}
5034
size={size}
5135
variant={variant}
52-
onClick={copy}
53-
disabled={disabled || !!copied}
36+
onClick={e => {
37+
e.stopPropagation()
38+
copyToClipboard(text)
39+
}}
40+
disabled={disabled || !!isCopied}
5441
{...props}
5542
>
56-
{children(copied != null)}
43+
{children(isCopied != null)}
5744
</Button>
5845
)
5946
},
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { useState } from 'react'
2+
3+
type TimerID = ReturnType<typeof setTimeout>
4+
5+
export function useCopyClipboard(
6+
delay: number = 2000,
7+
): [(text: string) => void, TimerID | null] {
8+
const [isCopied, setIsCopied] = useState<TimerID | null>(null)
9+
10+
const copyToClipboard = (text: string) => {
11+
navigator.clipboard.writeText(text)
12+
setIsCopied(setTimeout(() => setIsCopied(null), delay))
13+
}
14+
15+
return [copyToClipboard, isCopied]
16+
}

web/common/src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ export {
5656
export { Tagline, type TaglineProps } from '@/components/Typography/Tagline'
5757
export { Text, type TextProps } from '@/components/Typography/Text'
5858

59+
// Hooks
60+
export { useCopyClipboard } from '@/hooks/useCopyClipboard'
61+
5962
// Utils
6063
export { cn, truncate } from '@/utils'
6164

0 commit comments

Comments
 (0)