Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/CaiJimmy/hugo-theme-stack.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJimmy Cai <github@jimmycai.com>2022-06-12 14:31:32 +0300
committerGitHub <noreply@github.com>2022-06-12 14:31:32 +0300
commitde08e29b003f0422c17441ebaa6aee66f53313af (patch)
treeceb2c48a6959eb7d943db11dc272b74fa4573782 /assets/ts/codeblock.ts
parentabf0c773aa2e6627ddc44f9984b3079837e273c5 (diff)
feat: use Hugo's code block render hook to implement code copy button
Now it can have i18n support
Diffstat (limited to 'assets/ts/codeblock.ts')
-rw-r--r--assets/ts/codeblock.ts28
1 files changed, 28 insertions, 0 deletions
diff --git a/assets/ts/codeblock.ts b/assets/ts/codeblock.ts
new file mode 100644
index 0000000..08c3328
--- /dev/null
+++ b/assets/ts/codeblock.ts
@@ -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);
+ });
+} \ No newline at end of file