-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathwithBreadcrumbs.tsx
More file actions
77 lines (62 loc) · 2.44 KB
/
withBreadcrumbs.tsx
File metadata and controls
77 lines (62 loc) · 2.44 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
'use client';
import type { BreadcrumbLink } from '@node-core/ui-components/Common/Breadcrumbs';
import Breadcrumbs from '@node-core/ui-components/Common/Breadcrumbs';
import { useTranslations } from 'next-intl';
import type { FC } from 'react';
import Link from '#site/components/Link';
import {
useClientContext,
useMediaQuery,
useSiteNavigation,
} from '#site/hooks';
import type { NavigationKeys } from '#site/types';
import { dashToCamelCase } from '#site/util/string';
type WithBreadcrumbsProps = {
navKeys?: Array<NavigationKeys>;
};
const WithBreadcrumbs: FC<WithBreadcrumbsProps> = ({ navKeys = [] }) => {
const { getSideNavigation } = useSiteNavigation();
const t = useTranslations();
const { pathname } = useClientContext();
const isMobileScreen = useMediaQuery('(max-width: 639px)');
const maxLength = isMobileScreen ? 2 : 4;
const getBreadcrumbs = () => {
const navigationTree = getSideNavigation(navKeys);
const pathList = pathname
.split('/')
.filter(item => item !== '')
.map(dashToCamelCase);
let currentNode = navigationTree;
// Reduce the pathList to a breadcrumbs array by finding each path in the current navigation layer,
// updating the currentNode to the found node's items(next layer) for the next iteration.
return pathList.reduce((breadcrumbs, path, index) => {
const nodeWithCurrentPath = currentNode.find(
([nodePath, entry]) =>
// Checking link in cases where nodePath cannot = path. Like 'discoverJavaScriptTimers'
(nodePath === path || entry.link === pathname) &&
// Skip checking child path if it is the last path since there is no more child item inside
(index === pathList.length - 1 ||
entry.items.some(
([childPath, entry]) =>
childPath === pathList[index + 1] || entry.link === pathname
))
);
if (nodeWithCurrentPath) {
const [, { label, link = '', items = [] }] = nodeWithCurrentPath;
// Goes deeper on the tree of items if there are any.
currentNode = items;
return label ? [...breadcrumbs, { label, href: link }] : breadcrumbs;
}
return breadcrumbs;
}, [] as Array<BreadcrumbLink>);
};
return (
<Breadcrumbs
links={getBreadcrumbs()}
maxLength={maxLength}
as={Link}
homeLinkAriaLabel={t('components.common.breadcrumbs.navigateToHome')}
/>
);
};
export default WithBreadcrumbs;