Skip to content

Commit f3199dd

Browse files
[site-content] Add custom nav HTML generator (#1411)
1 parent 772d68a commit f3199dd

File tree

2 files changed

+59
-6
lines changed

2 files changed

+59
-6
lines changed

packages/site-content/site/_includes/layouts/docs.11ty.cjs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
* SPDX-License-Identifier: Apache-2.0
55
*/
66

7+
const {navToHTML} = require('./nav.cjs');
8+
79
module.exports = {
810
async render(data) {
911
const {renderPage, html, unsafeHTML} = await import(
@@ -19,17 +21,17 @@ module.exports = {
1921

2022
const navigationEntries = this.eleventyNavigation(data.collections.all);
2123

22-
// TODO: use custom navigation HTML generation so that we can leave out
23-
// links for section items.
24-
// See https://github.com/lit/lit.dev/blob/main/packages/lit-dev-content/site/_includes/docs-nav.html
25-
const navigationHTML = this.eleventyNavigationToHtml(navigationEntries);
24+
const navigationHTML = navToHTML(
25+
navigationEntries,
26+
{slot: 'outline'},
27+
data.page
28+
);
2629

2730
return [
2831
...renderPage({
2932
...data,
3033
content: html`<wco-nav-page>
31-
<div slot="outline">${unsafeHTML(navigationHTML)}</div>
32-
${unsafeHTML(data.content)}
34+
${unsafeHTML(navigationHTML)} ${unsafeHTML(data.content)}
3335
</wco-nav-page>`,
3436
}),
3537
].join('');
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)