From 382b372f0463ed2758dc4b4402171a63ef4f740d Mon Sep 17 00:00:00 2001 From: Sartxi Date: Thu, 17 Oct 2024 16:31:00 -0600 Subject: [PATCH] better logic and check for text nodes in elements --- libs/utils/decorate.js | 19 ++++++------------- libs/utils/utils.js | 8 ++++++++ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/libs/utils/decorate.js b/libs/utils/decorate.js index 4117c3d3b1..e0acdac87f 100644 --- a/libs/utils/decorate.js +++ b/libs/utils/decorate.js @@ -1,4 +1,4 @@ -import { createTag, loadStyle, getConfig, createIntersectionObserver } from './utils.js'; +import { createTag, loadStyle, getConfig, createIntersectionObserver, elementHasText } from './utils.js'; const { miloLibs, codeRoot } = getConfig(); @@ -77,19 +77,12 @@ export function decorateBlockText(el, config = ['m', 's', 'm'], type = null) { decorateIconArea(el); } } - const bodyDefault = `body-${config[1]}`; - const emptyEls = el.querySelectorAll('p:not([class]), ul:not([class]), ol:not([class])'); + const bodyStyle = `body-${config[1]}`; + const emptyEls = el.querySelectorAll('p:not([class]), ul:not([class]), ol:not([class], div:not([class]))'); if (emptyEls.length) { - emptyEls.forEach((p) => p.classList.add(bodyDefault)); - } else { - const emptyDivs = el.querySelectorAll('div:not([class])'); - if (emptyDivs.length) { - [...emptyDivs].filter((div) => div.textContent.trim() !== '').forEach((text) => { - text.classList.add(bodyDefault); - }); - } else if (!el.classList.length) { - el.classList.add(bodyDefault); - } + [...emptyEls].filter(elementHasText).forEach((e) => e.classList.add(bodyStyle)); + } else if (!el.classList.length && elementHasText(el)) { + el.classList.add(bodyStyle); } } const buttonSize = config.length > 3 ? `button-${config[3]}` : ''; diff --git a/libs/utils/utils.js b/libs/utils/utils.js index 11e4548bd5..81ce767420 100644 --- a/libs/utils/utils.js +++ b/libs/utils/utils.js @@ -260,6 +260,14 @@ export function isInTextNode(node) { return node.parentElement.firstChild.nodeType === Node.TEXT_NODE; } +export function elementHasText(el) { + return !![...el.childNodes].filter((node) => { + const { nodeType, textContent, innerText } = node; + if (nodeType === Node.ELEMENT_NODE) return innerText.trim() !== ''; + return nodeType === Node.TEXT_NODE && textContent.trim() !== ''; + }).length; +} + export function createTag(tag, attributes, html, options = {}) { const el = document.createElement(tag); if (html) {