Skip to content

Commit eeb3b9d

Browse files
committed
feat: add copy button for code (#106)
* feat: add copy button for code * chore: format * refactor: use string template instead of template ref * chore: remove alert code * fix: try and catch error when copying code
1 parent 8b2e9bf commit eeb3b9d

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

src/components/CodeBlock.vue

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<template>
22
<div class="code-block-wrapper">
33
<div :class="className">
4+
<button class="copy" @click="copyCode">{{ copyText }}</button>
45
<pre
56
:class="className"
67
><code :class="className" v-html="highlightCode"></code></pre>
@@ -20,7 +21,7 @@ import 'prismjs/components/prism-json'
2021
import 'prismjs/components/prism-python'
2122
import 'prismjs/components/prism-markdown'
2223
import 'prismjs/themes/prism-tomorrow.css'
23-
import { computed, toRefs } from 'vue'
24+
import { computed, ref, toRefs } from 'vue'
2425
2526
export default {
2627
props: {
@@ -35,6 +36,7 @@ export default {
3536
},
3637
setup(props) {
3738
const { lang, code } = toRefs(props)
39+
const copyText = ref('Copy')
3840
3941
// computed properties
4042
const className = computed(() => {
@@ -52,8 +54,17 @@ export default {
5254
const getLineNumbers = computed(() => {
5355
return code.value.split('\n').length
5456
})
57+
const copyCode = async () => {
58+
try {
59+
await navigator.clipboard.writeText(code.value)
60+
} catch (e) {
61+
console.error(e)
62+
}
63+
copyText.value = 'Copied'
64+
setTimeout(() => (copyText.value = 'Copy'), 3000)
65+
}
5566
56-
return { className, highlightCode, getLineNumbers }
67+
return { className, highlightCode, getLineNumbers, copyCode, copyText }
5768
}
5869
}
5970
</script>
@@ -67,7 +78,17 @@ div[class*='language-'] {
6778
position: relative;
6879
}
6980
70-
div[class*='language-']::before {
81+
.copy {
82+
right: 3em !important;
83+
background: transparent;
84+
padding-top: 0;
85+
padding-bottom: 0;
86+
line-height: inherit;
87+
cursor: pointer;
88+
}
89+
90+
div[class*='language-']::before,
91+
.copy {
7192
position: absolute;
7293
color: var(--c-white-dark);
7394
font-size: 0.75rem;

0 commit comments

Comments
 (0)