From 3840eaae163cc9307c8d8525ad03c59752443b2b Mon Sep 17 00:00:00 2001 From: Divyansh Singh <40380293+brc-dd@users.noreply.github.com> Date: Sat, 5 Aug 2023 23:15:02 +0530 Subject: [PATCH] fix(theme): update sidebar active link status on hash change (#2736) --- .../components/VPSidebarItem.vue | 6 +++++ .../theme-default/composables/sidebar.ts | 24 ++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/client/theme-default/components/VPSidebarItem.vue b/src/client/theme-default/components/VPSidebarItem.vue index b7d00dc8..6b1c1b20 100644 --- a/src/client/theme-default/components/VPSidebarItem.vue +++ b/src/client/theme-default/components/VPSidebarItem.vue @@ -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, diff --git a/src/client/theme-default/composables/sidebar.ts b/src/client/theme-default/composables/sidebar.ts index a8bb6df1..c18a28dd 100644 --- a/src/client/theme-default/composables/sidebar.ts +++ b/src/client/theme-default/composables/sidebar.ts @@ -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, @@ -22,7 +23,7 @@ export interface SidebarControl { collapsed: Ref collapsible: ComputedRef isLink: ComputedRef - isActiveLink: ComputedRef + isActiveLink: Ref hasActiveLink: ComputedRef hasChildren: ComputedRef toggle(): void @@ -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 ): SidebarControl { @@ -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) {