forked from nuotsu/sanitypress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Img.tsx
102 lines (94 loc) · 1.94 KB
/
Img.tsx
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
import {
useNextSanityImage,
type UseNextSanityImageOptions,
} from 'next-sanity-image'
import client from '@/lib/sanity/client'
import { urlFor } from '@/lib/sanity/urlFor'
import { stegaClean } from '@sanity/client/stega'
const SIZES = [
120, 160, 200, 240, 320, 400, 480, 520, 560, 600, 640, 800, 960, 1280, 1440,
1600, 1800, 2000,
]
export default function Img({
image,
imageWidth,
imageSizes = SIZES,
alt = '',
options,
...props
}: {
image: Sanity.Image | undefined
imageWidth?: number
imageSizes?: number[]
options?: UseNextSanityImageOptions
} & React.ImgHTMLAttributes<HTMLImageElement>) {
if (!image?.asset) return null
const { src, width, height } = useNextSanityImage(
client,
image,
imageWidth ? { imageBuilder: (b) => b.width(imageWidth) } : options,
)
return (
<img
src={src}
srcSet={
generateSrcset(image, { width: imageWidth, sizes: imageSizes }) || src
}
width={width}
height={height}
alt={stegaClean(image.alt) || alt}
loading={stegaClean(image.loading) || 'lazy'}
decoding="async"
{...props}
/>
)
}
export function Source({
image,
imageWidth,
imageSizes = SIZES,
options,
media = '(max-width: 768px)',
}: {
image: Sanity.Image | undefined
imageWidth?: number
imageSizes?: number[]
options?: UseNextSanityImageOptions
media?: string
}) {
if (!image) return null
const { src, width, height } = useNextSanityImage(
client,
image,
imageWidth ? { imageBuilder: (b) => b.width(imageWidth) } : options,
)
return (
<source
srcSet={
generateSrcset(image, { width: imageWidth, sizes: imageSizes }) || src
}
width={width}
height={height}
media={media}
/>
)
}
function generateSrcset(
image: Sanity.Image,
{
width,
sizes = SIZES,
}: {
width?: number
sizes: number[]
},
) {
return (
sizes
.filter((size) => !width || size <= width)
.map(
(size) => `${urlFor(image).width(size).auto('format').url()} ${size}w`,
)
.join(', ') || undefined
)
}