This repository has been archived on 2025-12-24. You can view files and clone it, but cannot push or open issues or pull requests.
site-template/packages/imagetools/api/utils/getImageSources.js
2025-03-07 14:59:06 +01:00

92 lines
2.2 KiB
JavaScript

// @ts-check
import getSrcset from "./getSrcset.js";
import getConfigOptions from "./getConfigOptions.js";
import getFallbackImage from "./getFallbackImage.js";
import pMap from "p-map";
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export default async function getImageSources(
src,
base,
image,
format,
imageWidth,
imagesizes,
breakpoints,
placeholder,
imageFormat,
formatOptions,
fallbackFormat,
includeSourceFormat,
rest
) {
try {
const calculatedConfigs = getConfigOptions(
imageWidth,
imagesizes,
breakpoints,
format,
imageFormat,
fallbackFormat,
includeSourceFormat
);
const { formats, requiredBreakpoints } = calculatedConfigs;
imagesizes = calculatedConfigs.imagesizes;
const maxWidth = requiredBreakpoints[requiredBreakpoints.length - 1];
const sliceLength = -(maxWidth.toString().length + 2);
const sources = await pMap(
formats,
async (format) => {
try {
await delay(250);
const srcset = await getSrcset(src, base, requiredBreakpoints, format, {
...rest,
...formatOptions[format],
});
const srcsets = srcset.split(", ");
const srcObject =
format === fallbackFormat
? { src: srcsets[srcsets.length - 1].slice(0, sliceLength) }
: {};
return {
...srcObject,
format,
srcset,
};
} catch (error) {
console.error(`Error processing format ${format}:`, error);
return null;
}
},
{ concurrency: 1 }
);
const filteredSources = sources.filter(Boolean);
const sizes = {
width: maxWidth,
height: Math.round(maxWidth / rest.aspect),
};
const fallback = await getFallbackImage(
src,
placeholder,
image,
fallbackFormat,
formatOptions,
rest
)
return { sources: filteredSources, sizes, fallback, imagesizes };
} catch (error) {
console.error("Error in getImageSources:", error);
return { sources: [], sizes: {}, fallback: null, imagesizes: null };
}
}