-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
243 lines (189 loc) · 6.75 KB
/
router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**@import Component from "./core/template/component.js";*/
/**
* @typedef {Object} Route
* @property {boolean} keepMounted
* @property {string[]} accessibleRoutes
* @property {(params: Record<string,string>) => Component} page
*/
/**
* @typedef {Object} RouterDescriptor
* @property {HTMLElement} root
* @property {boolean} debug
* @property {string} default
* @property {Record<string,Route>} routes
*/
/**
* @typedef {Object} Route
* @property {string} route
* @property {Record<string,string>} params
*/
class Router {
#root;
/**
* @type {Map<string,Route>}
*/
#routes;
/**
* @type {Map<string,Component>}
*/
#mountedRoutes;
#currentRoute = '/';
/**
* @type {Set<( next: Route, previous: Route ) => void>}
*
*/
#onRouteEnter = new Set();
/**
* @param {string} current
* @param {Map<string,Route>} states
* @param {Set<string>} visited - reached states
*/
static #analyze( current, states, visited, parent = '/' ){
const state = states.get( current );
if( !state ){
throw new Error(`[Router]: no match for route "${current}", reachable from parent route "${parent}"`)
}
const neighbors = state.accessibleRoutes;
if( !neighbors.length )
return visited;
for( let i = 0; i < neighbors.length; i++ ){
if( visited.has( neighbors[i] ) )
continue;
visited.add( neighbors[i] );
Router.#analyze( neighbors[i], states, visited, current );
}
}
/**
* @param {RouterDescriptor} descriptor
*/
constructor( descriptor ){
this.#root = descriptor.root;
this.#routes = new Map();
this.#mountedRoutes = new Map();
if( !descriptor.routes[descriptor.default] ){
throw new Error('[Router]: default route must be added');
}
Object
.entries( descriptor.routes )
.forEach( ([k,v]) => {
if( k[0] != '/' )
throw new Error(`[Router]: routes names must start with '/'. "${k}"`);
this.#routes.set(k,v);
})
if( descriptor.debug ){
const visited = new Set();
const unreachable = [];
Router.#analyze( descriptor.default, this.#routes, visited );
this.#routes.forEach( (v,k) => {
if( !visited.has(k) )
unreachable.push(k);
});
if( unreachable.length > 0 ){
throw new Error(`[Router]: some state are detected as unreachable, please, remove theme or correct their nextState list ${unreachable}` );
}
}
window.addEventListener('popstate', e => {
const { params, route } = this.#getRouteInfo();
this.#renderPage( route, params );
}, true );
this.push( descriptor.default, {} );
}
/**
*
* @returns {Route}
*/
#getRouteInfo(){
const [route, paramsStr] = location.hash.replaceAll('#', '').split( '?', 2 );
const params = {};
if( paramsStr ){
for( let i = 0; i < paramsStr.length; i++ ){
const equalIdx = paramsStr.indexOf('=', i);
const k = paramsStr.slice( i, equalIdx );
let v = '';
if( equalIdx < i ){
throw new Error(`[Router] error while parsing parameters ${paramsStr}`)
}
// skip the equal and the last element
for( i = equalIdx + 1; i < paramsStr.length; i++ ){
if( paramsStr[i] == ','){
break;
}
v += paramsStr[i];
}
params[k] = v;
}
}
return {
params,
route,
}
}
/**
* @param {string} route
* @param {Record<string,string>} props
*/
#renderPage( route, props ){
if( route == this.#currentRoute )
return this;
const current = this.#routes.get(this.#currentRoute);
const next = this.#routes.get( route );
let component;
if( !next ){
throw new Error(`[Router]: route "${route}" doesn't exists`)
}
if( next.keepMounted && this.#mountedRoutes.has( route ) ){
component = this.#mountedRoutes.get( route );
}else{
component = next.page( props );
this.#mountedRoutes.set( route, component );
}
const oldComponent = this.#mountedRoutes.get( this.#currentRoute );
if( current && !current.keepMounted ){
this.#mountedRoutes.delete( this.#currentRoute );
}
if( oldComponent )
oldComponent.dispose();
this.#root.append( ...component.render({ args: [], tree: [], refToArgs: [], idx: 0, }) )
this.#currentRoute = route;
return this;
}
/**
* @param {string} route
* @param {Record<string,string>} param
*/
push( route, param ){
let paramStr = '';
if( param && Object.entries( param ).length > 0 ){
paramStr = '?' + Object.entries( param ).map( ([k,v]) => `${k}=${v}` ).reduce( (p,c) => `${p},${c}`, '')
}
const prev = this.#getRouteInfo();
const next = {
route,
params: param,
};
this.#onRouteEnter.forEach( f => f( next, prev ) );
location.hash = route + paramStr;
return this;
}
/**
* @param {( next: Route, previous: Route ) => void} listener
*/
onRouteEnter( listener ){
this.#onRouteEnter.add( listener );
return this;
}
/**
* @param {( next: Route, previous: Route ) => void} listener
*/
removeOnRouteEnter( listener ){
this.#onRouteEnter.delete( listener );
return this;
}
}
/**
* @param {RouterDescriptor} descriptor
*/
export default function createRouter( descriptor ){
const router = new Router(descriptor);
return () => router;
};