Skip to content

Commit

Permalink
better logic and check for text nodes in elements
Browse files Browse the repository at this point in the history
  • Loading branch information
Sartxi committed Oct 17, 2024
1 parent ba29e8a commit 382b372
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
19 changes: 6 additions & 13 deletions libs/utils/decorate.js
Original file line number Diff line number Diff line change
@@ -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();

Expand Down Expand Up @@ -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]}` : '';
Expand Down
8 changes: 8 additions & 0 deletions libs/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 382b372

Please sign in to comment.