File size: 939 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import NextImage, { ImageLoaderProps } from "next/image";
import { transformImageUrl } from "@kontent-ai/delivery-sdk";

const srcIsKontentAsset = (src: string) => {
  try {
    const { hostname } = new URL(src);
    return hostname.endsWith(".kc-usercontent.com");
  } catch {
    return false;
  }
};

const kontentImageLoader = ({
  src,
  width,
  quality = 75,
}: ImageLoaderProps): string => {
  return transformImageUrl(src)
    .withWidth(width)
    .withQuality(quality)
    .withCompression("lossless")
    .withAutomaticFormat()
    .getUrl();
};

const getLoader = (src: string) => {
  return srcIsKontentAsset(src) ? kontentImageLoader : undefined;
};

type ImageType = {
  width?: number;
  height?: number;
  src: string;
  layout?: string;
  className: string;
  alt: string;
};

export default function Image(props: ImageType) {
  const loader = getLoader(props.src);

  return <NextImage {...props} loader={loader} />;
}