feat(core): Add support for base paths and sub-routers.

This commit is contained in:
Philipp Kunz 2024-10-06 20:15:21 +02:00
parent 90466ff2b6
commit 8492192e72
3 changed files with 30 additions and 6 deletions

View File

@ -1,5 +1,11 @@
# Changelog
## 2024-10-06 - 1.2.0 - feat(core)
Add support for base paths and sub-routers.
- Added basePath feature to SmartRouter for handling base paths.
- Introduced createSubRouter method to create a sub-router with a specific prefix.
## 2024-10-06 - 1.1.1 - fix(core)
Remove SelectionDimension functionality

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartrouter',
version: '1.1.1',
version: '1.2.0',
description: 'A JavaScript library providing routing capabilities for web applications.'
}

View File

@ -36,15 +36,21 @@ export class SmartRouter {
handler: THandlerFunction;
}> = [];
/**
* base path for this router
*/
private basePath: string;
/**
* Creates an instance of Router.
*/
constructor(optionsArg: IRouterOptions) {
constructor(optionsArg: IRouterOptions, basePath: string = '') {
// lets set the router options
this.options = {
...this.options,
...optionsArg,
};
this.basePath = basePath;
// lets subscribe to route changes
window.addEventListener('popstate', (popStateEventArg) => {
@ -53,14 +59,25 @@ export class SmartRouter {
});
}
/**
* Create a sub-router with a specific prefix
* @param {string} subPath
* @param {IRouterOptions} [options]
*/
public createSubRouter(subPath: string, options?: IRouterOptions): SmartRouter {
const newBasePath = `${this.basePath}${subPath}`;
return new SmartRouter({ ...this.options, ...options }, newBasePath);
}
/**
* Push route state to history stack
*/
public async pushUrl(url: string = '/', state: any = {}) {
if (url !== window.location.pathname) {
window.history.pushState(state, window.document.title, url);
const fullUrl = `${this.basePath}${url}`;
if (fullUrl !== window.location.pathname) {
window.history.pushState(state, window.document.title, fullUrl);
} else {
window.history.replaceState(state, window.document.title, url);
window.history.replaceState(state, window.document.title, fullUrl);
}
await this._handleRouteState();
}
@ -71,8 +88,9 @@ export class SmartRouter {
* @param {function} handlerArg
*/
public on(routeArg: string, handlerArg: THandlerFunction) {
const fullRoute = `${this.basePath}${routeArg}`;
const routeObject = {
matchFunction: plugins.pathToRegExp.match(routeArg),
matchFunction: plugins.pathToRegExp.match(fullRoute),
handler: handlerArg,
};
this.routes.push(routeObject);