-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTableOfContents.vue
More file actions
189 lines (165 loc) · 4.62 KB
/
TableOfContents.vue
File metadata and controls
189 lines (165 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<script setup lang="ts">
import TocTree from './TocTree.vue'
const pageRoute = useRoute()
// Interface for our TOC structure
interface TocLink {
id: string
text: string
level: number
children: TocLink[]
}
// Create a reactive reference for our TOC links
const tocLinks = ref<TocLink[]>([])
const pageTitle = ref('Table of Contents')
// Function to scan the page for headings and build the TOC
function scanHeadings() {
// Wait for the DOM to be ready
if (typeof document === 'undefined') {
return
}
// Find all headings (h1-h6) with IDs
const headings = document.querySelectorAll('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')
const links: TocLink[] = []
// Get the page title from the first h1
const h1 = document.querySelector('h1')
if (h1) {
pageTitle.value = h1.textContent || 'Table of Contents'
}
// Process each heading
headings.forEach((heading) => {
// Skip the first h1 as it's the page title
if (heading.tagName === 'H1' && heading === h1) {
return
}
const id = heading.id
const level = Number.parseInt(heading.tagName.substring(1), 10)
// Create a TOC link
const link: TocLink = { id, text: heading.textContent || '', level, children: [] }
links.push(link)
})
// Build a robust hierarchical structure in a single pass
const hierarchicalLinks: TocLink[] = []
const parents: TocLink[] = []
for (const link of links) {
// Always ensure children is initialized
if (!('children' in link) || !Array.isArray(link.children)) {
(link as TocLink).children = []
}
// Find the last parent of lower level
while (parents.length > 0 && parents[parents.length - 1]!.level >= link.level) {
parents.pop()
}
if (parents.length === 0) {
hierarchicalLinks.push(link)
}
else {
parents[parents.length - 1]!.children.push(link)
}
parents.push(link)
}
tocLinks.value = hierarchicalLinks
}
// Check if we're in the browser
let observer: MutationObserver | null = null
onMounted(() => {
// Initial scan
scanHeadings()
// Re-scan when route changes (for SPA navigation)
watch(() => pageRoute.path, () => {
nextTick(() => {
scanHeadings()
})
})
// Watch for DOM mutations affecting headings
observer = new MutationObserver((mutations) => {
let shouldRescan = false
for (const mutation of mutations) {
if (
Array.from(mutation.addedNodes).some(isHeadingNode)
|| Array.from(mutation.removedNodes).some(isHeadingNode)
|| (mutation.type === 'attributes' && isHeadingNode(mutation.target))
) {
shouldRescan = true
break
}
}
if (shouldRescan) {
scanHeadings()
}
})
observer.observe(document.body, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['id'],
})
})
onBeforeUnmount(() => {
if (observer) {
observer.disconnect()
observer = null
}
})
function isHeadingNode(node: Node | EventTarget): boolean {
if (!(node instanceof HTMLElement)) {
return false
}
return /^H[1-6]$/.test(node.tagName)
}
function checkActive(hash: string) {
return pageRoute.hash === hash ? 'active' : null
}
function toTop() {
window.scrollTo({
top: 0,
behavior: 'smooth',
})
setTimeout(() => {
window.location.hash = ''
}, 600)
}
function toBottom() {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth',
})
}
function scrollToHeading(id: string) {
const el = document.getElementById(id)
if (el) {
el.scrollIntoView({ behavior: 'smooth', block: 'start' })
// Update the hash after the scroll
history.replaceState(null, '', `#${id}`)
}
}
</script>
<template>
<Flex col>
<Menu v-if="tocLinks.length" class="md:menu-sm xl:menu-md w-full">
<NuxtLink href="#" custom>
<template #default="{ route }">
<MenuItem class="text-base-content cursor-pointer">
<a
class="flex flex-row items-center justify-between font-semibold bg-neutral/30"
:class="checkActive(route?.hash || '')" @click="toTop"
>
{{ pageTitle }}
<Icon name="feather:arrow-up" class="text-base" />
</a>
</MenuItem>
</template>
</NuxtLink>
<TocTree
:links="tocLinks"
:check-active="checkActive"
:scroll-to-heading="scrollToHeading"
/>
<MenuItem>
<a class="flex flex-row items-center justify-between hover:bg-accent/25 mt-6" @click="toBottom">
scroll to bottom
<Icon name="feather:arrow-down" class="text-base" />
</a>
</MenuItem>
</Menu>
</Flex>
</template>