Skip to content

Commit 7a7850f

Browse files
committed
Fix lineos=true breaking copy to clipboard
Change selector used to the .highlight class Add regex to remove line numbers Update regex to remove carriage returns start and end of block
1 parent 636ac04 commit 7a7850f

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

assets/js/code-copy.js

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,31 @@
11
function CopyCode(clipboard) {
2-
document.querySelectorAll('pre > code').forEach(function(codeBlock) {
3-
var button = document.createElement('button');
4-
button.className = 'code-copy';
5-
button.type = 'button';
6-
button.innerHTML = '<i class="fas fa-copy"></i> Copy';
2+
document.querySelectorAll(".highlight").forEach((codeBlock) => {
3+
const button = document.createElement("button");
4+
button.className = "code-copy";
5+
button.type = "button";
6+
button.innerHTML = '<i class="fas fa-copy"></i> Copy';
77

8-
button.addEventListener('click', function() {
9-
// removes return carriage from copied text
10-
clipboard.writeText(codeBlock.textContent.replace(/\n$/g, "")).then(
11-
function() {
12-
button.blur(); /* Chrome fix */
13-
button.innerHTML = '<i class="fas fa-check"></i> Copied!';
14-
setTimeout(function() {
15-
button.innerHTML = '<i class="fas fa-copy"></i> Copy';
16-
}, 2000);
17-
},
18-
function(error) {
19-
button.innerHTML = '<i class="fas fa-exclamation"></i> Error';
20-
console.error(error);
21-
}
22-
);
23-
});
8+
button.addEventListener("click", async () => {
9+
try {
10+
await clipboard.writeText(
11+
codeBlock.textContent
12+
.replace(/^\s*\d+\s/gm, "") // remove line numbers
13+
.replace(/^\s*|\s*$/g, "") // remove carriage returns at top and bottom of block
14+
);
2415

25-
var pre = codeBlock.parentNode;
26-
if (pre.parentNode.classList.contains('highlight')) {
27-
var highlight = pre.parentNode;
28-
highlight.parentNode.insertBefore(button, highlight);
29-
}
16+
button.blur(); /* Chrome fix */
17+
button.innerHTML = '<i class="fas fa-check"></i> Copied!';
18+
setTimeout(() => {
19+
button.innerHTML = '<i class="fas fa-copy"></i> Copy';
20+
}, 2000);
21+
} catch (error) {
22+
button.innerHTML = '<i class="fas fa-exclamation"></i> Error';
23+
console.error(error);
24+
}
3025
});
26+
27+
codeBlock.parentNode.insertBefore(button, codeBlock);
28+
});
3129
}
3230

3331
CopyCode(navigator.clipboard);

0 commit comments

Comments
 (0)