_includes/shortcodes/headshot.js

/**
* @file Defines a shortcode for formatting headshot images
* @author Reuben L. Lillie <reubenlillie@gmail.com>
*/


/**
* Import Eleventy’s build-time image formatting plugin
* @see {@link https://www.11ty.dev/docs/plugins/image/ Eleventy documentation}
*/

import Image from '@11ty/eleventy-img'

/**
* Import modules for Cloudinary image management
* @see {@link https://cloudinary.com/documentation/node_integration Cloudinary Documentation}
*/

import dotenv from 'dotenv'
import cloudinary from 'cloudinary'

dotenv.config()
cloudinary.v2.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
})

/**
* Format repsonsive images
* @module _includes/shortcodes/responsive-image
* @since 1.0.0
* @param {string} src Image filepath
* @return {string} The rendered shortcode
* @example
* // In an Eleventy template
* `${this.responsiveImage(src)}`
*/

export default async ({
src: source,
alt,
width = 300,
height = 300,
classList
}
) => {
/**
* From the Cloudinary API
* @type {Object}
*/

var src
try {
src = cloudinary.v2.url(source, {
secure: true,
transformation: [
{
quality: 'auto',
}
]
})
} catch (err) {
console.error(err)
return
}

/**
* An HTML `class` attribute
* @type {string}
*/

var cssClasses = Array.isArray(classList) > 0
? classList.length > 0
? classList.map(cssClass => cssClass).join(' ')
: null
: null

/**
* Output from Eleventy’s Image plugin
* @type {Promise<Object>}
*/

var stats = await Image(src, {
widths: [788],
outputDir: './_site/img/'
})

/**
* The image file path for the smallest image size
* @type {string}
*/

var lowestSrc = stats.jpeg[0]

return `<!--_includes/shortcodes/headshot.js--><picture class="headshot${cssClasses
? ` ${cssClasses}`
: ''}
" loading="lazy">
${Object.values(stats).map(imageFormat => `<!--image sources-->
<source type="image/
${imageFormat[0].format}"
srcset="
${imageFormat.map(entry => entry.srcset).join(', ')}">`

).join('\n')}

<img src="
${lowestSrc.url}"
width="
${width ? width : lowestSrc.width}"
height="
${height ? height : lowestSrc.height}"
alt="
${alt}">
</picture>
`

}