docs/.vitepress/theme/components/extrepo/useCopy.ts

22 lines · 583 bytes

2 symbols in this file
 1import { onUnmounted, ref } from 'vue'
 2import { COPY_RESET_MS } from './constants'
 3
 4export function useCopy() {
 5  const copiedKey = ref<string | null>(null)
 6  let timer: ReturnType<typeof setTimeout> | undefined
 7
 8  async function copy(key: string, value: string) {
 9    await navigator.clipboard.writeText(value)
10    copiedKey.value = key
11    if (timer) clearTimeout(timer)
12    timer = setTimeout(() => {
13      if (copiedKey.value === key) copiedKey.value = null
14    }, COPY_RESET_MS)
15  }
16
17  onUnmounted(() => {
18    if (timer) clearTimeout(timer)
19  })
20
21  return { copiedKey, copy }
22}