Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: blog toc height scrolls #48 #49

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 67 additions & 24 deletions components/blog/Toc.vue
Original file line number Diff line number Diff line change
Expand Up @@ -24,58 +24,101 @@ function toggleSection(id: string) {
}

const isExpanded = (id: string) => expandedSections.value.has(id)

const currentSection = ref<null | string>(null);
let observer: IntersectionObserver

onMounted(() => {
observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const sectionHref = entry.target.querySelector('a')?.getAttribute('href')
if (sectionHref) {

currentSection.value = sectionHref

// Update the TOC to highlight the corresponding link
updateToc(sectionHref)
}
}
})
}, { threshold: 1.0 })

// Observe the article sections
document.querySelectorAll('.article-section h2, .article-section h3, .article-section h4').forEach((section) => {
observer.observe(section)
})
})

onUnmounted(() => {
observer.disconnect()
})

function updateToc(sectionHref: string) {
const tocLinks = document.querySelectorAll('#toc-content a');
const currentLinkEndsWithSectionHref = ({ sectionHref, linkHref }: { sectionHref: string, linkHref: string }): boolean => {
const regex = new RegExp(`^.*${sectionHref}$`);
return regex.test(linkHref!)

}
tocLinks.forEach((link) => {
link.classList.remove('active')
const linkHref = link.getAttribute('href')

if (linkHref && currentLinkEndsWithSectionHref({ linkHref, sectionHref })) {
link.classList.add('active')
}
})
}

</script>

<template>
<div class="lg:col-span-3 sticky top-28 mt-5 h-96 hidden lg:block justify-self-end w-full">
<div class="lg:col-span-3 sticky top-28 mt-5 h-96 hidden lg:block justify-self-end w-full" id="toc-container">
<div class="border dark:border-zinc-500 p-4 rounded-md w-[250px] max-w-[350px] dark:bg-slate-900 shadow-md">
<h2 class="text-lg font-bold mb-4 border-b dark:border-zinc-500 pb-2 text-hoppr-green">
Table des matières
</h2>
<div class="relative">
<div
v-for="(link, index) in links" :key="link.id" class="flex items-start relative" :class="{
'mb-4': link.depth === 2,
'mb-2': link.depth === 3 && isExpanded(link.parent),
}"
>
<div class="relative" id="toc-content">
<div v-for="(link, index) in links" :key="link.id" class="flex items-start relative" :class="{
'mb-4': link.depth === 2,
'mb-2': link.depth === 3 && isExpanded(link.parent),
}">
<div class="w-6 flex-shrink-0 flex items-center justify-center">
<button
v-if="link.depth === 2"
<button v-if="link.depth === 2"
class="text-hoppr-green hover:text-opacity-80 transition-colors duration-200 w-full text-left"
@click="toggleSection(link.id)"
>
@click="toggleSection(link.id)">
{{ link.children ? (isExpanded(link.id) ? '▾' : '▸') : '•' }}
</button>
</div>
<div
v-if="link.depth === 3 && isExpanded(link.parent)"
<div v-if="link.depth === 3 && isExpanded(link.parent)"
class="absolute left-0 top-0 bottom-0 w-px bg-gray-300 dark:bg-zinc-600" :style="{
top: index > 0 && links[index - 1].depth === 2 ? '0' : '-4px',
height: 'calc(100% + 8px)',
left: '0.75rem',
}"
/>
<div
v-if="link.depth === 3 && isExpanded(link.parent)" class="absolute w-2 h-px bg-gray-300 dark:bg-zinc-600"
}" />
<div v-if="link.depth === 3 && isExpanded(link.parent)" class="absolute w-2 h-px bg-gray-300 dark:bg-zinc-600"
:style="{
top: '0.9rem',
left: '0.75rem',
}"
/>
<NuxtLink
v-if="link.depth === 2 || (link.depth === 3 && isExpanded(link.parent))" :to="`#${link.id}`"
}" />
<NuxtLink v-if="link.depth === 2 || (link.depth === 3 && isExpanded(link.parent))" :to="`#${link.id}`"
class="block text-sm transition-colors duration-200 flex-grow" :class="{
'font-semibold hover:text-hoppr-green': link.depth === 2,
'text-gray-600 dark:text-gray-400 hover:text-hoppr-green dark:hover:text-hoppr-green': link.depth === 3,
'ml-0': link.depth === 2,
'ml-4': link.depth === 3,
}"
>
}">
{{ link.text }}
</NuxtLink>
</div>
</div>
</div>
</div>
</template>
<style>
.active {
color: hotpink !important;

}
</style>
80 changes: 80 additions & 0 deletions components/blog/Toc/Toc.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useDisplayActiveSection } from './composables/useDisplayActiveSection'

