Files
web/packages/design-system/lib/components/Image/imageLoader.ts
Rasmus Langvad d0546926a9 Merged in fix/3697-prettier-configs (pull request #3396)
fix(SW-3691): Setup one prettier config for whole repo

* Setup prettierrc in root and remove other configs


Approved-by: Joakim Jäderberg
Approved-by: Linus Flood
2026-01-07 12:45:50 +00:00

58 lines
1.5 KiB
TypeScript

import { ImageLoaderProps } from "next/image"
export const imageLoader =
({
dimensions,
}: {
focalPoint?: { x: number; y: number }
dimensions?: { width: number; height: number }
}) =>
({ quality, src, width }: ImageLoaderProps) => {
const isAbsoluteUrl =
src.startsWith("https://") || src.startsWith("http://")
const hasQS = src.indexOf("?") !== -1
if (
dimensions &&
isLargerThanAspectRatio(dimensions, "3:2") &&
width < dimensions.width
) {
// If image is wider than 3:2, compensate for low height when rendering in a 3:2 container
const scale = width / dimensions.width
const minWidthFor32Aspect =
dimensions.height * scale * aspectRatios["3:2"] * 2
width = Math.max(minWidthFor32Aspect, width)
}
if (width < 500) {
// Compensate for bad resizing library used by netlify
width += width / 2
}
width = roundToNearest(width, 10)
if (isAbsoluteUrl) {
return `https://img.scandichotels.com/.netlify/images?url=${src}&w=${width}${quality ? "&q=" + quality : ""}`
}
return `${src}${hasQS ? "&" : "?"}w=${width}${quality ? "&q=" + quality : ""}`
}
const aspectRatios = {
"3:2": 3 / 2,
}
function isLargerThanAspectRatio(
dimensions: {
width: number
height: number
},
aspectRatio: keyof typeof aspectRatios
) {
return dimensions.width / dimensions.height > aspectRatios[aspectRatio]
}
function roundToNearest(value: number, nearest: number) {
return Math.ceil(value / nearest) * nearest
}