eleventy-plugin-nav 0.0.3 → 0.0.4

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/README.md CHANGED
@@ -1,5 +1,3 @@
1
- <!-- DO NOT EDIT THIS FILE DIRECTLY, EDIT README.src.md INSTEAD -->
2
-
3
1
  # eleventy-plugin-nav
4
2
 
5
3
  Semi-automatic hierarchical navigation for 11ty.
@@ -34,16 +32,19 @@ export default function (eleventyConfig) {
34
32
  }
35
33
  ```
36
34
 
37
- ### Options
35
+ ## Configuration
36
+
37
+ ### Global Options
38
38
 
39
39
  The following options are available to customize the plugin behavior:
40
40
 
41
41
  | Option | Type | Default value | Description |
42
42
  | ------ | ---- | ------------- | ----------- |
43
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. |
44
+ | `hidden` | `page: CollectionItem => boolean` | `page => page.data.unlisted` | A function that takes a page and returns true if the page should be hidden from listings. |
45
+ | `areas` | `string[]` | `[]` | A list of URLs for your site’s top-level "areas". If specified, the plugin will add `area*` data to each page, to facilitate top-level navigation menus, versioning, localization etc. |
45
46
 
46
- ## Usage
47
+ ### Page-level Data
47
48
 
48
49
  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
50
  Stuff should just work.
@@ -56,7 +57,7 @@ For example:
56
57
  - etc.
57
58
 
58
59
  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
+ These are just 11ty data, so you can specify them in any way that is convenient: via the frontmatter, directory data etc.
60
61
 
61
62
  #### `parent`
62
63
 
@@ -89,7 +90,11 @@ and each restaurant has a list of dishes, whose URL is `restaurants/foo/dishes/b
89
90
  However, you also want to have `dishes/bar` pages that list all restaurants that serve a given dish.
90
91
  Assuming each dish page was using a `dish` tag, you could specify `parentOf: dish` on the dish page across all restaurants.
91
92
 
92
- ### Output Page Data
93
+ ## Usage
94
+
95
+ The plugin adds several data items to every page, as well as some filters and collections that can be used to build navigation-related UI.
96
+
97
+ ### Page Data
93
98
 
94
99
  This plugin makes several data items available on every page, which can be used to construct a variety of navigation-related UI,
95
100
  such as indices, navbars, breadcrumbs and the like.
@@ -97,7 +102,7 @@ such as indices, navbars, breadcrumbs and the like.
97
102
  | Data | Type | Description |
98
103
  | -------------- | ------------------ | ----------------------------------------------------------------------------- |
99
104
  | `parent` | `string` | Slug of parent page |
100
- | `parentURL` | `string` | `page.url` of parent page |
105
+ | `parentUrl` | `string` | `page.url` of parent page |
101
106
  | `parentItem` | `CollectionItem` | Collection item for parent page |
102
107
  | `children` | `CollectionItem[]` | Array of a page's direct children |
103
108
  | `lineage` | `CollectionItem[]` | Array of a page's ancestors, starting from the root, plus the page itself. |
@@ -108,87 +113,41 @@ such as indices, navbars, breadcrumbs and the like.
108
113
  | `previousPage` | `CollectionItem` | The page that comes after the current page in the parent's children |
109
114
  | `hidden` | `boolean` | Whether the page should be included in listings |
110
115
  | `shown` | `boolean` | Whether the page should be included in listings |
116
+ | `rootItem` | `CollectionItem` | The item of the page’s homepage. |
117
+ | `areaUrl` | `string` | The area URL of the site this page belongs to, if specified. `"/"` if no areas. |
118
+ | `areaItems` | `CollectionItem[]` | A collection of the items for all top-level areas. |
119
+ | `areaItem` | `CollectionItem` | The collection item for the area this page belongs to, if specified. Resolves to `rootItem` if no areas are specified. |
111
120
 
112
121
  You can access this data by their names on the page itself, or on `item.data` on a collection item.
113
122
 
