Skip to content

Commit

Permalink
feat(useClipboard): support legacy copy (#2336)
Browse files Browse the repository at this point in the history
Co-authored-by: zhihao.lin@mobvista.com <zhihao.lin@mobvista.com>
  • Loading branch information
lumdzeehol and zhihao.lin@mobvista.com committed Oct 25, 2022
1 parent be36a7d commit 5ec654a
Showing 1 changed file with 39 additions and 7 deletions.
46 changes: 39 additions & 7 deletions packages/core/useClipboard/index.ts
Expand Up @@ -3,7 +3,7 @@
import type { MaybeComputedRef } from '@vueuse/shared'
import { resolveUnref, useTimeoutFn } from '@vueuse/shared'
import type { ComputedRef, Ref } from 'vue-demi'
import { ref } from 'vue-demi'
import { computed, ref } from 'vue-demi'
import type { WindowEventName } from '../useEventListener'
import { useEventListener } from '../useEventListener'
import { useSupported } from '../useSupported'
Expand All @@ -29,6 +29,13 @@ export interface UseClipboardOptions<Source> extends ConfigurableNavigator {
* @default 1500
*/
copiedDuring?: number

/**
* Whether fallback to document.execCommand('copy') if clipboard is undefined.
*
* @default false
*/
legacy?: boolean
}

export interface UseClipboardReturn<Optional> {
Expand All @@ -52,19 +59,25 @@ export function useClipboard(options: UseClipboardOptions<MaybeComputedRef<strin
read = false,
source,
copiedDuring = 1500,
legacy = false,
} = options

const events = ['copy', 'cut']
const isSupported = useSupported(() => navigator && 'clipboard' in navigator)
const isClipboardApiSupported = useSupported(() => (navigator && 'clipboard' in navigator))
const isSupported = computed(() => isClipboardApiSupported.value || legacy)
const text = ref('')
const copied = ref(false)

const timeout = useTimeoutFn(() => copied.value = false, copiedDuring)

function updateText() {
navigator!.clipboard.readText().then((value) => {
text.value = value
})
if (isClipboardApiSupported.value) {
navigator!.clipboard.readText().then((value) => {
text.value = value
})
}
else {
text.value = legacyRead()
}
}

if (isSupported.value && read) {
Expand All @@ -74,13 +87,32 @@ export function useClipboard(options: UseClipboardOptions<MaybeComputedRef<strin

async function copy(value = resolveUnref(source)) {
if (isSupported.value && value != null) {
await navigator!.clipboard.writeText(value)
if (isClipboardApiSupported.value)
await navigator!.clipboard.writeText(value)
else
legacyCopy(value)

text.value = value
copied.value = true
timeout.start()
}
}

function legacyCopy(value: string) {
const ta = document.createElement('textarea')
ta.value = value ?? ''
ta.style.position = 'absolute'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
document.execCommand('copy')
ta.remove()
}

function legacyRead() {
return document?.getSelection?.()?.toString() ?? ''
}

return {
isSupported,
text: text as ComputedRef<string>,
Expand Down

0 comments on commit 5ec654a

Please sign in to comment.