-
Notifications
You must be signed in to change notification settings - Fork 1
/
eleventy.config.pictures.js
73 lines (59 loc) · 2.68 KB
/
eleventy.config.pictures.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
const path = require("path");
const eleventyImage = require("@11ty/eleventy-img");
module.exports = (eleventyConfig) => {
function relativeToInputPath(inputPath, relativeFilePath) {
let split = inputPath.split("/");
split.pop();
return path.resolve(split.join(path.sep), relativeFilePath);
}
// Eleventy Pictures shortcode
// EXAMPLE
// {% pictures
// {"desk":"https://res.cloudinary.com/nrityagram/image/upload/v1647179355/Space-cat2-desk_rix0hl.jpg",
// "tab":"https://res.cloudinary.com/nrityagram/image/upload/v1620417697/ipad/08-dhruva-ipad_ppl3ra.jpg",
// "mob":"https://res.cloudinary.com/nrityagram/image/upload/v1582614660/mobile/9_s1ma2d.jpg"},
// "Pictures Shortcode Test",
// {"mob": ["425"], "tab": ["768"], "desk":["1600"]}, {"desk":"65em", "tab":"50em", "mob":"35em"},
// "eager", "high" %}
eleventyConfig.addAsyncShortcode(
"pictures",
async function (srclist, alt = "Alt Text Req", widthslist, screenwidths, loadingOption, fetchPriorityOption, imgClass = "") {
// console.log("IMAGE CLASS = " + imgClass)
// fetchOption = low / high
// loadingOption = lazy / eager
// Warning: Avif can be resource-intensive so take care!
let formats = [ "webp" ];
// If you are loading images from local folder
// for (const key in srclist) {
// srclist[key] = relativeToInputPath(this.page.inputPath, srclist[key]);
// }
let metadatalist = {};
let metadataKeys = [ "desk", "tab", "mob" ];
for (const key of metadataKeys) {
metadatalist[ key ] = await eleventyImage(srclist[ key ], {
widths: widthslist[ key ] || [ "auto" ],
formats,
sharpWebpOptions: { quality: 90 },
webpQuality: 90,
outputDir: path.join(eleventyConfig.dir.output, "img"),
urlPath: "/img/",
});
}
// generate 6 source tags
// TODO: rewrite forEach loop using map() and join()
let sourceList = ''
metadataKeys.forEach(key => {
let formats = Object.keys(metadatalist[ key ])
formats.forEach(format => {
let formatDetails = metadatalist[ key ][ format ]
let source = `<source srcset="${formatDetails[ 0 ].url}" width="${formatDetails[ 0 ].width}" height="${formatDetails[ 0 ].height}" media="(min-width: ${screenwidths[ key ]})" type="image/${formatDetails[ 0 ].format}" />`
sourceList = sourceList.concat(source)
})
})
// create img string with webp from mobile
let imgData = metadatalist[ metadataKeys.slice(-1) ][ formats[ 0 ] ][ 0 ]
let imgElem = `<img src="${imgData.url}" width="${imgData.width}" height="${imgData.height}" alt="${alt}" fetchPriority="${fetchPriorityOption}" loading="${loadingOption}" class="${imgClass}"/>`
return `<picture>${sourceList}${imgElem}</picture>`
}
);
};