feat: Added anchor links, refactored config file

This commit is contained in:
Keith Irwin 2023-11-01 10:32:36 -06:00
parent b6cb9e9d66
commit 1a4cec4f01
Signed by: ki9
GPG Key ID: DF773B3F4A88DA86
4 changed files with 255 additions and 189 deletions

View File

@ -111,6 +111,13 @@ h1, h2, h3 {
h4, h5, h6 { h4, h5, h6 {
font-family: 'ubuntu', sans-serif; font-family: 'ubuntu', sans-serif;
} }
.header-anchor {
text-decoration: none;
color: rgba(255,255,255,.75);
}
.header-anchor:hover {
color: rgba(255,255,255,1)
}
p:last-child { p:last-child {
margin-bottom: 0; margin-bottom: 0;
} }

View File

@ -5,235 +5,253 @@ const pluginRss = require('@11ty/eleventy-plugin-rss')
const pluginSyntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight') const pluginSyntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight')
const pluginNavigation = require('@11ty/eleventy-navigation') const pluginNavigation = require('@11ty/eleventy-navigation')
const markdownIt = require('markdown-it') const markdownIt = require('markdown-it')
const markdownItAnchor = require('markdown-it-anchor')
const createHash = require('crypto').createHash const createHash = require('crypto').createHash
const pluginImage = require('@11ty/eleventy-img') const pluginImage = require('@11ty/eleventy-img')
// Widths in pixels of responsive images to be generated // Widths in pixels of responsive images to be generated
const IMAGE_SIZES = [300, 600, 900, 1200] const IMAGE_SIZES = [300, 600, 900, 1200]
const dirs ={ const dirs ={
input: '_src', input: '_src',
includes: '_includes', includes: '_includes',
data: '_data', data: '_data',
output: '_site', output: '_site',
} }
module.exports = (eleventyConfig) => { module.exports = (eleventyConfig) => {
eleventyConfig.setServerOptions({ eleventyConfig.setServerOptions({
liveReload: false, liveReload: false,
}) })
// Add plugins // Add plugins
eleventyConfig.addPlugin(pluginRss) eleventyConfig.addPlugin(pluginRss)
eleventyConfig.addPlugin(pluginSyntaxHighlight) eleventyConfig.addPlugin(pluginSyntaxHighlight)
eleventyConfig.addPlugin(pluginNavigation) eleventyConfig.addPlugin(pluginNavigation)
// https://www.11ty.dev/docs/data-deep-merge/ // https://www.11ty.dev/docs/data-deep-merge/
eleventyConfig.setDataDeepMerge(true) eleventyConfig.setDataDeepMerge(true)
// Alias `layout: post` to `layout: layouts/post.njk` // Alias `layout: post` to `layout: layouts/post.njk`
eleventyConfig.addLayoutAlias('post', 'layouts/post.njk') eleventyConfig.addLayoutAlias('post', 'layouts/post.njk')
eleventyConfig.addFilter('readableDate', dateObj => { eleventyConfig.addFilter('readableDate', dateObj =>
return DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('dd LLL yyyy') DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('dd LLL yyyy')
}) )
// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
eleventyConfig.addFilter('htmlDateString', (dateObj) => { eleventyConfig.addFilter('htmlDateString', (dateObj) =>
return DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('yyyy-LL-dd') DateTime.fromJSDate(dateObj, {zone: 'utc'}).toFormat('yyyy-LL-dd')
}) )
// Get the first `n` elements of a collection. // Get the first `n` elements of a collection.
eleventyConfig.addFilter('head', (array, n) => eleventyConfig.addFilter('head', (array, n) =>
(n<0)? array.slice(n) : array.slice(0, n) (n<0)? array.slice(n): array.slice(0, n)
) )
// Sanitize out apostrophes // Sanitize out apostrophes
eleventyConfig.addFilter('noApostrophes', (str) => eleventyConfig.addFilter('noApostrophes', (str) =>
str.replace(/['"]+/g,'') str.replace(/['"]+/g,'')
) )
// Return the smallest number argument // Return the smallest number argument
eleventyConfig.addFilter('min', (...numbers) => eleventyConfig.addFilter('min', (...numbers) =>
Math.min.apply(null, numbers) Math.min.apply(null, numbers)
) )
eleventyConfig.addFilter('toFixed', (num,digits) => eleventyConfig.addFilter('toFixed', (num,digits) =>
num? num.toFixed(digits) : '' num? num.toFixed(digits) : ''
) )
eleventyConfig.addFilter('srintegrity', async (asset,bits=256) => eleventyConfig.addFilter('srintegrity', async (asset,bits=256) =>
`sha${String(bits)}-` + `sha${String(bits)}-` +
createHash(`sha${String(bits)}`) createHash(`sha${String(bits)}`)
.update(await fs.readFile(`${dirs.input}${asset}`)) .update(await fs.readFile(`${dirs.input}${asset}`))
.digest('base64') .digest('base64')
) )
eleventyConfig.addFilter('filterCatList', cats => eleventyConfig.addFilter('filterCatList', cats =>
// should match the list in categories.njk // should match the list in categories.njk
(cats || []).filter(cat => ['all','nav','post','posts'].indexOf(cat) === -1) (cats || []).filter(cat => ['all','nav','post','posts'].indexOf(cat) === -1)
) )
eleventyConfig.addFilter('filterTagList', tags => eleventyConfig.addFilter('filterTagList', tags =>
// should match the list in tags.njk // should match the list in tags.njk
(tags || []).filter(tag => ['all','nav','post','posts'].indexOf(tag) === -1) (tags || []).filter(tag => ['all','nav','post','posts'].indexOf(tag) === -1)
) )
eleventyConfig.addFilter('dimsToVol', (dims) => { return { eleventyConfig.addFilter('dimsToVol', (dims) => { return {
in3: Object.values(dims.in).reduce((a,c) => a*c, 1) in3: Object.values(dims.in).reduce((a,c) => a*c, 1)
} } ) } } )
// Create an array of all tags // Create an array of all tags
eleventyConfig.addCollection('tagList', function(collection) { eleventyConfig.addCollection('tagList', function(collection) {
let tagSet = new Set() let tagSet = new Set()
collection.getAll().forEach(item => { collection.getAll().forEach(item => {
(item.data.tags || []).forEach(tag => tagSet.add(tag)) (item.data.tags || []).forEach(tag => tagSet.add(tag))
}); });
return [...tagSet]; return [...tagSet];
}) })
// Customize Markdown library and settings: // Markdown "md" filter for nunjucks
let markdownLibrary = markdownIt({ // https://github.com/11ty/eleventy/issues/658#issuecomment-599173643
html: true, const mdFilter = new markdownIt({html:true})
breaks: true, eleventyConfig.addPairedShortcode('md', (content) =>
linkify: true mdFilter.render(content) )
})
eleventyConfig.setLibrary('md', markdownLibrary)
// Markdown "md" filter for nunjucks // Override Browsersync defaults (used only with --serve)
// https://github.com/11ty/eleventy/issues/658#issuecomment-599173643 eleventyConfig.setBrowserSyncConfig({
const mdFilter = new markdownIt({html:true}) callbacks: {
eleventyConfig.addPairedShortcode('md', (content) => ready: function(err, browserSync) {
mdFilter.render(content) ) const content_404 = fs.readFileSync('_site/404.html')
// Override Browsersync defaults (used only with --serve) browserSync.addMiddleware('*', (req, res) => {
eleventyConfig.setBrowserSyncConfig({ // Provides the 404 content without redirect.
callbacks: { res.writeHead(404, {
ready: function(err, browserSync) { 'Content-Type': 'text/html; charset=UTF-8' })
const content_404 = fs.readFileSync('_site/404.html') res.write(content_404)
res.end()
});
},
},
ui: false,
ghostMode: false,
})
eleventyConfig.addPassthroughCopy('_src/assets/fonts')
eleventyConfig.addPassthroughCopy('_src/assets/base.css')
eleventyConfig.addPassthroughCopy('_src/assets/shop.css')
eleventyConfig.addPassthroughCopy('_src/assets/site.webmanifest')
eleventyConfig.addPassthroughCopy('_src/assets/scripts')
browserSync.addMiddleware('*', (req, res) => { // Optimized images
// Provides the 404 content without redirect. // https://www.11ty.dev/docs/plugins/image/#make-your-own-markup
res.writeHead(404, {'Content-Type': 'text/html; charset=UTF-8'}) eleventyConfig.addShortcode('image', async (src, alt) => {
res.write(content_404) const metadata = await pluginImage(`./_src${src}`, {
res.end() widths: [...IMAGE_SIZES, 'auto'],
}); formats: ['auto', 'webp', 'avif'],
}, // https://www.11ty.dev/docs/plugins/image/#custom-filenames
}, filenameFormat: (id, src, width, format) =>
ui: false, `${path.basename(src,path.extname(src))}-${width}w.${format}`,
ghostMode: false, // https://alexpeterhall.com/blog/2021/04/05/responsive-images-eleventy/#eleventy-configuration
}) urlPath: path.dirname(src),
outputDir: `_site/${path.dirname(src)}`,
eleventyConfig.addPassthroughCopy('_src/assets/fonts') })
eleventyConfig.addPassthroughCopy('_src/assets/base.css') const lowsrc = metadata.webp[0]
eleventyConfig.addPassthroughCopy('_src/assets/shop.css') const highsrc = metadata.webp[metadata.webp.length - 1]
eleventyConfig.addPassthroughCopy('_src/assets/site.webmanifest') return `<a href="${src}"><picture>${Object.values(metadata).map(imageFormat =>
eleventyConfig.addPassthroughCopy('_src/assets/scripts') `\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('')}<img src="${lowsrc.url}" width="${highsrc.width}" height="${highsrc.height}" alt="${alt}" decoding="async"></picture></a>`
})
// Resize images // Video embed
// https://www.11ty.dev/docs/plugins/image/#make-your-own-markup eleventyConfig.addShortcode('vid', (src, autoplay=false) =>
eleventyConfig.addShortcode("image", async (src, alt='') => { `<video controls ${(autoplay)?'autoplay':''}width="100%"><source src="${src}" type="video/${src.split('.').pop()}">Embedded videos are not supported in this browser.</video>`
if (alt==='') alt = path.basename(src) )
const metadata = await pluginImage(`./_src${src}`, { eleventyConfig.addShortcode('vidraw', (src) =>
widths: [...IMAGE_SIZES, 'auto'], `<video width="100%"><source src="${src}">Embedded videos are not supported in this browser.</video>`
formats: ['auto', 'webp', 'avif'], )
// https://www.11ty.dev/docs/plugins/image/#custom-filenames
filenameFormat: (id, src, width, format) =>
`${path.basename(src,path.extname(src))}-${width}w.${format}`,
// https://alexpeterhall.com/blog/2021/04/05/responsive-images-eleventy/#eleventy-configuration
urlPath: path.dirname(src),
outputDir: `_site/${path.dirname(src)}`,
})
const lowsrc = metadata.webp[0]
const highsrc = metadata.webp[metadata.webp.length - 1]
return `<picture>\n${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) =>
`(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>`
})
// Video shortcode // YouTube
eleventyConfig.addShortcode('vid', (videoName) => ` eleventyConfig.addShortcode('yt', (shortcode) =>
<video controls width="100%"> `<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>`
<source src="${videoName}" type="video/${videoName.split('.').pop()}"> )
<a href="${videoName}">${videoName}</a>
</video>`)
// Youtube shortcode // Audio embed
eleventyConfig.addShortcode('yt', (shortCode) => `<iframe width="100%" height="400vh" src="https://www.youtube-nocookie.com/embed/${shortCode}" frameborder="0" allow="autoplay;clipboard-write;encrypted-media;picture-in-picture" allowfullscreen></iframe>`) eleventyConfig.addShortcode('audio', (src, fmt) =>
`<audio controls><source src="${src}" type="audio/${fmt}">Embedded audio is not supported in this browser.</audio>`
)
// Products and categories collections // iFrame
eleventyConfig.addCollection('products', async (ca) => eleventyConfig.addShortcode('iframe', (url, height) =>
ca.getFilteredByTag('product') `<iframe width="100%" height="${height}" src="${url}"</iframe>`
) )
eleventyConfig.addCollection('featured', async (ca) =>
ca.getFilteredByTags('product', 'featured')
)
eleventyConfig.addCollection('computers', async (ca) =>
ca.getFilteredByTags('product', 'computer')
)
eleventyConfig.addCollection('desktops', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'desktop')
)
eleventyConfig.addCollection('laptops', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'laptop')
)
eleventyConfig.addCollection('all-in-ones', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'all-in-one')
)
eleventyConfig.addCollection('phones', async (ca) =>
ca.getFilteredByTags('product', 'phone')
)
eleventyConfig.addCollection('routers', async (ca) =>
ca.getFilteredByTags('product', 'router')
)
eleventyConfig.addCollection('accessories', async (ca) =>
ca.getFilteredByTags('product', 'accessory')
)
return { // Customize Markdown library and settings:
// Control which files Eleventy will process eleventyConfig.setLibrary("md", markdownIt({
// e.g.: *.md, *.njk, *.html, *.liquid html: true,
templateFormats: [ breaks: true,
'md', linkify: true,
'txt', }).use(markdownItAnchor, {
'njk', permalink: markdownItAnchor.permalink.headerLink(),
'html', level: [2, 3, 4, 5, 6],
'liquid', slugify: eleventyConfig.getFilter('slugify'),
'pdf', tabIndex: false,
'png', }))
'webp',
'jpg',
'svg',
'ico',
'gif',
'mp4',
],
// ----------------------------------------------------------------- // Products and categories collections
// If your site deploys to a subdirectory, change `pathPrefix`. eleventyConfig.addCollection('products', async (ca) =>
// Dont worry about leading and trailing slashes, we normalize these. ca.getFilteredByTag('product')
)
eleventyConfig.addCollection('featured', async (ca) =>
ca.getFilteredByTags('product', 'featured')
)
eleventyConfig.addCollection('computers', async (ca) =>
ca.getFilteredByTags('product', 'computer')
)
eleventyConfig.addCollection('desktops', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'desktop')
)
eleventyConfig.addCollection('laptops', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'laptop')
)
eleventyConfig.addCollection('all-in-ones', async (ca) =>
ca.getFilteredByTags('product', 'computer', 'all-in-one')
)
eleventyConfig.addCollection('phones', async (ca) =>
ca.getFilteredByTags('product', 'phone')
)
eleventyConfig.addCollection('routers', async (ca) =>
ca.getFilteredByTags('product', 'router')
)
eleventyConfig.addCollection('accessories', async (ca) =>
ca.getFilteredByTags('product', 'accessory')
)
// If you dont have a subdirectory, use '' or '/' (they do the same thing) return {
// This is only used for link URLs (it does not affect your file structure) // Control which files Eleventy will process
// Best paired with the `url` filter: https://www.11ty.dev/docs/filters/url/ // e.g.: *.md, *.njk, *.html, *.liquid
templateFormats: [
'md',
'txt',
'njk',
'html',
'liquid',
'pdf',
'png',
'webp',
'jpg',
'svg',
'ico',
'gif',
'mp4',
],
// You can also pass this in on the command line using `--pathprefix` // -----------------------------------------------------------------
// If your site deploys to a subdirectory, change `pathPrefix`.
// Dont worry about leading and trailing slashes, we normalize these.
// Optional (default is shown) // If you dont have a subdirectory, use '' or '/' (they do the same thing)
pathPrefix: '/', // 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/
// Pre-process *.md files with: (default: `liquid`) // You can also pass this in on the command line using `--pathprefix`
markdownTemplateEngine: 'njk',
// Pre-process *.html files with: (default: `liquid`) // Optional (default is shown)
htmlTemplateEngine: 'njk', pathPrefix: '/',
// -----------------------------------------------------------------
// Opt-out of pre-processing global data JSON files: (default: `liquid`) // Pre-process *.md files with: (default: `liquid`)
dataTemplateEngine: false, markdownTemplateEngine: 'njk',
// Set at top // Pre-process *.html files with: (default: `liquid`)
dir: dirs, htmlTemplateEngine: 'njk',
}
// Opt-out of pre-processing global data JSON files: (default: `liquid`)
dataTemplateEngine: false,
// Set at top
dir: dirs,
}
} }

