From edd02f464e032d614177af17a123d1c708b2b2df Mon Sep 17 00:00:00 2001 From: Fredrik Jonsson Date: Mon, 9 Jun 2025 11:40:50 +0200 Subject: [PATCH] Adding codeblocks.js. --- assets/js/codeblocks.js | 29 +++++++++++++++++++ layouts/_markup/example-render-codeblock.html | 1 + layouts/_partials/head/scripts.html | 7 +++++ 3 files changed, 37 insertions(+) create mode 100644 assets/js/codeblocks.js diff --git a/assets/js/codeblocks.js b/assets/js/codeblocks.js new file mode 100644 index 0000000..6939b02 --- /dev/null +++ b/assets/js/codeblocks.js @@ -0,0 +1,29 @@ +/** + * @file + * A JavaScript file to add a copy code button to codeblocks. + */ + +(function () { + async function writeClipboardText(text) { + try { + await navigator.clipboard.writeText(text); + } catch (error) { + console.error(error.message); + } + } + + const copybuttons = document.querySelectorAll('[data-codebutton]'); + copybuttons.forEach(function (button) { + button.addEventListener('click', function (e) { + const codeblock = e.target.parentElement; + const codeid = e.target.dataset.codebutton; + const codesnippet = codeblock.querySelector('[data-codetext]').getAttribute('content'); + const codearea = codeblock.querySelector('pre'); + codearea.classList.add('flash-item'); + writeClipboardText(JSON.parse(codesnippet)); + setTimeout(function () { + codearea.classList.remove('flash-item'); + }, 700); + }); + }); +})(); diff --git a/layouts/_markup/example-render-codeblock.html b/layouts/_markup/example-render-codeblock.html index 1278c84..97f678c 100644 --- a/layouts/_markup/example-render-codeblock.html +++ b/layouts/_markup/example-render-codeblock.html @@ -1,3 +1,4 @@ +{{ .Page.Store.Set "codeblocks" true -}} {{ $result := transform.HighlightCodeBlock . -}}
diff --git a/layouts/_partials/head/scripts.html b/layouts/_partials/head/scripts.html index 2fab26e..18bc052 100644 --- a/layouts/_partials/head/scripts.html +++ b/layouts/_partials/head/scripts.html @@ -1,3 +1,5 @@ +{{ $noop := .WordCount -}} + {{ $opts := dict "minify" true -}} {{ if eq hugo.Environment "development" -}} {{ $opts = merge $opts (dict "minify" false) -}} @@ -43,6 +45,11 @@ {{ end -}} +{{ if or ($.Param "codeblocks") (.Page.Store.Get "codeblocks") -}} +{{ $codeblocks := resources.Get "js/codeblocks.js" | js.Build $opts | fingerprint -}} + +{{ end -}} + {{ if .HasShortcode "contact" -}} {{ $contact := resources.Get "js/contact.js" | js.Build $opts | fingerprint -}}