-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.astro
106 lines (96 loc) · 2.56 KB
/
index.astro
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
---
import { type ImgAttributes, getImage } from 'astro:assets'
import type { ImageMetadata, ImageOutputFormat } from 'astro'
import styles from './index.module.css'
type Props = ImgAttributes & {
src: ImageMetadata
width: number
height?: number
class?: string
objectFit?: boolean
}
const {
title,
alt,
src,
class: className,
width,
height,
objectFit
} = Astro.props
const formats: ImageOutputFormat[] = ['webp', 'jpg']
const sizes = [
Math.round(Number(width) / 2),
Number(width),
Math.round(Number(width) * 2)
]
const originalSize = src.width
const images: { format: ImageOutputFormat; size: number; src: string }[] = []
const srcFallback = await getImage({
src,
width: Math.round(Number(width) / 2),
format: 'jpg'
})
for (const format of formats) {
for (const size of sizes) {
const image = await getImage({ src, width: size, format, quality: 75 })
// Check if the original image is smaller than the target size,
// if the image is smaller, add the original size instead
images.push({
format,
size: originalSize >= size ? size : originalSize,
src: image.src
})
}
}
// Generate srcSet strings
const srcSetStrings = formats.reduce((acc: Record<string, string>, format) => {
const filteredImages = images.filter((img) => img.format === format)
acc[format] = filteredImages
.map((img) => `${img.src} ${img.size}w`)
.join(', ')
return acc
}, {})
---
<figure
class={`picture ${styles.image} ${className ? className : ''} ${
objectFit ? styles['objectFit'] : ''
}`}
>
{
objectFit ? (
<div style={`max-width:${width}px;display:block`}>
<img
aria-hidden="true"
src={`data:image/svg+xml;charset=utf-8,%3Csvg%20height="${height}"%20width="${width}"%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%3E%3C/svg%3E`}
style="max-width:100%;display:block;position:static"
alt="placeholder"
/>
</div>
) : null
}
<picture>
{
formats
.filter((format) => format !== 'jpg')
.map((format) => (
<source
type={`image/${format}`}
srcset={srcSetStrings[format]}
sizes={`(min-width: ${width}px) ${width}px, 100vw`}
/>
))
}
<img
width={width}
height={height}
sizes={`(min-width: ${width}px) ${width}px, 100vw`}
decoding="async"
loading="lazy"
src={srcFallback.src}
srcset={srcSetStrings['jpg']}
alt={alt}
/>
</picture>
{title && <figcaption class={styles.imageTitle}>{title}</figcaption>}
</figure>