useDisplayActiveSection()

const { path } = useRoute()
const articles = await queryContent(path).findOne()

const expandedSections = ref<Set<string>>(new Set(articles?.body?.toc?.links.map(link => link.id) || []))

const links = computed(() => {
const result: any[] = []
articles?.body?.toc?.links.forEach((link) => {
result.push(link)
if (link.children)
result.push(...link.children.map(child => ({ ...child, parent: link.id })))
})
return result
})

function toggleSection(id: string) {
if (expandedSections.value.has(id))
expandedSections.value.delete(id)
else
expandedSections.value.add(id)
}

const isExpanded = (id: string) => expandedSections.value.has(id)
</script>

<template>
<div class="lg:col-span-3 sticky top-28 mt-5 h-96 hidden lg:block justify-self-end w-full" id="toc-container">
<div class="border dark:border-zinc-500 p-4 rounded-md w-[250px] max-w-[350px] dark:bg-slate-900 shadow-md">
<h2 class="text-lg font-bold mb-4 border-b dark:border-zinc-500 pb-2 text-hoppr-green">
Table des matières
</h2>
<div class="relative" id="toc-content">
<div v-for="(link, index) in links" :key="link.id" class="flex items-start relative" :class="{
'mb-4': link.depth === 2,
'mb-2': link.depth === 3 && isExpanded(link.parent),
}">
<div class="w-6 flex-shrink-0 flex items-center justify-center">
<button v-if="link.depth === 2"
class="text-hoppr-green hover:text-opacity-80 transition-colors duration-200 w-full text-left"
@click="toggleSection(link.id)">
{{ link.children ? (isExpanded(link.id) ? '▾' : '▸') : '•' }}
</button>
</div>
<div v-if="link.depth === 3 && isExpanded(link.parent)"
class="absolute left-0 top-0 bottom-0 w-px bg-gray-300 dark:bg-zinc-600" :style="{
top: index > 0 && links[index - 1].depth === 2 ? '0' : '-4px',
height: 'calc(100% + 8px)',
left: '0.75rem',
}" />
<div v-if="link.depth === 3 && isExpanded(link.parent)" class="absolute w-2 h-px bg-gray-300 dark:bg-zinc-600"
:style="{
top: '0.9rem',
left: '0.75rem',
}" />
<NuxtLink v-if="link.depth === 2 || (link.depth === 3 && isExpanded(link.parent))" :to="`#${link.id}`"
class="block text-sm transition-colors duration-200 flex-grow" :class="{
'font-semibold hover:text-hoppr-green': link.depth === 2,
'text-gray-600 dark:text-gray-400 hover:text-hoppr-green dark:hover:text-hoppr-green': link.depth === 3,
'ml-0': link.depth === 2,
'ml-4': link.depth === 3,
}">
{{ link.text }}
</NuxtLink>
</div>
</div>
</div>
</div>
</template>
<style>
.active {
color: hotpink !important;

}
</style>
49 changes: 49 additions & 0 deletions components/blog/Toc/composables/useDisplayActiveSection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { onMounted, onUnmounted, ref } from 'vue';

export function useDisplayActiveSection() {
const currentSection = ref<null | string>(null);
let observer: IntersectionObserver;

onMounted(() => {
observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const sectionHref = entry.target.querySelector('a')?.getAttribute('href')
if (sectionHref) {

currentSection.value = sectionHref

// Update the TOC to highlight the corresponding link
updateToc(sectionHref)
}
}
})
}, { threshold: 1.0 })

// Observe the article sections
document.querySelectorAll('.article-section h2, .article-section h3, .article-section h4').forEach((section) => {
observer.observe(section)
})
})

onUnmounted(() => {
observer.disconnect()
})

function updateToc(sectionHref: string) {
const tocLinks = document.querySelectorAll('#toc-content a');
const currentLinkEndsWithSectionHref = ({ sectionHref, linkHref }: { sectionHref: string, linkHref: string }): boolean => {
const regex = new RegExp(`^.*${sectionHref}$`);
return regex.test(linkHref!)

}
tocLinks.forEach((link) => {
link.classList.remove('active')
const linkHref = link.getAttribute('href')

if (linkHref && currentLinkEndsWithSectionHref({ linkHref, sectionHref })) {
link.classList.add('active')
}
})
}
}
2 changes: 1 addition & 1 deletion pages/blogs/[blog].vue
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ defineOgImageComponent('About', {
prose-h2:border-l-4 prose-h2:border-hoppr-green prose-h2:pl-2
prose-h3:italic"
>
<ContentRenderer v-if="article" :value="article">
<ContentRenderer v-if="article" :value="article" class="article-section">
<template #empty>
<p>No content found.</p>
</template>
Expand Down