-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
311 lines (263 loc) · 10.3 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
// const select = require(`unist-util-select`)
const _ = require(`lodash`)
const cheerio = require(`cheerio`)
const fetch = require("node-fetch")
const isRelativeUrl = require(`is-relative-url`)
const path = require(`path`)
const slash = require(`slash`)
const visitWithParents = require(`unist-util-visit-parents`)
const {fluid, getImageDimentions, createSignature} = require(`../gatsby-plugin-uplyfile`)
module.exports = async (
{ files, markdownNode, markdownAST, pathPrefix, getNode, reporter, cache }, pluginOptions
) => {
const findParentLinks = ({ children }) =>
children.some(
node =>
(node.type === `html` && !!node.value.match(/<a /)) ||
node.type === `link`
)
// This will allow the use of html image tags
// const rawHtmlNodes = select(markdownAST, `html`)
// let rawHtmlNodes = []
// visitWithParents(markdownAST, `html`, (node, ancestors) => {
// const inLink = ancestors.some(findParentLinks)
// rawHtmlNodes.push({ node, inLink })
// })
// console.log("rawHtmlNodes", rawHtmlNodes)
let markdownImageNodes = []
visitWithParents(markdownAST, `image`, (node, ancestors) => {
const inLink = ancestors.some(findParentLinks)
markdownImageNodes.push({ node, inLink })
})
var now = new Date();
var later = new Date();
later.setHours(now.getHours() + 2);
let expires = +later
let uplySignature = createSignature(pluginOptions.secretKey, expires)
var uplyfileSeverListCache = await cache.get("gatsby-remark-images-uplyfile-cache")
if (uplyfileSeverListCache === undefined) {
let response = await fetch(
"https://uplycdn.com/api/v1/files/",
// "http://localhost:8001/api/v1/files/",
{
headers: {
"Content-Type": "application/json",
"Uply-Public-Key": pluginOptions.publicKey,
"Uply-Signature": uplySignature,
"Uply-Expires": expires,
}
}
);
if (response.status != 200) {
if (response.status == 403) {
let error = await response.json()
console.log("ERROR:", error)
throw `Uplyfile files list endpoint returned ${response.status}.`
}
throw `Uplyfile files list endpoint returned ${response.status}.`
}
let filesList = await response.json()
uplyfileSeverListCache = {}
for (var i in filesList) {
let file = filesList[i]
uplyfileSeverListCache[file.etag] = file.url
}
await cache.set("gatsby-remark-images-uplyfile-cache", uplyfileSeverListCache)
}
const generateImagesAndUpdateNode = async function(node, resolve, inLink, uplyfileSeverListCache) {
// 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
console.log("node.url", node.url)
if (parentNode && parentNode.dir) {
imagePath = slash(path.join(parentNode.dir, node.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()
}
imageNode.internal.contentDigest
let url = uplyfileSeverListCache[imageNode.internal.contentDigest];
var imageUplyfile = null
for (let i in imageNode.children){
let childUID = imageNode.children[i]
let childNode = getNode(childUID)
if (childNode.internal.type == "ImageUplyfile") {
imageUplyfile = childNode
break;
}
}
console.log("imageNode", imageNode)
console.log("imageUplyfile", imageUplyfile)
var imageDimentions = getImageDimentions(imageNode.absolutePath)
let fluidResult = await fluid(url, {
maxWidth: pluginOptions.maxWidth,
width: imageDimentions.width,
height: imageDimentions.height,
imageWidth: imageDimentions.width,
})
console.log("fluidResult", fluidResult)
return `<img src="${url.full}" srcSet="${fluidResult.srcSet}" sizes="${fluidResult.sizes}">`
// 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 = node.url.split(`/`)
// const fileName = srcSplit[srcSplit.length - 1]
// const fileNameNoExt = fileName.replace(/\.[^/.]+$/, ``)
// const defaultAlt = fileNameNoExt.replace(/[^A-Z0-9]/gi, ` `)
// const imageStyle = `
// width: 100%;
// height: 100%;
// margin: 0;
// vertical-align: middle;
// position: absolute;
// top: 0;
// left: 0;
// box-shadow: inset 0px 0px 0px 400px ${options.backgroundColor};`.replace(
// /\s*(\S+:)\s*/g,
// `$1`
// )
// // Create our base image tag
// let imageTag = `
// <img
// class="${imageClass}"
// style="${imageStyle}"
// alt="${node.alt ? node.alt : defaultAlt}"
// title="${node.title ? node.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,
// defaults
// ),
// 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}"
// style="${imageStyle}"
// src="${fallbackSrc}"
// alt="${node.alt ? node.alt : defaultAlt}"
// title="${node.title ? node.title : ``}"
// />
// </picture>
// `.trim()
// }
// const ratio = `${(1 / fluidResult.aspectRatio) * 100}%`
// // Construct new image node w/ aspect ratio placeholder
// const showCaptions = options.showCaptions && node.title
// let rawHTML = `
// <span
// class="${imageWrapperClass}"
// style="position: relative; display: block; ${
// showCaptions ? `` : options.wrapperStyle
// } max-width: ${presentationWidth}px; margin-left: auto; margin-right: auto;"
// >
// <span
// class="${imageBackgroundClass}"
// style="padding-bottom: ${ratio}; position: relative; bottom: 0; left: 0; background-image: url('${
// fluidResult.base64
// }'); background-size: cover; display: block;"
// ></span>
// ${imageTag}
// </span>
// `.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()
// }
// // Wrap in figure and use title as caption
// if (showCaptions) {
// rawHTML = `
// <figure class="gatsby-resp-image-figure" style="${options.wrapperStyle}">
// ${rawHTML}
// <figcaption class="gatsby-resp-image-figcaption">${node.title}</figcaption>
// </figure>
// `.trim()
// }
// return rawHTML
}
// console.log("rawHtmlNodes", rawHtmlNodes)
markdownImageNodes.map(
({ node, inLink }) =>
new Promise(async (resolve, reject) => {
const fileType = node.url.slice(-3)
// 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,
uplyfileSeverListCache,
)
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()
}
})
)
}