-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathImg.tsx
117 lines (105 loc) · 2.28 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import {
useNextSanityImage,
type UseNextSanityImageOptions,
} from 'next-sanity-image'
import { client } from '@/sanity/lib/client'
import { urlFor } from '@/sanity/lib/image'
import { preload } from 'react-dom'
import { stegaClean } from 'next-sanity'
const SIZES = [
120, 240, 360, 480, 640, 720, 800, 880, 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,
)
if (stegaClean(image.loading) === 'eager') {
preload(src, { as: 'image' })
}
return (
<img
src={src}
{...generateSrcset(image, { width: imageWidth, sizes: imageSizes })}
width={width}
height={height}
alt={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?.asset) return null
const { src, width, height } = useNextSanityImage(
client,
image,
imageWidth ? { imageBuilder: (b) => b.width(imageWidth) } : options,
)
if (stegaClean(image.loading) === 'eager') {
preload(src, { as: 'image' })
}
return (
<source
{...generateSrcset(image, { width: imageWidth, sizes: imageSizes })}
width={width}
height={height}
media={media}
/>
)
}
function generateSrcset(
image: Sanity.Image,
{
width,
sizes = SIZES,
}: {
width?: number
sizes: number[]
},
) {
const filtered = sizes.filter((size) => !width || size <= width)
return {
srcSet:
filtered
.map(
(size) =>
`${urlFor(image).width(size).auto('format').url()} ${size}w`,
)
.join(', ') || undefined,
sizes:
filtered
.map(
(size, i) =>
`${i < filtered.length - 1 ? `(max-width: ${size + 1}px) ` : ''}${size}px`,
)
.join(', ') || undefined,
}
}