Skip to content

Commit 24915a9

Browse files
authored
feat(article): copy button for highlight block (#295)
This button only shows on highlighted code blocks, because it uses the wrapper div.highlight
1 parent 4a0cbac commit 24915a9

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

assets/scss/partials/layout/article.scss

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,4 +415,30 @@
415415
margin-right: calc((var(--card-padding)) * -1);
416416
width: calc(100% + var(--card-padding) * 2);
417417
}
418+
419+
.highlight {
420+
position: relative;
421+
422+
&:hover {
423+
.copyCodeButton {
424+
opacity: 1;
425+
}
426+
}
427+
}
428+
429+
.copyCodeButton {
430+
position: absolute;
431+
top: calc(var(--card-padding));
432+
right: 0;
433+
background: var(--card-background);
434+
border: none;
435+
box-shadow: var(--shadow-l2);
436+
border-radius: var(--tag-border-radius);
437+
padding: 8px 16px;
438+
color: var(--card-text-color-main);
439+
cursor: pointer;
440+
font-size: 14px;
441+
opacity: 0;
442+
transition: opacity 0.3s ease;
443+
}
418444
}

assets/ts/main.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,38 @@ let Stack = {
5454
observer.observe(articleTile)
5555
}
5656

57+
58+
/**
59+
* Add copy button to code block
60+
*/
61+
const codeBlocks = document.querySelectorAll('.article-content .highlight');
62+
const copyText = `Copy`,
63+
copiedText = `Copied!`;
64+
codeBlocks.forEach(codeBlock => {
65+
const copyButton = document.createElement('button');
66+
copyButton.innerHTML = copyText;
67+
copyButton.classList.add('copyCodeButton');
68+
codeBlock.appendChild(copyButton);
69+
70+
const pre = codeBlock.getElementsByTagName('pre');
71+
const code = pre[0].textContent;
72+
73+
copyButton.addEventListener('click', () => {
74+
navigator.clipboard.writeText(code)
75+
.then(() => {
76+
copyButton.textContent = copiedText;
77+
78+
setTimeout(() => {
79+
copyButton.textContent = copyText;
80+
}, 1000);
81+
})
82+
.catch(err => {
83+
alert(err)
84+
console.log('Something went wrong', err);
85+
});
86+
});
87+
});
88+
5789
new StackColorScheme(document.getElementById('dark-mode-toggle'));
5890
}
5991
}

0 commit comments

Comments
 (0)