flex-wrap-layout
Version:
Experiments with flexbox layout
33 lines (32 loc) • 1.45 kB
JavaScript
function getTopPosition(el) {
const { top } = el.getBoundingClientRect();
const { marginTop } = getComputedStyle(el);
return top - parseInt(marginTop, 10);
}
export function detectWrappedElements(rootElement, wrapChildrenClassName, nextIsWrappedClassName, hasChildWrappedClassName) {
const parents = Array.from(rootElement.getElementsByClassName(wrapChildrenClassName));
if (rootElement.classList.contains(wrapChildrenClassName))
parents.unshift(rootElement);
parents.forEach(parent => {
const { children } = parent;
for (let i = 0; i < children.length; i++) {
const child = children[i];
const prev = child.previousElementSibling;
if (prev !== null) {
const top = getTopPosition(child);
const prevTop = getTopPosition(prev);
if (top > prevTop) {
prev.classList.add(nextIsWrappedClassName);
}
else if (top === prevTop) {
prev.classList.remove(nextIsWrappedClassName);
}
}
if (child.nextElementSibling === null) {
child.classList.remove(nextIsWrappedClassName);
}
}
});
const containsChildNextIsWrapped = rootElement.getElementsByClassName(nextIsWrappedClassName).length > 0;
rootElement.classList.toggle(hasChildWrappedClassName, containsChildNextIsWrapped);
}