-
Notifications
You must be signed in to change notification settings - Fork 507
/
Copy pathimages-optimization.ts
336 lines (299 loc) · 9.23 KB
/
images-optimization.ts
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { getImage } from 'astro:assets';
import { transformUrl, parseUrl } from 'unpic';
import type { ImageMetadata } from 'astro';
import type { HTMLAttributes } from 'astro/types';
type Layout = 'fixed' | 'constrained' | 'fullWidth' | 'cover' | 'responsive' | 'contained';
export interface ImageProps extends Omit<HTMLAttributes<'img'>, 'src'> {
src?: string | ImageMetadata | null;
width?: string | number | null;
height?: string | number | null;
alt?: string | null;
loading?: 'eager' | 'lazy' | null;
decoding?: 'sync' | 'async' | 'auto' | null;
style?: string;
srcset?: string | null;
sizes?: string | null;
fetchpriority?: 'high' | 'low' | 'auto' | null;
layout?: Layout;
widths?: number[] | null;
aspectRatio?: string | number | null;
objectPosition?: string;
}
export type ImagesOptimizer = (
image: ImageMetadata | string,
breakpoints: number[],
width?: number,
height?: number
) => Promise<Array<{ src: string; width: number }>>;
/* ******* */
const config = {
// FIXME: Use this when image.width is minor than deviceSizes
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
deviceSizes: [
640, // older and lower-end phones
750, // iPhone 6-8
828, // iPhone XR/11
960, // older horizontal phones
1080, // iPhone 6-8 Plus
1280, // 720p
1668, // Various iPads
1920, // 1080p
2048, // QXGA
2560, // WQXGA
3200, // QHD+
3840, // 4K
4480, // 4.5K
5120, // 5K
6016, // 6K
],
formats: ['image/webp'],
};
const computeHeight = (width: number, aspectRatio: number) => {
return Math.floor(width / aspectRatio);
};
const parseAspectRatio = (aspectRatio: number | string | null | undefined): number | undefined => {
if (typeof aspectRatio === 'number') return aspectRatio;
if (typeof aspectRatio === 'string') {
const match = aspectRatio.match(/(\d+)\s*[/:]\s*(\d+)/);
if (match) {
const [, num, den] = match.map(Number);
if (den && !isNaN(num)) return num / den;
} else {
const numericValue = parseFloat(aspectRatio);
if (!isNaN(numericValue)) return numericValue;
}
}
return undefined;
};
/**
* Gets the `sizes` attribute for an image, based on the layout and width
*/
export const getSizes = (width?: number, layout?: Layout): string | undefined => {
if (!width || !layout) {
return undefined;
}
switch (layout) {
// If screen is wider than the max size, image width is the max size,
// otherwise it's the width of the screen
case `constrained`:
return `(min-width: ${width}px) ${width}px, 100vw`;
// Image is always the same width, whatever the size of the screen
case `fixed`:
return `${width}px`;
// Image is always the width of the screen
case `fullWidth`:
return `100vw`;
default:
return undefined;
}
};
const pixelate = (value?: number) => (value || value === 0 ? `${value}px` : undefined);
const getStyle = ({
width,
height,
aspectRatio,
layout,
objectFit = 'cover',
objectPosition = 'center',
background,
}: {
width?: number;
height?: number;
aspectRatio?: number;
objectFit?: string;
objectPosition?: string;
layout?: string;
background?: string;
}) => {
const styleEntries: Array<[prop: string, value: string | undefined]> = [
['object-fit', objectFit],
['object-position', objectPosition],
];
// If background is a URL, set it to cover the image and not repeat
if (background?.startsWith('https:') || background?.startsWith('http:') || background?.startsWith('data:')) {
styleEntries.push(['background-image', `url(${background})`]);
styleEntries.push(['background-size', 'cover']);
styleEntries.push(['background-repeat', 'no-repeat']);
} else {
styleEntries.push(['background', background]);
}
if (layout === 'fixed') {
styleEntries.push(['width', pixelate(width)]);
styleEntries.push(['height', pixelate(height)]);
styleEntries.push(['object-position', 'top left']);
}
if (layout === 'constrained') {
styleEntries.push(['max-width', pixelate(width)]);
styleEntries.push(['max-height', pixelate(height)]);
styleEntries.push(['aspect-ratio', aspectRatio ? `${aspectRatio}` : undefined]);
styleEntries.push(['width', '100%']);
}
if (layout === 'fullWidth') {
styleEntries.push(['width', '100%']);
styleEntries.push(['aspect-ratio', aspectRatio ? `${aspectRatio}` : undefined]);
styleEntries.push(['height', pixelate(height)]);
}
if (layout === 'responsive') {
styleEntries.push(['width', '100%']);
styleEntries.push(['height', 'auto']);
styleEntries.push(['aspect-ratio', aspectRatio ? `${aspectRatio}` : undefined]);
}
if (layout === 'contained') {
styleEntries.push(['max-width', '100%']);
styleEntries.push(['max-height', '100%']);
styleEntries.push(['object-fit', 'contain']);
styleEntries.push(['aspect-ratio', aspectRatio ? `${aspectRatio}` : undefined]);
}
if (layout === 'cover') {
styleEntries.push(['max-width', '100%']);
styleEntries.push(['max-height', '100%']);
}
const styles = Object.fromEntries(styleEntries.filter(([, value]) => value));
return Object.entries(styles)
.map(([key, value]) => `${key}: ${value};`)
.join(' ');
};
const getBreakpoints = ({
width,
breakpoints,
layout,
}: {
width?: number;
breakpoints?: number[];
layout: Layout;
}): number[] => {
if (layout === 'fullWidth' || layout === 'cover' || layout === 'responsive' || layout === 'contained') {
return breakpoints || config.deviceSizes;
}
if (!width) {
return [];
}
const doubleWidth = width * 2;
if (layout === 'fixed') {
return [width, doubleWidth];
}
if (layout === 'constrained') {
return [
// Always include the image at 1x and 2x the specified width
width,
doubleWidth,
// Filter out any resolutions that are larger than the double-res image
...(breakpoints || config.deviceSizes).filter((w) => w < doubleWidth),
];
}
return [];
};
/* ** */
export const astroAsseetsOptimizer: ImagesOptimizer = async (image, breakpoints, _width, _height) => {
if (!image) {
return [];
}
return Promise.all(
breakpoints.map(async (w: number) => {
const url = (await getImage({ src: image, width: w, inferSize: true })).src;
return {
src: url,
width: w,
};
})
);
};
export const isUnpicCompatible = (image: string) => {
return typeof parseUrl(image) !== 'undefined';
};
/* ** */
export const unpicOptimizer: ImagesOptimizer = async (image, breakpoints, width, height) => {
if (!image || typeof image !== 'string') {
return [];
}
const urlParsed = parseUrl(image);
if (!urlParsed) {
return [];
}
return Promise.all(
breakpoints.map(async (w: number) => {
const url =
transformUrl({
url: image,
width: w,
height: width && height ? computeHeight(w, width / height) : height,
cdn: urlParsed.cdn,
}) || image;
return {
src: String(url),
width: w,
};
})
);
};
/* ** */
export async function getImagesOptimized(
image: ImageMetadata | string,
{
src: _,
width,
height,
sizes,
aspectRatio,
objectPosition,
widths,
layout = 'constrained',
style = '',
...rest
}: ImageProps,
transform: ImagesOptimizer = () => Promise.resolve([])
): Promise<{ src: string; attributes: HTMLAttributes<'img'> }> {
if (typeof image !== 'string') {
width ||= Number(image.width) || undefined;
height ||= typeof width === 'number' ? computeHeight(width, image.width / image.height) : undefined;
}
width = (width && Number(width)) || undefined;
height = (height && Number(height)) || undefined;
widths ||= config.deviceSizes;
sizes ||= getSizes(Number(width) || undefined, layout);
aspectRatio = parseAspectRatio(aspectRatio);
// Calculate dimensions from aspect ratio
if (aspectRatio) {
if (width) {
if (height) {
/* empty */
} else {
height = width / aspectRatio;
}
} else if (height) {
width = Number(height * aspectRatio);
} else if (layout !== 'fullWidth') {
// Fullwidth images have 100% width, so aspectRatio is applicable
console.error('When aspectRatio is set, either width or height must also be set');
console.error('Image', image);
}
} else if (width && height) {
aspectRatio = width / height;
} else if (layout !== 'fullWidth') {
// Fullwidth images don't need dimensions
console.error('Either aspectRatio or both width and height must be set');
console.error('Image', image);
}
let breakpoints = getBreakpoints({ width: width, breakpoints: widths, layout: layout });
breakpoints = [...new Set(breakpoints)].sort((a, b) => a - b);
const srcset = (await transform(image, breakpoints, Number(width) || undefined, Number(height) || undefined))
.map(({ src, width }) => `${src} ${width}w`)
.join(', ');
return {
src: typeof image === 'string' ? image : image.src,
attributes: {
width: width,
height: height,
srcset: srcset || undefined,
sizes: sizes,
style: `${getStyle({
width: width,
height: height,
aspectRatio: aspectRatio,
objectPosition: objectPosition,
layout: layout,
})}${style ?? ''}`,
...rest,
},
};
}