refactor: ♻️ Fix formatting and remove gap above images

master
Keith Irwin 2023-11-01 10:30:43 -06:00
parent 897ad020c6
commit a5ccef9235
Signed by: ki9
GPG Key ID: DF773B3F4A88DA86
1 changed files with 146 additions and 126 deletions

View File

@ -9,86 +9,107 @@ const IMAGE_SIZES = [300, 600, 900, 1200]
module.exports = function(eleventyConfig) { module.exports = function(eleventyConfig) {
// https://www.11ty.dev/docs/data-deep-merge/ // https://www.11ty.dev/docs/data-deep-merge/
eleventyConfig.setDataDeepMerge(true) eleventyConfig.setDataDeepMerge(true)
// https://www.11ty.dev/docs/plugins/image/#make-your-own-markup // Optimized images
eleventyConfig.addShortcode("image", async (src, alt) => { // https://www.11ty.dev/docs/plugins/image/#make-your-own-markup
const metadata = await pluginImage(`./_src${src}`, { eleventyConfig.addShortcode('image', async (src, alt) => {
widths: [...IMAGE_SIZES, 'auto'], const metadata = await pluginImage(`./_src${src}`, {
formats: ['auto', 'webp', 'avif'], widths: [...IMAGE_SIZES, 'auto'],
// https://www.11ty.dev/docs/plugins/image/#custom-filenames formats: ['auto', 'webp', 'avif'],
filenameFormat: (id, src, width, format) => // https://www.11ty.dev/docs/plugins/image/#custom-filenames
`${path.basename(src,path.extname(src))}-${width}w.${format}`, filenameFormat: (id, src, width, format) =>
// https://alexpeterhall.com/blog/2021/04/05/responsive-images-eleventy/#eleventy-configuration `${path.basename(src,path.extname(src))}-${width}w.${format}`,
urlPath: path.dirname(src), // https://alexpeterhall.com/blog/2021/04/05/responsive-images-eleventy/#eleventy-configuration
outputDir: `_site/${path.dirname(src)}`, urlPath: path.dirname(src),
}) outputDir: `_site/${path.dirname(src)}`,
})
const lowsrc = metadata.webp[0] const lowsrc = metadata.webp[0]
const highsrc = metadata.webp[metadata.webp.length - 1] const highsrc = metadata.webp[metadata.webp.length - 1]
return `<a href="${src}"><picture>\n${Object.values(metadata).map(imageFormat => return `<a href="${src}"><picture>${Object.values(metadata).map(imageFormat =>
`\t<source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => entry.srcset).join(", ")}" sizes="${IMAGE_SIZES.reverse().reduce((str,size) => `\t<source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => entry.srcset).join(', ')}" sizes="${IMAGE_SIZES.reverse().reduce((str,size) =>
`(max-width:${size}px) ${size}px, ${str}`,'100vw')}">`).join("\n")}\n\t<img src="${lowsrc.url}" width="${highsrc.width}" height="${highsrc.height}" alt="${alt}" decoding="async">\n</picture></a>` `(max-width:${size}px) ${size}px, ${str}`,'100vw')}">`).join('')}<img src="${lowsrc.url}" width="${highsrc.width}" height="${highsrc.height}" alt="${alt}" decoding="async"></picture></a>`
}) })
eleventyConfig.addFilter('readableDate', dateObj => { // Video embed
return DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('dd LLL yyyy') eleventyConfig.addShortcode('vid', (src, autoplay=false) =>
}) `<video controls ${(autoplay)?'autoplay':''}width="100%"><source src="${src}" type="video/${src.split('.').pop()}">Embedded videos are not supported in this browser.</video>`
)
eleventyConfig.addShortcode('vidraw', (src) =>
`<video width="100%"><source src="${src}">Embedded videos are not supported in this browser.</video>`
)
// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string // YouTube
eleventyConfig.addFilter('htmlDateString', (dateObj) => { eleventyConfig.addShortcode('yt', (shortcode) =>
return DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('yyyy-LL-dd') `<iframe width="100%" height="500vh" src="https://www.youtube.com/embed/${shortcode}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`
}) )
// Get the first `n` elements of a collection. // Audio embed
eleventyConfig.addFilter('head', (array, n) => { eleventyConfig.addShortcode('audio', (src, fmt) =>
if( n < 0 ) { `<audio controls><source src="${src}" type="audio/${fmt}">Embedded audio is not supported in this browser.</audio>`
return array.slice(n) )
}
return array.slice(0, n) // iFrame
}) eleventyConfig.addShortcode('iframe', (url, height) =>
`<iframe width="100%" height="${height}" src="${url}"</iframe>`
)
// Return the smallest number argument eleventyConfig.addFilter('readableDate', dateObj =>
eleventyConfig.addFilter('min', (...numbers) => { DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('dd LLL yyyy')
return Math.min.apply(null, numbers) )
})
eleventyConfig.addFilter('filterTagList', tags => { // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
// should match the list in tags.njk eleventyConfig.addFilter('htmlDateString', (dateObj) =>
return (tags || []).filter(tag => ['all', 'nav', 'post', 'posts'].indexOf(tag) === -1) DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('yyyy-LL-dd')
}) )
// Convert text to hex // Get the first `n` elements of a collection.
eleventyConfig.addFilter('toHex', (str) => { eleventyConfig.addFilter('head', (array, n) =>
let hex = '' (n<0)? array.slice(n): array.slice(0, n)
for(let i=0; i<str.length; i++){ )
let h = str.codePointAt(i).toString(16)
if(h.length===1) h='0'+h
hex += h + ' '
if( h.length>4 ) i++
} return hex.trim()
})
// Fold lines // Return the smallest number argument
eleventyConfig.addFilter('fold', (str, size) => { eleventyConfig.addFilter('min', (...numbers) =>
// https://stackoverflow.com/a/29202760/3006854 Math.min.apply(null, numbers)
const numChunks = Math.ceil(str.length/size) )
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size)
chunks[i] = str.substr(o, size)
return chunks.join('\n')
})
// Create an array of all tags eleventyConfig.addFilter('filterTagList', tags =>
eleventyConfig.addCollection('tagList', function(collection) { // should match the list in tags.njk
let tagSet = new Set() (tags || []).filter(tag => ['all', 'nav', 'post', 'posts'].indexOf(tag) === -1)
collection.getAll().forEach(item => { )
(item.data.tags || []).forEach(tag => tagSet.add(tag))
}); return [...tagSet] // Convert text to hex
}) eleventyConfig.addFilter('toHex', (str) => {
let hex = ''
for(let i=0; i<str.length; i++){
let h = str.codePointAt(i).toString(16)
if(h.length===1) h='0'+h
hex += h + ' '
if( h.length>4 ) i++
} return hex.trim()
})
// Customize Markdown library and settings: // Fold lines
eleventyConfig.setLibrary("md", markdownIt({ eleventyConfig.addFilter('fold', (str, size) => {
// https://stackoverflow.com/a/29202760/3006854
const numChunks = Math.ceil(str.length/size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size)
chunks[i] = str.substr(o, size)
return chunks.join('\n')
})
// Create an array of all tags
eleventyConfig.addCollection('tagList', function(collection) {
let tagSet = new Set()
collection.getAll().forEach(item => {
(item.data.tags || []).forEach(tag => tagSet.add(tag))
}); return [...tagSet]
})
// Customize Markdown library and settings:
eleventyConfig.setLibrary('md', markdownIt({
html: true, html: true,
breaks: true, breaks: true,
linkify: true, linkify: true,
@ -99,73 +120,72 @@ module.exports = function(eleventyConfig) {
tabIndex: false, tabIndex: false,
})) }))
// Override Browsersync defaults (used only with --serve) // Override Browsersync defaults (used only with --serve)
eleventyConfig.setBrowserSyncConfig({ eleventyConfig.setBrowserSyncConfig({
callbacks: { callbacks: {
ready: async (err, browserSync) => { ready: async (err, browserSync) => {
const content_404 = await fs.readFile('_site/404.html') const content_404 = await fs.readFile('_site/404.html')
browserSync.addMiddleware("*", (req, res) => { browserSync.addMiddleware('*', (req, res) => {
// Provides the 404 content without redirect. // Provides the 404 content without redirect.
res.writeHead(404, {"Content-Type": "text/html charset=UTF-8"}) res.writeHead(404, {
res.write(content_404) 'Content-Type': 'text/html charset=UTF-8' })
res.end() res.write(content_404)
}) res.end()
}, })
}, },
ui: false, },
ghostMode: false ui: false,
}) ghostMode: false
})
return { return {
// Control which files Eleventy will process templateFormats: [
// e.g.: *.md, *.njk, *.html, *.liquid 'md',
templateFormats: [ 'njk',
"md", 'html',
"njk", 'liquid',
'html', 'css',
'liquid', 'png',
'css', 'webp',
'png', 'jpg',
'webp', 'gif',
'jpg', 'js',
'gif', 'crt',
'js', 'pem',
'crt', 'ttf',
'pem', 'webmanifest',
'ttf', ],
'webmanifest',
],
// ----------------------------------------------------------------- // -----------------------------------------------------------------
// If your site deploys to a subdirectory, change `pathPrefix`. // If your site deploys to a subdirectory, change `pathPrefix`.
// Dont worry about leading and trailing slashes, we normalize these. // Dont worry about leading and trailing slashes, we normalize these.
// If you dont have a subdirectory, use "" or "/' (they do the same thing) // If you dont have a subdirectory, use "" or "/' (they do the same thing)
// This is only used for link URLs (it does not affect your file structure) // This is only used for link URLs (it does not affect your file structure)
// Best paired with the `url` filter: https://www.11ty.dev/docs/filters/url/ // Best paired with the `url` filter: https://www.11ty.dev/docs/filters/url/
// You can also pass this in on the command line using `--pathprefix` // You can also pass this in on the command line using `--pathprefix`
// Optional (default is shown) // Optional (default is shown)
pathPrefix: '/', pathPrefix: '/',
// ----------------------------------------------------------------- // -----------------------------------------------------------------
// Pre-process *.md files with: (default: `liquid`) // Pre-process *.md files with: (default: `liquid`)
markdownTemplateEngine: 'njk', markdownTemplateEngine: 'njk',
// Pre-process *.html files with: (default: `liquid`) // Pre-process *.html files with: (default: `liquid`)
htmlTemplateEngine: 'njk', htmlTemplateEngine: 'njk',
// Opt-out of pre-processing global data JSON files: (default: `liquid`) // Opt-out of pre-processing global data JSON files: (default: `liquid`)
dataTemplateEngine: false, dataTemplateEngine: false,
// These are all optional (defaults are shown): // These are all optional (defaults are shown):
dir: { dir: {
input: '_src', input: '_src',
includes: '_includes', includes: '_includes',
data: '_data', data: '_data',
output: '_site' output: '_site'
} }
} }
} }