@@ -32,6 +32,12 @@ function scanHeadings() {
3232 pageTitle .value = h1 .textContent || ' Table of Contents'
3333 }
3434
35+ // If no headings found, it might mean content hasn't loaded yet
36+ // But also check if we have at least an h1 to ensure page content exists
37+ if (headings .length === 0 && ! h1 ) {
38+ return
39+ }
40+
3541 // Process each heading
3642 headings .forEach ((heading ) => {
3743 // Skip the first h1 as it's the page title
@@ -75,16 +81,39 @@ function scanHeadings() {
7581let observer: MutationObserver | null = null
7682
7783onMounted (() => {
78- // Initial scan
79- scanHeadings ()
84+ // Initial scan with a small delay to ensure content is rendered
85+ setTimeout (() => {
86+ scanHeadings ()
87+ }, 100 )
8088
8189 // Re-scan when route changes (for SPA navigation)
8290 watch (() => pageRoute .path , () => {
91+ // Clear current TOC immediately when route changes
92+ tocLinks .value = []
93+ pageTitle .value = ' Table of Contents'
94+
95+ // Use multiple strategies to ensure content is fully loaded
8396 nextTick (() => {
97+ // First attempt after nextTick
8498 scanHeadings ()
99+
100+ // Second attempt with a delay to handle slow rendering
101+ setTimeout (() => {
102+ scanHeadings ()
103+ }, 200 )
104+
105+ // Third attempt with a longer delay as fallback
106+ setTimeout (() => {
107+ scanHeadings ()
108+ }, 500 )
85109 })
86110 })
87111
112+ // Also watch for hash changes to update active states
113+ watch (() => pageRoute .hash , () => {
114+ // No need to rescan, just update active states
115+ })
116+
88117 // Watch for DOM mutations affecting headings
89118 observer = new MutationObserver ((mutations ) => {
90119 let shouldRescan = false
@@ -99,7 +128,10 @@ onMounted(() => {
99128 }
100129 }
101130 if (shouldRescan ) {
102- scanHeadings ()
131+ // Add a small delay to allow DOM to stabilize
132+ setTimeout (() => {
133+ scanHeadings ()
134+ }, 50 )
103135 }
104136 })
105137 observer .observe (document .body , {
0 commit comments