-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
image-data.ts
352 lines (311 loc) · 8.91 KB
/
image-data.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/* eslint-disable no-unused-expressions */
import { IGatsbyImageData } from "gatsby-plugin-image"
import { GatsbyCache, Node } from "gatsby"
import { Reporter } from "gatsby-cli/lib/reporter/reporter"
import { rgbToHex, calculateImageSizes, getSrcSet, getSizes } from "./utils"
import { traceSVG, getImageSizeAsync, base64, batchQueueImageResizing } from "."
import sharp from "./safe-sharp"
import { createTransformObject } from "./plugin-options"
const DEFAULT_BLURRED_IMAGE_WIDTH = 20
type ImageFormat = "jpg" | "png" | "webp" | "avif" | "" | "auto"
export interface ISharpGatsbyImageArgs {
layout?: "fixed" | "fluid" | "constrained"
formats?: Array<ImageFormat>
placeholder?: "tracedSVG" | "dominantColor" | "blurred" | "none"
tracedSVGOptions?: Record<string, unknown>
width?: number
height?: number
maxWidth?: number
maxHeight?: number
sizes?: string
quality?: number
transformOptions: {
fit?: "contain" | "cover" | "fill" | "inside" | "outside"
cropFocus?: typeof sharp.strategy | typeof sharp.gravity | string
}
jpgOptions: Record<string, unknown>
pngOptions: Record<string, unknown>
webpOptions: Record<string, unknown>
avifOptions: Record<string, unknown>
blurredOptions: { width?: number; toFormat?: ImageFormat }
}
export type FileNode = Node & {
absolutePath?: string
extension: string
}
export interface IImageMetadata {
width?: number
height?: number
format?: string
density?: number
dominantColor?: string
}
const metadataCache = new Map<string, IImageMetadata>()
export async function getImageMetadata(
file: FileNode,
getDominantColor?: boolean
): Promise<IImageMetadata> {
if (!getDominantColor) {
// If we don't need the dominant color we can use the cheaper size function
const { width, height, type } = await getImageSizeAsync(file)
return { width, height, format: type }
}
let metadata = metadataCache.get(file.internal.contentDigest)
if (metadata && process.env.NODE_ENV !== `test`) {
return metadata
}
const pipeline = sharp(file.absolutePath)
const { width, height, density, format } = await pipeline.metadata()
const { dominant } = await pipeline.stats()
// Fallback in case sharp doesn't support dominant
const dominantColor = dominant
? rgbToHex(dominant.r, dominant.g, dominant.b)
: `#000000`
metadata = { width, height, density, format, dominantColor }
metadataCache.set(file.internal.contentDigest, metadata)
return metadata
}
export interface IImageDataProps {
file: FileNode
args: ISharpGatsbyImageArgs
cache: GatsbyCache
reporter: Reporter
}
export interface IImageDataArgs {
file: FileNode
args: ISharpGatsbyImageArgs
pathPrefix: string
cache: GatsbyCache
reporter: Reporter
}
function normalizeFormat(format: string): ImageFormat {
if (format === `jpeg`) {
return `jpg`
}
return format as ImageFormat
}
export async function generateImageData({
file,
args,
pathPrefix,
reporter,
cache,
}: IImageDataArgs): Promise<IGatsbyImageData | undefined> {
const {
layout = `constrained`,
placeholder = `blurred`,
tracedSVGOptions = {},
transformOptions = {},
quality,
} = args
args.formats = args.formats || [`auto`, `webp`]
const {
fit = `cover`,
cropFocus = sharp.strategy.attention,
} = transformOptions
const metadata = await getImageMetadata(file, placeholder === `dominantColor`)
if (layout === `fixed` && !args.width && !args.height) {
args.width = metadata.width
}
if (
layout !== `fixed` &&
!args.maxWidth &&
!args.maxHeight &&
metadata.width
) {
if (layout === `constrained`) {
args.maxWidth = metadata.width
} else if (layout === `fluid`) {
args.maxWidth = Math.round(metadata.width / 2)
}
}
const formats = new Set(args.formats)
let useAuto = formats.has(``) || formats.has(`auto`) || formats.size === 0
if (formats.has(`jpg`) && formats.has(`png`)) {
reporter.warn(
`Specifying both "jpg" and "png" formats is not supported and will be ignored. Please use "auto" instead.`
)
useAuto = true
}
let primaryFormat: ImageFormat | undefined
let options: Record<string, unknown> | undefined
if (useAuto) {
primaryFormat = normalizeFormat(metadata.format || file.extension)
} else if (formats.has(`png`)) {
primaryFormat = `png`
options = args.pngOptions
} else if (formats.has(`jpg`)) {
primaryFormat = `jpg`
options = args.jpgOptions
} else if (formats.has(`webp`)) {
primaryFormat = `webp`
options = args.webpOptions
} else if (formats.has(`avif`)) {
reporter.warn(
`Image ${file.relativePath} specified only AVIF format, with no fallback format. This will mean your site cannot be viewed in all browsers.`
)
primaryFormat = `avif`
options = args.webpOptions
}
const imageSizes: {
sizes: Array<number>
presentationWidth: number
presentationHeight: number
aspectRatio: number
unscaledWidth: number
} = calculateImageSizes({
file,
layout,
...args,
imgDimensions: metadata,
reporter,
})
const transforms = imageSizes.sizes.map(outputWidth => {
const width = Math.round(outputWidth)
const transform = createTransformObject({
quality,
...transformOptions,
fit,
cropFocus,
...options,
tracedSVGOptions,
width,
height: Math.round(width / imageSizes.aspectRatio),
toFormat: primaryFormat,
})
if (pathPrefix) transform.pathPrefix = pathPrefix
return transform
})
const images = batchQueueImageResizing({
file,
transforms,
reporter,
})
const srcSet = getSrcSet(images)
const sizes = args.sizes || getSizes(imageSizes.unscaledWidth, layout)
const primaryIndex = imageSizes.sizes.findIndex(
size => size === imageSizes.unscaledWidth
)
if (primaryIndex === -1) {
reporter.error(
`No image of the specified size found. Images may not have been processed correctly.`
)
return undefined
}
const primaryImage = images[primaryIndex]
if (!images?.length) {
return undefined
}
const imageProps: IGatsbyImageData = {
layout,
placeholder: undefined,
images: {
fallback: {
src: primaryImage.src,
srcSet,
sizes,
},
sources: [],
},
}
if (primaryFormat !== `avif` && formats.has(`avif`)) {
const transforms = imageSizes.sizes.map(outputWidth => {
const width = Math.round(outputWidth)
const transform = createTransformObject({
quality,
...transformOptions,
fit,
cropFocus,
...args.avifOptions,
width,
height: Math.round(width / imageSizes.aspectRatio),
toFormat: `avif`,
})
return transform
})
const avifImages = batchQueueImageResizing({
file,
transforms,
reporter,
})
imageProps.images.sources?.push({
srcSet: getSrcSet(avifImages),
type: `image/avif`,
sizes,
})
}
if (primaryFormat !== `webp` && formats.has(`webp`)) {
const transforms = imageSizes.sizes.map(outputWidth => {
const width = Math.round(outputWidth)
const transform = createTransformObject({
quality,
...transformOptions,
fit,
cropFocus,
...args.webpOptions,
width,
height: Math.round(width / imageSizes.aspectRatio),
toFormat: `webp`,
})
return transform
})
const webpImages = batchQueueImageResizing({
file,
transforms,
reporter,
})
imageProps.images.sources?.push({
srcSet: getSrcSet(webpImages),
type: `image/webp`,
sizes,
})
}
if (placeholder === `blurred`) {
const placeholderWidth =
args.blurredOptions?.width || DEFAULT_BLURRED_IMAGE_WIDTH
const { src: fallback } = await base64({
file,
args: {
...options,
...transformOptions,
fit,
cropFocus,
toFormatBase64: args.blurredOptions?.toFormat,
width: placeholderWidth,
height: Math.round(placeholderWidth / imageSizes.aspectRatio),
},
reporter,
})
imageProps.placeholder = {
fallback,
}
} else if (placeholder === `tracedSVG`) {
const fallback: string = await traceSVG({
file,
args: tracedSVGOptions,
fileArgs: args,
cache,
reporter,
})
imageProps.placeholder = {
fallback,
}
} else if (metadata.dominantColor) {
imageProps.backgroundColor = metadata.dominantColor
}
primaryImage.aspectRatio = primaryImage.aspectRatio || 1
switch (layout) {
case `fixed`:
imageProps.width = imageSizes.presentationWidth
imageProps.height = imageSizes.presentationHeight
break
case `fluid`:
imageProps.width = 1
imageProps.height = 1 / primaryImage.aspectRatio
break
case `constrained`:
imageProps.width = args.maxWidth || primaryImage.width || 1
imageProps.height = (imageProps.width || 1) / primaryImage.aspectRatio
}
return imageProps
}