From 80f5994d960f4a50239d93ea94ed33e01271eb75 Mon Sep 17 00:00:00 2001 From: BBaoVanC Date: Sun, 22 Jan 2023 00:09:34 -0600 Subject: [PATCH] Improve code block copy text - Use JS to get it directly from the code block instead of needing a separate `pre.code-raw` to get it from. That makes it possible to: - bashsession: Don't copy prompt or command output --- assets/js/bobatheme.js | 13 +++++++++---- layouts/_default/_markup/render-codeblock.html | 12 +++++++----- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/assets/js/bobatheme.js b/assets/js/bobatheme.js index af463bd..efb9efe 100644 --- a/assets/js/bobatheme.js +++ b/assets/js/bobatheme.js @@ -12,14 +12,19 @@ window.onscroll = function() { window.onload = () => { document.querySelectorAll(".code-block").forEach(codeBlock => { const button = codeBlock.querySelector(".code-header > .code-copy-button"); - // TODO: maybe get this from HTMLElement.innerText on the actual code block content element - // but it's hard to select it; `data-lang` attribute might not always be there (if lang is unset) - const rawCode = codeBlock.querySelector("pre.code-raw").innerText; + + // lang will not be unset because we default it to text + // clone it so it doesn't change the actual DOM element + const codeElem = codeBlock.querySelector("code[data-lang]").cloneNode(true); + // bashsession: remove command output lines + codeElem.querySelectorAll(".go").forEach(e => e.parentNode.removeChild(e)); + // bashsession: remove prompt symbol + codeElem.querySelectorAll(".gp").forEach(e => e.parentNode.removeChild(e)); + const rawCode = codeElem.innerText; const originalCopyText = button.innerHTML; button.onclick = event => { navigator.clipboard.writeText(rawCode); - console.log(rawCode); // TODO: maybe we could add a fancier indicator, like a flash or something event.target.innerHTML = "Copied!"; setTimeout(() => { diff --git a/layouts/_default/_markup/render-codeblock.html b/layouts/_default/_markup/render-codeblock.html index ea3a58d..ba4e001 100644 --- a/layouts/_default/_markup/render-codeblock.html +++ b/layouts/_default/_markup/render-codeblock.html @@ -1,13 +1,15 @@ +{{ $type := "text" }} +{{ with .Type }} + {{ $type = . }} +{{ end }}
- {{ .Type }} + {{ $type }} {{ i18n "copy_to_clipboard" }}
- {{/* a div.highlight is already created by highlight function */}} - {{ highlight .Inner .Type }} - {{/* for copy to clipboard */}} - + {{/* a div.highlight is already created by highlight function */}} + {{ highlight .Inner $type }}