-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
extend-node-type.js
666 lines (597 loc) · 17.9 KB
/
extend-node-type.js
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
const fs = require(`fs`)
const path = require(`path`)
const crypto = require(`crypto`)
const Promise = require(`bluebird`)
const {
GraphQLObjectType,
GraphQLBoolean,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLJSON,
GraphQLNonNull,
} = require(`gatsby/graphql`)
const qs = require(`qs`)
const base64Img = require(`base64-img`)
const _ = require(`lodash`)
const cacheImage = require(`./cache-image`)
// By default store the images in `.cache` but allow the user to override
// and store the image cache away from the gatsby cache. After all, the gatsby
// cache is more likely to go stale than the images (which never go stale)
// Note that the same image might be requested multiple times in the same run
if (process.env.GATSBY_REMOTE_CACHE) {
console.warn(
`Please be aware that the \`GATSBY_REMOTE_CACHE\` env flag is not officially supported and could be removed at any time`
)
}
const REMOTE_CACHE_FOLDER =
process.env.GATSBY_REMOTE_CACHE ??
path.join(process.cwd(), `.cache/remote_cache`)
const CACHE_IMG_FOLDER = path.join(REMOTE_CACHE_FOLDER, `images`)
const {
ImageFormatType,
ImageResizingBehavior,
ImageCropFocusType,
} = require(`./schemes`)
// @see https://www.contentful.com/developers/docs/references/images-api/#/reference/resizing-&-cropping/specify-width-&-height
const CONTENTFUL_IMAGE_MAX_SIZE = 4000
const isImage = image =>
_.includes(
[`image/jpeg`, `image/jpg`, `image/png`, `image/webp`, `image/gif`],
_.get(image, `file.contentType`)
)
const getBase64Image = imageProps => {
if (!imageProps) return null
const requestUrl = `https:${imageProps.baseUrl}?w=20`
// Note: sha1 is unsafe for crypto but okay for this particular case
const shasum = crypto.createHash(`sha1`)
shasum.update(requestUrl)
const urlSha = shasum.digest(`hex`)
// TODO: Find the best place for this step. This is definitely not it.
fs.mkdirSync(CACHE_IMG_FOLDER, { recursive: true })
const cacheFile = path.join(CACHE_IMG_FOLDER, urlSha)
if (fs.existsSync(cacheFile)) {
// TODO: against dogma, confirm whether readFileSync is indeed slower
return fs.promises.readFile(cacheFile, `utf8`)
}
return new Promise(resolve => {
base64Img.requestBase64(requestUrl, (a, b, body) => {
// TODO: against dogma, confirm whether writeFileSync is indeed slower
fs.promises.writeFile(cacheFile, body).then(() => resolve(body))
})
})
}
const getBasicImageProps = (image, args) => {
let aspectRatio
if (args.width && args.height) {
aspectRatio = args.width / args.height
} else {
aspectRatio =
image.file.details.image.width / image.file.details.image.height
}
return {
baseUrl: image.file.url,
contentType: image.file.contentType,
aspectRatio,
width: image.file.details.image.width,
height: image.file.details.image.height,
}
}
const createUrl = (imgUrl, options = {}) => {
// Convert to Contentful names and filter out undefined/null values.
const args = _.pickBy(
{
w: options.width,
h: options.height,
fl: options.jpegProgressive ? `progressive` : null,
q: options.quality,
fm: options.toFormat || ``,
fit: options.resizingBehavior || ``,
f: options.cropFocus || ``,
bg: options.background || ``,
},
_.identity
)
return `${imgUrl}?${qs.stringify(args)}`
}
exports.createUrl = createUrl
const resolveFixed = (image, options) => {
if (!isImage(image)) return null
const { baseUrl, width, aspectRatio } = getBasicImageProps(image, options)
let desiredAspectRatio = aspectRatio
// If no dimension is given, set a default width
if (options.width === undefined && options.height === undefined) {
options.width = 400
}
// If we're cropping, calculate the specified aspect ratio.
if (options.width !== undefined && options.height !== undefined) {
desiredAspectRatio = options.width / options.height
}
// If the user selected a height and width (so cropping) and fit option
// is not set, we'll set our defaults
if (options.width !== undefined && options.height !== undefined) {
if (!options.resizingBehavior) {
options.resizingBehavior = `fill`
}
}
// Create sizes (in width) for the image. If the width of the
// image is 800px, the sizes would then be: 800, 1200, 1600,
// 2400.
//
// This is enough sizes to provide close to the optimal image size for every
// device size / screen resolution
let fixedSizes = []
fixedSizes.push(options.width)
fixedSizes.push(options.width * 1.5)
fixedSizes.push(options.width * 2)
fixedSizes.push(options.width * 3)
fixedSizes = fixedSizes.map(Math.round)
// Filter out sizes larger than the image's width and the contentful image's max size.
const filteredSizes = fixedSizes.filter(size => {
const calculatedHeight = Math.round(size / desiredAspectRatio)
return (
size <= CONTENTFUL_IMAGE_MAX_SIZE &&
calculatedHeight <= CONTENTFUL_IMAGE_MAX_SIZE &&
size <= width
)
})
// Sort sizes for prettiness.
const sortedSizes = _.sortBy(filteredSizes)
// Create the srcSet.
const srcSet = sortedSizes
.map((size, i) => {
let resolution
switch (i) {
case 0:
resolution = `1x`
break
case 1:
resolution = `1.5x`
break
case 2:
resolution = `2x`
break
case 3:
resolution = `3x`
break
default:
}
const h = Math.round(size / desiredAspectRatio)
return `${createUrl(baseUrl, {
...options,
width: size,
height: h,
})} ${resolution}`
})
.join(`,\n`)
let pickedHeight, pickedWidth
if (options.height) {
pickedHeight = options.height
pickedWidth = options.height * desiredAspectRatio
} else {
pickedHeight = options.width / desiredAspectRatio
pickedWidth = options.width
}
return {
aspectRatio: desiredAspectRatio,
baseUrl,
width: Math.round(pickedWidth),
height: Math.round(pickedHeight),
src: createUrl(baseUrl, {
...options,
width: options.width,
}),
srcSet,
}
}
exports.resolveFixed = resolveFixed
const resolveFluid = (image, options) => {
if (!isImage(image)) return null
const { baseUrl, width, aspectRatio } = getBasicImageProps(image, options)
let desiredAspectRatio = aspectRatio
// If no dimension is given, set a default maxWidth
if (options.maxWidth === undefined && options.maxHeight === undefined) {
options.maxWidth = 800
}
// If only a maxHeight is given, calculate the maxWidth based on the height and the aspect ratio
if (options.maxHeight !== undefined && options.maxWidth === undefined) {
options.maxWidth = Math.round(options.maxHeight * desiredAspectRatio)
}
// If we're cropping, calculate the specified aspect ratio.
if (options.maxHeight !== undefined && options.maxWidth !== undefined) {
desiredAspectRatio = options.maxWidth / options.maxHeight
}
// If the users didn't set a default sizes, we'll make one.
if (!options.sizes) {
options.sizes = `(max-width: ${options.maxWidth}px) 100vw, ${options.maxWidth}px`
}
// Create sizes (in width) for the image. If the max width of the container
// for the rendered markdown file is 800px, the sizes would then be: 200,
// 400, 800, 1200, 1600, 2400.
//
// This is enough sizes to provide close to the optimal image size for every
// device size / screen resolution
let fluidSizes = []
fluidSizes.push(options.maxWidth / 4)
fluidSizes.push(options.maxWidth / 2)
fluidSizes.push(options.maxWidth)
fluidSizes.push(options.maxWidth * 1.5)
fluidSizes.push(options.maxWidth * 2)
fluidSizes.push(options.maxWidth * 3)
fluidSizes = fluidSizes.map(Math.round)
// Filter out sizes larger than the image's maxWidth and the contentful image's max size.
const filteredSizes = fluidSizes.filter(size => {
const calculatedHeight = Math.round(size / desiredAspectRatio)
return (
size <= CONTENTFUL_IMAGE_MAX_SIZE &&
calculatedHeight <= CONTENTFUL_IMAGE_MAX_SIZE &&
size <= width
)
})
// Add the original image (if it isn't already in there) to ensure the largest image possible
// is available for small images.
if (
!filteredSizes.includes(parseInt(width)) &&
parseInt(width) < CONTENTFUL_IMAGE_MAX_SIZE &&
Math.round(width / desiredAspectRatio) < CONTENTFUL_IMAGE_MAX_SIZE
) {
filteredSizes.push(width)
}
// Sort sizes for prettiness.
const sortedSizes = _.sortBy(filteredSizes)
// Create the srcSet.
const srcSet = sortedSizes
.map(width => {
const h = Math.round(width / desiredAspectRatio)
return `${createUrl(image.file.url, {
...options,
width,
height: h,
})} ${Math.round(width)}w`
})
.join(`,\n`)
return {
aspectRatio: desiredAspectRatio,
baseUrl,
src: createUrl(baseUrl, {
...options,
width: options.maxWidth,
height: options.maxHeight,
}),
srcSet,
sizes: options.sizes,
}
}
exports.resolveFluid = resolveFluid
const resolveResize = (image, options) => {
if (!isImage(image)) return null
const { baseUrl, aspectRatio } = getBasicImageProps(image, options)
// If no dimension is given, set a default width
if (options.width === undefined && options.height === undefined) {
options.width = 400
}
// If the user selected a height and width (so cropping) and fit option
// is not set, we'll set our defaults
if (options.width !== undefined && options.height !== undefined) {
if (!options.resizingBehavior) {
options.resizingBehavior = `fill`
}
}
let pickedHeight = options.height,
pickedWidth = options.width
if (pickedWidth === undefined) {
pickedWidth = pickedHeight * aspectRatio
}
if (pickedHeight === undefined) {
pickedHeight = pickedWidth / aspectRatio
}
return {
src: createUrl(image.file.url, options),
width: Math.round(pickedWidth),
height: Math.round(pickedHeight),
aspectRatio,
baseUrl,
}
}
exports.resolveResize = resolveResize
const fixedNodeType = ({ name, getTracedSVG }) => {
return {
type: new GraphQLObjectType({
name: name,
fields: {
base64: {
type: GraphQLString,
resolve(imageProps) {
return getBase64Image(imageProps)
},
},
tracedSVG: {
type: GraphQLString,
resolve: getTracedSVG,
},
aspectRatio: { type: GraphQLFloat },
width: { type: new GraphQLNonNull(GraphQLFloat) },
height: { type: new GraphQLNonNull(GraphQLFloat) },
src: { type: new GraphQLNonNull(GraphQLString) },
srcSet: { type: new GraphQLNonNull(GraphQLString) },
srcWebp: {
type: GraphQLString,
resolve({ image, options, context }) {
if (
_.get(image, `file.contentType`) === `image/webp` ||
options.toFormat === `webp`
) {
return null
}
const fixed = resolveFixed(image, {
...options,
toFormat: `webp`,
})
return _.get(fixed, `src`)
},
},
srcSetWebp: {
type: GraphQLString,
resolve({ image, options, context }) {
if (
_.get(image, `file.contentType`) === `image/webp` ||
options.toFormat === `webp`
) {
return null
}
const fixed = resolveFixed(image, {
...options,
toFormat: `webp`,
})
return _.get(fixed, `srcSet`)
},
},
},
}),
args: {
width: {
type: GraphQLInt,
},
height: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
background: {
type: GraphQLString,
defaultValue: null,
},
},
resolve: (image, options, context) =>
Promise.resolve(resolveFixed(image, options)).then(node => {
if (!node) return null
return {
...node,
image,
options,
context,
}
}),
}
}
const fluidNodeType = ({ name, getTracedSVG }) => {
return {
type: new GraphQLObjectType({
name: name,
fields: {
base64: {
type: GraphQLString,
resolve(imageProps) {
return getBase64Image(imageProps)
},
},
tracedSVG: {
type: GraphQLString,
resolve: getTracedSVG,
},
aspectRatio: { type: new GraphQLNonNull(GraphQLFloat) },
src: { type: new GraphQLNonNull(GraphQLString) },
srcSet: { type: new GraphQLNonNull(GraphQLString) },
srcWebp: {
type: GraphQLString,
resolve({ image, options, context }) {
if (
_.get(image, `file.contentType`) === `image/webp` ||
options.toFormat === `webp`
) {
return null
}
const fluid = resolveFluid(image, {
...options,
toFormat: `webp`,
})
return _.get(fluid, `src`)
},
},
srcSetWebp: {
type: GraphQLString,
resolve({ image, options, context }) {
if (
_.get(image, `file.contentType`) === `image/webp` ||
options.toFormat === `webp`
) {
return null
}
const fluid = resolveFluid(image, {
...options,
toFormat: `webp`,
})
return _.get(fluid, `srcSet`)
},
},
sizes: { type: new GraphQLNonNull(GraphQLString) },
},
}),
args: {
maxWidth: {
type: GraphQLInt,
},
maxHeight: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
background: {
type: GraphQLString,
defaultValue: null,
},
sizes: {
type: GraphQLString,
},
},
resolve: (image, options, context) =>
Promise.resolve(resolveFluid(image, options)).then(node => {
if (!node) return null
return {
...node,
image,
options,
context,
}
}),
}
}
exports.extendNodeType = ({ type, store }) => {
if (type.name.match(/contentful.*RichTextNode/)) {
return {
nodeType: {
type: GraphQLString,
deprecationReason: `This field is deprecated, please use 'json' instead.`,
},
json: {
type: GraphQLJSON,
resolve: (source, fieldArgs) => {
const contentJSON = JSON.parse(source.internal.content)
return contentJSON
},
},
}
}
if (type.name !== `ContentfulAsset`) {
return {}
}
const getTracedSVG = async args => {
const { traceSVG } = require(`gatsby-plugin-sharp`)
const { image, options } = args
const {
file: { contentType },
} = image
if (contentType.indexOf(`image/`) !== 0) {
return null
}
const absolutePath = await cacheImage(store, image, options)
const extension = path.extname(absolutePath)
return traceSVG({
file: {
internal: image.internal,
name: image.file.fileName,
extension,
absolutePath,
},
args: { toFormat: `` },
fileArgs: options,
})
}
// TODO: Remove resolutionsNode and sizesNode for Gatsby v3
const fixedNode = fixedNodeType({ name: `ContentfulFixed`, getTracedSVG })
const resolutionsNode = fixedNodeType({
name: `ContentfulResolutions`,
getTracedSVG,
})
resolutionsNode.deprecationReason = `Resolutions was deprecated in Gatsby v2. It's been renamed to "fixed" https://example.com/write-docs-and-fix-this-example-link`
const fluidNode = fluidNodeType({ name: `ContentfulFluid`, getTracedSVG })
const sizesNode = fluidNodeType({ name: `ContentfulSizes`, getTracedSVG })
sizesNode.deprecationReason = `Sizes was deprecated in Gatsby v2. It's been renamed to "fluid" https://example.com/write-docs-and-fix-this-example-link`
return {
fixed: fixedNode,
resolutions: resolutionsNode,
fluid: fluidNode,
sizes: sizesNode,
resize: {
type: new GraphQLObjectType({
name: `ContentfulResize`,
fields: {
base64: {
type: GraphQLString,
resolve(imageProps) {
return getBase64Image(imageProps)
},
},
tracedSVG: {
type: GraphQLString,
resolve: getTracedSVG,
},
src: { type: GraphQLString },
width: { type: GraphQLInt },
height: { type: GraphQLInt },
aspectRatio: { type: GraphQLFloat },
},
}),
args: {
width: {
type: GraphQLInt,
},
height: {
type: GraphQLInt,
},
quality: {
type: GraphQLInt,
defaultValue: 50,
},
jpegProgressive: {
type: GraphQLBoolean,
defaultValue: true,
},
resizingBehavior: {
type: ImageResizingBehavior,
},
toFormat: {
type: ImageFormatType,
defaultValue: ``,
},
cropFocus: {
type: ImageCropFocusType,
defaultValue: null,
},
background: {
type: GraphQLString,
defaultValue: null,
},
},
resolve(image, options, context) {
return resolveResize(image, options)
},
},
}
}