|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright 2023 Google LLC |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * Converts an eleventy-navigation entries array to a nested <ul> list. |
| 9 | + * |
| 10 | + * Entries with `url: false` (caused by `permalink: false` in page data) do |
| 11 | + * not generate a link, and so are just section headers. |
| 12 | + * |
| 13 | + * When an entry matches the current page, it's `<li>` element is give the |
| 14 | + * `active` class. |
| 15 | + */ |
| 16 | +const navToHTML = (navigationEntries, attributes, page) => { |
| 17 | + const makeItems = (entries) => |
| 18 | + entries |
| 19 | + ?.map( |
| 20 | + (e) => |
| 21 | + `<li ${getEntryClassString(e, page)}>${maybeWrapInLink( |
| 22 | + e, |
| 23 | + e.key |
| 24 | + )}${renderChildren(e.children, page)}</li>` |
| 25 | + ) |
| 26 | + .join('') ?? ''; |
| 27 | + |
| 28 | + return `<ul ${getAttributesString(attributes)}>${makeItems( |
| 29 | + navigationEntries |
| 30 | + )}</ul>`; |
| 31 | +}; |
| 32 | + |
| 33 | +const getEntryClassString = (entry, page) => |
| 34 | + entry.url === page.url ? 'class="active"' : ''; |
| 35 | + |
| 36 | +const maybeWrapInLink = (entry, s) => |
| 37 | + entry.url !== false ? `<a href="${entry.url}">${s}</a>` : s; |
| 38 | + |
| 39 | +const renderChildren = (children, page) => |
| 40 | + children?.length > 0 ? navToHTML(children, {}, page) : ''; |
| 41 | + |
| 42 | +const getAttributesString = (attributes) => |
| 43 | + attributes !== undefined |
| 44 | + ? Object.entries(attributes) |
| 45 | + .map(([name, value]) => `${name}="${value}"`) |
| 46 | + .join(' ') |
| 47 | + : ''; |
| 48 | + |
| 49 | +module.exports = { |
| 50 | + navToHTML, |
| 51 | +}; |
0 commit comments