114
- ### Roots collection
123
+ ### Filters
115
124
 
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.
125
+ The plugin also adds several filters to help you work with the data.
126
+ | Filter | Arguments | Description |
127
+ | --------------- | --------- | --------------------------------------------------------------------------- |
128
+ | `isCurrentPage` | `url` | Returns `true` if the page is the current page, based on the URL. |
129
+ | `isAncestorPage` | `url` | Returns `true` if the page is an ancestor of the current page, based on the URL. |
130
+ | `isAncestorOrCurrentPage | `url` | Returns `true` if the page is an ancestor or the current page, based on the URL. |
119
131
 
120
- ## Examples / Recipes
121
-
122
- ### Nested sidebar
132
+ ### Collections
123
133
 
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
+ All collections added are sorted by the default sort order you specify.
134
135
 
135
- `sidebar-item.njk`:
136
+ | Collection | Description |
137
+ | ---------- | ----------- |
138
+ | `roots` | Contains all pages that are not children of any other page. Useful for creating a top-level navigation menu or listing all pages in the site. |
136
139
 
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 %}
140
+ ## Examples / Recipes
152
141
 
153
- ```
142
+ ### Nested sidebar
154
143
 
144
+ - [Sidebar](_includes/sidebar/groups.njk)
145
+ - [Sidebar item](_includes/sidebar/item.njk)
155
146
 
156
147
  ### Breadcrumbs
157
148
 
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
- -----
149
+ - [Basic breadcrumbs](_includes/breadcrumbs/basic.njk)
150
+ - [Advanced breadcrumbs](_includes/breadcrumbs/advanced.njk) (with menu of siblings)
190
151
 
191
152
  You can find more recipes in [`_includes`](_includes).
192
153
 
193
- If you want to use a recipe directly, and don’t need to tweak it at all,
194
- you can
@@ -1,5 +1,5 @@
1
1
  <ul>
2
- {% for page in collection.roots %}
2
+ {% for page in collections.roots %}
3
3
  {% include './item.njk' %}
4
4
  {% endfor %}
5
5
  </ul>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eleventy-plugin-nav",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "description": "Description",
