@ekwoka/x-rias
Version:
A simple Alpine Directive for use with Cloudinary Fetch API for handling Responsive Images
51 lines (49 loc) • 1.3 kB
JavaScript
const getURLMaker = (value, onShopify, cloudURL) => {
if (onShopify)
return getShopifyUrl(value);
if (cloudURL)
return getCloudinaryUrl(value, cloudURL);
throw new TypeError("Invalid options");
};
const getCloudinaryUrl = (value, cloudURL) => {
value = new URL(value, document.baseURI).href;
if (value.includes("localhost"))
return () => value;
return (v) => (cloudURL + value).replace("{width}", String(v));
};
const getShopifyUrl = (value) => {
if (value.includes("{width}"))
return (v) => value.replaceAll("{width}", String(v));
if (regexp.test(value)) {
const modified = value.replace(regexp, "_{width}x$1");
return (v) => modified.replaceAll("{width}", String(v));
}
return (v) => {
const url = new URL(value, document.baseURI);
url.searchParams.set("width", String(v));
return url.href;
};
};
const widths = [
180,
360,
540,
720,
900,
1080,
1296,
1512,
1728,
1944,
2160,
2376,
2592,
2808,
3024
];
const makeSrcSet = (urlGenerator, maxSize = Infinity) => {
return widths.filter((w) => w <= maxSize).map((w) => `${urlGenerator(w)} ${w}w`).join(",");
};
const regexp = /_\d+x(\.jpg|\.png)/;
export { getCloudinaryUrl, getShopifyUrl, getURLMaker, makeSrcSet, widths };
//# sourceMappingURL=utils.js.map