mirror of
https://github.com/CaiJimmy/hugo-theme-stack.git
synced 2024-11-23 10:21:46 +01:00
feat(article): copy button for highlight block (#295)
This button only shows on highlighted code blocks, because it uses the wrapper div.highlight
This commit is contained in:
parent
4a0cbac234
commit
24915a912f
2 changed files with 58 additions and 0 deletions
|
@ -415,4 +415,30 @@
|
|||
margin-right: calc((var(--card-padding)) * -1);
|
||||
width: calc(100% + var(--card-padding) * 2);
|
||||
}
|
||||
|
||||
.highlight {
|
||||
position: relative;
|
||||
|
||||
&:hover {
|
||||
.copyCodeButton {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.copyCodeButton {
|
||||
position: absolute;
|
||||
top: calc(var(--card-padding));
|
||||
right: 0;
|
||||
background: var(--card-background);
|
||||
border: none;
|
||||
box-shadow: var(--shadow-l2);
|
||||
border-radius: var(--tag-border-radius);
|
||||
padding: 8px 16px;
|
||||
color: var(--card-text-color-main);
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s ease;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -54,6 +54,38 @@ let Stack = {
|
|||
observer.observe(articleTile)
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add copy button to code block
|
||||
*/
|
||||
const codeBlocks = document.querySelectorAll('.article-content .highlight');
|
||||
const copyText = `Copy`,
|
||||
copiedText = `Copied!`;
|
||||
codeBlocks.forEach(codeBlock => {
|
||||
const copyButton = document.createElement('button');
|
||||
copyButton.innerHTML = copyText;
|
||||
copyButton.classList.add('copyCodeButton');
|
||||
codeBlock.appendChild(copyButton);
|
||||
|
||||
const pre = codeBlock.getElementsByTagName('pre');
|
||||
const code = pre[0].textContent;
|
||||
|
||||
copyButton.addEventListener('click', () => {
|
||||
navigator.clipboard.writeText(code)
|
||||
.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'));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue