_includes/shortcodes/nav.js

/**
* @file Defines a shortcode for displaying navigation menus on a grid
* @author Reuben L. Lillie <reubenlillie@gmail.com>
*/


/**
* Defines markup for navigation links based on the current page
* @since 1.0.0
* @param {Object} item An item in an Eleventy collection
* @param {Object} page Eleventy’s `data.page` object
* @return {string} HTML
*/

function pageLink({data: {collections, shortTitle, title}, url}, page) {
var trimmedUrl = url.slice(1, -1)
var children = Array.isArray(collections[trimmedUrl])
? collections[trimmedUrl].filter(item => item.data.page.fileSlug === page.fileSlug)
: null

// Check if the URL points to the current page
return url === page.url
? `<!--link is to the current page-->
<li data-current-page="true">
<a href="
${url}" aria-current="page">
${shortTitle ? shortTitle : title}
</a>
</li>
`

: `<!--this link is not to the current page-->
<li
${children !== null && children.length > 0 ? 'data-tabbed="true"' : ''}>
<a href="
${url}">
${shortTitle ? shortTitle : title}
</a>
</li>
`

}

/**
* Defines markup for a `<nav>` using CSS Grid
* @module _includes/shortcodes/grid-nav
* @since 1.0.0
* @since 1.4.0 Check if the first tag is `pages` (directory data)
* @param {Object} collection An Eleventy collection
* @param {Object} page Eleventy’s `data.page` object
* @return {string} HTML
* @example
* // In an Eleventy template
* `${this.nav(data.collections.policies, data.page)}`
* @see {@link https://www.11ty.dev/docs/collections/ Collections in Eleventy}
* @see {@link https://www.11ty.dev/docs/data-template-dir/ Template and Directory Data Files in Eleventy}
* @see {@link https://developer.mozilla.org/en-us/docs/Web/CSS/CSS_Grid_Layout CSS Grid Layout on MDN}
*/

export default (collection, page) => {
/**
* Matches any character in the Latin alphabet
* @type {Object.<RegExp>}
*/

var RE_UPPERCASE = /(?<upperCase>[A-Z])/u

/**
* The first or second tag in the `data.tags` array
* @type {string}
* @since 1.3.0
*/

var tag = collection && collection.length > 0
// Is the first tag `pages` (directory data)?
? collection[0].data.tags[0] === 'pages'
? collection[0].data.tags[1]
: collection[0].data.tags[0]
: null

// Reformat camelCase tags for use as an `aria-label`
tag = tag !== null
? tag.replace(RE_UPPERCASE, ' $1').toLowerCase()
: null

// Does the collection exist?
return collection && collection.length > 0
? `<!-- Collection has items in ./_includes/shortcodes/nav.js -->
<nav aria-label="
${tag}">
<ul class="flex no-list-style no-margin-block no-padding-inline-start">
${collection
.sort((a, b) => a.data.weight - b.data.weight)
.map(item => pageLink(item, page))
.join('\n')
}

</ul>
</nav>
`

: '<!-- Collection does not have items in ./_includes/shortcodes/nav.js -->'
}