/
index.js
416 lines (366 loc) · 11.6 KB
/
index.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
const {
DEFAULT_OPTIONS,
imageClass,
imageBackgroundClass,
imageWrapperClass,
} = require(`./constants`)
const visitWithParents = require(`unist-util-visit-parents`)
const getDefinitions = require(`mdast-util-definitions`)
const path = require(`path`)
const queryString = require(`query-string`)
const isRelativeUrl = require(`is-relative-url`)
const _ = require(`lodash`)
const { fluid, traceSVG } = require(`gatsby-plugin-sharp`)
const Promise = require(`bluebird`)
const cheerio = require(`cheerio`)
const slash = require(`slash`)
// If the image is relative (not hosted elsewhere)
// 1. Find the image file
// 2. Find the image's size
// 3. Filter out any responsive image fluid sizes that are greater than the image's width
// 4. Create the responsive images.
// 5. Set the html w/ aspect ratio helper.
module.exports = (
{ files, markdownNode, markdownAST, pathPrefix, getNode, reporter, cache },
pluginOptions
) => {
const options = _.defaults(pluginOptions, { pathPrefix }, DEFAULT_OPTIONS)
const findParentLinks = ({ children }) =>
children.some(
node =>
(node.type === `html` && !!node.value.match(/<a /)) ||
node.type === `link`
)
// Get all the available definitions in the markdown tree
const definitions = getDefinitions(markdownAST)
// This will allow the use of html image tags
// const rawHtmlNodes = select(markdownAST, `html`)
let rawHtmlNodes = []
visitWithParents(markdownAST, [`html`, `jsx`], (node, ancestors) => {
const inLink = ancestors.some(findParentLinks)
rawHtmlNodes.push({ node, inLink })
})
// This will only work for markdown syntax image tags
let markdownImageNodes = []
visitWithParents(
markdownAST,
[`image`, `imageReference`],
(node, ancestors) => {
const inLink = ancestors.some(findParentLinks)
markdownImageNodes.push({ node, inLink })
}
)
const getImageInfo = uri => {
const { url, query } = queryString.parseUrl(uri)
return {
ext: path
.extname(url)
.split(`.`)
.pop(),
url,
query,
}
}
const getImageCaption = (node, alt, defaultAlt) => {
const captionOptions = Array.isArray(options.showCaptions)
? options.showCaptions
: options.showCaptions === true
? [`title`, `alt`]
: false
if (captionOptions) {
for (const option of captionOptions) {
switch (option) {
case `title`:
if (node.title) {
return node.title
}
break
case `alt`:
if (alt && alt !== defaultAlt) {
return alt
}
break
}
}
}
return ``
}
// Takes a node and generates the needed images and then returns
// the needed HTML replacement for the image
const generateImagesAndUpdateNode = async function(
node,
resolve,
inLink,
overWrites = {}
) {
// Check if this markdownNode has a File parent. This plugin
// won't work if the image isn't hosted locally.
const parentNode = getNode(markdownNode.parent)
let imagePath
if (parentNode && parentNode.dir) {
imagePath = slash(path.join(parentNode.dir, getImageInfo(node.url).url))
} else {
return null
}
const imageNode = _.find(files, file => {
if (file && file.absolutePath) {
return file.absolutePath === imagePath
}
return null
})
if (!imageNode || !imageNode.absolutePath) {
return resolve()
}
let fluidResult = await fluid({
file: imageNode,
args: options,
reporter,
cache,
})
if (!fluidResult) {
return resolve()
}
const originalImg = fluidResult.originalImg
const fallbackSrc = fluidResult.src
const srcSet = fluidResult.srcSet
const presentationWidth = fluidResult.presentationWidth
// Generate default alt tag
const srcSplit = getImageInfo(node.url).url.split(`/`)
const fileName = srcSplit[srcSplit.length - 1]
const fileNameNoExt = fileName.replace(/\.[^/.]+$/, ``)
const defaultAlt = fileNameNoExt.replace(/[^A-Z0-9]/gi, ` `)
const alt = _.escape(
overWrites.alt ? overWrites.alt : node.alt ? node.alt : defaultAlt
)
const title = node.title ? node.title : alt
// Create our base image tag
let imageTag = `
<img
class="${imageClass}"
alt="${alt}"
title="${title}"
src="${fallbackSrc}"
srcset="${srcSet}"
sizes="${fluidResult.sizes}"
/>
`.trim()
// if options.withWebp is enabled, generate a webp version and change the image tag to a picture tag
if (options.withWebp) {
const webpFluidResult = await fluid({
file: imageNode,
args: _.defaults(
{ toFormat: `WEBP` },
// override options if it's an object, otherwise just pass through defaults
options.withWebp === true ? {} : options.withWebp,
pluginOptions,
DEFAULT_OPTIONS
),
reporter,
})
if (!webpFluidResult) {
return resolve()
}
imageTag = `
<picture>
<source
srcset="${webpFluidResult.srcSet}"
sizes="${webpFluidResult.sizes}"
type="${webpFluidResult.srcSetType}"
/>
<source
srcset="${srcSet}"
sizes="${fluidResult.sizes}"
type="${fluidResult.srcSetType}"
/>
<img
class="${imageClass}"
src="${fallbackSrc}"
alt="${alt}"
title="${title}"
/>
</picture>
`.trim()
}
let placeholderImageData = fluidResult.base64
// if options.tracedSVG is enabled generate the traced SVG and use that as the placeholder image
if (options.tracedSVG) {
let args = typeof options.tracedSVG === `object` ? options.tracedSVG : {}
// Translate Potrace constants (e.g. TURNPOLICY_LEFT, COLOR_AUTO) to the values Potrace expects
const { Potrace } = require(`potrace`)
const argsKeys = Object.keys(args)
args = argsKeys.reduce((result, key) => {
const value = args[key]
result[key] = Potrace.hasOwnProperty(value) ? Potrace[value] : value
return result
}, {})
const tracedSVG = await traceSVG({
file: imageNode,
args,
fileArgs: args,
cache,
reporter,
})
// Escape single quotes so the SVG data can be used in inline style attribute with single quotes
placeholderImageData = tracedSVG.replace(/'/g, `\\'`)
}
const ratio = `${(1 / fluidResult.aspectRatio) * 100}%`
const wrapperStyle =
typeof options.wrapperStyle === `function`
? options.wrapperStyle(fluidResult)
: options.wrapperStyle
// Construct new image node w/ aspect ratio placeholder
const imageCaption =
options.showCaptions && getImageCaption(node, alt, defaultAlt)
let rawHTML = `
<span
class="${imageBackgroundClass}"
style="padding-bottom: ${ratio}; position: relative; bottom: 0; left: 0; background-image: url('${placeholderImageData}'); background-size: cover; display: block;"
></span>
${imageTag}
`.trim()
// Make linking to original image optional.
if (!inLink && options.linkImagesToOriginal) {
rawHTML = `
<a
class="gatsby-resp-image-link"
href="${originalImg}"
style="display: block"
target="_blank"
rel="noopener"
>
${rawHTML}
</a>
`.trim()
}
rawHTML = `
<span
class="${imageWrapperClass}"
style="position: relative; display: block; margin-left: auto; margin-right: auto; ${
imageCaption ? `` : wrapperStyle
} max-width: ${presentationWidth}px;"
>
${rawHTML}
</span>
`.trim()
// Wrap in figure and use title as caption
if (imageCaption) {
rawHTML = `
<figure class="gatsby-resp-image-figure" style="${wrapperStyle}">
${rawHTML}
<figcaption class="gatsby-resp-image-figcaption">${imageCaption}</figcaption>
</figure>
`.trim()
}
return rawHTML
}
return Promise.all(
// Simple because there is no nesting in markdown
markdownImageNodes.map(
({ node, inLink }) =>
new Promise(async (resolve, reject) => {
const overWrites = {}
let refNode
if (
!node.hasOwnProperty(`url`) &&
node.hasOwnProperty(`identifier`)
) {
//consider as imageReference node
refNode = node
node = definitions(refNode.identifier)
// pass original alt from referencing node
overWrites.alt = refNode.alt
if (!node) {
// no definition found for image reference,
// so there's nothing for us to do.
return resolve()
}
}
const fileType = getImageInfo(node.url).ext
// Ignore gifs as we can't process them,
// svgs as they are already responsive by definition
if (
isRelativeUrl(node.url) &&
fileType !== `gif` &&
fileType !== `svg`
) {
const rawHTML = await generateImagesAndUpdateNode(
node,
resolve,
inLink,
overWrites
)
if (rawHTML) {
// Replace the image or ref node with an inline HTML node.
if (refNode) {
node = refNode
}
node.type = `html`
node.value = rawHTML
}
return resolve(node)
} else {
// Image isn't relative so there's nothing for us to do.
return resolve()
}
})
)
).then(markdownImageNodes =>
// HTML image node stuff
Promise.all(
// Complex because HTML nodes can contain multiple images
rawHtmlNodes.map(
({ node, inLink }) =>
new Promise(async (resolve, reject) => {
if (!node.value) {
return resolve()
}
const $ = cheerio.load(node.value)
if ($(`img`).length === 0) {
// No img tags
return resolve()
}
let imageRefs = []
$(`img`).each(function() {
imageRefs.push($(this))
})
for (let thisImg of imageRefs) {
// Get the details we need.
let formattedImgTag = {}
formattedImgTag.url = thisImg.attr(`src`)
formattedImgTag.title = thisImg.attr(`title`)
formattedImgTag.alt = thisImg.attr(`alt`)
if (!formattedImgTag.url) {
return resolve()
}
const fileType = getImageInfo(formattedImgTag.url).ext
// Ignore gifs as we can't process them,
// svgs as they are already responsive by definition
if (
isRelativeUrl(formattedImgTag.url) &&
fileType !== `gif` &&
fileType !== `svg`
) {
const rawHTML = await generateImagesAndUpdateNode(
formattedImgTag,
resolve,
inLink
)
if (rawHTML) {
// Replace the image string
thisImg.replaceWith(rawHTML)
} else {
return resolve()
}
}
}
// Replace the image node with an inline HTML node.
node.type = `html`
node.value = $(`body`).html() // fix for cheerio v1
return resolve(node)
})
)
).then(htmlImageNodes =>
markdownImageNodes.concat(htmlImageNodes).filter(node => !!node)
)
)
}