feat: update image shortcode to use captions

This commit is contained in:
Devin Haska 2024-02-19 14:12:17 -08:00
parent 28baa94b93
commit b717907ab8
26 changed files with 89 additions and 53 deletions

View file

@ -1,8 +1,18 @@
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,
alt = "",
caption = "",
className = undefined,
widths = [400, 800, 1280],
formats = ["webp", "jpeg"],
@ -15,19 +25,41 @@ const imageShortcode = async (
urlPath: "/assets/images",
});
let imageAttributes = {
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,
sizes,
loading: "lazy",
decoding: "async",
};
});
if (className) {
imageAttributes.className = className;
}
const imageElement = caption
? `<figure class="[ flow flex-col items-center justify-center ]${className ? ` ${className}` : ""}">
<picture>
${imageSources}
<img
${imageAttributes}>
</picture>
<figcaption>${caption}</figcaption>
</figure>`
: `<picture class="[ flex-col items-center justify-center ]${className ? `${className}` : ""}">
${imageSources}
<img
${imageAttributes}>
</picture>`;
// You bet we throw an error on a missing alt (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
return imageElement;
};
module.exports = imageShortcode;