Created
October 10, 2024 00:58
-
-
Save ricealexander/0825fa254ee86ed6280ec0eee08c0328 to your computer and use it in GitHub Desktop.
Turn a Grove RichText Module into an Accordian
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createCollapsingSection (title, contents) { | |
let section = document.createElement('section') | |
section.style.marginTop = '10px' | |
section.style.borderBottom = '1px solid var(--secC3)' | |
section.style.marginBottom = '10px' | |
section.innerHTML = ` | |
<details class="RTB" style="padding-bottom: 10px"> | |
<summary tabindex="0" role="button"> | |
<h2 style="display: inline;">${title}</h2> | |
</summary> | |
<div style="padding-top: 10px;"></div> | |
</details> | |
` | |
let contentWrapper = section.querySelector('details > div') | |
for (let element of contents) { | |
contentWrapper.append(element) | |
} | |
return section | |
} | |
let richTextModules = document.querySelectorAll('.Enh .RichTextModule') | |
for (let module of richTextModules) { | |
let moduleContainer = module.parentElement | |
let children = module.querySelector('.RichTextModule-items').children | |
let results = [] | |
let hasStarted = false | |
let title = '' | |
let contents = [] | |
for (let element of [...children]) { | |
// We can only contain elements following a heading | |
if (element.nodeName != 'H2' && !hasStarted) { | |
results.push(element) | |
continue | |
} | |
if (element.nodeName == 'H2' && !hasStarted) { | |
title = element.textContent | |
hasStarted = true | |
continue | |
} | |
// Collect elements following an h2. Dump contents once we encounter another | |
if (element.nodeName == 'H2') { | |
// Dump the previous section and start a new one | |
results.push(createCollapsingSection(title, contents)) | |
title = element.textContent | |
contents = [] | |
} | |
else { | |
contents.push(element) | |
} | |
} | |
if (hasStarted) results.push(createCollapsingSection(title, contents)) | |
for (let element of results) { | |
// eslint-disable-next-line unicorn/prefer-modern-dom-apis | |
moduleContainer.before(element) | |
} | |
if (hasStarted) moduleContainer.remove() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment