mirror of
https://github.com/adityatelange/hugo-PaperMod.git
synced 2025-07-20 01:42:36 +02:00
add buttons to copy code block contents
Adds a clickable "copy" link in the top-right corner of each code block. If available, uses the navigator.clipboard API. Falls back to selecting the text and calling document.execCommand('copy') to copy text.
This commit is contained in:
@@ -41,5 +41,21 @@
|
||||
}
|
||||
|
||||
code {
|
||||
direction: ltr
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
div.highlight {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.copy-code {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 16px;
|
||||
color: var(--secondary);
|
||||
}
|
||||
|
||||
.copy-code:hover {
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
@@ -96,3 +96,34 @@
|
||||
|
||||
</script>
|
||||
{{- end }}
|
||||
|
||||
{{- if (not .Site.Params.disableCodeCopy) }}
|
||||
<script>
|
||||
document.querySelectorAll('pre > code').forEach((codeblock) => {
|
||||
const container = codeblock.parentNode.parentNode;
|
||||
|
||||
const copybutton = document.createElement('div');
|
||||
copybutton.classList.add('copy-code');
|
||||
copybutton.innerHTML = 'copy';
|
||||
|
||||
copybutton.addEventListener('click', (cb) => {
|
||||
if ('clipboard' in navigator) {
|
||||
navigator.clipboard.writeText(codeblock.textContent);
|
||||
return;
|
||||
}
|
||||
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(codeblock);
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
} catch (e) {};
|
||||
selection.removeRange(range);
|
||||
});
|
||||
|
||||
container.appendChild(copybutton);
|
||||
});
|
||||
</script>
|
||||
{{- end }}
|
||||
|
Reference in New Issue
Block a user