Skip to content

⬅️ Back to Table of Contents

📄 useClipboard

📊 Analysis Summary

Metric Count
🔧 Functions 7
📦 Imports 13
⚡ Async/Await Patterns 3
🟢 Vue Composition API 1
📐 Interfaces 2
📑 Type Aliases 1

📚 Table of Contents

🛠️ File Location:

📂 packages/core/useClipboard/index.ts

📦 Imports

Name Source
MaybeRefOrGetter vue
ShallowRef vue
ConfigurableNavigator ../_configurable
Supportable ../types
useTimeoutFn @vueuse/shared
computed vue
shallowReadonly vue
shallowRef vue
toValue vue
defaultNavigator ../_configurable
useEventListener ../useEventListener
usePermission ../usePermission
useSupported ../useSupported

Async/Await Patterns

Type Function Await Expressions Promise Chains
async-function updateText navigator!.clipboard.readText() none
async-function copy navigator!.clipboard.write([clipboardItem]), resolvedValue() none
promise-chain createClipboardItem none value().then

Vue Composition API

Name Type Reactive Variables Composables
computed computed none none

Functions

useClipboard(options: UseClipboardOptions<undefined>): UseClipboardReturn<false>

Reactive Clipboard API.

Parameters:

  • options any: No description

See: https://vueuse.org/useClipboard

Tags: @__NO_SIDE_EFFECTS__

Raw JSDoc
/**
 * Reactive Clipboard API.
 *
 * @see https://vueuse.org/useClipboard
 * @param options
 *
 * @__NO_SIDE_EFFECTS__
 */
Code
export function useClipboard(options?: UseClipboardOptions<undefined>): UseClipboardReturn<false>

Internal helpers

Declared inside another function in this file.

updateText(): Promise<void>

Returns: Promise<void>

Calls:

  • isAllowed
  • navigator!.clipboard.readText
  • legacyRead
Code
async function updateText() {
    let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionRead.value))
    if (!useLegacy) {
      try {
        text.value = await navigator!.clipboard.readText()
      }
      catch {
        useLegacy = true
      }
    }
    if (useLegacy) {
      text.value = legacyRead()
    }
  }

copy(value: ClipboardValue): Promise<void>

Parameters:

  • value ClipboardValue

Returns: Promise<void>

Calls:

  • toValue (from vue)
  • isAllowed
  • createClipboardItem
  • navigator!.clipboard.write
  • legacyCopy
  • resolvedValue
  • timeout.start

Internal Comments:

// For async functions in legacy mode, resolve and copy (x2)

Code
async function copy(value?: ClipboardValue) {
    const resolvedValue = value ?? toValue(source)
    if (isSupported.value && resolvedValue != null) {
      copyPending.value = true
      let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionWrite.value))

      if (!useLegacy) {
        try {
          const clipboardItem = createClipboardItem(resolvedValue)
          await navigator!.clipboard.write([clipboardItem])
        }
        catch {
          useLegacy = true
        }
      }

      if (useLegacy) {
        if (typeof resolvedValue === 'string') {
          text.value = resolvedValue
          legacyCopy(resolvedValue)
        }
        else {
          // For async functions in legacy mode, resolve and copy
          const currentId = ++lastLegacyId
          const resolvedText = await resolvedValue()
          if (resolvedText != null && currentId === lastLegacyId) {
            text.value = resolvedText
            legacyCopy(resolvedText)
          }
        }
      }

      copied.value = true
      timeout.start()
      copyPending.value = false
    }
  }

createClipboardItem(value: ClipboardValue): ClipboardItem

Parameters:

  • value ClipboardValue

Returns: ClipboardItem

Calls:

  • value().then
Code
function createClipboardItem(value: ClipboardValue): ClipboardItem {
    if (typeof value === 'string') {
      text.value = value
      return new ClipboardItem({ 'text/plain': value })
    }
    else {
      return new ClipboardItem({
        'text/plain': value().then((resolvedText = '') => {
          text.value = resolvedText
          return new Blob([resolvedText], { type: 'text/plain' })
        }),
      })
    }
  }

legacyCopy(value: string): void

Parameters:

  • value string

Returns: void

Calls:

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

legacyRead(): string

Returns: string

Calls:

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

isAllowed(status: PermissionState | undefined): boolean

Parameters:

  • status PermissionState | undefined

Returns: boolean

Code
function isAllowed(status: PermissionState | undefined) {
    return status === 'granted' || status === 'prompt'
  }

Interfaces

UseClipboardOptions<Source>

Interface Code
export interface UseClipboardOptions<Source> extends ConfigurableNavigator {
  /**
   * Enabled reading for clipboard
   *
   * @default false
   */
  read?: boolean

  /**
   * Copy source
   */
  source?: Source

  /**
   * Milliseconds to reset state of `copied` ref
   *
   * @default 1500
   */
  copiedDuring?: number

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

Properties

Name Type Optional Description
read boolean not shown
source Source not shown
copiedDuring number not shown
legacy boolean not shown

UseClipboardReturn<Optional>

Interface Code
export interface UseClipboardReturn<Optional> extends Supportable {
  text: Readonly<ShallowRef<string>>
  copied: Readonly<ShallowRef<boolean>>
  copyPending: Readonly<ShallowRef<boolean>>
  copy: Optional extends true
    ? (text?: ClipboardValue) => Promise<void>
    : (text: ClipboardValue) => Promise<void>
}

Properties

Name Type Optional Description
text Readonly<ShallowRef<string>> not shown
copied Readonly<ShallowRef<boolean>> not shown
copyPending Readonly<ShallowRef<boolean>> not shown
copy Optional extends true ? (text?: ClipboardValue) => Promise<void> : (text: Cli... not shown

Type Aliases

ClipboardValue

type ClipboardValue = string | (() => Promise<string | undefined>);

Generated by Syntax Scribe