Add code copy button to all code fields in the blog (#81)

This commit is contained in:
Alexander Dunkel 2019-08-18 16:27:31 +02:00 committed by Track3
parent a9f2ddcfa9
commit 16c9d78ae5
10 changed files with 110 additions and 6 deletions

56
assets/js/code-copy.js Normal file
View file

@ -0,0 +1,56 @@
/**
* Utils
*/
// Add code-copy buttons using progressive enhancement
// © 2019. Tom Spencer
// https://www.fiznool.com/blog/2018/09/14/adding-click-to-copy-buttons-to-a-hugo-powered-blog/
(function() {
'use strict';
if(!document.queryCommandSupported('copy')) {
return;
}
function flashCopyMessage(el, msg) {
el.textContent = msg;
setTimeout(function() {
el.textContent = "Copy";
}, 1000);
}
function selectText(node) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
return selection;
}
function addCopyButton(containerEl) {
var copyBtn = document.createElement("button");
copyBtn.className = "highlight-copy-btn";
copyBtn.textContent = "Copy";
var codeEl = containerEl.firstElementChild;
copyBtn.addEventListener('click', function() {
try {
var selection = selectText(codeEl);
document.execCommand('copy');
selection.removeAllRanges();
flashCopyMessage(copyBtn, 'Copied!')
} catch(e) {
console && console.log(e);
flashCopyMessage(copyBtn, 'Failed :\'(')
}
});
containerEl.appendChild(copyBtn);
}
// Add copy button to code blocks
var highlightBlocks = document.getElementsByClassName('highlight');
Array.prototype.forEach.call(highlightBlocks, addCopyButton);
})();

View file

@ -153,6 +153,37 @@ table {
display: none;
}
// Code copy buttons
//
.highlight {
position: relative;
}
.highlight pre {
padding-right: 75px;
}
.highlight-copy-btn {
position: absolute;
bottom: 7px;
right: 7px;
border: 0;
border-radius: 4px;
padding: 1px;
font-size: 0.7em;
line-height: 1.8;
color: #fff;
background-color: #777;
opacity: 0.6;
min-width: 55px;
text-align: center;
}
.highlight-copy-btn:hover {
background-color: #666;
}
// Accessibility
//
.screen-reader-text {