summaryrefslogtreecommitdiff
path: root/src/components/common/Image.astro
blob: d113b68a75a8f30cc60f78dbee93967369085434 (plain)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
---
import type { HTMLAttributes } from 'astro/types';
import { findImage } from '~/utils/images';
import {
  getImagesOptimized,
  astroAssetsOptimizer,
  unpicOptimizer,
  isUnpicCompatible,
  type ImageProps,
} from '~/utils/images-optimization';

type Props = ImageProps;
type ImageType = {
  src: string;
  attributes: HTMLAttributes<'img'>;
};

const props = Astro.props;

if (props.alt === undefined || props.alt === null) {
  throw new Error();
}

if (typeof props.width === 'string') {
  props.width = parseInt(props.width);
}

if (typeof props.height === 'string') {
  props.height = parseInt(props.height);
}

if (!props.loading) {
  props.loading = 'lazy';
}

if (!props.decoding) {
  props.decoding = 'async';
}

const _image = await findImage(props.src);

let image: ImageType | undefined = undefined;

if (
  typeof _image === 'string' &&
  (_image.startsWith('http://') || _image.startsWith('https://')) &&
  isUnpicCompatible(_image)
) {
  image = await getImagesOptimized(_image, props, unpicOptimizer);
} else if (_image) {
  image = await getImagesOptimized(_image, props, astroAssetsOptimizer);
}
---

{
  !image ? (
    <Fragment />
  ) : (
    <img src={image.src} crossorigin="anonymous" referrerpolicy="no-referrer" {...image.attributes} />
  )
}