38
package-lock.json generated
View File

@ -23,6 +23,9 @@
"markdown-it": "^13.0.1", "markdown-it": "^13.0.1",
"nodemailer": "^6.9.1", "nodemailer": "^6.9.1",
"stripe": "^11.13.0" "stripe": "^11.13.0"
},
"devDependencies": {
"markdown-it-anchor": "^8.6.7"
} }
}, },
"node_modules/@11ty/dependency-tree": { "node_modules/@11ty/dependency-tree": {
@ -332,6 +335,31 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/@types/linkify-it": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-3.0.4.tgz",
"integrity": "sha512-hPpIeeHb/2UuCw06kSNAOVWgehBLXEo0/fUs0mw3W2qhqX89PI2yvok83MnuctYGCPrabGIoi0fFso4DQ+sNUQ==",
"dev": true,
"peer": true
},
"node_modules/@types/markdown-it": {
"version": "13.0.4",
"resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-13.0.4.tgz",
"integrity": "sha512-FAIUdEXrCDnQmAAmJC+UeW/3p0eCI4QZ/+W0lX/h83VD3v78IgTFYftjnAeXS8H0g4PFQCgipc51cQDA8tjgLw==",
"dev": true,
"peer": true,
"dependencies": {
"@types/linkify-it": "*",
"@types/mdurl": "*"
}
},
"node_modules/@types/mdurl": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-1.0.4.tgz",
"integrity": "sha512-ARVxjAEX5TARFRzpDRVC6cEk0hUIXCCwaMhz8y7S1/PxU6zZS1UMjyobz7q4w/D/R552r4++EhwmXK1N2rAy0A==",
"dev": true,
"peer": true
},
"node_modules/@types/minimatch": { "node_modules/@types/minimatch": {
"version": "3.0.5", "version": "3.0.5",
"resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.5.tgz", "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-3.0.5.tgz",
@ -1994,6 +2022,16 @@
"markdown-it": "bin/markdown-it.js" "markdown-it": "bin/markdown-it.js"
} }
}, },
"node_modules/markdown-it-anchor": {
"version": "8.6.7",
"resolved": "https://registry.npmjs.org/markdown-it-anchor/-/markdown-it-anchor-8.6.7.tgz",
"integrity": "sha512-FlCHFwNnutLgVTflOYHPW2pPcl2AACqVzExlkGQNsi4CJgqOHN7YTgDd4LuhgN1BFO3TS0vLAruV1Td6dwWPJA==",
"dev": true,
"peerDependencies": {
"@types/markdown-it": "*",
"markdown-it": "*"
}
},
"node_modules/markdown-it/node_modules/argparse": { "node_modules/markdown-it/node_modules/argparse": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",

View File

@ -39,5 +39,8 @@
"markdown-it": "^13.0.1", "markdown-it": "^13.0.1",
"nodemailer": "^6.9.1", "nodemailer": "^6.9.1",
"stripe": "^11.13.0" "stripe": "^11.13.0"
},
"devDependencies": {
"markdown-it-anchor": "^8.6.7"
} }
} }