Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add copy code button
Browse files Browse the repository at this point in the history
BernatBC committed Aug 31, 2024
1 parent 02e5e99 commit 62f9b68
Showing 5 changed files with 55 additions and 0 deletions.
34 changes: 34 additions & 0 deletions assets/scripts/features/copyCode/copyCode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
if (navigator && navigator.clipboard) {
addCopyButtons(navigator.clipboard)
} else {
const script = document.createElement('script')
script.src =
'https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/2.7.0/clipboard-polyfill.promise.js'
script.integrity = 'sha256-waClS2re9NUbXRsryKoof+F9qc1gjjIhc2eT7ZbIv94='
script.crossOrigin = 'anonymous'
script.onload = function () {
addCopyButtons(clipboard)

Check failure on line 10 in assets/scripts/features/copyCode/copyCode.js

GitHub Actions / lint

'clipboard' is not defined
}

document.body.appendChild(script)
}

function addCopyButtons(clipboard) {
document.querySelectorAll('pre > code').forEach(function (codeBlock) {
const button = document.createElement('a')
button.className = 'copy-code-button'
button.innerHTML = "<i class='fa-regular fa-copy'></i>"

button.addEventListener('click', function () {
clipboard.writeText(codeBlock.innerText)
})

const pre = codeBlock.parentNode
if (pre.parentNode.classList.contains('highlight')) {
const highlight = pre.parentNode
highlight.parentNode.insertBefore(button, highlight)
} else {
pre.parentNode.insertBefore(button, pre)
}
})
}
1 change: 1 addition & 0 deletions assets/scripts/features/copyCode/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import './copyCode'
4 changes: 4 additions & 0 deletions assets/scripts/features/index.js
Original file line number Diff line number Diff line change
@@ -25,3 +25,7 @@ if (process.env.FEATURE_MATH === '1') {
if (process.env.FEATURE_EMBEDPDF === '1') {
import('./embedpdf')
}

if (process.env.FEATURE_COPYCODEBUTTON === '1') {
import('./copyCode')
}
12 changes: 12 additions & 0 deletions assets/styles/components/misc.scss
Original file line number Diff line number Diff line change
@@ -50,6 +50,18 @@ pre {
}
}

.copy-code-button {
display: flex;
justify-content: right;
margin-right: 0.2em;
margin-bottom: -1.2em;
font-size: 20pt;
}

.highlight pre {
margin: 0;
}

html[data-theme='dark'] {
.paginator {
.page-item {
4 changes: 4 additions & 0 deletions exampleSite/hugo.yaml
Original file line number Diff line number Diff line change
@@ -91,6 +91,10 @@ params:
# Configure various features of this theme
features:

# Enables copy code button
copyCodeButton:
enable: true

# Enable dark theme
darkMode:
enable: true

0 comments on commit 62f9b68

Please sign in to comment.