-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy patheleventy-navigation.js
More file actions
277 lines (242 loc) · 8.27 KB
/
Copy patheleventy-navigation.js
File metadata and controls
277 lines (242 loc) · 8.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
const DepGraph = require("dependency-graph").DepGraph;
function findNavigationEntries(nodes = [], key = "") {
let keys = key.split(",").filter(k => Boolean(k));
let pages = {};
for(let entry of nodes) {
let data = entry?.data || {};
if(data?.eleventyNavigation) {
let {eleventyNavigation} = data || {};
let pageKey;
if(!key && !eleventyNavigation.parent) { // top level (no parents)
pageKey = "__default";
} else if(keys.includes(eleventyNavigation.parent)) {
pageKey = eleventyNavigation.parent;
}
if(pageKey) {
if(!pages[pageKey]) {
pages[pageKey] = [];
}
let url = eleventyNavigation.url ?? data?.page?.url;
pages[pageKey].push(Object.assign({ data }, eleventyNavigation, {
...(url ? { url } : {}),
pluginType: "eleventy-navigation",
...(keys.length > 0 ? { parentKey: eleventyNavigation.parent } : {}),
}));
}
}
}
return Object.values(pages).flat().sort(function(a, b) {
if(a.pinned && b.pinned) {
return (a.order || 0) - (b.order || 0);
}
let order = [a.order, b.order];
if(a.pinned) {
order[0] = -Infinity;
}
if(b.pinned) {
order[1] = -Infinity;
}
if(order[0] === undefined && order[1] === undefined) {
return 0;
}
if(order[1] === undefined) {
return -1;
}
if(order[0] === undefined) {
return 1;
}
return order[0] - order[1];
}).map(function(entry) {
if(!entry.title) {
entry.title = entry.key;
}
if(entry.key) {
entry.children = findNavigationEntries(nodes, entry.key);
}
return entry;
});
}
function findDependencies(pages, depGraph, parentKey) {
for( let page of pages ) {
depGraph.addNode(page.key, page);
if(parentKey) {
depGraph.addDependency(page.key, parentKey);
}
if(page.children) {
findDependencies(page.children, depGraph, page.key);
}
}
}
function getDependencyGraph(nodes) {
let pages = findNavigationEntries(nodes);
let graph = new DepGraph();
findDependencies(pages, graph);
return graph;
}
function isOptionMatch(options, name) {
// Liquid.js issue #35
if(Array.isArray(options)) {
return options[options.indexOf(name)]
}
return options[name];
}
function findBreadcrumbEntries(nodes, activeKey, options = {}) {
let graph = getDependencyGraph(nodes);
if (isOptionMatch(options, "allowMissing") && !graph.hasNode(activeKey)) {
// Fail gracefully if the key isn't in the graph
return [];
}
let deps = graph.dependenciesOf(activeKey);
if(isOptionMatch(options, "includeSelf")) {
deps.push(activeKey);
}
return activeKey ? deps.map(key => {
let data = Object.assign({}, graph.getNodeData(key));
delete data.children;
data._isBreadcrumb = true;
return data;
}) : [];
}
function getUrlFilter(eleventyConfig) {
// eleventyConfig.pathPrefix was first available in Eleventy 2.0.0-canary.15
// And in Eleventy 2.0.0-canary.15 we recommend the a built-in transform for pathPrefix
if(eleventyConfig.pathPrefix !== undefined) {
return function(url) {
return url;
};
}
if("getFilter" in eleventyConfig) {
// v0.10.0 and above
return eleventyConfig.getFilter("url");
} else if("nunjucksFilters" in eleventyConfig) {
// backwards compat, hardcoded key
return eleventyConfig.nunjucksFilters.url;
} else {
// Theoretically we could just move on here with a `url => url` but then `pathPrefix`
// would not work and it wouldn’t be obvious why—so let’s fail loudly to avoid that.
throw new Error("Could not find a `url` filter for the eleventy-navigation plugin in eleventyNavigationToHtml filter.");
}
}
function buildHtmlAttr(name, values) {
// values could be array or string
if (!values || !values.length) {
return '';
}
const valueStr = Array.isArray(values) ? values.join(" ") : values;
return ` ${name}="${valueStr}"`;
}
function buildAllHtmlAttrs(attrs) {
return attrs.reduce((acc, { name, values }) => acc + buildHtmlAttr(name, values), '');
}
function navigationToHtml(pages, options = {}) {
options = Object.assign({
listElement: "ul",
listItemElement: "li",
listClass: "",
listItemClass: "",
listItemHasChildrenClass: "",
activeKey: "",
activeListItemClass: "",
anchorClass: "",
activeAnchorClass: "",
useAriaCurrentAttr: false,
showExcerpt: false,
isChildList: false,
useTopLevelDetails: false,
anchorElementWithoutHref: "a", // default, better to use span
}, options);
let isChildList = !!options.isChildList;
options.isChildList = true;
let urlFilter;
if(pages.length && pages[0].pluginType !== "eleventy-navigation") {
throw new Error("Incorrect argument passed to eleventyNavigationToHtml filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToHtml | safe`");
}
return pages.length ? `<${options.listElement}${!isChildList && options.listClass ? ` class="${options.listClass}"` : ''}>${pages.map(entry => {
let liClass = [];
let aClass = [];
let aAttrs = [];
if(options.listItemClass) {
liClass.push(options.listItemClass);
}
if(options.anchorClass) {
aClass.push(options.anchorClass);
}
if(entry.url) {
if(!urlFilter) {
// don’t get if not used
urlFilter = getUrlFilter(this);
}
aAttrs.push({name: "href", values: urlFilter(entry.url)})
}
if(options.activeKey === entry.key) {
if(options.activeListItemClass) {
liClass.push(options.activeListItemClass);
}
if(options.activeAnchorClass) {
aClass.push(options.activeAnchorClass);
}
if(options.useAriaCurrentAttr) {
aAttrs.push({ name: "aria-current", values: "page" });
}
}
if(options.listItemHasChildrenClass && entry.children && entry.children.length) {
liClass.push(options.listItemHasChildrenClass);
}
if(aClass.length) {
aAttrs.push({ name: "class", values: aClass });
}
let postfix = "";
// Helper to show pin/order in text:
// let hasOrder = entry.order || entry.order === 0;
// if(process.env.ELEVENTY_RUN_MODE === "serve" && (hasOrder || entry.pinned)) {
// postfix = ` (${entry.pinned ? "📌" : ""}${entry.order ?? ""})`;
// }
let aAttrsStr = buildAllHtmlAttrs(aAttrs);
let hasLink = aAttrs.find(entry => entry.name === "href");
let itemTitle = entry.title + postfix;
let titleHtmlStart = `<a${aAttrsStr}>${itemTitle}</a>`;
// purely defensive use of `useTopLevelDetails` here
if(options.anchorElementWithoutHref && !hasLink) {
titleHtmlStart = `<${options.anchorElementWithoutHref}>${itemTitle}</${options.anchorElementWithoutHref}>`;
}
let titleHtmlEnd = "";
if(options.useTopLevelDetails && !isChildList && entry.children) {
if(hasLink) {
// `<a>` must be sibling: no other interactive elements in <summary>
titleHtmlStart = `${titleHtmlStart}<details><summary>${itemTitle}</summary>`;
} else {
titleHtmlStart = `<details><summary>${itemTitle}</summary>`;
}
titleHtmlEnd = "</details>";
}
let childContentStr = entry.children ? navigationToHtml.call(this, entry.children, options) : "";
return `<${options.listItemElement}${buildHtmlAttr("class", liClass)}>${titleHtmlStart}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}${childContentStr}${titleHtmlEnd}</${options.listItemElement}>`;
}).join("\n")}</${options.listElement}>` : "";
}
function navigationToMarkdown(pages, options = {}) {
options = Object.assign({
showExcerpt: false,
childDepth: 0
}, options);
let childDepth = 1 + options.childDepth;
options.childDepth++;
let urlFilter;
if(pages.length && pages[0].pluginType !== "eleventy-navigation") {
throw new Error("Incorrect argument passed to eleventyNavigationToMarkdown filter. You must call `eleventyNavigation` or `eleventyNavigationBreadcrumb` first, like: `collection.all | eleventyNavigation | eleventyNavigationToMarkdown | safe`");
}
let indent = (new Array(childDepth)).join(" ") || "";
return pages.length ? `${pages.map(entry => {
if(entry.url && !urlFilter) {
// don’t get if not used
urlFilter = getUrlFilter(this);
}
return `${indent}* ${entry.url ? `[` : ""}${entry.title}${entry.url ? `](${urlFilter(entry.url)})` : ""}${options.showExcerpt && entry.excerpt ? `: ${entry.excerpt}` : ""}\n${entry.children ? navigationToMarkdown.call(this, entry.children, options) : ""}`;
}).join("")}` : "";
}
module.exports = {
getDependencyGraph,
findNavigationEntries,
findBreadcrumbEntries,
toHtml: navigationToHtml,
toMarkdown: navigationToMarkdown
};