forked from vueuse/vueuse
/
index.ts
87 lines (75 loc) · 2.27 KB
/
index.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* this implementation is original ported from https://github.com/logaretm/vue-use-web by Abdelrahman Awad */
import { MaybeRef, useTimeoutFn } from '@vueuse/shared'
import { ComputedRef, ref, unref } from 'vue-demi'
import { useEventListener, WindowEventName } from '../useEventListener'
import { ConfigurableNavigator, defaultNavigator } from '../_configurable'
export interface ClipboardOptions<Source> extends ConfigurableNavigator {
/**
* Enabled reading for clipboard
*
* @default true
*/
read?: boolean
/**
* Copy source
*/
source?: Source
/**
* Milliseconds to reset state of `copied` ref
*
* @default 1500
*/
copiedDuring?: number
}
export interface ClipboardReturn<Optional> {
isSupported: boolean
text: ComputedRef<string>
copied: ComputedRef<boolean>
copy: Optional extends true ? (text?: string) => Promise<void> : (text: string) => Promise<void>
}
/**
* Reactive Clipboard API.
*
* @see https://vueuse.org/useClipboard
* @param options
*/
export function useClipboard(options?: ClipboardOptions<undefined>): ClipboardReturn<false>
export function useClipboard(options: ClipboardOptions<MaybeRef<string>>): ClipboardReturn<true>
export function useClipboard(options: ClipboardOptions<MaybeRef<string> | undefined> = {}): ClipboardReturn<boolean> {
const {
navigator = defaultNavigator,
read = true,
source,
copiedDuring = 1500,
} = options
const events = ['copy', 'cut']
const isSupported = Boolean(navigator && 'clipboard' in navigator)
const text = ref('')
const copied = ref(false)
const timeout = useTimeoutFn(() => copied.value = false, copiedDuring)
function updateText() {
// @ts-expect-error untyped API
navigator.clipboard.readText().then((value) => {
text.value = value
})
}
if (isSupported && read) {
for (const event of events)
useEventListener(event as WindowEventName, updateText)
}
async function copy(value = unref(source)) {
if (isSupported && value != null) {
// @ts-expect-error untyped API
await navigator.clipboard.writeText(value)
text.value = value
copied.value = true
timeout.start()
}
}
return {
isSupported,
text: text as ComputedRef<string>,
copied: copied as ComputedRef<boolean>,
copy,
}
}