Skip to content

Commit 460f39b

Browse files
committed
feat(shared): add resolveRoutePathFromUrl util
1 parent d8874a0 commit 460f39b

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { resolveRoutePathFromUrl } from '@vuepress/shared'
2+
3+
const testCases: [
4+
Parameters<typeof resolveRoutePathFromUrl>,
5+
ReturnType<typeof resolveRoutePathFromUrl>
6+
][] = [
7+
// with default base `/`
8+
[['https://vuepress.vuejs.org/base/foo'], '/base/foo'],
9+
[['http://vuepress.vuejs.org/base/foo'], '/base/foo'],
10+
[['//vuepress.vuejs.org/base/foo'], '/base/foo'],
11+
[['/base/foo'], '/base/foo'],
12+
[['base/foo'], 'base/foo'],
13+
14+
// with base `/base/`
15+
[['https://vuepress.vuejs.org/base/foo', '/base/'], '/foo'],
16+
[['http://vuepress.vuejs.org/base/foo', '/base/'], '/foo'],
17+
[['//vuepress.vuejs.org/base/foo', '/base/'], '/foo'],
18+
[['//vuepress.vuejs.org/foo/bar', '/base/'], '/foo/bar'],
19+
[['/base/foo', '/base/'], '/foo'],
20+
[['/foo/bar', '/base/'], '/foo/bar'],
21+
[['base/foo', '/base/'], 'base/foo'],
22+
[['foo/bar', '/base/'], 'foo/bar'],
23+
]
24+
25+
describe('shared > resolveRoutePathFromUrl', () => {
26+
describe('should resolve route path correctly', () => {
27+
testCases.forEach(([source, expected]) => {
28+
it(`url: ${source[0]}, base: ${
29+
source[1] || '/'
30+
} => expected: ${expected}`, () => {
31+
expect(resolveRoutePathFromUrl(...source)).toEqual(expected)
32+
})
33+
})
34+
})
35+
})

packages/@vuepress/shared/src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ export * from './removeEndingSlash'
1717
export * from './removeLeadingSlash'
1818
export * from './resolveHeadIdentifier'
1919
export * from './resolveLocalePath'
20+
export * from './resolveRoutePathFromUrl'
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const resolveRoutePathFromUrl = (url: string, base = '/'): string =>
2+
url
3+
// remove url origin
4+
.replace(/^(https?:)?\/\/[^/]*/, '')
5+
// remove site base
6+
.replace(new RegExp(`^${base}`), '/')

0 commit comments

Comments
 (0)