diff --git a/exampleSite/config.toml b/exampleSite/config.toml index 00800d40..c5226b5c 100644 --- a/exampleSite/config.toml +++ b/exampleSite/config.toml @@ -28,6 +28,7 @@ pygmentsCodeFences=true accentColor = "#FD3519" mainSections = ['portfolio'] # values: ['post', 'portfolio'] only accept one section, to be displayed bellow 404 rendererSafe = false # set to true if wish to remove the unsafe renderer setting below (recommended). Titles will not be run through markdownify + copyCodeButtonEnabled = false # set to true if copy button should be placed on top of code blocks [params.notFound] gopher = "/images/gopher.png" # checkout https://gopherize.me/ diff --git a/exampleSite/content/post/config-file.md b/exampleSite/content/post/config-file.md index 9d33e929..f154c0d5 100644 --- a/exampleSite/content/post/config-file.md +++ b/exampleSite/content/post/config-file.md @@ -42,6 +42,8 @@ pygmentsCodeFences=true accentColor = "#FD3519" mainSections = ['portfolio'] rendererSafe = true # set to true if the renderer is not marked unsafe + copyCodeButtonEnabled = false # set to true if copy button should be placed on top of code blocks + [params.notFound] gopher = "/images/gopher.png" diff --git a/layouts/partials/footer.html b/layouts/partials/footer.html index c9c4a2fb..9cc8e399 100644 --- a/layouts/partials/footer.html +++ b/layouts/partials/footer.html @@ -25,5 +25,10 @@ } }); + {{ if $.Site.Params.copyCodeButtonEnabled }} + {{ if (findRE " + {{ end }} + {{ end }} \ No newline at end of file diff --git a/static/js/copy-code-button.js b/static/js/copy-code-button.js new file mode 100644 index 00000000..f37e3d62 --- /dev/null +++ b/static/js/copy-code-button.js @@ -0,0 +1,36 @@ +function addCopyButtons(clipboard) { + document.querySelectorAll('pre > code').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'; + }); + }); + + var pre = codeBlock.parentNode; + if (pre.parentNode.classList.contains('highlight')) { + var highlight = pre.parentNode; + highlight.parentNode.insertBefore(button, highlight); + } else { + pre.parentNode.insertBefore(button, pre); + } + }); +} + +if (navigator && navigator.clipboard) { + addCopyButtons(navigator.clipboard); +}