Skip to content

feat: add scroll support for the TOC #4735

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
35 changes: 31 additions & 4 deletions src/client/theme-default/composables/outline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const ignoreRE = /\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\b/

// cached list of anchor elements from resolveHeaders
const resolvedHeaders: { element: HTMLHeadElement; link: string }[] = []
let asideOutlineLinkDomList: NodeListOf<HTMLLIElement> | null = null
let asideContainerDom: HTMLDivElement | null = null

export function resolveTitle(theme: DefaultTheme.Config): string {
return (
Expand Down Expand Up @@ -99,6 +101,27 @@ export function useActiveAnchor(
window.removeEventListener('scroll', onScroll)
})

function scrollToActiveLink(i: number) {
if (!asideContainerDom) {
asideContainerDom = document.querySelector('.aside-container')!
}
const containerClientHeight = container.value.clientHeight
const asideContainerClientHeight = asideContainerDom.clientHeight
if (containerClientHeight > asideContainerClientHeight) {
if (!asideOutlineLinkDomList) {
asideOutlineLinkDomList = document.querySelectorAll(
'.VPDocOutlineItem.root .outline-link'
)
}
const height = asideOutlineLinkDomList[i]?.clientHeight
if (height) {
asideContainerDom.scrollTo({
top: i * height
})
}
}
}

function setActiveLink() {
if (!isAsideEnabled.value) {
return
Expand Down Expand Up @@ -137,14 +160,18 @@ export function useActiveAnchor(
}

// find the last header above the top of viewport
let activeLink: string | null = null
for (const { link, top } of headers) {
let activeIndex: number | null = null
for (let i = 0; i < headers.length; i++) {
const { top } = headers[i]
if (top > scrollY + getScrollOffset() + 4) {
break
}
activeLink = link
activeIndex = i
}
if (activeIndex !== null) {
scrollToActiveLink(activeIndex)
activateLink(headers[activeIndex].link)
}
activateLink(activeLink)
}

function activateLink(hash: string | null) {
Expand Down