From 311f1da61b552582499abc3bd371469c4e84981f Mon Sep 17 00:00:00 2001 From: Patrick Kollitsch Date: Tue, 7 May 2024 23:41:42 +0700 Subject: [PATCH] fix: proper handling of multiple tabs for the copy button fixes davidsneighbour/kollitsch.dev#849 Signed-off-by: Patrick Kollitsch --- .../assets/js/plugins/clipboard.js | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/modules/renderhooks/assets/js/plugins/clipboard.js b/modules/renderhooks/assets/js/plugins/clipboard.js index b02fad4d2..6f4b1b524 100644 --- a/modules/renderhooks/assets/js/plugins/clipboard.js +++ b/modules/renderhooks/assets/js/plugins/clipboard.js @@ -1,3 +1,4 @@ +// @ts-ignore - is mounted via gohugo module import ClipboardJS from '../libs/clipboard'; // initiate clipboard.js on all buttons with class .btn-clipboard @@ -19,3 +20,44 @@ clipboard.on('success', (/** @type {{ clearSelection: () => void; }} */ event) = // handling errors clipboard.on('error', (/** @type {any} */ event) => { }); + +// handle copy button on multi-tab highlighting components +if (document.readyState === 'loading') { // if loading hasn't finished yet + document.addEventListener('DOMContentLoaded', setupCopyButton); +} else { // `DOMContentLoaded` has already fired + setupCopyButton(); +} +function setupCopyButton() { + // all .component--highlight blocks + const highlightComponents = document.querySelectorAll('.component--highlight'); + highlightComponents.forEach(component => { + // copy buttons within this component (in case there are multiple) + const copyButtons = component.querySelectorAll('.btn-clipboard'); + if (copyButtons.length > 0) { + // update the copy button's target for each button + function updateClipboardTarget(newTarget) { + if (newTarget) { + copyButtons.forEach(copyButton => { + copyButton.setAttribute('data-clipboard-target', newTarget); + }); + } else { + console.error('No new target specified.'); + } + } + // Add event listeners to all tab buttons within this block, excluding the copy button + component.querySelectorAll('.nav-link:not(.btn-clipboard)').forEach(tabButton => { + tabButton.addEventListener('click', () => { + const newTarget = tabButton.getAttribute('data-bs-target'); + updateClipboardTarget(newTarget); + }); + }); + // Set initial clipboard target to the currently active tab within this block + const activeTabButton = component.querySelector('.nav-link.active:not(.btn-clipboard)'); + if (activeTabButton) { + updateClipboardTarget(activeTabButton.getAttribute('data-bs-target')); + } + } else { + console.error('.btn-clipboard button(s) not found in the component.'); + } + }); +}