Add copy code button
This commit is contained in:
parent
02e5e99cf6
commit
62f9b68a16
5 changed files with 55 additions and 0 deletions
34
assets/scripts/features/copyCode/copyCode.js
Normal file
34
assets/scripts/features/copyCode/copyCode.js
Normal file
|
@ -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)
|
||||
}
|
||||
|
||||
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
assets/scripts/features/copyCode/index.js
Normal file
1
assets/scripts/features/copyCode/index.js
Normal file
|
@ -0,0 +1 @@
|
|||
import './copyCode'
|
|
@ -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')
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue