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
This commit is contained in:
BBaoVanC 2023-01-22 00:09:34 -06:00
parent 342710a755
commit 80f5994d96
Signed by: bbaovanc
GPG Key ID: 18089E4E3CCF1D3A
2 changed files with 16 additions and 9 deletions

View File

@ -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(() => {

View File

@ -1,13 +1,15 @@
{{ $type := "text" }}
{{ with .Type }}
{{ $type = . }}
{{ end }}
<div class="code-block">
<div class="code-header">
<span class="code-type">{{ .Type }}</span>
<span class="code-type">{{ $type }}</span>
<a class="code-copy-button">
{{ i18n "copy_to_clipboard" }}
</a>
</div>
{{/* a div.highlight is already created by highlight function */}}
{{ highlight .Inner .Type }}
{{/* for copy to clipboard */}}
<pre class="code-raw" style="display: none;">{{ .Inner }}</pre>
{{/* a div.highlight is already created by highlight function */}}
{{ highlight .Inner $type }}
</div>