-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
img2picture.js
262 lines (230 loc) · 6.81 KB
/
img2picture.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
// @ts-check
const cheerio = require("cheerio");
const Image = require("@11ty/eleventy-img");
const path = require("path");
const debug = require("debug")("img2picture");
const {
isUrl,
isAllowedExtension,
generateWidths,
objectToAttributes,
hasBodyTag,
} = require("./helpers.js");
/**
* @typedef {(id?: string, src?: string, width?: string, format?: string, options?: object) => string} filenameFormatFn
*/
/**
* @typedef {Object} Img2PictureOptions
* @property {string=} eleventyInputDir
* @property {string=} imagesOutputDir
* @property {string=} urlPath
* @property {Array<string>=} extensions
* @property {Array<string>=} formats
* @property {string=} sizes
* @property {number=} minWidth
* @property {number=} maxWidth
* @property {number=} widthStep
* @property {filenameFormatFn=} filenameFormat
* @property {boolean=} fetchRemote
* @property {boolean=} dryRun
* @property {Object=} sharpOptions
* @property {Object=} cacheOptions
* @property {Object=} sharpWebpOptions
* @property {Object=} sharpPngOptions
* @property {Object=} sharpJpegOptions
* @property {Object=} sharpAvifOptions
*/
/** @type {Img2PictureOptions} */
const defaultOptions = {
eleventyInputDir: ".",
imagesOutputDir: "_site",
urlPath: "",
extensions: ["jpg", "png", "jpeg"],
formats: ["avif", "webp", "jpeg"],
sizes: "100vw",
minWidth: 150,
maxWidth: 1500,
widthStep: 150,
fetchRemote: false,
dryRun: false,
cacheOptions: {},
sharpOptions: {},
sharpWebpOptions: {},
sharpPngOptions: {},
sharpJpegOptions: {},
sharpAvifOptions: {},
};
/**
* Remove attributes which are unnecessary
*
* @param {Object} obj The object
* @return {Object}
*/
function cleanAttributes(obj) {
const cleanedObj = { ...obj };
delete cleanedObj["data-img2picture-ignore"];
delete cleanedObj.src;
delete cleanedObj.class;
delete cleanedObj.width;
delete cleanedObj.height;
delete cleanedObj.sizes;
return cleanedObj;
}
/**
* Generates image filename
* @type filenameFormatFn
*/
const filenameFormatter = function (id, src, width, format) {
const extension = path.extname(src);
const name = path.basename(src, extension);
return `${name}-${id}-${width}w.${format}`;
};
/**
*
* Returns the last (assumed to be most compatible) format metadata
*
*
* @param {Object} metadata The metadata
* @param {Img2PictureOptions} options The options
* @return {Object} The the last from metadata
*/
const getFallbackFormat = (metadata, options) => {
const { formats } = options;
const fallbackFormat = formats[formats.length - 1];
return metadata[fallbackFormat];
};
/**
* Generates <picture> elements from Image metadata
*
* @param {Object} metadata The metadata
* @param {Object} attrs The attributes
* @param {Img2PictureOptions} options The options
* @return {string} The <picture> element
*/
function generatePicture(metadata, attrs, options) {
const { sizes } = options;
const pictureAttrs = {
class: attrs.class,
};
const imgAttrs = {
...cleanAttributes(attrs),
loading: attrs.loading || "lazy",
decoding: attrs.decoding || "async",
};
const fallbackFormat = getFallbackFormat(metadata, options);
const lowsrc = fallbackFormat[0];
const highsrc = fallbackFormat[fallbackFormat.length - 1];
return `<picture${objectToAttributes(pictureAttrs)}>${Object.values(metadata)
.map((imageFormat) => {
return `<source type="${imageFormat[0].sourceType}" srcset="${imageFormat
.map((entry) => entry.srcset)
.join(", ")}" sizes="${attrs.sizes || sizes}">`;
})
.join("")}<img
src="${lowsrc.url}"
width="${highsrc.width}"
height="${highsrc.height}"
${objectToAttributes(imgAttrs)}></picture>`;
}
/**
* Generate responsive image files returns corresponding <picture> element
*
* @param {Record<string, string>} attrs The attributes
* @param {Img2PictureOptions} options The options
* @return {Promise} { description_of_the_return_value }
*/
async function generateImage(attrs, options) {
const {
cacheOptions,
dryRun,
eleventyInputDir,
filenameFormat,
formats,
imagesOutputDir,
maxWidth,
minWidth,
sharpAvifOptions,
sharpJpegOptions,
sharpOptions,
sharpPngOptions,
sharpWebpOptions,
urlPath,
widthStep,
} = options;
const widths = generateWidths(minWidth, maxWidth, widthStep);
const { src } = attrs;
const filePath = isUrl(src) ? src : path.join(eleventyInputDir, src);
const filenameFormatFn =
typeof filenameFormat === "function" ? filenameFormat : filenameFormatter;
// eslint-disable-next-line new-cap
const metadata = await Image(filePath, {
formats,
filenameFormat: filenameFormatFn,
widths,
urlPath,
outputDir: imagesOutputDir,
sharpOptions,
sharpWebpOptions,
sharpPngOptions,
sharpJpegOptions,
sharpAvifOptions,
dryRun,
cacheOptions,
});
return generatePicture(metadata, attrs, options);
}
/**
* Replaces local path <img> tags using <picture>
* with different sizes and formats
*
* @param {string} content The content
* @param {Img2PictureOptions} options The options
* @return {Promise<string>} HTML content with <img> replaced with <picture> elements
*/
async function replaceImages(content, options) {
const { extensions, fetchRemote } = options;
const $ = cheerio.load(content);
let images = $("img")
.not("picture img") // Ignore images wrapped in <picture>
.not("[data-img2picture-ignore]") // Ignore excluded images
.filter((i, el) => {
const src = $(el).attr("src");
return isAllowedExtension(src, extensions);
});
// Ignore remote images if fetchRemote is false
if (!fetchRemote) {
images = images.filter((i, el) => {
const src = $(el).attr("src");
return !isUrl(src);
});
}
const promises = [];
for (let i = 0; i < images.length; i++) {
const img = images[i];
const attrs = $(img).attr();
debug(`Optimizing: ${attrs.src}`);
promises[i] = generateImage(attrs, options);
}
const pictures = await Promise.all(promises);
pictures.forEach((picture, i) => {
$(images[i]).replaceWith(picture);
});
return hasBodyTag(content) ? $.html() : $("body").html();
}
/**
* Initialise transformer function
*
* @param {Img2PictureOptions=} userOptions The options
* @return {(content: string) => Promise<string>} The transformer function
*/
function img2picture(userOptions) {
/** @type {Img2PictureOptions} */
const options = { ...defaultOptions, ...(userOptions || {}) };
return async function (content, outputPath) {
if (outputPath && outputPath.endsWith(".html")) {
return replaceImages(content, options);
}
return content;
};
}
module.exports = img2picture;