Skip to content

Commit

Permalink
feat: add copy button for code (#106)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
ydcjeff committed May 21, 2021
1 parent 8b2e9bf commit eeb3b9d
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/components/CodeBlock.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<template>
<div class="code-block-wrapper">
<div :class="className">
<button class="copy" @click="copyCode">{{ copyText }}</button>
<pre
:class="className"
><code :class="className" v-html="highlightCode"></code></pre>
Expand All @@ -20,7 +21,7 @@ import 'prismjs/components/prism-json'
import 'prismjs/components/prism-python'
import 'prismjs/components/prism-markdown'
import 'prismjs/themes/prism-tomorrow.css'
import { computed, toRefs } from 'vue'
import { computed, ref, toRefs } from 'vue'
export default {
props: {
Expand All @@ -35,6 +36,7 @@ export default {
},
setup(props) {
const { lang, code } = toRefs(props)
const copyText = ref('Copy')
// computed properties
const className = computed(() => {
Expand All @@ -52,8 +54,17 @@ export default {
const getLineNumbers = computed(() => {
return code.value.split('\n').length
})
const copyCode = async () => {
try {
await navigator.clipboard.writeText(code.value)
} catch (e) {
console.error(e)
}
copyText.value = 'Copied'
setTimeout(() => (copyText.value = 'Copy'), 3000)
}
return { className, highlightCode, getLineNumbers }
return { className, highlightCode, getLineNumbers, copyCode, copyText }
}
}
</script>
Expand All @@ -67,7 +78,17 @@ div[class*='language-'] {
position: relative;
}
div[class*='language-']::before {
.copy {
right: 3em !important;
background: transparent;
padding-top: 0;
padding-bottom: 0;
line-height: inherit;
cursor: pointer;
}
div[class*='language-']::before,
.copy {
position: absolute;
color: var(--c-white-dark);
font-size: 0.75rem;
Expand Down

0 comments on commit eeb3b9d

Please sign in to comment.