feat: codeblock improvements (#1328)

* fix: do not show codeblock copy button if clipboard api is not available

related: https://github.com/CaiJimmy/hugo-theme-stack/issues/1309

* fix: remove duplicated codeblock script in main.ts

* feat: add i18n support to codeblock copy button

* feat: add translation strings for codeblock copy button
This commit is contained in:
Jimmy
2026-04-26 13:40:46 +02:00
committed by GitHub
parent 9ddd11797b
commit 08a8b5d767
35 changed files with 181 additions and 34 deletions
+2 -32
View File
@@ -11,6 +11,7 @@ import StackColorScheme from './colorScheme';
import { setupScrollspy } from './scrollspy';
import { setupSmoothAnchors } from './smoothAnchors';
import { setupPaginationJump } from './pagination';
import { setupCodeCopy } from './code-copy';
let Stack = {
init: () => {
@@ -23,42 +24,11 @@ let Stack = {
if (articleContent) {
setupSmoothAnchors();
setupScrollspy();
setupCodeCopy();
}
setupPaginationJump();
/**
* Add copy button to code block
*/
const highlights = document.querySelectorAll('.article-content div.highlight');
const copyText = `Copy`,
copiedText = `Copied!`;
highlights.forEach(highlight => {
const copyButton = document.createElement('button');
copyButton.innerHTML = copyText;
copyButton.classList.add('copyCodeButton');
highlight.appendChild(copyButton);
const codeBlock = highlight.querySelector('code[data-lang]');
if (!codeBlock) return;
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(codeBlock.textContent)
.then(() => {
copyButton.textContent = copiedText;
setTimeout(() => {
copyButton.textContent = copyText;
}, 1000);
})
.catch(err => {
alert(err)
console.log('Something went wrong', err);
});
});
});
new StackColorScheme(document.getElementById('dark-mode-toggle')!);
}
}