92 lines
2.3 KiB
JavaScript
92 lines
2.3 KiB
JavaScript
// @ts-check
|
|
import getSrcset from "./getSrcset.js";
|
|
import getConfigOptions from "./getConfigOptions.js";
|
|
import getFallbackImage from "./getFallbackImage.js";
|
|
import pMap from "p-map";
|
|
import { DEFAULT_IO_DELAY } from "../../constants.js";
|
|
|
|
function delay(ms = DEFAULT_IO_DELAY) {
|
|
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();
|
|
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) {
|
|
return { sources: [], sizes: {}, fallback: null, imagesizes: null };
|
|
}
|
|
}
|