5
5
  "keywords": [
6
6
  "eleventy-plugin"
@@ -19,7 +19,6 @@
19
19
  "main": "src/index.js",
20
20
  "scripts": {
21
21
  "release": "release-it",
22
- "build": "node _build/readme.js",
23
22
  "test": "echo \"Error: no test specified\" && exit 1"
24
23
  },
25
24
  "devDependencies": {
@@ -0,0 +1,12 @@
1
+ import { sort } from "./util.js";
2
+
3
+ // Top-level items with no parent
4
+ export function roots (options, collectionsApi) {
5
+ let roots = collectionsApi.getAll().filter(item => {
6
+ return !item.data.parent;
7
+ });
8
+
9
+ roots = sort(roots, options.sort);
10
+
11
+ return roots;
12
+ }
@@ -1,4 +1,4 @@
1
- import { getCollectionItemFromUrl } from "./util.js";
1
+ import { getCollectionItemFromUrl } from "../util.js";
2
2
 
3
3
  /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
4
 
@@ -28,7 +28,7 @@ export function lineage (data) {
28
28
  }
29
29
 
30
30
  /**
31
- * Ancestors of current page, not including the root.
31
+ * Ancestors of current page, not including the root or the current page.
32
32
  * @returns {CollectionItem[]}
33
33
  */
34
34
  export function trail (data) {
@@ -0,0 +1,41 @@
1
+ import { getCollectionItemFromUrl } from "../util.js";
2
+ import config from "../config.js";
3
+
4
+ export function areaItems(data) {
5
+ if (!data.collections.all?.length) {
6
+ // First pass
7
+ return undefined;
8
+ }
9
+
10
+ if (!config.areas) {
11
+ return [data.rootItem];
12
+ }
13
+
14
+ return config.areas.map(area => getCollectionItemFromUrl(area, data)).filter(Boolean);
15
+ }
16
+
17
+ export function areaUrl(data) {
18
+ let { lineage } = data;
19
+
20
+ if (data.areaUrl) {
21
+ return data.areaUrl;
22
+ }
23
+
24
+ if (!config.areas) {
25
+ return "/";
26
+ }
27
+
28
+ let areas = new Set(config.areas);
29
+
30
+ if (areas.has(data.page.url)) {
31
+ return data.page.url;
32
+ }
33
+
34
+ return lineage?.find?.(item => areas.has(item.page.url))?.page.url;
35
+ }
36
+
37
+ export function areaItem(data) {
38
+ let { areaUrl, rootItem } = data;
39
+
40
+ return areaUrl ? getCollectionItemFromUrl(areaUrl, data) : rootItem;
41
+ }
@@ -1,4 +1,5 @@
1
- import { sort } from "../filters.js";
1
+ import { sort } from "../util.js";
2
+ import { parentUrl as getParentUrl, parentItem as getParentItem } from "./parent.js";
2
3
 
3
4
  /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
5
 
@@ -14,10 +15,30 @@ export function children (data) {
14
15
  }
15
16
 
16
17
  let collection = collections.all ?? [];
17
- let url = page.url;
18
+
19
+ if (!collection.length) {
20
+ // Cannot be computed yet
21
+ return undefined;
22
+ }
18
23
 
19
24
  let ret = collection.filter(item => {
20
- return item.data.parentUrl === url;
25
+ let d = { ...item.data };
26
+ d.parentUrl ||= getParentUrl(item.data);
27
+
28
+ if (d.parentUrl && page.url) {
29
+ // Both pages have URLs, so we can just compare those
30
+
31
+ return d.parentUrl === page.url;
32
+ }
33
+ else {
34
+ d.parentItem ??= getParentItem(d);
35
+ if (d.parentItem) {
36
+ // We compare input paths because not all pages have a URL
37
+ return d.parentItem.inputPath === page.inputPath;
38
+ }
39
+ }
40
+
41
+ return false;
21
42
  });
22
43
 
23
44
  sort(ret);
@@ -1,7 +1,11 @@
1
- import { getCollectionItemFromUrl } from "./util.js";
1
+ import { getCollectionItemFromUrl } from "../util.js";
2
2
 
3
3
  /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
4
 
5
+ export function rootItem (data) {
6
+ return getCollectionItemFromUrl("/", data);
7
+ }
8
+
5
9
  /**
6
10
  * Default parent slug. Can be overridden by explicitly setting parent in the data.
7
11
  * It can be either the URL slug of a page in the same directory or a parent directory.
@@ -14,64 +18,106 @@ export function parent (data) {
14
18
  return parent;
15
19
  }
16
20
 
21
+ if (page.url === false) {
22
+ return undefined;
23
+ }
24
+
17
25
  return page.url.split("/").filter(Boolean).at(-2);
18
26
  }
19
27
 
28
+ /**
29
+ * Collection item of parent page
30
+ * @returns {CollectionItem | null} Parent page item
31
+ */
32
+ export function parentItem (data) {
33
+ let { parent, page, collections } = data;
34
+
35
+ if (parent === undefined) {
36
+ // Root page
37
+ return null;
38
+ }
39
+
40
+ if (!collections.all?.length) {
41
+ // First pass, cannot be computed yet
42
+ return undefined;
43
+ }
44
+
45
+ let parentUrl = getParentUrl(page.url, parent);
46
+
47
+ if (!parentUrl) {
48
+ return null;
49
+ }
50
+
51
+ let parentItem = getCollectionItemFromUrl(parentUrl, data);
52
+
53
+ if (parentItem) {
54
+ return parentItem;
55
+ }
56
+
57
+ // If we're here, our parent may be a page with permalink: false
58
+ let dirPath = getDirPath(page.inputPath);
59
+
60
+ let ret = findParent(dirPath, parent, collections.all);
61
+
62
+ return ret ?? null;
63
+ }
64
+
20
65
  /**
21
66
  * URL of parent page
22
67
  * @returns {string | undefined}
23
68
  */
24
69
  export function parentUrl (data) {
25
- let { parent, page } = data;
26
- let ret = getParentUrl(page.url, parent);
70
+ if (data.parentItem) {
71
+ // Second pass
72
+ return data.parentItem?.url;
73
+ }
27
74
 
28
- return ret;
75
+ // First pass
76
+ return getParentUrl(data.page.url, data.parent);
29
77
  }
30
78
 
31
- /**
32
- * Collection item of parent page
33
- * @returns {CollectionItem | undefined} Parent page item
34
- */
35
- export function parentItem (data) {
36
- return getCollectionItemFromUrl(data.parentUrl, data);
79
+ function findParent (dirPath, parent, collection) {
80
+ return collection?.filter(item => {
81
+ let itemDirPath = getDirPath(item.inputPath);
82
+ return dirPath.startsWith(itemDirPath) && item.fileSlug === parent;
83
+ })[0];
37
84
  }
38
85
 
39
- /**
40
- * Resolve a parent slug against a page URL
41
- * @param {string} url - The URL of the page
42
- * @param {string} parent - The slug of the parent page
43
- * @returns {string} The resolved URL of the parent page
44
- */
45
- function getParentUrl (url, parent) {
46
- if (!url || !parent) {
47
- return undefined;
86
+ function getDirPath (inputPath) {
87
+ let parts = inputPath.split("/");
88
+ let trailingSlash = parts.at(-1) === "";
89
+
90
+ let ret = parts.slice(0, trailingSlash ? -2 : -1);
91
+
92
+ if (!trailingSlash) {
93
+ // If no trailing slash, add one
94
+ ret.push("");
48
95
  }
49
96
 
50
- let parts = url.split("/").filter(Boolean);
51
- let ancestorIndex = parts.findLastIndex(part => part === parent);
52
- let retParts = parts.slice();
97
+ return ret.join("/");
98
+ }
53
99
 
54
- if (ancestorIndex > -1) {
55
- // parent is an ancestor
56
- retParts.splice(ancestorIndex + 1);
100
+ function getParentUrl (url, parent) {
101
+ if (!url || url === "/") {
102
+ return undefined;
57
103
  }
58
- else {
59
- // parent is a sibling in the same directory
60
- retParts.splice(-1, 1, parent);
104
+
105
+ if (!parent) {
106
+ return "/";
61
107
  }
62
108
 
63
- let ret = retParts.join("/");
109
+ let parts = url.split("/");
110
+ let trailingSlash = parts.at(-1) === "";
111
+ let ancestorIndex = parts.findLastIndex(part => part === parent);
112
+ let retParts = parts.slice(0, ancestorIndex > -1 ? ancestorIndex : trailingSlash ? -2 : -1);
113
+ retParts.push(parent);
64
114
 
65
- if (url.startsWith("/")) {
66
- // If the current page starts with a slash, make sure the parent does too
67
- // This is pretty much always the case with 11ty page URLs
68
- ret = "/" + ret;
69
- }
115
+ let ret = retParts.join("/");
70
116
 
71
117
  if (!retParts.at(-1)?.includes(".") && !ret.endsWith("/")) {
72
118
  // If no extension, make sure to end with a slash
73
119
  ret += "/";
74
120
  }
75
121
 
76
- return ret;
122
+ return ret || "/";
77
123
  }
@@ -1,4 +1,4 @@
1
- import { getCollectionItemFromUrl } from "./util.js";
1
+ import { getCollectionItemFromUrl } from "../util.js";
2
2
 
3
3
  /** @typedef {import("@11ty/eleventy").CollectionItem} CollectionItem */
4
4
 
@@ -27,7 +27,11 @@ export function siblingIndex (data) {
27
27
 
28
28
  if (index === -1) {
29
29
  // Try another way
30
- index = allSiblings.findIndex(item => item.url === url);
30
+ index = allSiblings.findIndex(
31
+ item =>
32
+ (url && item.url === url) ||
33
+ (page.inputPath && item.page.inputPath === page.inputPath),
34
+ );
31
35
  }
32
36
 
33
37
  return index;
@@ -39,7 +43,16 @@ export function siblingIndex (data) {
39
43
  **/
40
44
  export function siblingsBefore (data) {
41
45
  let { allSiblings, siblingIndex } = data;
42
- return siblingIndex > -1 ? allSiblings.slice(0, siblingIndex) : allSiblings;
46
+
47
+ if (siblingIndex > -1) {
48
+ return allSiblings.slice(0, siblingIndex);
49
+ }
50
+
51
+ if (allSiblings) {
52
+ return [...allSiblings];
53
+ }
54
+
55
+ return [];
43
56
  }
44
57
 
45
58
  /**
@@ -48,7 +61,16 @@ export function siblingsBefore (data) {
48
61
  **/
49
62
  export function siblingsAfter (data) {
50
63
  let { allSiblings, siblingIndex } = data;
51
- return siblingIndex > -1 ? allSiblings.slice(siblingIndex + 1) : allSiblings;
64
+
65
+ if (siblingIndex > -1) {
66
+ return allSiblings.slice(siblingIndex + 1);
67
+ }
68
+
69
+ if (allSiblings) {
70
+ return [...allSiblings];
71
+ }
72
+
73
+ return [];
52
74
  }
53
75
 
54
76
  /**
@@ -56,26 +78,32 @@ export function siblingsAfter (data) {
56
78
  * @returns {CollectionItem[]}
57
79
  **/
58
80
  export function siblings (data) {
59
- let { siblingIndex, siblingsBefore, siblingsAfter } = data;
81
+ let { siblingIndex, allSiblings } = data;
82
+
83
+ if (!allSiblings) {
84
+ return [];
85
+ }
86
+
87
+ let ret = [...allSiblings];
60
88
 
61
89
  if (siblingIndex > -1) {
62
- return [...siblingsBefore, ...siblingsAfter];
90
+ ret.splice(siblingIndex, 1);
63
91
  }
64
92
 
65
- return allSiblings;
93
+ return ret;
66
94
  }
67
95
 
68
96
  export function nextPage (data) {
69
- while (data && !data.siblingsAfter[0]) {
70
- data = data.parentItem?.data;
97
+ while (data && data.parentItem && !data.siblingsAfter[0]) {
98
+ data = data.parentItem.data;
71
99
  }
72
100
 
73
101
  return data?.siblingsAfter[0];
74
102
  }
75
103
 
76
104
  export function previousPage (data) {
77
- while (data && !data.siblingsBefore.at(-1)) {
78
- data = data.parentItem?.data;
105
+ while (data && data.parentItem && !data.siblingsBefore.at(-1)) {
106
+ data = data.parentItem.data;
79
107
  }
80
108
 
81
109
  return data?.siblingsBefore.at(-1);
@@ -1,16 +1,16 @@
1
1
  import config from "../config.js";
2
- import { toArray } from "./util.js";
2
+ import { toArray } from "../util.js";
3
3
 
4
4
  export function hidden (data) {
5
5
  let ret = true;
6
6
 
7
7
  if (config.hidden) {
8
- ret = toArray(config.hidden).some(hidden => hidden(data.page));
8
+ ret = toArray(config.hidden).some(hidden => hidden.call(this, data.page));
9
9
  }
10
10
 
11
11
  return ret;
12
12
  }
13
13
 
14
14
  export function shown (data) {
15
- return !hidden(data);
15
+ return !hidden.call(this, data);
16
16
  }
package/src/data.js CHANGED
@@ -7,3 +7,4 @@ export * from "./data/children.js";
7
7
  export * from "./data/ancestors.js";
8
8
  export * from "./data/siblings.js";
9
9
  export * from "./data/visible.js";
10
+ export * from "./data/areas.js";
package/src/filters.js CHANGED
@@ -1,5 +1,3 @@
1
- import config from "./config.js";
2
-
3
1
  function getCollection (name) {
4
2
  // From https://github.com/11ty/eleventy/blob/d3d24ccddb804e6e14773501d8c4e07e2c4b9c2b/src/Filters/GetLocaleCollectionItem.js#L39-L43
5
3
  return (
@@ -17,62 +15,14 @@ export function getCollectionItemFromUrl (url, collection) {
17
15
  return collection.find(item => item.url === url);
18
16
  }
19
17
 
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));
18
+ export function isCurrentPage (url) {
19
+ return url === this.page.url;
27
20
  }
28
21
 
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);
22
+ export function isAncestorOrCurrentPage (url) {
23
+ return this.data.lineage.some(item => item.url === url);
55
24
  }
56
25
 
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
- });
26
+ export function isAncestorPage (url) {
27
+ return !isCurrentPage.call(this, url) && isAncestorOrCurrentPage.call(this, url);
78
28
  }
package/src/index.js CHANGED
@@ -1,13 +1,16 @@
1
+ import config from "./config.js";
1
2
  import * as filters from "./filters.js";
2
3
  import * as data from "./data.js";
3
- import config from "./config.js";
4
+ import * as collections from "./collections.js";
4
5
 
5
6
  /**
6
7
  * @param {import("@11ty/eleventy").UserConfig} eleventyConfig
7
8
  * @param {typeof config} [options]
8
9
  */
9
- export default function eleventyNav (eleventyConfig, options = config) {
10
- Object.assign(config, options);
10
+ export default function eleventyNav (eleventyConfig, options) {
11
+ if (options) {
12
+ Object.assign(config, options);
13
+ }
11
14
 
12
15
  eleventyConfig.addGlobalData("eleventyComputed", data);
13
16
 
@@ -15,14 +18,7 @@ export default function eleventyNav (eleventyConfig, options = config) {
15
18
  eleventyConfig.addFilter(name, filters[name]);
16
19
  }
17
20
 
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
- });
21
+ for (let name in collections) {
22
+ eleventyConfig.addCollection(name, collections[name].bind(this, config));
23
+ }
28
24
  }
package/src/util.js ADDED
@@ -0,0 +1,93 @@
1
+ import config from "./config.js";
2
+
3
+ export function deepGet (obj, key) {
4
+ key = Array.isArray(key) ? key : key.split(".");
5
+ return key.reduce((subObj, property) => subObj?.[property], obj);
6
+ }
7
+
8
+ export function isNumeric (value) {
9
+ return typeof value === "number" || (typeof value === "string" && !isNaN(value));
10
+ }
11
+
12
+ export function isEmpty (value) {
13
+ return value === null || value === undefined || value === "";
14
+ }
15
+
16
+ export function getCollectionItemFromUrl (url, data) {
17
+ if (url === false) {
18
+ return null;
19
+ }
20
+
21
+ if (!data?.collections?.all) {
22
+ return;
23
+ }
24
+
25
+ return data.collections.all.find(item => item.url === url);
26
+ }
27
+
28
+ /**
29
+ * Convert a value to an array. `undefined` and `null` values are converted to an empty array.
30
+ * @param {*} value - The value to convert.
31
+ * @returns {any[]} The converted array.
32
+ */
33
+ export function toArray (value) {
34
+ value ??= [];
35
+
36
+ if (Array.isArray(value)) {
37
+ return value;
38
+ }
39
+
40
+ // Don't convert "foo" into ["f", "o", "o"]
41
+ if (typeof value !== "string" && typeof value[Symbol.iterator] === "function") {
42
+ return Array.from(value);
43
+ }
44
+
45
+ return [value];
46
+ }
47
+
48
+ function compare (a, b) {
49
+ let isEmptyA = isEmpty(a);
50
+ let isEmptyB = isEmpty(b);
51
+
52
+ if (isEmptyA) {
53
+ if (isEmptyB) {
54
+ return 0;
55
+ }
56
+ else {
57
+ return 1;
58
+ }
59
+ }
60
+ else if (isEmptyB) {
61
+ return -1;
62
+ }
63
+
64
+ // Both strings, and at least one non-numeric
65
+ if (isNumeric(a) || isNumeric(b)) {
66
+ return a - b;
67
+ }
68
+
69
+ return (a + "").localeCompare(b);
70
+ }
71
+
72
+ /**
73
+ * Sort an array of objects by one or more of their properties
74
+ **/
75
+ export function sort (arr, sortBy = config.sort) {
76
+ let keys = Array.isArray(sortBy) ? sortBy : Object.keys(sortBy);
77
+
78
+ return arr.sort((a, b) => {
79
+ let aValues = keys.map(key => deepGet(a, key) ?? sortBy[key]);
80
+ let bValues = keys.map(key => deepGet(b, key) ?? sortBy[key]);
81
+
82
+ for (let i = 0; i < aValues.length; i++) {
83
+ let aVal = aValues[i];
84
+ let bVal = bValues[i];
85
+ let result = compare(aVal, bVal);
86
+
87
+ // They are not equal in terms of comparison OR we're at the last key
88
+ if (result !== 0 || i === aValues.length - 1) {
89
+ return result;
90
+ }
91
+ }
92
+ });
93
+ }
package/README.src.md DELETED
@@ -1,146 +0,0 @@
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
package/_build/readme.js DELETED
@@ -1,42 +0,0 @@
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();
package/src/data/util.js DELETED
@@ -1,27 +0,0 @@
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
- }