Skip to content

Commit

Permalink
fix(theme): update sidebar active link status on hash change (#2736)
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Aug 5, 2023
1 parent 1a6efba commit 3840eaa
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
6 changes: 6 additions & 0 deletions src/client/theme-default/components/VPSidebarItem.vue
Expand Up @@ -165,6 +165,12 @@ function onCaretClick() {
color: var(--vp-c-brand);
}
.VPSidebarItem.level-0.has-active > .item > .text,
.VPSidebarItem.level-1.has-active > .item > .text,
.VPSidebarItem.level-2.has-active > .item > .text,
.VPSidebarItem.level-3.has-active > .item > .text,
.VPSidebarItem.level-4.has-active > .item > .text,
.VPSidebarItem.level-5.has-active > .item > .text,
.VPSidebarItem.level-0.has-active > .item > .link > .text,
.VPSidebarItem.level-1.has-active > .item > .link > .text,
.VPSidebarItem.level-2.has-active > .item > .link > .text,
Expand Down
24 changes: 18 additions & 6 deletions src/client/theme-default/composables/sidebar.ts
Expand Up @@ -5,12 +5,13 @@ import {
onMounted,
onUnmounted,
ref,
watchEffect
watchEffect,
watch
} from 'vue'
import { useMediaQuery } from '@vueuse/core'
import { useRoute } from 'vitepress'
import type { DefaultTheme } from 'vitepress/theme'
import { isActive } from '../../shared'
import { inBrowser, isActive } from '../../shared'
import {
hasActiveLink as containsActiveLink,
getSidebar,
Expand All @@ -22,7 +23,7 @@ export interface SidebarControl {
collapsed: Ref<boolean>
collapsible: ComputedRef<boolean>
isLink: ComputedRef<boolean>
isActiveLink: ComputedRef<boolean>
isActiveLink: Ref<boolean>
hasActiveLink: ComputedRef<boolean>
hasChildren: ComputedRef<boolean>
toggle(): void
Expand Down Expand Up @@ -127,6 +128,13 @@ export function useCloseSidebarOnEscape(
}
}

const hashRef = ref(inBrowser ? location.hash : '')
if (inBrowser) {
window.addEventListener('hashchange', () => {
hashRef.value = location.hash
})
}

export function useSidebarControl(
item: ComputedRef<DefaultTheme.SidebarItem>
): SidebarControl {
Expand All @@ -142,9 +150,13 @@ export function useSidebarControl(
return !!item.value.link
})

const isActiveLink = computed(() => {
return isActive(page.value.relativePath, item.value.link)
})
const isActiveLink = ref(false)
const updateIsActiveLink = () => {
isActiveLink.value = isActive(page.value.relativePath, item.value.link)
}

watch([page, item, hashRef], updateIsActiveLink)
onMounted(updateIsActiveLink)

const hasActiveLink = computed(() => {
if (isActiveLink.value) {
Expand Down

0 comments on commit 3840eaa

Please sign in to comment.