forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreadcrumbs.js
76 lines (65 loc) · 2.3 KB
/
breadcrumbs.js
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
export default async function breadcrumbs(req, res, next) {
if (!req.context.page) return next()
if (req.context.page.hidden) return next()
req.context.breadcrumbs = []
// Return an empty array on the landing page.
if (req.context.page.documentType === 'homepage') {
return next()
}
const currentSiteTree =
req.context.siteTree[req.context.currentLanguage][req.context.currentVersion]
const fallbackSiteTree = req.context.siteTree.en[req.context.currentVersion]
req.context.breadcrumbs = await getBreadcrumbs(
// Array of child pages on the root, i.e., the product level.
currentSiteTree.childPages,
fallbackSiteTree.childPages,
req.context.currentPath.slice(3),
req.context.currentLanguage
)
return next()
}
async function getBreadcrumbs(
pageArray,
fallbackPageArray,
currentPathWithoutLanguage,
intendedLanguage
) {
// Find the page that starts with the requested path
let childPage = pageArray.find((page) =>
currentPathWithoutLanguage.startsWith(page.href.slice(3))
)
// Find the page in the fallback page array (likely the English sub-tree)
const fallbackChildPage =
(fallbackPageArray || []).find((page) => {
return currentPathWithoutLanguage.startsWith(page.href.slice(3))
}) || childPage
// No matches, we bail
if (!childPage && !fallbackChildPage) {
return []
}
// Didn't find the intended page, but found the fallback
if (!childPage) {
childPage = fallbackChildPage
}
const breadcrumb = {
documentType: childPage.page.documentType,
// give the breadcrumb the intendedLanguage, so nav through breadcrumbs doesn't inadvertantly change the user's selected language
href: `/${intendedLanguage}/${childPage.href.slice(4)}`,
title: childPage.renderedShortTitle || childPage.renderedFullTitle,
}
// Recursively loop through the childPages and create each breadcrumb, until we reach the
// point where the current siteTree page is the same as the requested page. Then stop.
if (childPage.childPages && currentPathWithoutLanguage !== childPage.href.slice(3)) {
return [
breadcrumb,
...(await getBreadcrumbs(
childPage.childPages,
fallbackChildPage.childPages,
currentPathWithoutLanguage,
intendedLanguage
)),
]
} else {
return [breadcrumb]
}
}