Adding codeblocks.js.
This commit is contained in:
parent
0effd8ee1a
commit
edd02f464e
3 changed files with 37 additions and 0 deletions
29
assets/js/codeblocks.js
Normal file
29
assets/js/codeblocks.js
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
{{ .Page.Store.Set "codeblocks" true -}}
|
||||
{{ $result := transform.HighlightCodeBlock . -}}
|
||||
<div data-codeblock itemscope itemtype="https://schema.org/SoftwareSourceCode" {{ range $k, $v := .Attributes }}{{ printf " %s=%q" $k $v | safeHTMLAttr }}{{ end }}>
|
||||
<button data-codebutton class="codebutton" title="{{ i18n "copy_code" }}"><span>⧉</span></button>
|
||||
|
|
|
|||
|
|
@ -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 @@
|
|||
<script defer src="{{ $tables.RelPermalink }}"></script>
|
||||
{{ end -}}
|
||||
|
||||
{{ if or ($.Param "codeblocks") (.Page.Store.Get "codeblocks") -}}
|
||||
{{ $codeblocks := resources.Get "js/codeblocks.js" | js.Build $opts | fingerprint -}}
|
||||
<script defer src="{{ $codeblocks.RelPermalink }}"></script>
|
||||
{{ end -}}
|
||||
|
||||
{{ if .HasShortcode "contact" -}}
|
||||
{{ $contact := resources.Get "js/contact.js" | js.Build $opts | fingerprint -}}
|
||||
<script defer src="{{ $contact.RelPermalink }}"></script>
|
||||
|
|
|
|||
Loading…
Reference in a new issue