@@ -3,6 +3,7 @@ import { Section } from '../Link/Section';
3
3
import { PageFrontMatter } from '../../models' ;
4
4
import { Link } from '../Link/Link' ;
5
5
import { ParentLink } from '../Link/ParentLink' ;
6
+ import { useRouter } from 'next/router' ;
6
7
7
8
export interface INavGroupProps {
8
9
items : PageFrontMatter [ ] ;
@@ -13,6 +14,9 @@ export const NavGroup: React.FunctionComponent<INavGroupProps> = ({
13
14
items,
14
15
item
15
16
} : React . PropsWithChildren < INavGroupProps > ) => {
17
+ const router = useRouter ( ) ;
18
+ const [ hasActiveLink , setHasActiveLink ] = React . useState < boolean > ( false ) ;
19
+
16
20
const getLinks = React . useMemo ( ( ) => {
17
21
const { content } = item ;
18
22
const links = Array . from ( content . matchAll ( / ^ # # ( .* $ ) / gim) ) ;
@@ -24,16 +28,25 @@ export const NavGroup: React.FunctionComponent<INavGroupProps> = ({
24
28
return null ;
25
29
}
26
30
31
+ const crntPath = router . asPath . replace ( / \/ # / , '#' ) ;
32
+ let activeLink = ! ! links . find ( link => crntPath === link [ 1 ] . replace ( / \/ # / , '#' ) ) ;
33
+ if ( ! activeLink && subItems && subItems . length > 0 ) {
34
+ activeLink = ! ! subItems . find ( link => crntPath === `/docs/${ link . slug } ` . replace ( / \/ # / , '#' ) ) ;
35
+ }
36
+ setHasActiveLink ( ! ! activeLink ) ;
37
+
27
38
return (
28
39
< ul className = { `mt-2 space-y-2` } >
29
- { links . map ( ( link , index ) => (
30
- < li key = { index } >
31
- < Link
32
- title = { link [ 1 ] }
33
- link = { `/docs/${ item . slug !== "index" ? item . slug : '' } #${ link [ 1 ] . toLowerCase ( ) . replace ( / \s / g, '-' ) } ` }
34
- />
35
- </ li >
36
- ) ) }
40
+ { links . map ( ( link , index ) => {
41
+ return (
42
+ < li key = { index } >
43
+ < Link
44
+ title = { link [ 1 ] }
45
+ link = { `/docs/${ item . slug !== "index" ? item . slug : '' } #${ link [ 1 ] . toLowerCase ( ) . replace ( / \s / g, '-' ) } ` }
46
+ />
47
+ </ li >
48
+ ) ;
49
+ } ) }
37
50
38
51
{ subItems . map ( ( subItem ) => (
39
52
< li key = { subItem . slug } className = { `group` } >
@@ -51,7 +64,8 @@ export const NavGroup: React.FunctionComponent<INavGroupProps> = ({
51
64
return (
52
65
< Section
53
66
title = { item . title }
54
- link = { `/docs/${ item . slug !== "index" ? item . slug : '' } ` } >
67
+ link = { `/docs/${ item . slug !== "index" ? item . slug : '' } ` }
68
+ hasActiveLink = { hasActiveLink } >
55
69
{ getLinks }
56
70
</ Section >
57
71
) ;
0 commit comments