Line data Source code
1 : import { useToast } from '@/components/ui/toast/toastStore'
2 :
3 : import { t } from '@/i18n'
4 :
5 0 : function legacyCopy(text: string): boolean {
6 0 : const textarea = document.createElement('textarea')
7 0 : textarea.setAttribute('readonly', '')
8 0 : textarea.value = text
9 0 : textarea.style.position = 'fixed'
10 0 : textarea.style.left = '-9999px'
11 0 : textarea.style.top = '-9999px'
12 0 : document.body.appendChild(textarea)
13 0 : textarea.select()
14 0 : try {
15 0 : return document.execCommand('copy')
16 : } finally {
17 0 : textarea.remove()
18 : }
19 : }
20 :
21 2896 : export function useCopyToClipboard() {
22 2896 : const toast = useToast()
23 :
24 4 : async function copyToClipboard(
25 : text: string,
26 : { toastOnSuccess = true }: { toastOnSuccess?: boolean } = {}
27 : ): Promise<boolean> {
28 4 : let success = false
29 :
30 4 : try {
31 4 : await navigator.clipboard.writeText(text)
32 4 : success = true
33 : } catch {
34 : // Modern clipboard API failed, fall through to legacy
35 : }
36 :
37 4 : if (!success) {
38 0 : try {
39 0 : success = legacyCopy(text)
40 : } catch {
41 : // Legacy also failed
42 : }
43 : }
44 :
45 4 : if (success && !toastOnSuccess) return true
46 :
47 4 : if (success) {
48 4 : toast.success(t('g.success'), {
49 : description: t('clipboard.successMessage'),
50 : duration: 3000
51 : })
52 : } else {
53 0 : toast.error(t('g.error'), {
54 : description: t('clipboard.errorMessage')
55 : })
56 : }
57 4 : return success
58 : }
59 :
60 2896 : return {
61 : copyToClipboard
62 : }
63 : }
|