62 lines
1.8 KiB
JavaScript
62 lines
1.8 KiB
JavaScript
import Image from '@11ty/eleventy-img';
|
|
import path from 'node:path';
|
|
|
|
const stringifyAttributes = attributeMap => {
|
|
return Object.entries(attributeMap)
|
|
.map(([attribute, value]) => {
|
|
if (typeof value === 'undefined') return '';
|
|
return `${attribute}="${value}"`;
|
|
})
|
|
.join(' ');
|
|
};
|
|
|
|
export const imageShortcode = async (
|
|
src,
|
|
alt = '',
|
|
caption = '',
|
|
loading = 'lazy',
|
|
containerClass,
|
|
imageClass,
|
|
sizes = '100vw',
|
|
widths = [650, 960, 1200],
|
|
formats = ['avif', 'webp', 'jpeg']
|
|
) => {
|
|
const metadata = await Image(src, {
|
|
widths: [...widths],
|
|
formats: [...formats],
|
|
urlPath: '/assets/images/',
|
|
outputDir: './dist/assets/images/',
|
|
filenameFormat: (id, src, width, format, options) => {
|
|
const extension = path.extname(src);
|
|
const name = path.basename(src, extension);
|
|
return `${name}-${width}w.${format}`;
|
|
}
|
|
});
|
|
|
|
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,
|
|
'decoding': loading === 'eager' ? 'sync' : 'async',
|
|
...(imageClass && {class: imageClass}),
|
|
'eleventy:ignore': ''
|
|
});
|
|
|
|
const pictureElement = `<picture> ${imageSources}<img ${imageAttributes}></picture>`;
|
|
|
|
return caption
|
|
? `<figure slot="image"${containerClass ? ` class="${containerClass}"` : ''}>${pictureElement}<figcaption>${caption}</figcaption></figure>`
|
|
: `<picture slot="image"${containerClass ? ` class="${containerClass}"` : ''}>${imageSources}<img ${imageAttributes}></picture>`;
|
|
};
|