Skip to content

Commit

Permalink
feat(useClipboard): support customize
Browse files Browse the repository at this point in the history
support to pass a parameter |transform2ClipboardItems| to customize clipboardItems

fix #3450
  • Loading branch information
Doctor-wu committed Oct 16, 2023
1 parent aca6a79 commit 207ed0e
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions packages/core/useClipboard/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@ export interface UseClipboardOptions<Source> extends ConfigurableNavigator {
* @default false
*/
legacy?: boolean

/**
* This function will be used to transform the source to ClipboardItems,
* This way you can customize the ClipboardItem, such as specifying the mime type.
*
* @param source Copy source
* @returns Array of ClipboardItems
* @default
```
(source: string) => {
const type = "text/plain";
const blob = new Blob([toValue(source)], { type });
return [
new ClipboardItem({ [type]: blob }),
]
}
```
*/
transform2ClipboardItems?: (source: string) => ClipboardItem[]
}

export interface UseClipboardReturn<Optional> {
Expand All @@ -59,6 +78,13 @@ export function useClipboard(options: UseClipboardOptions<MaybeRefOrGetter<strin
source,
copiedDuring = 1500,
legacy = false,
transform2ClipboardItems = (source) => {
const type = 'text/plain'
const blob = new Blob([toValue(source)], { type })
return [
new ClipboardItem({ [type]: blob }),
]
},
} = options

const isClipboardApiSupported = useSupported(() => (navigator && 'clipboard' in navigator))
Expand All @@ -83,10 +109,13 @@ export function useClipboard(options: UseClipboardOptions<MaybeRefOrGetter<strin

async function copy(value = toValue(source)) {
if (isSupported.value && value != null) {
if (isClipboardApiSupported.value)
await navigator!.clipboard.writeText(value)
else
if (isClipboardApiSupported.value) {
const clipItems = transform2ClipboardItems(value)
await navigator!.clipboard.write(clipItems)
}
else {
legacyCopy(value)
}

text.value = value
copied.value = true
Expand Down

0 comments on commit 207ed0e

Please sign in to comment.