fix(core): update

This commit is contained in:
2020-07-15 18:51:17 +00:00
parent 8955fd5fa3
commit b1ecf655ad
5 changed files with 8449 additions and 726 deletions

View File

@ -1,6 +1,6 @@
import * as plugins from './smartrouter.plugins';
const routeLog = message => {
const routeLog = (message) => {
console.log(`%c[Router]%c ${message}`, 'color: rgb(255, 105, 100);', 'color: inherit');
};
@ -8,12 +8,19 @@ export interface IRouterOptions {
debug?: boolean;
}
export type THandlerFunction = <T extends object>(routeArg: IRouteInfo) => Promise<any>;
export interface IRouteInfo {
path: string;
index:number;
params: {[key: string]: string};
}
/**
* Router
*/
export class SmartRouter {
public options: IRouterOptions = {
debug: false
debug: false,
};
/**
@ -21,7 +28,7 @@ export class SmartRouter {
*/
public routes: Array<{
matchFunction: plugins.pathToRegExp.MatchFunction;
handler: <T extends object>(matchArg: plugins.pathToRegExp.Match<T>) => Promise<any>;
handler: THandlerFunction;
}> = [];
/**
@ -31,11 +38,11 @@ export class SmartRouter {
// lets set the router options
this.options = {
...this.options,
...optionsArg
...optionsArg,
};
// lets subscribe to route changes
window.addEventListener('popstate', popStateEventArg => {
window.addEventListener('popstate', (popStateEventArg) => {
popStateEventArg.preventDefault();
this._handleRouteState();
});
@ -61,10 +68,10 @@ export class SmartRouter {
* @param {string|RegExp} routeArg
* @param {function} handlerArg
*/
public on(routeArg: string, handlerArg: () => Promise<any>) {
public on(routeArg: string, handlerArg: THandlerFunction) {
this.routes.push({
matchFunction: plugins.pathToRegExp.match(routeArg),
handler: handlerArg
handler: handlerArg,
});
}
@ -73,13 +80,13 @@ export class SmartRouter {
*/
async _handleRouteState() {
const currentLocation = window.location.pathname;
const wantedRoute = this.routes.find(routeArg => {
const wantedRoute = this.routes.find((routeArg) => {
return !!routeArg.matchFunction(currentLocation);
});
if (wantedRoute) {
const routeResult = wantedRoute.matchFunction(currentLocation);
await wantedRoute.handler(routeResult);
await wantedRoute.handler(routeResult.valueOf() as IRouteInfo);
}
}
}