Add copy code button to code snippets (#945)

Hello everyone, this is my implementation for the copy button on the snippet (requested in #924)

The implementation is made 100% javascript as with or without a jekyll template modification you still have to execute some javascript code, and I consider it the best choice.

the button only appears if the mouse is over it, to allow the entire line to be read

the important CSS changes were made to make the copy button work even in the long code situation:


![image](https://user-images.githubusercontent.com/26844016/187731472-d4bf7828-2356-4d94-9c2d-9db863228f5f.png)

to avoid this:

![image](https://user-images.githubusercontent.com/26844016/183292313-d7f73d7d-58c0-4c7b-b5ba-e08bd285514b.png)

Co-authored-by: Matt Wang <matt@matthewwang.me>
This commit is contained in:
Simone
2022-12-27 01:45:37 +01:00
committed by GitHub
parent 56bda83528
commit ce3f34bbc7
6 changed files with 154 additions and 25 deletions

View File

@@ -479,6 +479,47 @@ jtd.onReady(function(){
scrollNav();
});
// Copy button on code
{%- if site.enable_copy_code_button != false %}
jtd.onReady(function(){
var codeBlocks = document.querySelectorAll('div.highlighter-rouge, div.listingblock, figure.highlight');
var svgCopied = '<svg viewBox="0 0 24 24" class="copy-icon"><use xlink:href="#svg-copied"></use></svg>';
var svgCopy = '<svg viewBox="0 0 24 24" class="copy-icon"><use xlink:href="#svg-copy"></use></svg>';
codeBlocks.forEach(codeBlock => {
var copyButton = document.createElement('button');
var timeout = null;
copyButton.type = 'button';
copyButton.ariaLabel = 'Copy code to clipboard';
copyButton.innerHTML = svgCopy;
codeBlock.append(copyButton);
copyButton.addEventListener('click', function () {
if(timeout === null) {
var code = codeBlock.querySelector('code').innerText.trim();
window.navigator.clipboard.writeText(code);
copyButton.innerHTML = svgCopied;
var timeoutSetting = 4000;
timeout = setTimeout(function () {
copyButton.innerHTML = svgCopy;
timeout = null;
}, timeoutSetting);
}
});
});
});
{%- endif %}
})(window.jtd = window.jtd || {});
{% include js/custom.js %}