-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
index.js
261 lines (227 loc) · 7.72 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
const crypto = require(`crypto`)
const select = require(`unist-util-select`)
const sharp = require(`sharp`)
const axios = require(`axios`)
const _ = require(`lodash`)
const Promise = require(`bluebird`)
const cheerio = require(`cheerio`)
const { buildResponsiveSizes } = require(`./utils`)
// If the image is hosted on contentful
// 1. Find the image file
// 2. Find the image's size
// 3. Filter out any responsive image sizes that are greater than the image's width
// 4. Create the responsive images.
// 5. Set the html w/ aspect ratio helper.
module.exports = async (
{ files, markdownNode, markdownAST, pathPrefix, getNode, reporter, cache },
pluginOptions
) => {
const defaults = {
maxWidth: 650,
wrapperStyle: ``,
backgroundColor: `white`,
linkImagesToOriginal: true,
showCaptions: false,
pathPrefix,
withWebp: false,
}
// This will only work for markdown syntax image tags
const markdownImageNodes = select(markdownAST, `image`)
// This will also allow the use of html image tags
const rawHtmlNodes = select(markdownAST, `html`)
const generateImagesAndUpdateNode = async function(node, resolve) {
// Ignore if it is not contentful image
if (node.url.indexOf(`images.ctfassets.net`) === -1) {
return resolve()
}
let originalImg = node.url
if (!/^(http|https)?:\/\//i.test(node.url)) {
originalImg = `https:${node.url}`
}
const srcSplit = node.url.split(`/`)
const fileName = srcSplit[srcSplit.length - 1]
const options = _.defaults(pluginOptions, defaults)
const optionsHash = crypto
.createHash(`md5`)
.update(JSON.stringify(options))
.digest(`hex`)
const cacheKey = `remark-images-ctf-${fileName}-${optionsHash}`
let cahedRawHTML = await cache.get(cacheKey)
if (cahedRawHTML) {
return cahedRawHTML
}
const metaReader = sharp()
const response = await axios({
method: `GET`,
url: originalImg, // for some reason there is a './' prefix
responseType: `stream`,
})
response.data.pipe(metaReader)
const metadata = await metaReader.metadata()
response.data.destroy()
const responsiveSizesResult = await buildResponsiveSizes({
metadata,
imageUrl: originalImg,
options,
})
// Calculate the paddingBottom %
const ratio = `${(1 / responsiveSizesResult.aspectRatio) * 100}%`
const fallbackSrc = originalImg
const srcSet = responsiveSizesResult.srcSet
const presentationWidth = responsiveSizesResult.presentationWidth
// Generate default alt tag
const fileNameNoExt = fileName.replace(/\.[^/.]+$/, ``)
const defaultAlt = fileNameNoExt.replace(/[^A-Z0-9]/gi, ` `)
// Create our base image tag
let imageTag = `
<img
class="gatsby-resp-image-image"
style="width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px ${
options.backgroundColor
};"
alt="${node.alt ? node.alt : defaultAlt}"
title="${node.title ? node.title : ``}"
src="${fallbackSrc}"
srcset="${srcSet}"
sizes="${responsiveSizesResult.sizes}"
/>
`.trim()
// if options.withWebp is enabled, generate a webp version and change the image tag to a picture tag
if (options.withWebp) {
imageTag = `
<picture>
<source
srcset="${responsiveSizesResult.webpSrcSet}"
sizes="${responsiveSizesResult.sizes}"
type="image/webp"
/>
<source
srcset="${srcSet}"
sizes="${responsiveSizesResult.sizes}"
/>
<img
class="gatsby-resp-image-image"
style="width: 100%; height: 100%; margin: 0; vertical-align: middle; position: absolute; top: 0; left: 0; box-shadow: inset 0px 0px 0px 400px ${
options.backgroundColor
};"
alt="${node.alt ? node.alt : defaultAlt}"
title="${node.title ? node.title : ``}"
src="${fallbackSrc}"
/>
</picture>
`.trim()
}
// Construct new image node w/ aspect ratio placeholder
let rawHTML = `
<span
class="gatsby-resp-image-wrapper"
style="position: relative; display: block; ${
options.wrapperStyle
}; max-width: ${presentationWidth}px; margin-left: auto; margin-right: auto;"
>
<span
class="gatsby-resp-image-background-image"
style="padding-bottom: ${ratio}; position: relative; bottom: 0; left: 0; background-image: url('${
responsiveSizesResult.base64
}'); background-size: cover; display: block;"
>
${imageTag}
</span>
</span>
`.trim()
// Make linking to original image optional.
if (options.linkImagesToOriginal) {
rawHTML = `
<a
class="gatsby-resp-image-link"
href="${originalImg}"
style="display: block"
target="_blank"
rel="noopener"
>
${rawHTML}
</a>
`.trim()
}
// Wrap in figure and use title as caption
if (options.showCaptions && node.title) {
rawHTML = `
<figure class="gatsby-resp-image-figure">
${rawHTML}
<figcaption class="gatsby-resp-image-figcaption">${node.title}</figcaption>
</figure>`
}
await cache.set(cacheKey, rawHTML)
return rawHTML
}
return Promise.all(
// Simple because there is no nesting in markdown
markdownImageNodes.map(
node =>
new Promise(async (resolve, reject) => {
if (node.url.indexOf(`images.ctfassets.net`) !== -1) {
const rawHTML = await generateImagesAndUpdateNode(node, resolve)
if (rawHTML) {
// Replace the image node with an inline HTML node.
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 =>
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()
}
if (formattedImgTag.url.indexOf(`images.ctfassets.net`) !== -1) {
const rawHTML = await generateImagesAndUpdateNode(
formattedImgTag,
resolve
)
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)
)
)
}