Skip to content

Commit

Permalink
update copy-code js
Browse files Browse the repository at this point in the history
  • Loading branch information
StefonSimmons committed Apr 15, 2024
1 parent b7109ee commit d7e5f8a
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions assets/scripts/components/copy-code.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Tooltip from 'bootstrap/js/dist/tooltip';
// Script to add copy buttons to markdown fenced (```), and {{ highlight }} hugo function code blocks

function initCopyCode () {
addCopyButton()
addCopyButton(['shell', 'json', 'yaml'])

// Add Event Listener
const copyButtons = document.querySelectorAll(['.js-copy-button', '#tryRuleModal .copy-icon']);
Expand All @@ -17,17 +17,18 @@ function initCopyCode () {

}


// Adds copy button to code examples that use the highlight hugo function or are fenced code blocks in markdown
function addCopyButton () {
const fencedLang = ['shell', 'json', 'yaml'] // target specific fenced codeblocks by language
/**
* Adds copy button to code examples that use the highlight hugo function or are fenced code blocks in markdown
* @param {Array} fencedLangs - Array of languages to target specific fenced codeblocks
*/
function addCopyButton (fencedLangs) {
const highlights = document.querySelectorAll("div.highlight")

highlights.forEach(highlightEl => {
const dl = highlightEl.querySelector('[data-lang]');
const codeLang = dl ? dl.dataset.lang : "";
const isNestedInAppendableContainer = highlightEl.parentElement.classList.contains('append-copy-btn') //
const isFencedCodeExample = [...fencedLang].includes(codeLang) // markdown fenced code block
const isFencedCodeExample = [...fencedLangs].includes(codeLang) // markdown fenced code block

const shouldAddCopyBtn = isFencedCodeExample || isNestedInAppendableContainer
if(shouldAddCopyBtn){
Expand Down Expand Up @@ -77,4 +78,5 @@ function getCode (btn){

initCopyCode()

module.exports = {initCopyCode}
// Export the functions for testing
module.exports = {initCopyCode, getCode, copyCode, addCopyButton}

0 comments on commit d7e5f8a

Please sign in to comment.