eleventy-plugin-nav 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.editorconfig ADDED
@@ -0,0 +1,8 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = tab
5
+ charset = utf-8
6
+ trim_trailing_whitespace = true
7
+ insert_final_newline = true
8
+ end_of_line = lf
@@ -0,0 +1,17 @@
1
+ {
2
+ "plugins": [
3
+ "prettier-plugin-brace-style",
4
+ "prettier-plugin-space-before-function-paren",
5
+ "prettier-plugin-merge"
6
+ ],
7
+ "braceStyle": "stroustrup",
8
+ "arrowParens": "avoid",
9
+ "bracketSpacing": true,
10
+ "endOfLine": "auto",
11
+ "semi": true,
12
+ "singleQuote": false,
13
+ "tabWidth": 4,
14
+ "useTabs": true,
15
+ "trailingComma": "all",
16
+ "printWidth": 100
17
+ }
package/README.md ADDED
@@ -0,0 +1,194 @@
1
+ <!-- DO NOT EDIT THIS FILE DIRECTLY, EDIT README.src.md INSTEAD -->
2
+
3
+ # eleventy-plugin-nav
4
+
5
+ Semi-automatic hierarchical navigation for 11ty.
6
+
7
+ Sidebar menus, breadcrumbs, next/previous page, all made easy with minimal work (often none) on your part.
8
+
9
+ This is intended to be used on websites whose URL structure largely mirrors their content structure, allowing you to get fully automated hierarchical navigation while only having to specify the exceptions — the common case is automatically inferred for you.
10
+
11
+ ## Installation
12
+
13
+ Just like any other plugin:
14
+
15
+ ```js
16
+ import eleventyNav from "eleventy-plugin-nav";
17
+
18
+ export default function (eleventyConfig) {
19
+ // ...
20
+ eleventyConfig.addPlugin(eleventyNav);
21
+ }
22
+ ```
23
+
24
+ You can also provide options:
25
+
26
+ ```js
27
+ import eleventyNav from "eleventy-plugin-nav";
28
+
29
+ export default function (eleventyConfig) {
30
+ // ...
31
+ eleventyConfig.usePlugin(eleventyNav, {
32
+ hidden: page => page.data.unlisted || page.data.customHiddenOption
33
+ });
34
+ }
35
+ ```
36
+
37
+ ### Options
38
+
39
+ The following options are available to customize the plugin behavior:
40
+
41
+ | Option | Type | Default value | Description |
42
+ | ------ | ---- | ------------- | ----------- |
43
+ | `sort` | `object` | `{ "data.order": 1, "data.title": "" }` | What to sort by and any default values. |
44
+ | `hidden` | `function` | `page => page.data.unlisted` | A function that takes a page and returns true if the page should be hidden from listings. |
45
+
46
+ ## Usage
47
+
48
+ In general, you should not need to specify anything for common cases where URL structure and content hierarchy are aligned and the page order is the default.
49
+ Stuff should just work.
50
+ However, there are always anomalies, where you want to expose a different content hierarchy than what is inferred.
51
+
52
+ For example:
53
+ - Having external URLs as part of your sitemap
54
+ - Having pages whose children are not in child directories
55
+ - Having pages whose parent is not the URL-based ancestor
56
+ - etc.
57
+
58
+ Below, we list all data options you can specify on pages to override the default behavior.
59
+ These are just 11ty data you specify in your front matter.
60
+
61
+ #### `parent`
62
+
63
+ For pages whose parent is different than their URL-based ancestor, specify the `parent` property.
64
+ The value is the parent slug, and can be either a sibling in the same directory, or an ancestor page.
65
+ E.g. given two pages with URLs `docs/items/foo` and `docs/items/foo-item`, to make `foo-item` have the former as its parent you'd use `parent: foo` in its front matter.
66
+
67
+ Completely disconnected pages are not currently supported, but if you need this, please [let us know](https://github.com/h-docs/eleventy-plugin-nav/issues/5)!
68
+
69
+ #### `order`
70
+
71
+ By default, pages are sorted by title.
72
+ To override, you can specify an `order` property.
73
+ Its value is a number, and is `1` by default.
74
+ Any (real) number is allowed — negative numbers, decimals, etc.
75
+ Multiple pages can have the same `order` value, in which case they are sorted by title.
76
+ For example, if you only use positive numbers < 100, you can make a page always appear before all others by using `order: 0` and after all others by using `order: 100`.
77
+
78
+ #### `unlisted`
79
+
80
+ Do not include the page in any listings.
81
+
82
+ #### `parentOf`
83
+
84
+ Override the page’s children with a collection name.
85
+ This is useful when you have a hierarchy where each page has a canonical parent, but also can be listed as a child of other pages.
86
+
87
+ For example, suppose you have a list of restaurants whose URL is `restaurants/foo`,
88
+ and each restaurant has a list of dishes, whose URL is `restaurants/foo/dishes/bar`.
89
+ However, you also want to have `dishes/bar` pages that list all restaurants that serve a given dish.
90
+ Assuming each dish page was using a `dish` tag, you could specify `parentOf: dish` on the dish page across all restaurants.
91
+
92
+ ### Output Page Data
93
+
94
+ This plugin makes several data items available on every page, which can be used to construct a variety of navigation-related UI,
95
+ such as indices, navbars, breadcrumbs and the like.
96
+
97
+ | Data | Type | Description |
98
+ | -------------- | ------------------ | ----------------------------------------------------------------------------- |
99
+ | `parent` | `string` | Slug of parent page |
100
+ | `parentURL` | `string` | `page.url` of parent page |
101
+ | `parentItem` | `CollectionItem` | Collection item for parent page |
102
+ | `children` | `CollectionItem[]` | Array of a page's direct children |
103
+ | `lineage` | `CollectionItem[]` | Array of a page's ancestors, starting from the root, plus the page itself. |
104
+ | `trail` | `CollectionItem[]` | Array of a page's ancestors, excluding the root |
105
+ | `siblingIndex` | `number` | The index of the current page among its parent’s children. `-1` if no parent. |
106
+ | `siblings` | `CollectionItem[]` | Other pages by the same parent. Excludes current page. |
107
+ | `nextPage` | `CollectionItem` | The page that comes before the current page in the parent's children |
108
+ | `previousPage` | `CollectionItem` | The page that comes after the current page in the parent's children |
109
+ | `hidden` | `boolean` | Whether the page should be included in listings |
110
+ | `shown` | `boolean` | Whether the page should be included in listings |
111
+
112
+ You can access this data by their names on the page itself, or on `item.data` on a collection item.
113
+
114
+ ### Roots collection
115
+
116
+ The plugin also adds a `roots` collection that contains all pages that are not children of any other page.
117
+ This is useful for creating a top-level navigation menu, or for listing all pages in the site.
118
+ These are also sorted by the default sort order you specify.
119
+
120
+ ## Examples / Recipes
121
+
122
+ ### Nested sidebar
123
+
124
+ `sidebar-items.njk`:
125
+
126
+ ```njk
127
+ <ul>
128
+ {% for page in collection.roots %}
129
+ {% include './sidebar-item.njk' %}
130
+ {% endfor %}
131
+ </ul>
132
+
133
+ ```
134
+
135
+ `sidebar-item.njk`:
136
+
137
+ ```njk
138
+ {% if page.data.shown -%}
139
+ <li>
140
+ <a href="{{ page.data.url or page.url }}">{{ page.data.title }}</a>
141
+
142
+ {% set children = page.data.children %}
143
+ {% if children.length > 0 %}
144
+ <ul>
145
+ {% for page in children %}
146
+ {% include 'sidebar-item.njk' %}
147
+ {% endfor %}
148
+ </ul>
149
+ {% endif %}
150
+ </li>
151
+ {%- endif %}
152
+
153
+ ```
154
+
155
+
156
+ ### Breadcrumbs
157
+
158
+ Basic breadcrumbs:
159
+
160
+ ```njk
161
+ {% if trail.length > 0 %}
162
+ <nav class="breadcrumbs">
163
+ {% for ancestor in trail %}
164
+ <a href="{{ ancestor.page.url }}">{{ ancestor.data.title }}</a>
165
+ {% endfor %}
166
+ {% endif %}
167
+
168
+ ```
169
+
170
+ You can even do more complex breadcrumbs that show a menu of siblings:
171
+
172
+ ```njk
173
+ {% if trail.length > 0 %}
174
+ <nav class="breadcrumbs">
175
+ {% for ancestor in trail %}
176
+ <a href="{{ ancestor.page.url }}">{{ ancestor.data.title }}</a>
177
+ {% if ancestor.data.siblings.length > 1 %}
178
+ <ul class="siblings">
179
+ {% for sibling in ancestor.data.siblings %}
180
+ <li><a href="{{ sibling.page.url }}">{{ sibling.data.title }}</a></li>
181
+ {% endfor %}
182
+ </ul>
183
+ {% endif %}
184
+ {% endfor %}
185
+ {% endif %}
186
+
187
+ ```
188
+
189
+ -----
190
+
191
+ You can find more recipes in [`_includes`](_includes).
192
+
193
+ If you want to use a recipe directly, and don’t need to tweak it at all,
194
+ you can
package/README.src.md ADDED
@@ -0,0 +1,146 @@
1
+ # eleventy-plugin-nav
2
+
3
+ Semi-automatic hierarchical navigation for 11ty.
4
+
5
+ Sidebar menus, breadcrumbs, next/previous page, all made easy with minimal work (often none) on your part.
6
+
7
+ This is intended to be used on websites whose URL structure largely mirrors their content structure, allowing you to get fully automated hierarchical navigation while only having to specify the exceptions — the common case is automatically inferred for you.
8
+
9
+ ## Installation
10
+
11
+ Just like any other plugin:
12
+
13
+ ```js
14
+ import eleventyNav from "eleventy-plugin-nav";
15
+
16
+ export default function (eleventyConfig) {
17
+ // ...
18
+ eleventyConfig.addPlugin(eleventyNav);
19
+ }
20
+ ```
21
+
22
+ You can also provide options:
23
+
24
+ ```js
25
+ import eleventyNav from "eleventy-plugin-nav";
26
+
27
+ export default function (eleventyConfig) {
28
+ // ...
29
+ eleventyConfig.usePlugin(eleventyNav, {
30
+ hidden: page => page.data.unlisted || page.data.customHiddenOption
31
+ });
32
+ }
33
+ ```
34
+
35
+ ### Options
36
+
37
+ The following options are available to customize the plugin behavior:
38
+
39
+ | Option | Type | Default value | Description |
40
+ | ------ | ---- | ------------- | ----------- |
41
+ | `sort` | `object` | `{ "data.order": 1, "data.title": "" }` | What to sort by and any default values. |
42
+ | `hidden` | `function` | `page => page.data.unlisted` | A function that takes a page and returns true if the page should be hidden from listings. |
43
+
44
+ ## Usage
45
+
46
+ In general, you should not need to specify anything for common cases where URL structure and content hierarchy are aligned and the page order is the default.
47
+ Stuff should just work.
48
+ However, there are always anomalies, where you want to expose a different content hierarchy than what is inferred.
49
+
50
+ For example:
51
+ - Having external URLs as part of your sitemap
52
+ - Having pages whose children are not in child directories
53
+ - Having pages whose parent is not the URL-based ancestor
54
+ - etc.
55
+
56
+ Below, we list all data options you can specify on pages to override the default behavior.
57
+ These are just 11ty data you specify in your front matter.
58
+
59
+ #### `parent`
60
+
61
+ For pages whose parent is different than their URL-based ancestor, specify the `parent` property.
62
+ The value is the parent slug, and can be either a sibling in the same directory, or an ancestor page.
63
+ E.g. given two pages with URLs `docs/items/foo` and `docs/items/foo-item`, to make `foo-item` have the former as its parent you'd use `parent: foo` in its front matter.
64
+
65
+ Completely disconnected pages are not currently supported, but if you need this, please [let us know](https://github.com/h-docs/eleventy-plugin-nav/issues/5)!
66
+
67
+ #### `order`
68
+
69
+ By default, pages are sorted by title.
70
+ To override, you can specify an `order` property.
71
+ Its value is a number, and is `1` by default.
72
+ Any (real) number is allowed — negative numbers, decimals, etc.
73
+ Multiple pages can have the same `order` value, in which case they are sorted by title.
74
+ For example, if you only use positive numbers < 100, you can make a page always appear before all others by using `order: 0` and after all others by using `order: 100`.
75
+
76
+ #### `unlisted`
77
+
78
+ Do not include the page in any listings.
79
+
80
+ #### `parentOf`
81
+
82
+ Override the page’s children with a collection name.
83
+ This is useful when you have a hierarchy where each page has a canonical parent, but also can be listed as a child of other pages.
84
+
85
+ For example, suppose you have a list of restaurants whose URL is `restaurants/foo`,
86
+ and each restaurant has a list of dishes, whose URL is `restaurants/foo/dishes/bar`.
87
+ However, you also want to have `dishes/bar` pages that list all restaurants that serve a given dish.
88
+ Assuming each dish page was using a `dish` tag, you could specify `parentOf: dish` on the dish page across all restaurants.
89
+
90
+ ### Output Page Data
91
+
92
+ This plugin makes several data items available on every page, which can be used to construct a variety of navigation-related UI,
93
+ such as indices, navbars, breadcrumbs and the like.
94
+
95
+ | Data | Type | Description |
96
+ | -------------- | ------------------ | ----------------------------------------------------------------------------- |
97
+ | `parent` | `string` | Slug of parent page |
98
+ | `parentURL` | `string` | `page.url` of parent page |
99
+ | `parentItem` | `CollectionItem` | Collection item for parent page |
100
+ | `children` | `CollectionItem[]` | Array of a page's direct children |
101
+ | `lineage` | `CollectionItem[]` | Array of a page's ancestors, starting from the root, plus the page itself. |
102
+ | `trail` | `CollectionItem[]` | Array of a page's ancestors, excluding the root |
103
+ | `siblingIndex` | `number` | The index of the current page among its parent’s children. `-1` if no parent. |
104
+ | `siblings` | `CollectionItem[]` | Other pages by the same parent. Excludes current page. |
105
+ | `nextPage` | `CollectionItem` | The page that comes before the current page in the parent's children |
106
+ | `previousPage` | `CollectionItem` | The page that comes after the current page in the parent's children |
107
+ | `hidden` | `boolean` | Whether the page should be included in listings |
108
+ | `shown` | `boolean` | Whether the page should be included in listings |
109
+
110
+ You can access this data by their names on the page itself, or on `item.data` on a collection item.
111
+
112
+ ### Roots collection
113
+
114
+ The plugin also adds a `roots` collection that contains all pages that are not children of any other page.
115
+ This is useful for creating a top-level navigation menu, or for listing all pages in the site.
116
+ These are also sorted by the default sort order you specify.
117
+
118
+ ## Examples / Recipes
119
+
120
+ ### Nested sidebar
121
+
122
+ `sidebar-items.njk`:
123
+
124
+ <!-- code _includes/sidebar/groups.njk -->
125
+
126
+ `sidebar-item.njk`:
127
+
128
+ <!-- code _includes/sidebar/item.njk -->
129
+
130
+
131
+ ### Breadcrumbs
132
+
133
+ Basic breadcrumbs:
134
+
135
+ <!-- code _includes/breadcrumbs/basic.njk -->
136
+
137
+ You can even do more complex breadcrumbs that show a menu of siblings:
138
+
139
+ <!-- code _includes/breadcrumbs/advanced.njk -->
140
+
141
+ -----
142
+
143
+ You can find more recipes in [`_includes`](_includes).
144
+
145
+ If you want to use a recipe directly, and don’t need to tweak it at all,
146
+ you can
@@ -0,0 +1,42 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ async function processReadme() {
5
+ try {
6
+ // Read the source README
7
+ const readmeSrc = await fs.readFile('README.src.md', 'utf-8');
8
+
9
+ // Regular expression to match comments like <!-- code _includes/sidebar-items.njk -->
10
+ const codeCommentRegex = /<!--\s*code\s+([^\s>]+)\s*-->/g;
11
+
12
+ // Process the file content
13
+ let processedContent = '<!-- DO NOT EDIT THIS FILE DIRECTLY, EDIT README.src.md INSTEAD -->\n\n' + readmeSrc;
14
+ let match;
15
+
16
+ while ((match = codeCommentRegex.exec(readmeSrc)) !== null) {
17
+ const filePath = match[1];
18
+ try {
19
+ // Read the referenced file
20
+ const fileContent = await fs.readFile(filePath, 'utf-8');
21
+
22
+ // Create the code block
23
+ const codeBlock = `\`\`\`${path.extname(filePath).slice(1) || 'text'}\n${fileContent}\n\`\`\``;
24
+
25
+ // Replace the comment with the code block
26
+ processedContent = processedContent.replace(match[0], codeBlock);
27
+ } catch (error) {
28
+ console.error(`Error reading file ${filePath}:`, error.message);
29
+ // Keep the original comment if file can't be read
30
+ }
31
+ }
32
+
33
+ // Write the processed content to README.md
34
+ await fs.writeFile('README.md', processedContent, 'utf-8');
35
+ console.log('Successfully processed README.md');
36
+ } catch (error) {
37
+ console.error('Error processing README:', error);
38
+ process.exit(1);
39
+ }
40
+ }
41
+
42
+ processReadme();
@@ -0,0 +1,13 @@
1
+ {% if trail.length > 0 %}
2
+ <nav class="breadcrumbs">
3
+ {% for ancestor in trail %}
4
+ <a href="{{ ancestor.page.url }}">{{ ancestor.data.title }}</a>
5
+ {% if ancestor.data.siblings.length > 1 %}
6
+ <ul class="siblings">
7
+ {% for sibling in ancestor.data.siblings %}
8
+ <li><a href="{{ sibling.page.url }}">{{ sibling.data.title }}</a></li>
9
+ {% endfor %}
10
+ </ul>
11
+ {% endif %}
12
+ {% endfor %}
13
+ {% endif %}
@@ -0,0 +1,6 @@
1
+ {% if trail.length > 0 %}
2
+ <nav class="breadcrumbs">
3
+ {% for ancestor in trail %}
4
+ <a href="{{ ancestor.page.url }}">{{ ancestor.data.title }}</a>
5
+ {% endfor %}
6
+ {% endif %}
@@ -0,0 +1,15 @@
1
+ <nav class="prev-next">
2
+ {% if previousPage -%}
3
+ <a class="previous" href="{{ previousPage.url }}">
4
+ <span class="desc">Previous page</span>
5
+ <span class="title">{{ previousPage.data.title }}</span>
6
+ </a>
7
+ {%- endif %}
8
+
9
+ {% if nextPage -%}
10
+ <a class="next" href="{{ nextPage.url }}">
11
+ <span class="desc">Previous page</span>
12
+ <span class="title">{{ nextPage.data.title }}</span>
13
+ </a>
14
+ {%- endif %}
15
+ </nav>
@@ -0,0 +1,5 @@
1
+ <ul>
2
+ {% for page in collection.roots %}
3
+ {% include './sidebar-item.njk' %}
4
+ {% endfor %}
5
+ </ul>
@@ -0,0 +1,14 @@
1
+ {% if page.data.shown -%}
2
+ <li>
3
+ <a href="{{ page.data.url or page.url }}">{{ page.data.title }}</a>
4
+
5
+ {% set children = page.data.children %}
6
+ {% if children.length > 0 %}
7
+ <ul>
8
+ {% for page in children %}
9
+ {% include 'sidebar-item.njk' %}
10
+ {% endfor %}
11
+ </ul>
12
+ {% endif %}
13
+ </li>
14
+ {%- endif %}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "eleventy-plugin-nav",
3
+ "version": "0.0.1",
4
+ "description": "Description",
5
+ "keywords": [
6
+ "eleventy-plugin"
7
+ ],
8
+ "homepage": "https://github.com/h-docs/eleventy-plugin-nav/#readme",
9
+ "bugs": {
10
+ "url": "https://github.com/h-docs/eleventy-plugin-nav/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/h-docs/eleventy-plugin-nav.git"
15
+ },
16
+ "license": "MIT",
17
+ "author": "Lea Verou",
18
+ "type": "module",
19
+ "main": "src/index.js",
20
+ "scripts": {
21
+ "release": "release-it",
22
+ "build": "node _build/readme.js",
23
+ "test": "echo \"Error: no test specified\" && exit 1"
24
+ },
25
+ "devDependencies": {
26
+ "prettier-plugin-brace-style": "^0.7.2",
27
+ "prettier-plugin-merge": "^0.7.2",
28
+ "prettier-plugin-space-before-function-paren": "^0.0.5",
29
+ "release-it": "^18.1.2"
30
+ },
31
+ "peerDependencies": {
32
+ "@11ty/eleventy": "^3"
33
+ }
34
+ }
package/src/config.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Default options
3
+ */
4
+ export const defaultConfig = {
5
+ hidden: page => page.data.unlisted,
6
+ sort: { "data.order": 1, "data.title": "" },
7
+ };
8
+
9
+ /**
10
+ * Current options (updated by index.js)
11
+ */
12
+ const config = Object.create(defaultConfig);
13
+ export default config;
@@ -0,0 +1,50 @@
1
+ import { getCollectionItemFromUrl } from "./util.js";
2
+
3
+ /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
+
5
+ /**
6
+ * All ancestors of current page, including the root, plus the page itself.
7
+ * @returns {CollectionItem[]}
8
+ */
9
+ export function lineage (data) {
10
+ let { page } = data;
11
+ let url = page.url;
12
+ let ret = [];
13
+ let currentItem = getCollectionItemFromUrl(url, data);
14
+
15
+ if (!currentItem) {
16
+ // Might have eleventyExcludeFromCollections, jump to parent
17
+ let parentUrl = data.parentUrl;
18
+ if (parentUrl) {
19
+ url = parentUrl;
20
+ }
21
+ }
22
+
23
+ for (let item; (item = getCollectionItemFromUrl(url, data)); url = item.data.parentUrl) {
24
+ ret.unshift(item);
25
+ }
26
+
27
+ return ret;
28
+ }
29
+
30
+ /**
31
+ * Ancestors of current page, not including the root.
32
+ * @returns {CollectionItem[]}
33
+ */
34
+ export function trail (data) {
35
+ let { page } = data;
36
+ let url = page.url;
37
+ let ret = data.lineage;
38
+
39
+ if (ret[0]?.page.url === "/") {
40
+ // Remove root
41
+ ret.shift();
42
+ }
43
+
44
+ if (ret.at(-1)?.page.url === url) {
45
+ // Remove current page
46
+ ret.pop();
47
+ }
48
+
49
+ return ret;
50
+ }
@@ -0,0 +1,26 @@
1
+ import { sort } from "../filters.js";
2
+
3
+ /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
+
5
+ /**
6
+ * Child pages of current page
7
+ * @returns {CollectionItem[]} Array of child pages
8
+ */
9
+ export function children (data) {
10
+ let { collections, page, parentOf } = data;
11
+
12
+ if (parentOf) {
13
+ return collections[parentOf];
14
+ }
15
+
16
+ let collection = collections.all ?? [];
17
+ let url = page.url;
18
+
19
+ let ret = collection.filter(item => {
20
+ return item.data.parentUrl === url;
21
+ });
22
+
23
+ sort(ret);
24
+
25
+ return ret;
26
+ }
@@ -0,0 +1,83 @@
1
+ import { getCollectionItemFromUrl } from "./util.js";
2
+ import config from "../config.js";
3
+
4
+ /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
5
+
6
+ /**
7
+ * Default parent slug. Can be overridden by explicitly setting parent in the data.
8
+ * It can be either the URL slug of a page in the same directory or a parent directory.
9
+ * @returns {string | undefined}
10
+ */
11
+ export function parent (data) {
12
+ let { parent, page } = data;
13
+
14
+ if (parent) {
15
+ return parent;
16
+ }
17
+
18
+ return page.url.split("/").filter(Boolean).at(-2);
19
+ }
20
+
21
+ /**
22
+ * URL of parent page
23
+ * @returns {string | undefined}
24
+ */
25
+ export function parentUrl (data) {
26
+ let { parent, page } = data;
27
+ let ret = getParentUrl(page.url, parent);
28
+
29
+ if (config.ignoreAncestor?.(ret)) {
30
+ let ancestorItem = getCollectionItemFromUrl(ret, data);
31
+ return ancestorItem.parentUrl;
32
+ }
33
+
34
+ return ret;
35
+ }
36
+
37
+ /**
38
+ * Collection item of parent page
39
+ * @returns {CollectionItem | undefined} Parent page item
40
+ */
41
+ export function parentItem (data) {
42
+ return getCollectionItemFromUrl(data.parentUrl, data);
43
+ }
44
+
45
+ /**
46
+ * Resolve a parent slug against a page URL
47
+ * @param {string} url - The URL of the page
48
+ * @param {string} parent - The slug of the parent page
49
+ * @returns {string} The resolved URL of the parent page
50
+ */
51
+ function getParentUrl (url, parent) {
52
+ if (!url || !parent) {
53
+ return undefined;
54
+ }
55
+
56
+ let parts = url.split("/").filter(Boolean);
57
+ let ancestorIndex = parts.findLastIndex(part => part === parent);
58
+ let retParts = parts.slice();
59
+
60
+ if (ancestorIndex > -1) {
61
+ // parent is an ancestor
62
+ retParts.splice(ancestorIndex + 1);
63
+ }
64
+ else {
65
+ // parent is a sibling in the same directory
66
+ retParts.splice(-1, 1, parent);
67
+ }
68
+
69
+ let ret = retParts.join("/");
70
+
71
+ if (url.startsWith("/")) {
72
+ // If the current page starts with a slash, make sure the parent does too
73
+ // This is pretty much always the case with 11ty page URLs
74
+ ret = "/" + ret;
75
+ }
76
+
77
+ if (!retParts.at(-1)?.includes(".") && !ret.endsWith("/")) {
78
+ // If no extension, make sure to end with a slash
79
+ ret += "/";
80
+ }
81
+
82
+ return ret;
83
+ }
@@ -0,0 +1,64 @@
1
+ import { getCollectionItemFromUrl } from "./util.js";
2
+
3
+ /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
+
5
+ /**
6
+ * Pages by the same parent, including the current page.
7
+ * @returns {CollectionItem[]}
8
+ **/
9
+ export function allSiblings (data) {
10
+ return data.parentItem?.children ?? data.collections.roots ?? [];
11
+ }
12
+
13
+ /**
14
+ * Index of current page among its parent's children
15
+ * @returns { number }
16
+ **/
17
+ export function siblingIndex (data) {
18
+ let { url, allSiblings } = data;
19
+ let currentItem = getCollectionItemFromUrl(url, data);
20
+ return allSiblings.indexOf(currentItem) ?? -1;
21
+ }
22
+
23
+ /**
24
+ * Other pages by the same parent that come before the current page.
25
+ * @returns {CollectionItem[]}
26
+ **/
27
+ export function siblingsBefore (data) {
28
+ let { allSiblings, siblingIndex } = data;
29
+ return siblingIndex > -1 ? allSiblings.slice(0, siblingIndex) : [];
30
+ }
31
+
32
+ /**
33
+ * Other pages by the same parent that come after the current page.
34
+ * @returns {CollectionItem[]}
35
+ **/
36
+ export function siblingsAfter (data) {
37
+ let { allSiblings, siblingIndex } = data;
38
+ return siblingIndex > -1 ? allSiblings.slice(siblingIndex) : [];
39
+ }
40
+
41
+ /**
42
+ * Other pages by the same parent. Excludes current page.
43
+ * @returns {CollectionItem[]}
44
+ **/
45
+ export function siblings (data) {
46
+ let { siblingsBefore, siblingsAfter } = data;
47
+ return [...siblingsBefore, ...siblingsAfter];
48
+ }
49
+
50
+ export function nextPage (data) {
51
+ while (data && !data.siblingsAfter[0]) {
52
+ data = data.parentItem?.data;
53
+ }
54
+
55
+ return data?.siblingsAfter[0];
56
+ }
57
+
58
+ export function previousPage (data) {
59
+ while (data && !data.siblingsBefore.at(-1)) {
60
+ data = data.parentItem?.data;
61
+ }
62
+
63
+ return data?.siblingsBefore.at(-1);
64
+ }
@@ -0,0 +1,27 @@
1
+ export function getCollectionItemFromUrl (url, data) {
2
+ if (!data?.collections?.all) {
3
+ return;
4
+ }
5
+
6
+ return data.collections.all.find(item => item.url === url);
7
+ }
8
+
9
+ /**
10
+ * Convert a value to an array. `undefined` and `null` values are converted to an empty array.
11
+ * @param {*} value - The value to convert.
12
+ * @returns {any[]} The converted array.
13
+ */
14
+ export function toArray (value) {
15
+ value ??= [];
16
+
17
+ if (Array.isArray(value)) {
18
+ return value;
19
+ }
20
+
21
+ // Don't convert "foo" into ["f", "o", "o"]
22
+ if (typeof value !== "string" && typeof value[Symbol.iterator] === "function") {
23
+ return Array.from(value);
24
+ }
25
+
26
+ return [value];
27
+ }
@@ -0,0 +1,16 @@
1
+ import config from "../config.js";
2
+ import { toArray } from "./util.js";
3
+
4
+ export function hidden (data) {
5
+ let ret = true;
6
+
7
+ if (config.hidden) {
8
+ ret = toArray(config.hidden).some(hidden => hidden(data.page));
9
+ }
10
+
11
+ return;
12
+ }
13
+
14
+ export function shown (data) {
15
+ return !hidden(data);
16
+ }
package/src/data.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Global data for all pages
3
+ */
4
+
5
+ export * from "./data/parent.js";
6
+ export * from "./data/children.js";
7
+ export * from "./data/ancestors.js";
8
+ export * from "./data/siblings.js";
package/src/filters.js ADDED
@@ -0,0 +1,78 @@
1
+ import config from "./config.js";
2
+
3
+ function getCollection (name) {
4
+ // From https://github.com/11ty/eleventy/blob/d3d24ccddb804e6e14773501d8c4e07e2c4b9c2b/src/Filters/GetLocaleCollectionItem.js#L39-L43
5
+ return (
6
+ this.collections?.[name] ||
7
+ this.ctx?.collections?.[name] ||
8
+ this.context?.environments?.collections?.[name]
9
+ );
10
+ }
11
+
12
+ export function getCollectionItemFromUrl (url, collection) {
13
+ if (!url) {
14
+ return null;
15
+ }
16
+ collection ??= getCollection.call(this, "all") || [];
17
+ return collection.find(item => item.url === url);
18
+ }
19
+
20
+ export function deepGet (obj, key) {
21
+ key = Array.isArray(key) ? key : key.split(".");
22
+ return key.reduce((subObj, property) => subObj?.[property], obj);
23
+ }
24
+
25
+ export function isNumeric (value) {
26
+ return typeof value === "number" || (typeof value === "string" && !isNaN(value));
27
+ }
28
+
29
+ export function isEmpty (value) {
30
+ return value === null || value === undefined || value === "";
31
+ }
32
+
33
+ function compare (a, b) {
34
+ let isEmptyA = isEmpty(a);
35
+ let isEmptyB = isEmpty(b);
36
+
37
+ if (isEmptyA) {
38
+ if (isEmptyB) {
39
+ return 0;
40
+ }
41
+ else {
42
+ return 1;
43
+ }
44
+ }
45
+ else if (isEmptyB) {
46
+ return -1;
47
+ }
48
+
49
+ // Both strings, and at least one non-numeric
50
+ if (isNumeric(a) || isNumeric(b)) {
51
+ return a - b;
52
+ }
53
+
54
+ return (a + "").localeCompare(b);
55
+ }
56
+
57
+ /**
58
+ * Sort an array of objects by one or more of their properties
59
+ **/
60
+ export function sort (arr, sortBy = config.sort) {
61
+ let keys = Array.isArray(sortBy) ? sortBy : Object.keys(sortBy);
62
+
63
+ return arr.sort((a, b) => {
64
+ let aValues = keys.map(key => deepGet(a, key) ?? sortBy[key]);
65
+ let bValues = keys.map(key => deepGet(b, key) ?? sortBy[key]);
66
+
67
+ for (let i = 0; i < aValues.length; i++) {
68
+ let aVal = aValues[i];
69
+ let bVal = bValues[i];
70
+ let result = compare(aVal, bVal);
71
+
72
+ // They are not equal in terms of comparison OR we're at the last key
73
+ if (result !== 0 || i === aValues.length - 1) {
74
+ return result;
75
+ }
76
+ }
77
+ });
78
+ }
package/src/index.js ADDED
@@ -0,0 +1,28 @@
1
+ import * as filters from "./filters.js";
2
+ import * as data from "./data.js";
3
+ import config from "./config.js";
4
+
5
+ /**
6
+ * @param {import("@11ty/eleventy").UserConfig} eleventyConfig
7
+ * @param {typeof config} [options]
8
+ */
9
+ export default function eleventyNav (eleventyConfig, options = config) {
10
+ Object.assign(config, options);
11
+
12
+ eleventyConfig.addGlobalData("eleventyComputed", data);
13
+
14
+ for (let name in filters) {
15
+ eleventyConfig.addFilter(name, filters[name]);
16
+ }
17
+
18
+ // Top-level items with no parent
19
+ eleventyConfig.addCollection("roots", collectionsApi => {
20
+ let roots = collectionsApi.getAll().filter(item => {
21
+ return !item.data.parent;
22
+ });
23
+
24
+ roots = filters.sort(roots, options.sort);
25
+
26
+ return roots;
27
+ });
28
+ }