fix(core): update

This commit is contained in:
Philipp Kunz 2022-01-22 13:29:23 +01:00
parent ee87a6269e
commit 8df4e21501
6 changed files with 2247 additions and 646 deletions

2631
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -13,11 +13,11 @@
"format": "(gitzone format)" "format": "(gitzone format)"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.27", "@gitzone/tsbuild": "^2.1.29",
"@gitzone/tsbundle": "^1.0.87", "@gitzone/tsbundle": "^1.0.88",
"@gitzone/tstest": "^1.0.57", "@gitzone/tstest": "^1.0.60",
"@pushrocks/tapbundle": "^3.2.14", "@pushrocks/tapbundle": "^4.0.0",
"@types/node": "^16.7.13", "@types/node": "^17.0.10",
"tslint": "^6.1.3", "tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0" "tslint-config-prettier": "^1.15.0"
}, },

View File

@ -1,17 +1,17 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, expectAsync, tap } from '@pushrocks/tapbundle';
import * as smartrouter from '../ts/index'; import * as smartrouter from '../ts/index';
let testrouter: smartrouter.SmartRouter; let testrouter: smartrouter.SmartRouter;
tap.test('first test', async () => { tap.test('first test', async () => {
testrouter = new smartrouter.SmartRouter({}); testrouter = new smartrouter.SmartRouter({});
expect(testrouter).to.be.instanceOf(smartrouter.SmartRouter); expect(testrouter).toBeInstanceOf(smartrouter.SmartRouter);
}); });
tap.test('should handle a route change', async (toolsArg) => { tap.test('should handle a route change', async (toolsArg) => {
const done = toolsArg.defer(); const done = toolsArg.defer();
testrouter.on('/myawesomeroute/:any', async (routeInfoArg) => { testrouter.on('/myawesomeroute/:any', async (routeInfoArg) => {
expect(routeInfoArg.params.any).to.equal('hello'); expect(routeInfoArg.params.any).toEqual('hello');
done.resolve(); done.resolve();
}); });
testrouter.pushUrl('/myawesomeroute/hello'); testrouter.pushUrl('/myawesomeroute/hello');
@ -21,26 +21,26 @@ tap.test('should handle a route change', async (toolsArg) => {
tap.test('should handle a route change', async (toolsArg) => { tap.test('should handle a route change', async (toolsArg) => {
const done = toolsArg.defer(); const done = toolsArg.defer();
testrouter.on('/myawesomeroute2/:wow', async (routeInfoArg) => { testrouter.on('/myawesomeroute2/:wow', async (routeInfoArg) => {
expect(routeInfoArg.params.wow).to.equal('hello2'); expect(routeInfoArg.params.wow).toEqual('hello2');
done.resolve(); done.resolve();
}); });
testrouter.pushUrl('/myawesomeroute2/hello2'); testrouter.pushUrl('/myawesomeroute2/hello2');
await done.promise; await done.promise;
expect(window.location.href).to.equal('http://localhost:3007/myawesomeroute2/hello2'); expect(window.location.href).toEqual('http://localhost:3007/myawesomeroute2/hello2');
}); });
tap.test('should find a query param', async (toolsArg) => { tap.test('should find a query param', async (toolsArg) => {
const done = toolsArg.defer(); const done = toolsArg.defer();
testrouter.on('/myawesomeroute2/:wow', async (routeInfoArg) => { testrouter.on('/myawesomeroute2/:wow', async (routeInfoArg) => {
expect(routeInfoArg.params.wow).to.equal('hello2'); expect(routeInfoArg.params.wow).toEqual('hello2');
expect(routeInfoArg.queryParams.aparam).to.equal('Yes'); expect(routeInfoArg.queryParams.aparam).toEqual('Yes');
console.log('Here is what queryParams looks like'); console.log('Here is what queryParams looks like');
console.log(JSON.stringify(routeInfoArg.queryParams)); console.log(JSON.stringify(routeInfoArg.queryParams));
done.resolve(); done.resolve();
}); });
testrouter.pushUrl('/myawesomeroute2/hello2?aparam=Yes'); testrouter.pushUrl('/myawesomeroute2/hello2?aparam=Yes');
await done.promise; await done.promise;
expect(window.location.href).to.equal('http://localhost:3007/myawesomeroute2/hello2?aparam=Yes'); expect(window.location.href).toEqual('http://localhost:3007/myawesomeroute2/hello2?aparam=Yes');
}); });
tap.start(); tap.start();

View File

@ -1,99 +1 @@
import * as plugins from './smartrouter.plugins'; export * from './smartrouter.classes.smartrouter';
const routeLog = (message) => {
console.log(`%c[Router]%c ${message}`, 'color: rgb(255, 105, 100);', 'color: inherit');
};
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 };
queryParams: { [key: string]: string };
}
/**
* Router
*/
export class SmartRouter {
public options: IRouterOptions = {
debug: false,
};
/**
* the routes we are handling
*/
public routes: Array<{
matchFunction: plugins.pathToRegExp.MatchFunction;
handler: THandlerFunction;
}> = [];
/**
* Creates an instance of Router.
*/
constructor(optionsArg: IRouterOptions) {
// lets set the router options
this.options = {
...this.options,
...optionsArg,
};
// lets subscribe to route changes
window.addEventListener('popstate', (popStateEventArg) => {
popStateEventArg.preventDefault();
this._handleRouteState();
});
window.addEventListener('DOMContentLoaded', () => {
this._handleRouteState();
});
}
/**
* 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);
} else {
window.history.replaceState(state, window.document.title, url);
}
await this._handleRouteState();
}
/**
* Attach route with handler
* @param {string|RegExp} routeArg
* @param {function} handlerArg
*/
public on(routeArg: string, handlerArg: THandlerFunction) {
this.routes.push({
matchFunction: plugins.pathToRegExp.match(routeArg),
handler: handlerArg,
});
}
/**
* Apply routes handler to current route
*/
async _handleRouteState() {
const currentLocation = window.location.pathname;
const urlSearchParams = new URLSearchParams(window.location.search);
// lets find all wanted routes.
const wantedRoutes = this.routes.filter((routeArg) => {
return !!routeArg.matchFunction(currentLocation);
});
for (const wantedRoute of wantedRoutes) {
const routeResult = wantedRoute.matchFunction(currentLocation);
wantedRoute.handler({
...(routeResult.valueOf() as Object),
queryParams: Object.fromEntries((urlSearchParams as any).entries()), // TODO check wether entries is supported in typings
} as IRouteInfo); // not waiting here
}
}
}

View File

@ -0,0 +1,31 @@
import * as plugins from './smartrouter.plugins';
export class QueryParams {
constructor() {}
public getAllAsObject() {
const urlSearchParams = new URLSearchParams(window.location.search);
return Object.fromEntries((urlSearchParams as any).entries());
}
public setQueryParam(queryKeyArg: string, queryContentArg: string, pushOrReplaceArg: 'push' | 'replace' = 'replace') {
var queryParams = new URLSearchParams(window.location.search);
queryParams.set(queryKeyArg, queryContentArg);
pushOrReplaceArg === 'push'
? history.pushState(null, null, '?' + queryParams.toString())
: history.replaceState(null, null, '?' + queryParams.toString());
}
public deleteQueryParam(queryKeyArg: string, pushOrReplaceArg: 'push' | 'replace' = 'replace') {
var queryParams = new URLSearchParams(window.location.search);
queryParams.delete(queryKeyArg);
pushOrReplaceArg === 'push'
? history.pushState(null, null, '?' + queryParams.toString())
: history.replaceState(null, null, '?' + queryParams.toString());
}
public getQueryParam(queryParamName: string) {
const queryParams = this.getAllAsObject();
return queryParams[queryParamName];
}
}

View File

@ -0,0 +1,105 @@
import * as plugins from './smartrouter.plugins';
import { QueryParams } from './smartrouter.classes.queryparams';
const routeLog = (message) => {
console.log(`%c[Router]%c ${message}`, 'color: rgb(255, 105, 100);', 'color: inherit');
};
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 };
queryParams: { [key: string]: string };
}
/**
* Router
*/
export class SmartRouter {
public options: IRouterOptions = {
debug: false,
};
public queryParams = new QueryParams();
/**
* the routes we are handling
*/
public routes: Array<{
matchFunction: plugins.pathToRegExp.MatchFunction;
handler: THandlerFunction;
}> = [];
/**
* Creates an instance of Router.
*/
constructor(optionsArg: IRouterOptions) {
// lets set the router options
this.options = {
...this.options,
...optionsArg,
};
// lets subscribe to route changes
window.addEventListener('popstate', (popStateEventArg) => {
popStateEventArg.preventDefault();
this._handleRouteState();
});
window.addEventListener('DOMContentLoaded', () => {
this._handleRouteState();
});
}
/**
* 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);
} else {
window.history.replaceState(state, window.document.title, url);
}
await this._handleRouteState();
}
/**
* Attach route with handler
* @param {string|RegExp} routeArg
* @param {function} handlerArg
*/
public on(routeArg: string, handlerArg: THandlerFunction) {
this.routes.push({
matchFunction: plugins.pathToRegExp.match(routeArg),
handler: handlerArg,
});
}
/**
* Apply routes handler to current route
*/
async _handleRouteState() {
const currentLocation = window.location.pathname;
// lets find all wanted routes.
const wantedRoutes = this.routes.filter((routeArg) => {
return !!routeArg.matchFunction(currentLocation);
});
for (const wantedRoute of wantedRoutes) {
const routeResult = wantedRoute.matchFunction(currentLocation);
wantedRoute.handler({
...(routeResult.valueOf() as Object),
queryParams: this.queryParams.getAllAsObject(), // TODO check wether entries is supported in typings
} as IRouteInfo); // not waiting here
}
}
}