Skip to content

Commit

Permalink
fix: sidebar not working correctly when path starts with slash
Browse files Browse the repository at this point in the history
It fixes the problems that:

1. When base url and sidebar link url join problem.
2. Sidebat headings without a link is marked as "active".
  • Loading branch information
kiaking committed Sep 5, 2020
1 parent 1b96f63 commit 610cc17
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/client/theme-default/components/SideBar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from 'vitepress'
import { computed, h, FunctionalComponent, VNode } from 'vue'
import { Header } from '../../../../types/shared'
import { isActive, getPathDirName } from '../utils'
import { isActive, joinUrl, getPathDirName } from '../utils'
import { DefaultTheme } from '../config'
import { useActiveSidebarLinks } from '../composables/activeSidebarLink'

Expand All @@ -21,7 +21,7 @@ const SideBarItem: FunctionalComponent<{
const pageData = usePageData()
const siteData = useSiteData()

const link = `${siteData.value.base}${relLink || ''}`
const link = resolveLink(siteData.value.base, relLink || '')
const active = isActive(route, link)
const headers = pageData.value.headers

Expand Down Expand Up @@ -150,6 +150,10 @@ function resolveMultiSidebar(
return []
}

function resolveLink(base: string, path: string): string | undefined {
return path ? joinUrl(base, path || '') : undefined
}

function createLink(active: boolean, text: string, link?: string): VNode {
const tag = link ? 'a' : 'p'

Expand Down
15 changes: 15 additions & 0 deletions src/client/theme-default/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ export function normalize(path: string): string {
return decodeURI(path).replace(hashRE, '').replace(extRE, '')
}

export function joinUrl(base: string, path: string): string {
const baseEndsWithSlash = base.endsWith('/')
const pathStartsWithSlash = path.startsWith('/')

if (baseEndsWithSlash && pathStartsWithSlash) {
return base.slice(0, -1) + path
}

if (!baseEndsWithSlash && !pathStartsWithSlash) {
return `${base}/${path}`
}

return base + path
}

/**
* get the path without filename (the last segment). for example, if the given
* path is `/guide/getting-started.html`, this method will return `/guide/`.
Expand Down

0 comments on commit 610cc17

Please sign in to comment.