feat: use Hugo's code block render hook to implement code copy button

Now it can have i18n support
This commit is contained in:
Jimmy Cai
2022-06-12 11:31:32 +00:00
committed by GitHub
parent abf0c773aa
commit de08e29b00
3 changed files with 50 additions and 33 deletions
+28
View File
@@ -0,0 +1,28 @@
/**
* Copy button for code blocks
*/
export default () => {
const copyButtons = document.querySelectorAll('.codeblock-copy');
copyButtons.forEach(button => {
const codeblockID = button.getAttribute('data-id'),
copyText = button.textContent,
copiedText = button.getAttribute('data-copied-text');
if (!codeblockID) return;
button.addEventListener('click', (e) => {
e.preventDefault();
const codeblock = document.getElementById(codeblockID) as HTMLElement;
if (!codeblockID) return;
navigator.clipboard.writeText(codeblock.textContent)
.then(() => {
button.textContent = copiedText;
setTimeout(() => {
button.textContent = copyText;
}, 1000);
})
.catch(err => {
alert(err)
console.log('Something went wrong', err);
});
}, false);
});
}