/**
* @file Defines a shortcode for formatting responsive background images
* @author Reuben L. Lillie <rlillie@loopnaz.org>
* @see {@link https://www.11ty.dev/docs/languages/javascript/#javascript-template-functions JavaScript template functions in 11ty}
*/
// Filters
import fromCloudinary from '../filters/from-cloudinary.js'
/**
* Eleventy’s build-time image formatting plugin
* @see {@link https://github.com/11ty/eleventy-img/ GitHub}
*/
import Image from '@11ty/eleventy-img'
/**
* Defines CSS rules for a page’s repsonsive background image
* @module _includes/shortcodes/responsive-background
* @param {string} src Image filepath
* @return {string} CSS
* @example
* // In an Eleventy template
* `${this.responsiveImage(src)}`
*/
export default async ({src, alt}, options, sizes = '100vw') => {
/**
* Transform images from Cloudinary using Eleventy’s Image plugin
* @type {Promise<Object>}
* @see {@link https://www.11ty.dev/docs/plugins/image/ Eleventy documentation}
*/
var metadata = await Image(fromCloudinary(src, options), {
widths: [800, 1200, null],
formats: ['webp', 'jpeg']
})
var lowsrc = metadata.jpeg[0];
/**
* Defines markup for a source element
* @param {Object[]} imageFormat From Eleventy Image
* @return {string} HTML
*/
function sourceAttr(imageFormat) {
return `<!--sourceAttr()-->
<source type="${imageFormat[0].sourceType}"
srcset="${imageFormat.map(entry => entry.srcset).join(', ')}"
sizes="${sizes}">`
}
return `<!--_includes/shortcodes/background-image.js-->
<picture loading="lazy">
${Object.values(metadata).map(imageFormat => sourceAttr(imageFormat)).join('\n')}
<img
src="${lowsrc.url}"
width="${lowsrc.width}"
height="${lowsrc.height}"
alt="${alt}"
loading="lazy"
decoding="async">
</picture>`
}