/**
* Wyrównywanie elementów w wierszach, funkcja ustawia wysokość elementów w wierszach na najwyższą wysokość w wierszu. Przydatne np. do wyrównywania tekstów w ramkach rekomendacji. Funkcja jest dostępna w obiekcie <b>app_shop.fn</b>. Patrz przykłady użycia
* @example
* // Wiele selektorów
* app_shop.fn.setHeight({ selectors: ['#search .product__prices', '#search .product__name'], container: '#search' });
*
* @example
* // Jeden selektor
* app_shop.fn.setHeight({ selector: '#search .product__name', container: '#search' });
*
* @param {Object} options - możliwe opcje "selector", "selectors", "container"
* @param {string} [options.selector] - Jeden selektor, którego elementy mają być wyrównane.
* @param {string[]} [options.selectors] - Lista selektorów, których elementy mają być wyrównane.
* @param {string} options.container - Selektor kontenera, w którym mają być wyrównane elementy.
* @returns {void} - Funkcja nie zwraca wartości.
*/
const setHeight = options => {
const { selector, selectors, container } = options || {};
if ((!selector && !selectors) || !container) return;
const containerElement = document.querySelector(container);
if (!containerElement) return;
const getWidthWithMargin = el => {
if (!el) return 0;
const { marginLeft, marginRight } = window.getComputedStyle(el);
return el.offsetWidth + parseInt(marginLeft, 10) + parseInt(marginRight, 10);
};
const containerWidth = getWidthWithMargin(containerElement);
const childWidth = getWidthWithMargin(containerElement.firstElementChild);
const adjustRowHeight = itemSelector => {
const elements = document.querySelectorAll(itemSelector);
if (!elements.length) return;
if (!childWidth) return;
const numCol = Math.round(containerWidth / childWidth);
if (!numCol) return;
const children = [...containerElement.children];
for (let i = 0; i < children.length; i += numCol) {
const slicedChildren = children.slice(i, i + numCol);
const targetChildren = slicedChildren.map(child => child.querySelector(itemSelector));
const maxHeight = Math.max(...targetChildren.map(el => el?.offsetHeight));
targetChildren.forEach(el => {
if (!el) return;
el.style.minHeight = `${maxHeight}px`;
});
}
};
if (selector) {
adjustRowHeight(selector);
}
if (selectors?.length) {
selectors.forEach(item => adjustRowHeight(item));
}
};