Skip to content

Commit

Permalink
add 'copy code to clipboard' button to code blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
EthanThatOneKid committed Mar 27, 2024
1 parent 6e0fd4b commit 859cecb
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
1 change: 1 addition & 0 deletions components/doc/doc_content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export default function DocContent(props: DocContentProps) {
<>
<Head>
<Hljs id="github" />
<script src="/copy.js" defer></script>
</Head>

<aside class="aside">
Expand Down
2 changes: 1 addition & 1 deletion lib/docs/md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const renderer: MarkdownIt = new MarkdownIt({
{ language, ignoreIllegals: true },
).value
: renderer.utils.escapeHtml(content);
return `<pre><code class="hljs">${html}</code></pre>`;
return `<pre data-lang="${language}"><code class="hljs">${html}</code></pre>`;
},
});

Expand Down
35 changes: 35 additions & 0 deletions static/copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Source: https://www.roboleary.net/2022/01/13/copy-code-to-clipboard-blog.html
//
const copyButtonLabel = "Copy Code";
const copiedButtonLabel = "Code Copied";

// use a class selector if available
const blocks = document.querySelectorAll("pre");

blocks.forEach((block) => {
// only add button if browser supports Clipboard API
if (navigator.clipboard) {
const button = document.createElement("button");

button.innerText = copyButtonLabel;
block.appendChild(button);

button.addEventListener("click", async () => {
await copyCode(block, button);
});
}
});

async function copyCode(block, button) {
const code = block.querySelector("code");
const text = code.innerText;
await navigator.clipboard.writeText(text)
.then(() => {
// visual feedback that task is completed
button.innerText = copiedButtonLabel;

setTimeout(() => {
button.innerText = copyButtonLabel;
}, 1e3);
});
}
23 changes: 23 additions & 0 deletions static/global.css
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,29 @@ pre code {
display: block;
padding: 1em;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
}

pre {
position: relative;
}

pre:before {
content: attr(data-lang);
font-size: 1.2em;
display: block;
text-transform: uppercase;
text-decoration: underline;
text-underline-offset: 0.3em;
padding: 0.6em 1em;
}

pre button {
position: absolute;
top: 5px;
right: 5px;
height: 2em;
}

@media (min-width: 768px) {
Expand Down

0 comments on commit 859cecb

Please sign in to comment.