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

feat: scroll active sidebar link into view on page load #3654

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/client/theme-default/components/VPSidebar.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import { useScrollLock } from '@vueuse/core'
import { inBrowser } from 'vitepress'
import { ref, watch } from 'vue'
import { nextTick, onMounted, ref, watch } from 'vue'
import { useSidebar } from '../composables/sidebar'
import VPSidebarItem from './VPSidebarItem.vue'

Expand All @@ -25,6 +25,11 @@ watch(
},
{ immediate: true, flush: 'post' }
)

// scroll active link into view
onMounted(() => {
nextTick(() => navEl.value?.querySelector('.is-active')?.scrollIntoView({ block: 'center'}))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And if the same route or pattern is placed 2+ times in the sidebar, is it working fine? also I'd calculate to scroll only when it is out of the viewport

})
</script>

<template>
Expand Down
1 change: 1 addition & 0 deletions src/client/theme-default/composables/outline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export function useActiveAnchor(

if (activeLink) {
activeLink.classList.add('active')
activeLink.scrollIntoView({ behavior: 'smooth', block: 'center' })

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR preview
image

Fixed
image

we also need to fix some edge cases like scroll to 0 when there is no active link, I'd also scroll only when it is out of viewport

marker.value.style.top = activeLink.offsetTop + 39 + 'px'
marker.value.style.opacity = '1'
} else {
Expand Down