| 1 |
import copy from 'copy-to-clipboard'; |
| 2 |
|
| 3 |
// Handle copy button |
| 4 |
addEventListener('DOMContentLoaded', () => { |
| 5 |
const buttons = Array.from( |
| 6 |
document.querySelectorAll('.code-block-pro-copy-button'), |
| 7 |
); |
| 8 |
buttons.forEach((button) => { |
| 9 |
// Setting it to block here lets users deactivate the plugin safely |
| 10 |
button.style.display = 'block'; |
| 11 |
button.addEventListener('click', (event) => { |
| 12 |
const b = event.target?.closest('span'); |
| 13 |
copy(b?.dataset?.code ?? '', { |
| 14 |
format: 'text/plain', |
| 15 |
}); |
| 16 |
b.classList.add('copying'); |
| 17 |
setTimeout(() => { |
| 18 |
b.classList.remove('copying'); |
| 19 |
}, 2000); |
| 20 |
}); |
| 21 |
}); |
| 22 |
}); |
| 23 |
|
| 24 |
// Handle highlighter |
| 25 |
addEventListener('DOMContentLoaded', () => { |
| 26 |
const codeBlocks = Array.from( |
| 27 |
document.querySelectorAll('.wp-block-kevinbatdorf-code-block-pro pre'), |
| 28 |
); |
| 29 |
|
| 30 |
codeBlocks.forEach((codeBlock) => { |
| 31 |
// search for highlights |
| 32 |
const highlighters = codeBlock.querySelectorAll('.cbp-line-highlight'); |
| 33 |
if (!highlighters.length) return; |
| 34 |
|
| 35 |
// We need to track the block width so we can adjust the |
| 36 |
// highlighter width in case of overflow |
| 37 |
const resizeObserver = new ResizeObserver((entries) => { |
| 38 |
entries.forEach((entry) => { |
| 39 |
// get width of inner code block |
| 40 |
codeBlock.style.setProperty('--cbp-block-width', '0'); |
| 41 |
const codeWidth = |
| 42 |
entry.target.querySelector('code').offsetWidth; |
| 43 |
const computed = |
| 44 |
codeWidth + 16 === entry.target.scrollWidth |
| 45 |
? codeWidth + 16 |
| 46 |
: entry.target.scrollWidth + 16; |
| 47 |
codeBlock.style.setProperty( |
| 48 |
'--cbp-block-width', |
| 49 |
`${computed}px`, |
| 50 |
); |
| 51 |
}); |
| 52 |
}); |
| 53 |
resizeObserver.observe(codeBlock); |
| 54 |
|
| 55 |
// add the highlighter |
| 56 |
highlighters.forEach((highlighter) => { |
| 57 |
highlighter.insertAdjacentHTML( |
| 58 |
'beforeend', |
| 59 |
'<span aria-hidden="true" class="cbp-line-highlighter"></span>', |
| 60 |
); |
| 61 |
}); |
| 62 |
}); |
| 63 |
}); |
| 64 |
|
| 65 |
// Handle font loading |
| 66 |
addEventListener('DOMContentLoaded', () => { |
| 67 |
if (!window.codeBlockPro?.pluginUrl) return; |
| 68 |
const fontsToLoad = new Set( |
| 69 |
Array.from( |
| 70 |
document.querySelectorAll('[data-code-block-pro-font-family]') ?? |
| 71 |
[], |
| 72 |
) |
| 73 |
.map((f) => f.dataset.codeBlockProFontFamily) |
| 74 |
.filter(Boolean), |
| 75 |
); |
| 76 |
[...fontsToLoad].forEach(async (fontName) => { |
| 77 |
const font = new FontFace( |
| 78 |
fontName, |
| 79 |
`url(${window.codeBlockPro.pluginUrl}/build/fonts/${fontName}.woff2)`, |
| 80 |
); |
| 81 |
await font.load(); |
| 82 |
document.fonts.add(font); |
| 83 |
}); |
| 84 |
}); |
| 85 |
|