17 Commits

Author SHA1 Message Date
26e8f1e2c1 1.0.17 2023-09-11 18:43:11 +02:00
110eddba08 fix(core): update 2023-09-11 18:43:10 +02:00
1dc6315ac2 switch to new org scheme 2023-07-10 10:17:49 +02:00
0be5a0bf3d 1.0.16 2023-04-11 12:04:18 +02:00
187a273309 fix(core): update 2023-04-11 12:04:17 +02:00
1264a11140 1.0.15 2023-04-11 11:46:53 +02:00
c2c4fc96a5 fix(core): update 2023-04-11 11:46:53 +02:00
7d01fe89bc 1.0.14 2023-03-18 19:52:33 +01:00
c6a7938a3e fix(core): update 2023-03-18 19:52:32 +01:00
41ba5c8e4f 1.0.13 2022-12-31 11:21:29 +01:00
41b6f04db6 fix(core): update 2022-12-31 11:21:29 +01:00
470f47f8bb 1.0.12 2022-01-22 13:29:24 +01:00
8df4e21501 fix(core): update 2022-01-22 13:29:23 +01:00
ee87a6269e 1.0.11 2021-09-08 22:25:52 +02:00
2d76e799a4 fix(core): update 2021-09-08 22:25:52 +02:00
f24520ea89 1.0.10 2021-09-08 22:11:48 +02:00
5072728118 fix(core): update 2021-09-08 22:11:48 +02:00
16 changed files with 6083 additions and 27403 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @gitzone/tsdoc
npmci command tsdoc
continue-on-error: true

View File

@ -1,137 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "current file", "command": "npm test",
"type": "node", "name": "Run npm test",
"request": "launch", "request": "launch",
"args": [ "type": "node-terminal"
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
} }
] ]
} }

View File

@ -3,10 +3,10 @@
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "gitlab.com",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "smartrouter", "gitrepo": "smartrouter",
"shortDescription": "a router for routing on websites", "description": "a router for routing on websites",
"npmPackagename": "@pushrocks/smartrouter", "npmPackagename": "@push.rocks/smartrouter",
"license": "MIT", "license": "MIT",
"projectDomain": "push.rocks" "projectDomain": "push.rocks"
} }

27090
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@pushrocks/smartrouter", "name": "@push.rocks/smartrouter",
"version": "1.0.9", "version": "1.0.17",
"private": false, "private": false,
"description": "a router for routing on websites", "description": "a router for routing on websites",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
@ -10,16 +10,15 @@
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild --web && tsbundle npm --web)", "build": "(tsbuild --web && tsbundle npm --web)",
"format": "(gitzone format)" "format": "(gitzone format)",
"buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.26", "@git.zone/tsbuild": "^2.1.70",
"@gitzone/tsbundle": "^1.0.87", "@git.zone/tsbundle": "^2.0.7",
"@gitzone/tstest": "^1.0.57", "@git.zone/tstest": "^1.0.81",
"@pushrocks/tapbundle": "^3.2.14", "@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^16.7.13", "@types/node": "^20.6.0"
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0"
}, },
"dependencies": { "dependencies": {
"path-to-regexp": "^6.2.0" "path-to-regexp": "^6.2.0"
@ -38,5 +37,6 @@
], ],
"browserslist": [ "browserslist": [
"last 1 chrome versions" "last 1 chrome versions"
] ],
"type": "module"
} }

5696
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,26 @@
# @pushrocks/smartrouter # @push.rocks/smartrouter
a router for routing on websites a router for routing on websites
## Availabililty and Links ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartrouter) * [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartrouter)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartrouter) * [gitlab.com (source)](https://gitlab.com/push.rocks/smartrouter)
* [github.com (source mirror)](https://github.com/pushrocks/smartrouter) * [github.com (source mirror)](https://github.com/push.rocks/smartrouter)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartrouter/) * [docs (typedoc)](https://push.rocks.gitlab.io/smartrouter/)
## Status for master ## Status for master
Status Category | Status Badge Status Category | Status Badge
-- | -- -- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartrouter/badges/master/pipeline.svg)](https://lossless.cloud) GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartrouter/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartrouter/badges/master/coverage.svg)](https://lossless.cloud) GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartrouter/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartrouter)](https://lossless.cloud) npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartrouter)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartrouter)](https://lossless.cloud) Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartrouter)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud) TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud) Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartrouter)](https://lossless.cloud) PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartrouter)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartrouter)](https://lossless.cloud) PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartrouter)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartrouter)](https://lossless.cloud) BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartrouter)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage ## Usage
@ -33,7 +32,6 @@ We are always happy for code contributions. If you are not the code contributing
For further information read the linked docs at the top of this readme. For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) ## Legal
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)

View File

@ -1,17 +1,17 @@
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
import * as smartrouter from '../ts/index'; import * as smartrouter from '../ts/index.js';
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();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartrouter',
version: '1.0.17',
description: 'a router for routing on websites'
}

View File

@ -1,99 +1 @@
import * as plugins from './smartrouter.plugins'; export * from './smartrouter.classes.smartrouter.js';
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.entries()),
} as IRouteInfo); // not waiting here
}
}
}

View File

@ -0,0 +1,35 @@
import * as plugins from './smartrouter.plugins.js';
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,99 @@
import * as plugins from './smartrouter.plugins.js';
import { QueryParams } from './smartrouter.classes.queryparams.js';
const routeLog = (message: string) => {
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();
});
}
/**
* 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
}
}
}

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}