This commit is contained in:
sairaj mote 2023-08-15 04:25:41 +05:30
parent 0c11ec1480
commit 802c6a2180

View File

@ -350,42 +350,48 @@ class Router {
this.state = state this.state = state
this.routingStart = routingStart this.routingStart = routingStart
this.routingEnd = routingEnd this.routingEnd = routingEnd
this.lastPage = null
window.addEventListener('hashchange', e => this.routeTo(window.location.hash)) window.addEventListener('hashchange', e => this.routeTo(window.location.hash))
} }
addRoute(route, callback) { addRoute(route, callback) {
this.routes[route] = callback this.routes[route] = callback
} }
set state(state) {
this._state = state
}
async routeTo(path) { async routeTo(path) {
let page try {
let wildcards = [] let page
let queryString let wildcards = []
let params let queryString
[path, queryString] = path.split('?'); let params
if (path.includes('#')) [path, queryString] = path.split('?');
path = path.split('#')[1]; if (path.includes('#'))
if (path.includes('/')) path = path.split('#')[1];
[, page, ...wildcards] = path.split('/') if (path.includes('/'))
else [, page, ...wildcards] = path.split('/')
page = path else
this.state = { page, wildcards } page = path
if (queryString) { this.state = { page, wildcards, lastPage: this.lastPage }
params = new URLSearchParams(queryString) if (queryString) {
this.state.params = Object.fromEntries(params) params = new URLSearchParams(queryString)
} this.state.params = Object.fromEntries(params)
if (this.routingStart) { }
this.routingStart(this.state) if (this.routingStart) {
} this.routingStart(this.state)
if (this.routes[page]) { }
await this.routes[page](this.state) if (this.routes[page]) {
this.state.lastPage = page await this.routes[page](this.state)
} else { this.lastPage = page
this.routes['404'](this.state) } else {
} if (this.routes['404']) {
if (this.routingEnd) { this.routes['404'](this.state);
this.routingEnd(this.state) } else {
console.error(`No route found for '${page}' and no '404' route is defined.`);
}
}
if (this.routingEnd) {
this.routingEnd(this.state)
}
} catch (e) {
console.error(e)
} }
} }
} }