From e262ef63d89b2bc90c7e42bfc302ba6c602fab16 Mon Sep 17 00:00:00 2001 From: Evan You Date: Fri, 1 Jan 2021 13:03:46 -0500 Subject: [PATCH] feat(theme-default): nav.item.activeMatch --- docs/.vitepress/config.js | 8 ++++++-- .../theme-default/composables/navLink.ts | 18 +++++++++++++++--- src/client/theme-default/config.ts | 1 + 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index d9a95499fff5..14c5bd691f9b 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -23,8 +23,12 @@ module.exports = { }, nav: [ - { text: 'Guide', link: '/' }, - { text: 'Config Reference', link: '/config/basics' }, + { text: 'Guide', link: '/', activeMatch: '^/$|^/guide/' }, + { + text: 'Config Reference', + link: '/config/basics', + activeMatch: '^/config/' + }, { text: 'Release Notes', link: 'https://github.com/vuejs/vitepress/releases' diff --git a/src/client/theme-default/composables/navLink.ts b/src/client/theme-default/composables/navLink.ts index 951a00cd5996..c9f4d7accd08 100644 --- a/src/client/theme-default/composables/navLink.ts +++ b/src/client/theme-default/composables/navLink.ts @@ -11,11 +11,22 @@ export function useNavLink(item: DefaultTheme.NavItemWithLink) { const isExternal = isExternalCheck(item.link) const props = computed(() => { + const routePath = normalizePath(route.path) + + let active = false + if (item.activeMatch) { + active = new RegExp(item.activeMatch).test(routePath) + } else { + const itemPath = normalizePath(withBase(item.link)) + active = + itemPath === '/' + ? itemPath === routePath + : routePath.startsWith(itemPath) + } + return { class: { - active: normalizePath(route.path).startsWith( - normalizePath(withBase(item.link)) - ), + active, isExternal }, href: isExternal ? item.link : withBase(item.link), @@ -36,4 +47,5 @@ function normalizePath(path: string): string { .replace(/#.*$/, '') .replace(/\?.*$/, '') .replace(/\.(html|md)$/, '') + .replace(/\/index$/, '/') } diff --git a/src/client/theme-default/config.ts b/src/client/theme-default/config.ts index e049bcb737d8..d72848717e19 100644 --- a/src/client/theme-default/config.ts +++ b/src/client/theme-default/config.ts @@ -80,6 +80,7 @@ export namespace DefaultTheme { target?: string rel?: string ariaLabel?: string + activeMatch?: string } export interface NavItemWithLink extends NavItemBase {