| 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462 | 1
1
1
1
1
1
1
1
1
42
42
42
42
42
42
42
42
42
42
42
42
42
42
42
3
3
3
25
25
25
25
25
25
25
25
13
25
25
25
14
14
1
1
6
6
6
16
16
4
12
12
12
12
32
32
32
32
32
32
32
28
28
27
28
5
28
28
28
28
28
28
20
20
20
20
20
20
20
20
20
28
28
3
1
2
2
2
2
5
4
7
1
6
6
5
5
13
13
13
13
8
8
13
13
11
13
13
2
2
2
2
2
11
6
6
5
6
6
1
5
4
1
6
5
5
5
5
1
33
33
33
1
6
5
5
5
| import {RouteRecognizer} from 'aurelia-route-recognizer';
import {Container} from 'aurelia-dependency-injection';
import {History} from 'aurelia-history';
import {NavigationInstruction} from './navigation-instruction';
import {NavModel} from './nav-model';
import {RouterConfiguration} from './router-configuration';
import {
_createRootedPath,
_resolveUrl} from './util';
import {RouteConfig} from './interfaces';
/**
* The primary class responsible for handling routing and navigation.
*
* @class Router
* @constructor
*/
export class Router {
container: Container;
history: History;
viewPorts: Object;
routes: RouteConfig[];
/**
* The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]].
*/
baseUrl: string;
/**
* True if the [[Router]] has been configured.
*/
isConfigured: boolean;
/**
* True if the [[Router]] is currently processing a navigation.
*/
isNavigating: boolean;
/**
* The navigation models for routes that specified [[RouteConfig.nav]].
*/
navigation: NavModel[];
/**
* The currently active navigation instruction.
*/
currentInstruction: NavigationInstruction;
/**
* The parent router, or null if this instance is not a child router.
*/
parent: Router = null;
options: Object = {};
/**
* @param container The [[Container]] to use when child routers.
* @param history The [[History]] implementation to delegate navigation requests to.
*/
constructor(container: Container, history: History) {
this.container = container;
this.history = history;
this.reset();
}
/**
* Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made.
* Use with caution (actually, avoid using this). Do not use this to simply change your navigation model.
*/
reset() {
this.viewPorts = {};
this.routes = [];
this.baseUrl = '';
this.isConfigured = false;
this.isNavigating = false;
this.navigation = [];
this.currentInstruction = null;
this._fallbackOrder = 100;
this._recognizer = new RouteRecognizer();
this._childRecognizer = new RouteRecognizer();
this._configuredPromise = new Promise(resolve => {
this._resolveConfiguredPromise = resolve;
});
}
/**
* Gets a value indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent.
*/
get isRoot(): boolean {
return !this.parent;
}
/**
* Registers a viewPort to be used as a rendering target for activated routes.
*
* @param viewPort The viewPort.
* @param name The name of the viewPort. 'default' if unspecified.
*/
registerViewPort(viewPort: any, name?: string): void {
name = name || 'default';
this.viewPorts[name] = viewPort;
}
/**
* Returns a Promise that resolves when the router is configured.
*/
ensureConfigured(): Promise<void> {
return this._configuredPromise;
}
/**
* Configures the router.
*
* @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]].
*/
configure(callbackOrConfig: RouterConfiguration|((config: RouterConfiguration) => RouterConfiguration)): Promise<void> {
this.isConfigured = true;
let result = callbackOrConfig;
let config;
Eif (typeof callbackOrConfig === 'function') {
config = new RouterConfiguration();
result = callbackOrConfig(config);
}
return Promise.resolve(result).then((c) => {
if (c && c.exportToRouter) {
config = c;
}
config.exportToRouter(this);
this.isConfigured = true;
this._resolveConfiguredPromise();
});
}
/**
* Navigates to a new location.
*
* @param fragment The URL fragment to use as the navigation destination.
* @param options The navigation options.
*/
navigate(fragment: string, options?: any): boolean {
Iif (!this.isConfigured && this.parent) {
return this.parent.navigate(fragment, options);
}
return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
}
/**
* Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed
* by [[Router.navigate]].
*
* @param route The name of the route to use when generating the navigation location.
* @param params The route parameters to be used when populating the route pattern.
* @param options The navigation options.
*/
navigateToRoute(route: string, params?: any, options?: any): boolean {
let path = this.generate(route, params);
return this.navigate(path, options);
}
/**
* Navigates back to the most recent location in history.
*/
navigateBack(): void {
this.history.navigateBack();
}
/**
* Creates a child router of the current router.
*
* @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified.
* @returns {Router} The new child Router.
*/
createChild(container?: Container): Router {
let childRouter = new Router(container || this.container.createChild(), this.history);
childRouter.parent = this;
return childRouter;
}
/**
* Generates a URL fragment matching the specified route pattern.
*
* @param name The name of the route whose pattern should be used to generate the fragment.
* @param params The route params to be used to populate the route pattern.
* @returns {string} A string containing the generated URL fragment.
*/
generate(name: string, params?: any, options?: any = {}): string {
let hasRoute = this._recognizer.hasRoute(name);
if ((!this.isConfigured || !hasRoute) && this.parent) {
return this.parent.generate(name, params);
}
Iif (!hasRoute) {
throw new Error(`A route with name '${name}' could not be found. Check that \`name: '${name}'\` was specified in the route's config.`);
}
let path = this._recognizer.generate(name, params);
let rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute);
return options.absolute ? `${this.history.getAbsoluteRoot()}${rootedPath}` : rootedPath;
}
/**
* Creates a [[NavModel]] for the specified route config.
*
* @param config The route config.
*/
createNavModel(config: RouteConfig): NavModel {
let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
navModel.title = config.title;
navModel.order = config.nav;
navModel.href = config.href;
navModel.settings = config.settings;
navModel.config = config;
return navModel;
}
/**
* Registers a new route with the router.
*
* @param config The [[RouteConfig]].
* @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes.
*/
addRoute(config: RouteConfig, navModel?: NavModel): void {
validateRouteConfig(config);
if (!('viewPorts' in config) && !config.navigationStrategy) {
config.viewPorts = {
'default': {
moduleId: config.moduleId,
view: config.view
}
};
}
if (!navModel) {
navModel = this.createNavModel(config);
}
this.routes.push(config);
let path = config.route;
Iif (path.charAt(0) === '/') {
path = path.substr(1);
}
let caseSensitive = config.caseSensitive === true;
let state = this._recognizer.add({path: path, handler: config, caseSensitive: caseSensitive});
if (path) {
let settings = config.settings;
delete config.settings;
let withChild = JSON.parse(JSON.stringify(config));
config.settings = settings;
withChild.route = `${path}/*childRoute`;
withChild.hasChildRouter = true;
this._childRecognizer.add({
path: withChild.route,
handler: withChild,
caseSensitive: caseSensitive
});
withChild.navModel = navModel;
withChild.settings = config.settings;
}
config.navModel = navModel;
if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) {
throw new Error('Invalid route config: dynamic routes must specify an href to be included in the navigation model.');
}
Eif (typeof navModel.order !== 'number') {
navModel.order = ++this._fallbackOrder;
}
this.navigation.push(navModel);
this.navigation = this.navigation.sort((a, b) => a.order - b.order);
}
}
/**
* Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name.
*
* @param name The name of the route to check.
*/
hasRoute(name: string): boolean {
return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
}
/**
* Gets a value indicating whether or not this [[Router]] has a route registered with the specified name.
*
* @param name The name of the route to check.
*/
hasOwnRoute(name: string): boolean {
return this._recognizer.hasRoute(name);
}
/**
* Register a handler to use when the incoming URL fragment doesn't match any registered routes.
*
* @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]].
*/
handleUnknownRoutes(config?: string|Function|RouteConfig): void {
if (!config) {
throw new Error('Invalid unknown route handler');
}
this.catchAllHandler = instruction => {
return this._createRouteConfig(config, instruction)
.then(c => {
instruction.config = c;
return instruction;
});
};
}
/**
* Updates the document title using the current navigation instruction.
*/
updateTitle(): void {
if (this.parent) {
return this.parent.updateTitle();
}
this.currentInstruction._updateTitle();
}
/**
* Updates the navigation routes with hrefs relative to the current location.
* Note: This method will likely move to a plugin in a future release.
*/
refreshNavigation(): void {
let nav = this.navigation;
for (let i = 0, length = nav.length; i < length; i++) {
let current = nav[i];
if (!current.href) {
current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
}
}
}
_refreshBaseUrl(): void {
if (this.parent) {
let baseUrl = this.parent.currentInstruction.getBaseUrl();
this.baseUrl = this.parent.baseUrl + baseUrl;
}
}
_createNavigationInstruction(url: string = '', parentInstruction: NavigationInstruction = null): Promise<NavigationInstruction> {
let fragment = url;
let queryString = '';
let queryIndex = url.indexOf('?');
if (queryIndex !== -1) {
fragment = url.substr(0, queryIndex);
queryString = url.substr(queryIndex + 1);
}
let results = this._recognizer.recognize(url);
if (!results || !results.length) {
results = this._childRecognizer.recognize(url);
}
let instructionInit = {
fragment,
queryString,
config: null,
parentInstruction,
previousInstruction: this.currentInstruction,
router: this,
options: {
compareQueryParams: this.options.compareQueryParams
}
};
if (results && results.length) {
let first = results[0];
let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {
params: first.params,
queryParams: first.queryParams || results.queryParams,
config: first.config || first.handler
}));
Iif (typeof first.handler === 'function') {
return evaluateNavigationStrategy(instruction, first.handler, first);
} else Iif (first.handler && 'navigationStrategy' in first.handler) {
return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
}
return Promise.resolve(instruction);
} else if (this.catchAllHandler) {
let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {
params: { path: fragment },
queryParams: results && results.queryParams,
config: null // config will be created by the catchAllHandler
}));
return evaluateNavigationStrategy(instruction, this.catchAllHandler);
}
return Promise.reject(new Error(`Route not found: ${url}`));
}
_createRouteConfig(config, instruction) {
return Promise.resolve(config)
.then(c => {
if (typeof c === 'string') {
return { moduleId: c };
} else if (typeof c === 'function') {
return c(instruction);
}
return c;
})
.then(c => typeof c === 'string' ? { moduleId: c } : c)
.then(c => {
c.route = instruction.params.path;
validateRouteConfig(c);
Eif (!c.navModel) {
c.navModel = this.createNavModel(c);
}
return c;
});
}
}
function validateRouteConfig(config: RouteConfig): void {
Iif (typeof config !== 'object') {
throw new Error('Invalid Route Config');
}
Iif (typeof config.route !== 'string') {
throw new Error('Invalid Route Config: You must specify a route pattern.');
}
Iif (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
throw new Error('Invalid Route Config: You must specify a moduleId, redirect, navigationStrategy, or viewPorts.');
}
}
function evaluateNavigationStrategy(instruction: NavigationInstruction, evaluator: Function, context: any): Promise<NavigationInstruction> {
return Promise.resolve(evaluator.call(context, instruction)).then(() => {
Eif (!('viewPorts' in instruction.config)) {
instruction.config.viewPorts = {
'default': {
moduleId: instruction.config.moduleId
}
};
}
return instruction;
});
}
|