MCPcopy Create free account
hub / github.com/APIParkLab/APIPark / useCopyToClipboard

Function useCopyToClipboard

frontend/packages/common/src/hooks/copy.ts:6–63  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

4import { useEffect, useState } from 'react'
5
6const useCopyToClipboard = () => {
7 const [isCopied, setIsCopied] = useState(false)
8
9 const copyToClipboard = (text: string) => {
10 if (navigator.clipboard && window.isSecureContext) {
11 navigator.clipboard
12 .writeText(text)
13 ?.then(() => {
14 message.success($t(RESPONSE_TIPS.copySuccess))
15 setIsCopied(true)
16 })
17 .catch((error) => {
18 console.error('Failed to copy text to clipboard:', error)
19 })
20 } else {
21 // 创建text partition
22 const textArea = document.createElement('textarea')
23 textArea.value = text
24 // 使text area不在viewport,同时设置不可见
25 textArea.style.position = 'absolute'
26 textArea.style.opacity = 0 + ''
27 textArea.style.left = '-999999px'
28 textArea.style.top = '-999999px'
29 document.body.appendChild(textArea)
30 // textArea.focus();
31 textArea.select()
32 new Promise<void>((resolve, reject) => {
33 if (document.execCommand('copy')) {
34 message.success($t(RESPONSE_TIPS.copySuccess))
35 setIsCopied(true)
36 resolve()
37 } else {
38 reject('Failed to copy text to clipboard:')
39 }
40 })
41 .catch((error) => {
42 console.error('Failed to copy text to clipboard:', error)
43 })
44 .finally(() => {
45 textArea.remove()
46 })
47 }
48 }
49
50 useEffect(() => {
51 if (isCopied) {
52 const timeout = setTimeout(() => {
53 setIsCopied(false)
54 }, 3000)
55
56 return () => {
57 clearTimeout(timeout)
58 }
59 }
60 }, [isCopied])
61
62 return { isCopied, copyToClipboard }
63}

Callers 7

ApiNetWorkDataPreviewFunction · 0.85
copy.test.tsFile · 0.85
ServiceInfoCardFunction · 0.85
CopyAddrListFunction · 0.85
ClipboardFunction · 0.85
IntegrateFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected