Skip to content

Commit

Permalink
Copy code button (#499)
Browse files Browse the repository at this point in the history
* add: copy code button

* Revert "add: copy code button"

This reverts commit dcbcccd.

* add: copy code button

* update: change copy-copied text + only show when hovered

* update: responsive copy-code button

* fix: copying line numbers and empty spaces
  • Loading branch information
mansoorbarri authored Sep 3, 2024
1 parent 276de53 commit fd74af4
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
31 changes: 31 additions & 0 deletions static/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -963,3 +963,34 @@ h4.see-also {
overflow-x: auto;
overflow-y: hidden;
}


.highlight {
box-sizing: border-box;
padding: 10px;
position: relative;
}

.copyCodeButton {
background-color: #f5f5f5;
border: 1px solid #ccc;
color: black;
cursor: pointer;
display: none;
font-size: 14px;
padding: 5px 10px;
position: absolute;
right: 10px;
top: 10px;
transition: background-color 0.3s ease;
z-index: 10;
}

.highlight:hover .copyCodeButton {
display: block;
}

.copyCodeButton:hover {
background-color: #e0e0e0;
}

48 changes: 47 additions & 1 deletion static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,4 +179,50 @@ var main = {

// 2fc73a3a967e97599c9763d05e564189

document.addEventListener('DOMContentLoaded', main.init);
document.addEventListener('DOMContentLoaded', main.init);
/**
* Add copy button to code block
*/
document.addEventListener('DOMContentLoaded', () => {
const highlights = document.querySelectorAll('.row div.highlight');
const copyText = '📋';
const copiedText = '✔️';

highlights.forEach((highlight) => {
const copyButton = document.createElement('button');
copyButton.innerHTML = copyText;
copyButton.classList.add('copyCodeButton');
highlight.appendChild(copyButton);

const codeBlock = highlight.querySelector('code[data-lang]');
if (!codeBlock) return;

copyButton.addEventListener('click', () => {
// Create a deep clone of the code block
const codeBlockClone = codeBlock.cloneNode(true);

// Remove line number elements from the clone
const lineNumbers = codeBlockClone.querySelectorAll('.ln');
lineNumbers.forEach(ln => ln.remove());

// Get the text content, splitting by lines, trimming each line, and joining back
const codeText = codeBlockClone.textContent
.split('\n') // Split into lines
.map(line => line.trim()) // Trim each line
.join('\n'); // Join lines back with newline

navigator.clipboard.writeText(codeText)
.then(() => {
copyButton.textContent = copiedText;

setTimeout(() => {
copyButton.textContent = copyText;
}, 1000);
})
.catch((err) => {
alert('Failed to copy text');
console.error('Something went wrong', err);
});
});
});
});

0 comments on commit fd74af4

Please sign in to comment.