64 lines
1.5 KiB
JavaScript
64 lines
1.5 KiB
JavaScript
// @ts-check
|
|
import { getSrcPath } from "./getSrcPath.js";
|
|
|
|
export default async function getSrcset(
|
|
src,
|
|
base,
|
|
breakpoints,
|
|
format,
|
|
options
|
|
) {
|
|
options = {
|
|
format,
|
|
w: breakpoints,
|
|
...options,
|
|
};
|
|
|
|
const keys = Object.keys(options);
|
|
|
|
const params = keys.length
|
|
? keys
|
|
.map((key) =>
|
|
Array.isArray(options[key])
|
|
? `&${key}=${options[key].join(";")}`
|
|
: `&${key}=${options[key]}`
|
|
)
|
|
.join("")
|
|
: "";
|
|
|
|
// Extract existing search params from src
|
|
const [cleanSrc, search] = src.split("?");
|
|
|
|
// Combine existing params (like s=...) with options
|
|
// Existing params come first so they can be overridden by options if needed,
|
|
// though 's' should typically be unique.
|
|
const searchParams = new URLSearchParams(search);
|
|
|
|
// Add options to searchParams
|
|
keys.forEach(key => {
|
|
const value = Array.isArray(options[key])
|
|
? options[key].join(";")
|
|
: options[key];
|
|
searchParams.set(key, value);
|
|
});
|
|
|
|
const id = `${cleanSrc}?${searchParams.toString()}`;
|
|
// @todo : remove this
|
|
const fullPath = await getSrcPath(id);
|
|
const { default: load } = await import("../../plugin/hooks/load.js");
|
|
// @ts-ignore
|
|
let srcset = null
|
|
|
|
try {
|
|
|
|
const loaded = await load(fullPath, base);
|
|
if (loaded) {
|
|
srcset = loaded.slice(16, -1);
|
|
}
|
|
} catch (error) {
|
|
console.error(`getSrcset::Error loading image ${fullPath}:`, error.message);
|
|
return null;
|
|
}
|
|
|
|
return srcset;
|
|
} |