Skip to content

Commit f3f11b1

Browse files
feat: use custom async clipboard
1 parent db85c7b commit f3f11b1

File tree

2 files changed

+47
-15
lines changed

2 files changed

+47
-15
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import type { ShallowRef } from 'vue'
2+
3+
type UseClipboardAsyncReturn = {
4+
copy: () => void
5+
copied: ShallowRef<boolean>
6+
}
7+
8+
type UseClipboardAsyncOptions = {
9+
copiedDuring: number
10+
}
11+
12+
export default function useClipboardAsync(
13+
fn: () => Promise<string>,
14+
options?: UseClipboardAsyncOptions,
15+
): UseClipboardAsyncReturn {
16+
const copied = shallowRef(false)
17+
const timeout = useTimeoutFn(() => (copied.value = false), options?.copiedDuring ?? 0, {
18+
immediate: false,
19+
})
20+
21+
function copy() {
22+
const asyncClipboard = new ClipboardItem({
23+
'text/plain': fn().then(text => {
24+
return new Blob([text], { type: 'text/plain' })
25+
}),
26+
})
27+
28+
copied.value = true
29+
navigator.clipboard.write([asyncClipboard])
30+
timeout.start()
31+
}
32+
33+
return {
34+
copy,
35+
copied,
36+
}
37+
}

app/pages/package/[[org]]/[name].vue

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -96,27 +96,22 @@ const {
9696
)
9797
9898
//copy README file as Markdown
99-
const { copied: copiedReadme, copy: copyReadme } = useClipboard({
100-
source: () => '',
101-
copiedDuring: 2000,
102-
legacy: true,
103-
})
99+
const { copied: copiedReadme, copy: copyReadme } = useClipboardAsync(
100+
async () => {
101+
await fetchReadmeMarkdown()
102+
return readmeMarkdownData.value?.markdown ?? ''
103+
},
104+
{
105+
copiedDuring: 2000,
106+
},
107+
)
104108
105109
function prefetchReadmeMarkdown() {
106110
if (readmeMarkdownStatus.value === 'idle') {
107111
fetchReadmeMarkdown()
108112
}
109113
}
110114
111-
async function copyReadmeHandler() {
112-
await fetchReadmeMarkdown()
113-
114-
const markdown = readmeMarkdownData.value?.markdown
115-
if (!markdown) return
116-
117-
await copyReadme(markdown)
118-
}
119-
120115
// Track active TOC item based on scroll position
121116
const tocItems = computed(() => readmeData.value?.toc ?? [])
122117
const { activeId: activeTocId } = useActiveTocItem(tocItems)
@@ -1020,7 +1015,7 @@ const showSkeleton = shallowRef(false)
10201015
<ButtonBase
10211016
@mouseenter="prefetchReadmeMarkdown"
10221017
@focus="prefetchReadmeMarkdown"
1023-
@click="copyReadmeHandler()"
1018+
@click="copyReadme"
10241019
:aria-pressed="copiedReadme"
10251020
:aria-label="
10261021
copiedReadme ? $t('common.copied') : $t('package.readme.copy_as_markdown')

0 commit comments

Comments
 (0)