Skip to content

Commit d8fa8dc

Browse files
committed
feat(router): basePath util to add base for routes
1 parent 5d2d1fd commit d8fa8dc

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

packages/kida-router/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,20 @@ paths.post({ id: '456', slug: 'hello-world' }) // '/posts/456/hello-world'
233233
paths.admin({ wildcard: 'settings/profile' }) // '/admin/settings/profile'
234234
```
235235

236+
### `basePath`
237+
238+
The `basePath` function allows you to set a base path for all routes in navigation:
239+
240+
```ts
241+
import { browserNavigation, basePath } from '@kidajs/router'
242+
243+
const routes = basePath('/github-pages', {
244+
home: '/',
245+
user: '/users/:id'
246+
})
247+
const [$location, navigation] = browserNavigation(routes)
248+
```
249+
236250
### `updateHref`
237251

238252
The `updateHref` function allows you to update parts of a URL string easily:

packages/kida-router/src/paths.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,27 @@ export function buildPaths<const R extends Routes>(routes: R) {
6161
{}
6262
) as Paths<R>
6363
}
64+
65+
/**
66+
* Adds a base path to all route patterns.
67+
* @param base - The base path to prepend.
68+
* @param routes - The original route patterns.
69+
* @returns New route patterns with the base path prepended.
70+
*/
71+
/* @__NO_SIDE_EFFECTS__ */
72+
export function basePath<const R extends Routes>(base: string, routes: R): R {
73+
const normalizedBase = removeTrailingSlash(base).replace(/^\.\//, '/')
74+
75+
if (normalizedBase === '' || normalizedBase === '/') {
76+
return routes
77+
}
78+
79+
return Object.entries(routes).reduce<Record<string, string>>(
80+
(paths, [route, pattern]) => {
81+
paths[route] = removeTrailingSlash(`${normalizedBase}${pattern}`)
82+
83+
return paths
84+
},
85+
{}
86+
) as R
87+
}

packages/kida-router/src/utils.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,4 +150,3 @@ export function updateLocation(
150150
action
151151
}
152152
}
153-

0 commit comments

Comments
 (0)