Skip to content

Commit 3840eaa

Browse files
authoredAug 5, 2023
fix(theme): update sidebar active link status on hash change (#2736)
1 parent 1a6efba commit 3840eaa

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed
 

‎src/client/theme-default/components/VPSidebarItem.vue

+6
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,12 @@ function onCaretClick() {
165165
color: var(--vp-c-brand);
166166
}
167167
168+
.VPSidebarItem.level-0.has-active > .item > .text,
169+
.VPSidebarItem.level-1.has-active > .item > .text,
170+
.VPSidebarItem.level-2.has-active > .item > .text,
171+
.VPSidebarItem.level-3.has-active > .item > .text,
172+
.VPSidebarItem.level-4.has-active > .item > .text,
173+
.VPSidebarItem.level-5.has-active > .item > .text,
168174
.VPSidebarItem.level-0.has-active > .item > .link > .text,
169175
.VPSidebarItem.level-1.has-active > .item > .link > .text,
170176
.VPSidebarItem.level-2.has-active > .item > .link > .text,

‎src/client/theme-default/composables/sidebar.ts

+18-6
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ import {
55
onMounted,
66
onUnmounted,
77
ref,
8-
watchEffect
8+
watchEffect,
9+
watch
910
} from 'vue'
1011
import { useMediaQuery } from '@vueuse/core'
1112
import { useRoute } from 'vitepress'
1213
import type { DefaultTheme } from 'vitepress/theme'
13-
import { isActive } from '../../shared'
14+
import { inBrowser, isActive } from '../../shared'
1415
import {
1516
hasActiveLink as containsActiveLink,
1617
getSidebar,
@@ -22,7 +23,7 @@ export interface SidebarControl {
2223
collapsed: Ref<boolean>
2324
collapsible: ComputedRef<boolean>
2425
isLink: ComputedRef<boolean>
25-
isActiveLink: ComputedRef<boolean>
26+
isActiveLink: Ref<boolean>
2627
hasActiveLink: ComputedRef<boolean>
2728
hasChildren: ComputedRef<boolean>
2829
toggle(): void
@@ -127,6 +128,13 @@ export function useCloseSidebarOnEscape(
127128
}
128129
}
129130

131+
const hashRef = ref(inBrowser ? location.hash : '')
132+
if (inBrowser) {
133+
window.addEventListener('hashchange', () => {
134+
hashRef.value = location.hash
135+
})
136+
}
137+
130138
export function useSidebarControl(
131139
item: ComputedRef<DefaultTheme.SidebarItem>
132140
): SidebarControl {
@@ -142,9 +150,13 @@ export function useSidebarControl(
142150
return !!item.value.link
143151
})
144152

145-
const isActiveLink = computed(() => {
146-
return isActive(page.value.relativePath, item.value.link)
147-
})
153+
const isActiveLink = ref(false)
154+
const updateIsActiveLink = () => {
155+
isActiveLink.value = isActive(page.value.relativePath, item.value.link)
156+
}
157+
158+
watch([page, item, hashRef], updateIsActiveLink)
159+
onMounted(updateIsActiveLink)
148160

149161
const hasActiveLink = computed(() => {
150162
if (isActiveLink.value) {

0 commit comments

Comments
 (0)
Please sign in to comment.