Skip to content

Commit 72534af

Browse files
authored
feat(theme): scroll toc if active item is out of view (#5377)
1 parent c197979 commit 72534af

2 files changed

Lines changed: 12 additions & 11 deletions

File tree

src/client/theme-default/components/VPDocOutlineItem.vue

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ defineProps<{
3737
font-size: 0.875rem;
3838
font-weight: 400;
3939
color: var(--vp-c-text-2);
40+
scroll-margin-top: calc(var(--vp-nav-height) + var(--vp-layout-top-height, 0px) + var(--vp-doc-top-height, 0px) + 2rem);
41+
scroll-margin-bottom: 3rem;
4042
white-space: nowrap;
4143
overflow: hidden;
4244
text-overflow: ellipsis;

src/client/theme-default/composables/outline.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -171,19 +171,17 @@ export function useActiveAnchor(
171171
}
172172

173173
function activateLink(hash: string | null) {
174-
if (prevActiveLink) {
175-
prevActiveLink.classList.remove('active')
176-
}
174+
const activeLink =
175+
hash != null
176+
? container.value.querySelector<HTMLAnchorElement>(
177+
`a[href$="${decodeURIComponent(hash)}"]`
178+
)
179+
: null
177180

178-
if (hash == null) {
179-
prevActiveLink = null
180-
} else {
181-
prevActiveLink = container.value.querySelector(
182-
`a[href$="${decodeURIComponent(hash)}"]`
183-
)
184-
}
181+
if (activeLink === prevActiveLink) return
185182

186-
const activeLink = prevActiveLink
183+
prevActiveLink?.classList.remove('active')
184+
prevActiveLink = activeLink
187185

188186
if (activeLink) {
189187
activeLink.classList.add('active')
@@ -195,6 +193,7 @@ export function useActiveAnchor(
195193
(activeLink.offsetHeight - marker.value.offsetHeight) / 2 +
196194
'px'
197195
marker.value.style.opacity = '1'
196+
activeLink.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
198197
} else {
199198
marker.value.style.top = ''
200199
marker.value.style.opacity = '0'

0 commit comments

Comments
 (0)