22
33import type { FC } from 'react' ;
44
5+ import type { BreadcrumbLink } from '@/components/Common/Breadcrumbs' ;
56import Breadcrumbs from '@/components/Common/Breadcrumbs' ;
67import { useClientContext , useMediaQuery , useSiteNavigation } from '@/hooks' ;
78import type { NavigationKeys } from '@/types' ;
9+ import { dashToCamelCase } from '@/util/stringUtils' ;
810
911const WithBreadcrumbs : FC = ( ) => {
1012 const { navigationItems, getSideNavigation } = useSiteNavigation ( ) ;
1113 const { pathname } = useClientContext ( ) ;
12-
1314 const isMobileScreen = useMediaQuery ( '(max-width: 639px)' ) ;
1415
16+ const maxLength = isMobileScreen ? 2 : 4 ;
17+
1518 const getBreadrumbs = ( ) => {
1619 const [ navigationKey ] =
1720 navigationItems . find ( ( [ , item ] ) => pathname . includes ( item . link ) ) || [ ] ;
@@ -20,16 +23,36 @@ const WithBreadcrumbs: FC = () => {
2023 return [ ] ;
2124 }
2225
23- return getSideNavigation ( [ navigationKey as NavigationKeys ] )
24- . map ( ( [ , item ] ) => item . items )
25- . flat ( )
26- . filter ( ( [ , item ] ) => pathname . includes ( item . link ) )
27- . map ( ( [ , item ] ) => ( { label : item . label , href : item . link } ) ) ;
26+ const navigationTree = getSideNavigation ( [ navigationKey as NavigationKeys ] ) ;
27+
28+ const pathList = pathname
29+ . split ( '/' )
30+ . filter ( item => item !== '' )
31+ . map ( dashToCamelCase ) ;
32+
33+ let currentNode = navigationTree ;
34+
35+ // Reduce the pathList to a breadcrumbs array by finding each path in the current navigation layer,
36+ // updating the currentNode to the found node's items(next layer) for the next iteration.
37+ return pathList . reduce ( ( breadcrumbs , path ) => {
38+ const nodeWithCurrentPath = currentNode . find (
39+ ( [ nodePath ] ) => nodePath === path
40+ ) ;
41+
42+ if ( nodeWithCurrentPath ) {
43+ const [ , { label, link = '' , items = [ ] } ] = nodeWithCurrentPath ;
44+
45+ // Goes deeper on the tree of items if there are any.
46+ currentNode = items ;
47+
48+ return label ? [ ...breadcrumbs , { label, href : link } ] : breadcrumbs ;
49+ }
50+
51+ return breadcrumbs ;
52+ } , [ ] as Array < BreadcrumbLink > ) ;
2853 } ;
2954
30- return (
31- < Breadcrumbs links = { getBreadrumbs ( ) } maxLength = { isMobileScreen ? 2 : 4 } />
32- ) ;
55+ return < Breadcrumbs links = { getBreadrumbs ( ) } maxLength = { maxLength } /> ;
3356} ;
3457
3558export default WithBreadcrumbs ;
0 commit comments