@@ -7,6 +7,8 @@ import {visit} from "unist-util-visit";
7
7
import { visitParents } from "unist-util-visit-parents" ;
8
8
import { toString } from "hast-util-to-string" ;
9
9
import rehypeStringify from "rehype-stringify" ;
10
+ import { html } from "./htm-rehype.js" ;
11
+ import { idFromTitle } from "./utils.js" ;
10
12
11
13
/**
12
14
* @param relative {string}
@@ -56,12 +58,30 @@ export function sidebarProcessor(activePath) {
56
58
*
57
59
* @param li {import('hast').Element}
58
60
*/
59
- function removeSubList ( li ) {
61
+ function collapseSubList ( li ) {
60
62
const ulIndex = li . children . findIndex ( ( { tagName} ) => tagName === 'ul' ) ;
61
63
if ( ulIndex < 0 ) {
62
64
return ;
63
65
}
64
- li . children . splice ( ulIndex , 1 ) ;
66
+ const childrenBeforeUl = li . children . slice ( 0 , ulIndex ) ;
67
+ let useCollapse = false ;
68
+ if ( ! childrenBeforeUl . find ( ( { tagName} ) => tagName === 'a' ) ) {
69
+ const index = childrenBeforeUl . findIndex ( ( { type} ) => type === 'text' ) ;
70
+ if ( index >= 0 ) {
71
+ const title = li . children [ index ] . value ;
72
+ const id = idFromTitle ( title ) ;
73
+ li . children [ index ] = html `< a data-bs-toggle ="collapse " href ="# ${ id } " role ="button " aria-expanded ="false "
74
+ aria-controls ="${ id } "> ${ title } </ a > ` ;
75
+ li . children [ ulIndex ] . properties = {
76
+ 'class' : [ 'collapse' ] ,
77
+ 'id' : id
78
+ }
79
+ useCollapse = true ;
80
+ }
81
+ }
82
+ if ( ! useCollapse ) {
83
+ li . children . splice ( ulIndex , 1 ) ;
84
+ }
65
85
}
66
86
67
87
return ( tree , vfile ) => {
@@ -83,7 +103,9 @@ export function sidebarProcessor(activePath) {
83
103
let active = false ;
84
104
visit ( li , node => node . tagName === 'a' && linkMatchesActive ( node ) , ( ) => active = true ) ;
85
105
if ( ! active ) {
86
- removeSubList ( li ) ;
106
+ collapseSubList ( li ) ;
107
+ } else {
108
+ li . properties . class = [ 'active' ] ;
87
109
}
88
110
} ) ;
89
111
} ;
0 commit comments