wonderfulfrog.com/config/shortcodes/image.js
Devin Haska 08da130d58
Feat/add weekly notes 10 (#10)
* fix: update some asset URLs

* feat: add weekly-notes-10

* feat(weekly-notes-10): Add a little more

* feat(weekly-notes-10: proof-reading

* feat(weekly-notes-10): more content

* feat(weekly-notes-10): proof-read

* feat: add `flow` class to footnotes section

* fix: center images within picture element

* feat(weekly-notes-10): more content and added skip
2024-11-21 22:34:46 -08:00

76 lines
1.8 KiB
JavaScript

const Image = require("@11ty/eleventy-img");
const stringifyAttributes = (attributeMap) => {
return Object.entries(attributeMap)
.map(([attribute, value]) => {
if (typeof value === "undefined") return "";
return `${attribute}="${value}"`;
})
.join(" ");
};
const imageShortcode = async (
src,
alt = "",
caption = "",
className = undefined,
placeholder = "",
widths = [400, 800, 1280],
formats = ["webp", "jpeg"],
sizes = "100vw",
) => {
if (!src) {
return `<div class="image-placeholder">${placeholder}</div>`;
}
const metadata = await Image(src, {
widths: [...widths, null],
formats: [...formats, null],
outputDir: "dist/assets/images",
urlPath: "/assets/images",
sharpOptions: {
animated: true,
},
cacheOptions: {
duration: "7d",
},
});
const lowsrc = metadata.jpeg[metadata.jpeg.length - 1];
const imageSources = Object.values(metadata)
.map((imageFormat) => {
return ` <source type="${imageFormat[0].sourceType}" srcset="${imageFormat
.map((entry) => entry.srcset)
.join(", ")}" sizes="${sizes}">`;
})
.join("\n");
const imageAttributes = stringifyAttributes({
src: lowsrc.url,
width: lowsrc.width,
height: lowsrc.height,
alt,
loading: "lazy",
decoding: "async",
});
const imageElement = caption
? `<figure class="[ flow flex-col items-center justify-center ${className ? ` ${className} ` : ""}]">
<picture class="flex items-center justify-center">
${imageSources}
<img
${imageAttributes}>
</picture>
<figcaption>${caption}</figcaption>
</figure>`
: `<picture class="[ flex-col items-center justify-center ${className ? ` ${className} ` : ""}]">
${imageSources}
<img
${imageAttributes}>
</picture>`;
return imageElement;
};
module.exports = imageShortcode;