@@ -33,9 +33,12 @@ function scrollHeaders() {
33
33
const headers = Array . from (
34
34
document . querySelectorAll ( ":is(h1, h2, h3, h4, h5, h6)[id]" ) ,
35
35
) ;
36
- const allShortcuts = Array . from (
37
- document . querySelectorAll ( "#shortcuts > div" ) ,
38
- ) ;
36
+ const shortcuts = document . getElementById ( "shortcuts" ) ;
37
+
38
+ // Exit early if shortcuts container doesn't exist
39
+ if ( ! shortcuts ) return ;
40
+
41
+ const allShortcuts = Array . from ( shortcuts . querySelectorAll ( "div" ) ) ;
39
42
40
43
headers . map ( ( currentSection ) => {
41
44
// get the position of the section
@@ -81,22 +84,38 @@ function remToPx(rem) {
81
84
}
82
85
83
86
function setupShortcuts ( shortcutDepth = 2 ) {
87
+ // Find the shortcut target container in the sidebar
88
+ const shortcutsTarget = document . getElementById ( "shortcuts" ) ;
89
+
90
+ /*
91
+ * Exit early if shortcuts container doesn't exist
92
+ * This is important to avoid errors when the theme
93
+ * is used on pages that don't have the shortcuts sidebar
94
+ */
95
+ if ( ! shortcutsTarget ) {
96
+ return ;
97
+ }
98
+
84
99
shortcutDepth += 1 ; // to account for the page title
85
100
86
- // Build a class selector for each header type, and concatenate with commas
101
+ // Build a class selector for each header level
87
102
let classes = "" ;
88
103
for ( let i = 2 ; i <= shortcutDepth ; i ++ ) {
89
104
if ( i != 2 ) {
90
105
classes += "," ;
91
106
}
92
- classes += " .content-container :not([role='tabpanel']) > h" + i ;
107
+ classes += ` .content-container > h${ i } ` ;
93
108
}
94
109
95
- // Content Page Shortcuts
96
- const shortcutsTarget = document . getElementById ( "shortcuts" ) ;
97
- if ( shortcutsTarget ) {
98
- const classElements = Array . from ( document . querySelectorAll ( classes ) ) ;
110
+ const classElements = Array . from ( document . querySelectorAll ( classes ) ) ;
111
+
112
+ // Only proceed if we found headers (to avoid creating an empty shortcuts section)
113
+ if ( classElements . length > 0 ) {
99
114
classElements . map ( ( el ) => {
115
+ if ( ! el . id ) {
116
+ return ;
117
+ }
118
+
100
119
const title = el . innerHTML ;
101
120
const elId = el . id ;
102
121
// Gets the element type (e.g. h2, h3)
@@ -139,10 +158,13 @@ function setupShortcuts(shortcutDepth = 2) {
139
158
const shortcuts = Array . from (
140
159
document . querySelectorAll ( "#shortcuts div:not(#shortcuts-header)" ) ,
141
160
) ;
142
- if ( shortcuts . length == 0 ) {
143
- const shortcutsContainer = document . getElementById ( "shortcuts-container" ) ;
144
- if ( shortcutsContainer ) {
161
+ const shortcutsContainer = document . getElementById ( "shortcuts-container" ) ;
162
+
163
+ if ( shortcutsContainer ) {
164
+ if ( shortcuts . length == 0 ) {
145
165
shortcutsContainer . style . display = "none" ;
166
+ } else {
167
+ shortcutsContainer . style . display = "" ; // make shortcuts display visible, if hidden
146
168
}
147
169
}
148
170
0 commit comments