UNPKG

@ekwoka/x-rias

Version:

A simple Alpine Directive for use with Cloudinary Fetch API for handling Responsive Images

44 lines (42 loc) 1.29 kB
const debounceObserver = (fn, delay) => { let timer; const allElements = /* @__PURE__ */ new Set(); return function(entries, observer2) { if (timer) clearTimeout(timer); entries.forEach(({ target }) => allElements.add(target)); timer = setTimeout(() => { fn(allElements, observer2); timer = null; }, delay); }; }; const observerCB = (els) => { els.forEach((el) => resize(el)); els.clear(); }; const resize = (el) => { const setSize = (width2) => el.setAttribute("sizes", (width2 | 0) + "px"); let width = 0; let height = 0; let parent = el; while (width < 100 && parent) { width = parent.offsetWidth; height = parent.offsetHeight; parent = parent.parentNode; } const objectFit = getComputedStyle(el).objectFit; if (objectFit !== "cover") return setSize(width); const imageRatio = Number(el.getAttribute("width")) / Number(el.getAttribute("height")); if (!imageRatio) return setSize(width); const displayedRatio = width / height; if (displayedRatio >= imageRatio + 0.1) return setSize(width); const newWidth = height * imageRatio; setSize(newWidth); }; const observer = new ResizeObserver(debounceObserver(observerCB, 800)); export { observer }; //# sourceMappingURL=resizeObserver.js.map