// Adapted from the following tutorials:
// https://www.dannyguo.com/blog/how-to-add-copy-to-clipboard-buttons-to-code-blocks-in-hugo/
// https://aaronluna.dev/blog/add-copy-button-to-code-blocks-hugo-chroma/
// https://logfetch.com/hugo-add-copy-to-clipboard-button/
const addCopyButtons = (clipboard) => {
// 1. Look for pre > code elements in the DOM
document.querySelectorAll('.highlight > pre > code').forEach((codeBlock) => {
// 2. Create a button that will trigger a copy operation
const button = document.createElement('button');
const svgCopy = '';
const svgCheck = '';
button.className = 'clipboard-button';
button.type = 'button';
button.innerHTML = svgCopy;
button.addEventListener('click', () => {
let textToCopy = '';
let codeBlockChildren = Array.from(codeBlock.children)
codeBlockChildren.forEach(function(span) {
// lastChild is required to avoid copying line numbers
textToCopy += span.lastChild.innerText;
});
clipboard.writeText(textToCopy).then(
() => {
button.blur();
button.innerHTML = svgCheck;
setTimeout(() => (button.innerHTML = svgCopy), 2000);
},
(error) => (button.innerHTML = 'Error')
);
});
// 3. Append the button directly before the pre tag
const pre = codeBlock.parentNode;
pre.parentNode.insertBefore(button, pre);
});
};
const clipboard = (() => {
if (navigator && navigator.clipboard) {
addCopyButtons(navigator.clipboard);
}
})();
export { clipboard };