polymech-astro/packages/imagetools_3/api/utils/getBreakpoints.js
2025-08-26 12:17:29 +02:00

78 lines
1.6 KiB
JavaScript

// @ts-check
import printWarning from "../../utils/printWarning.js";
export default function getBreakpoints(breakpoints, imageWidth) {
if (Array.isArray(breakpoints)) {
return breakpoints.sort((a, b) => a - b);
}
const { count, minWidth = 320 } = breakpoints || {};
const maxWidth = (() => {
if (breakpoints?.maxWidth) return breakpoints.maxWidth;
if (imageWidth > 3840) {
printWarning({
message:
"The width of the source image is greater than 3840px. The generated breakpoints will be capped at 3840px. If you need breakpoints larger than this, please pass the maxWidth option to the breakpoints property.",
});
return 3840;
}
return imageWidth;
})();
const breakPoints = [];
const diff = maxWidth - minWidth;
const n =
count ||
(maxWidth <= 400
? 1
: maxWidth <= 640
? 2
: maxWidth <= 800
? 3
: maxWidth <= 1024
? 4
: maxWidth <= 1280
? 5
: maxWidth <= 1440
? 6
: maxWidth <= 1920
? 7
: maxWidth <= 2560
? 8
: maxWidth <= 2880
? 9
: maxWidth <= 3840
? 10
: 11);
let currentWidth = minWidth;
n > 1 && breakPoints.push(currentWidth);
let steps = 0;
for (let i = 1; i < n; i++) {
steps += i;
}
const pixelsPerStep = diff / steps;
for (let i = 1; i < n - 1; i++) {
const next = pixelsPerStep * (n - i) + currentWidth;
breakPoints.push(Math.round(next));
currentWidth = next;
}
breakPoints.push(maxWidth);
return [...new Set(breakPoints)];
}