Skip to content

Commit

Permalink
feat(theme): add doc aside scroll spy
Browse files Browse the repository at this point in the history
  • Loading branch information
userquin committed Jan 1, 2025
1 parent 38a755e commit d6a5c13
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/client/theme-default/components/VPDoc.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { useRoute } from 'vitepress'
import { computed } from 'vue'
import { computed, nextTick, provide, ref } from 'vue'
import { useData } from '../composables/data'
import { useSidebar } from '../composables/sidebar'
import VPDocAside from './VPDocAside.vue'
Expand All @@ -10,10 +10,18 @@ const { theme } = useData()
const route = useRoute()
const { hasSidebar, hasAside, leftAside } = useSidebar()
const asideContainerRef = ref<HTMLDivElement | undefined>()
const pageName = computed(() =>
route.path.replace(/[./]+/g, '_').replace(/_html$/, '')
)
function scrollAside(position: number) {
nextTick(() => {
asideContainerRef.value?.scrollTo({ top: position, behavior: 'smooth' })
})
}
provide('scroll-aside', scrollAside)
</script>

<template>
Expand All @@ -25,7 +33,7 @@ const pageName = computed(() =>
<div class="container">
<div v-if="hasAside" class="aside" :class="{'left-aside': leftAside}">
<div class="aside-curtain" />
<div class="aside-container">
<div ref="asideContainerRef" class="aside-container">
<div class="aside-content">
<VPDocAside>
<template #aside-top><slot name="aside-top" /></template>
Expand Down
5 changes: 4 additions & 1 deletion src/client/theme-default/composables/outline.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getScrollOffset } from 'vitepress'
import type { DefaultTheme } from 'vitepress/theme'
import { onMounted, onUnmounted, onUpdated, type Ref } from 'vue'
import { inject, onMounted, onUnmounted, onUpdated, type Ref } from 'vue'
import type { Header } from '../../shared'
import { throttleAndDebounce } from '../support/utils'
import { useAside } from './aside'
Expand Down Expand Up @@ -84,6 +84,7 @@ export function useActiveAnchor(
marker: Ref<HTMLElement>
): void {
const { isAsideEnabled } = useAside()
const scrollAside = inject<(position: number) => void>('scroll-aside')

const onScroll = throttleAndDebounce(setActiveLink, 100)

Expand Down Expand Up @@ -170,9 +171,11 @@ export function useActiveAnchor(
activeLink.classList.add('active')
marker.value.style.top = activeLink.offsetTop + 39 + 'px'
marker.value.style.opacity = '1'
scrollAside?.(activeLink.offsetTop + 39)
} else {
marker.value.style.top = '33px'
marker.value.style.opacity = '0'
scrollAside?.(33)
}
}
}
Expand Down

0 comments on commit d6a5c13

Please sign in to comment.