Skip to content

Commit

Permalink
Add copy to clipboard buttons to code blocks
Browse files Browse the repository at this point in the history
Only load the JS on posts that actually have code blocks.
  • Loading branch information
dguo committed Dec 21, 2018
1 parent 0176694 commit 6953658
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
7 changes: 7 additions & 0 deletions layouts/blog/single.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,10 @@ <h1>{{ .Title }}</h1>

<div class="separator">
{{ end }}

{{ define "js-extra" }}
{{ if (findRE "class=\"highlight\"" .Content 1) }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/2.7.0/clipboard-polyfill.promise.js" integrity="sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94=" crossorigin="anonymous"></script>
<script src="/js/copy-code-button.js"></script>
{{ end }}
{{ end }}
35 changes: 35 additions & 0 deletions static/css/post.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,38 @@ h1 {
text-align: right;
width: 48%;
}

.copy-code-button {
color: #272822;
background-color: #FFF;
border-color: #272822;
border: 2px solid;
border-radius: 3px;

/* right-align */
display: block;
margin-left: auto;
margin-right: 0;

/* for some reason, there is space between the button and the code block */
margin-bottom: -10px;

padding: 3px 8px;
font-size: 0.8em;
}

.copy-code-button:hover {
cursor: pointer;
background-color: #F2F2F2;
}

.copy-code-button:focus {
/* avoid an ugly focus outline on click in Chrome, but darken the button
for accessibility. https://stackoverflow.com/a/25298082/1481479 */
background-color: #E6E6E6;
outline: 0;
}

.copy-code-button:active {
background-color: #D9D9D9;
}
26 changes: 26 additions & 0 deletions static/js/copy-code-button.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
if (clipboard) {
document.querySelectorAll('.highlight').forEach(function (codeBlock) {
var button = document.createElement('button');

button.className = 'copy-code-button';
button.type = 'button';
button.innerText = 'Copy';

button.addEventListener('click', function () {
clipboard.writeText(codeBlock.innerText).then(function () {
/* Chrome doesn't seem to blur automatically, leaving the button
in a focused state */
button.blur();

button.innerText = 'Copied!';
setTimeout(function () {
button.innerText = 'Copy';
}, 2000);
}, function (error) {
button.innerText = 'Error';
});
});

codeBlock.parentNode.insertBefore(button, codeBlock);
});
}

0 comments on commit 6953658

Please sign in to comment.