-
Notifications
You must be signed in to change notification settings - Fork 159
/
route-info.ts
561 lines (471 loc) · 14.8 KB
/
route-info.ts
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
import { Promise } from 'rsvp';
import { Dict, Option } from './core';
import Router, { SerializerFunc } from './router';
import InternalTransition, {
isTransition,
PARAMS_SYMBOL,
prepareResult,
PublicTransition as Transition,
QUERY_PARAMS_SYMBOL,
} from './transition';
import { isParam, isPromise, merge } from './utils';
import { throwIfAborted } from './transition-aborted-error';
interface IModel {
id?: string | number;
}
export interface Route {
inaccessibleByURL?: boolean;
routeName: string;
_internalName: string;
context: unknown;
events?: Dict<Function>;
model?(
params: Dict<unknown>,
transition: Transition
): Promise<Dict<unknown> | null | undefined> | undefined | Dict<unknown>;
deserialize?(params: Dict<unknown>, transition: Transition): Dict<unknown>;
serialize?(model: {}, params: string[]): Dict<unknown> | undefined;
beforeModel?(transition: Transition): Promise<any> | any;
afterModel?(resolvedModel: any, transition: Transition): Promise<any> | any;
setup?(
context: Dict<unknown> | PromiseLike<Dict<unknown> | null | undefined>,
transition: Transition
): void;
enter?(transition: Transition): void;
exit?(transition?: Transition): void;
_internalReset?(wasReset: boolean, transition?: Transition): void;
contextDidChange?(): void;
redirect?(context: Dict<unknown>, transition: Transition): void;
buildRouteInfoMetadata?(): unknown;
}
export interface RouteInfo {
readonly name: string;
readonly parent: RouteInfo | RouteInfoWithAttributes | null;
readonly child: RouteInfo | RouteInfoWithAttributes | null;
readonly localName: string;
readonly params: Dict<unknown>;
readonly paramNames: string[];
readonly queryParams: Dict<unknown>;
readonly metadata: unknown;
find(
predicate: (this: any, routeInfo: RouteInfo, i: number) => boolean,
thisArg?: any
): RouteInfo | undefined;
}
export interface RouteInfoWithAttributes extends RouteInfo {
attributes: any;
}
let ROUTE_INFOS = new WeakMap<InternalRouteInfo<Route>, RouteInfo | RouteInfoWithAttributes>();
export function toReadOnlyRouteInfo(
routeInfos: InternalRouteInfo<Route>[],
queryParams: Dict<unknown> = {},
includeAttributes = false
): RouteInfoWithAttributes[] | RouteInfo[] {
return routeInfos.map((info, i) => {
let { name, params, paramNames, context, route } = info;
if (ROUTE_INFOS.has(info) && includeAttributes) {
let routeInfo = ROUTE_INFOS.get(info)!;
routeInfo = attachMetadata(route!, routeInfo);
let routeInfoWithAttribute = createRouteInfoWithAttributes(routeInfo, context);
ROUTE_INFOS.set(info, routeInfoWithAttribute);
return routeInfoWithAttribute as RouteInfoWithAttributes;
}
let routeInfo: RouteInfo = {
find(
predicate: (this: any, routeInfo: RouteInfo, i: number, arr?: RouteInfo[]) => boolean,
thisArg: any
) {
let publicInfo;
let arr: RouteInfo[] = [];
if (predicate.length === 3) {
arr = routeInfos.map((info) => ROUTE_INFOS.get(info)!);
}
for (let i = 0; routeInfos.length > i; i++) {
publicInfo = ROUTE_INFOS.get(routeInfos[i])!;
if (predicate.call(thisArg, publicInfo, i, arr)) {
return publicInfo;
}
}
return undefined;
},
get name() {
return name;
},
get paramNames() {
return paramNames;
},
get metadata() {
return buildRouteInfoMetadata(info.route);
},
get parent() {
let parent = routeInfos[i - 1];
if (parent === undefined) {
return null;
}
return ROUTE_INFOS.get(parent)!;
},
get child() {
let child = routeInfos[i + 1];
if (child === undefined) {
return null;
}
return ROUTE_INFOS.get(child)!;
},
get localName() {
let parts = this.name.split('.');
return parts[parts.length - 1];
},
get params() {
return params;
},
get queryParams() {
return queryParams;
},
};
if (includeAttributes) {
routeInfo = createRouteInfoWithAttributes(routeInfo, context);
}
ROUTE_INFOS.set(info, routeInfo);
return routeInfo;
});
}
function createRouteInfoWithAttributes(
routeInfo: RouteInfo,
context: any
): RouteInfoWithAttributes {
let attributes = {
get attributes() {
return context;
},
};
if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('attributes')) {
return Object.freeze(Object.assign({}, routeInfo, attributes));
}
return Object.assign(routeInfo, attributes);
}
function buildRouteInfoMetadata(route?: Route) {
if (route !== undefined && route !== null && route.buildRouteInfoMetadata !== undefined) {
return route.buildRouteInfoMetadata();
}
return null;
}
function attachMetadata(route: Route, routeInfo: RouteInfo) {
let metadata = {
get metadata() {
return buildRouteInfoMetadata(route);
},
};
if (!Object.isExtensible(routeInfo) || routeInfo.hasOwnProperty('metadata')) {
return Object.freeze(Object.assign({}, routeInfo, metadata));
}
return Object.assign(routeInfo, metadata);
}
export default class InternalRouteInfo<T extends Route> {
private _routePromise?: Promise<T> = undefined;
private _route?: Option<T> = null;
protected router: Router<T>;
paramNames: string[];
name: string;
params: Dict<unknown> = {};
queryParams?: Dict<unknown>;
context?: Dict<unknown> | PromiseLike<Dict<unknown> | null | undefined> | null;
isResolved = false;
constructor(router: Router<T>, name: string, paramNames: string[], route?: T) {
this.name = name;
this.paramNames = paramNames;
this.router = router;
if (route) {
this._processRoute(route);
}
}
getModel(_transition: InternalTransition<T>) {
return Promise.resolve(this.context);
}
serialize(_context?: Dict<unknown>): Dict<unknown> | undefined {
return this.params || {};
}
resolve(transition: InternalTransition<T>): Promise<ResolvedRouteInfo<T>> {
return Promise.resolve(this.routePromise)
.then((route: Route) => {
throwIfAborted(transition);
return route;
})
.then(() => this.runBeforeModelHook(transition))
.then(() => throwIfAborted(transition))
.then(() => this.getModel(transition))
.then((resolvedModel) => {
throwIfAborted(transition);
return resolvedModel;
})
.then((resolvedModel) => this.runAfterModelHook(transition, resolvedModel))
.then((resolvedModel) => this.becomeResolved(transition, resolvedModel));
}
becomeResolved(
transition: InternalTransition<T> | null,
resolvedContext: Dict<unknown>
): ResolvedRouteInfo<T> {
let params = this.serialize(resolvedContext) as Dict<unknown>;
if (transition) {
this.stashResolvedModel(transition, resolvedContext);
transition[PARAMS_SYMBOL] = transition[PARAMS_SYMBOL] || {};
transition[PARAMS_SYMBOL][this.name] = params;
}
let context;
let contextsMatch = resolvedContext === this.context;
if ('context' in this || !contextsMatch) {
context = resolvedContext;
}
let cached = ROUTE_INFOS.get(this);
let resolved = new ResolvedRouteInfo(
this.router,
this.name,
this.paramNames,
params,
this.route!,
context
);
if (cached !== undefined) {
ROUTE_INFOS.set(resolved, cached);
}
return resolved;
}
shouldSupersede(routeInfo?: InternalRouteInfo<T>) {
// Prefer this newer routeInfo over `other` if:
// 1) The other one doesn't exist
// 2) The names don't match
// 3) This route has a context that doesn't match
// the other one (or the other one doesn't have one).
// 4) This route has parameters that don't match the other.
if (!routeInfo) {
return true;
}
let contextsMatch = routeInfo.context === this.context;
return (
routeInfo.name !== this.name ||
('context' in this && !contextsMatch) ||
(this.hasOwnProperty('params') && !paramsMatch(this.params, routeInfo.params))
);
}
get route(): T | undefined {
// _route could be set to either a route object or undefined, so we
// compare against null to know when it's been set
if (this._route !== null) {
return this._route;
}
return this.fetchRoute();
}
set route(route: T | undefined) {
this._route = route;
}
get routePromise(): Promise<T> {
if (this._routePromise) {
return this._routePromise;
}
this.fetchRoute();
return this._routePromise!;
}
set routePromise(routePromise: Promise<T>) {
this._routePromise = routePromise;
}
protected log(transition: InternalTransition<T>, message: string) {
if (transition.log) {
transition.log(this.name + ': ' + message);
}
}
private updateRoute(route: T) {
route._internalName = this.name;
return (this.route = route);
}
private runBeforeModelHook(transition: InternalTransition<T>) {
if (transition.trigger) {
transition.trigger(true, 'willResolveModel', transition, this.route);
}
let result;
if (this.route) {
if (this.route.beforeModel !== undefined) {
result = this.route.beforeModel(transition);
}
}
if (isTransition(result)) {
result = null;
}
return Promise.resolve(result);
}
private runAfterModelHook(
transition: InternalTransition<T>,
resolvedModel?: Dict<unknown> | null
): Promise<Dict<unknown>> {
// Stash the resolved model on the payload.
// This makes it possible for users to swap out
// the resolved model in afterModel.
let name = this.name;
this.stashResolvedModel(transition, resolvedModel!);
let result;
if (this.route !== undefined) {
if (this.route.afterModel !== undefined) {
result = this.route.afterModel(resolvedModel!, transition);
}
}
result = prepareResult(result);
return Promise.resolve(result).then(() => {
// Ignore the fulfilled value returned from afterModel.
// Return the value stashed in resolvedModels, which
// might have been swapped out in afterModel.
return transition.resolvedModels[name]!;
});
}
private stashResolvedModel(transition: InternalTransition<T>, resolvedModel: Dict<unknown>) {
transition.resolvedModels = transition.resolvedModels || {};
transition.resolvedModels[this.name] = resolvedModel;
}
private fetchRoute() {
let route = this.router.getRoute(this.name);
return this._processRoute(route);
}
private _processRoute(route: T | Promise<T>) {
// Setup a routePromise so that we can wait for asynchronously loaded routes
this.routePromise = Promise.resolve(route);
// Wait until the 'route' property has been updated when chaining to a route
// that is a promise
if (isPromise(route)) {
this.routePromise = this.routePromise.then((r) => {
return this.updateRoute(r);
});
// set to undefined to avoid recursive loop in the route getter
return (this.route = undefined);
} else if (route) {
return this.updateRoute(route);
}
return undefined;
}
}
export class ResolvedRouteInfo<T extends Route> extends InternalRouteInfo<T> {
isResolved: boolean;
constructor(
router: Router<T>,
name: string,
paramNames: string[],
params: Dict<unknown>,
route: T,
context?: Dict<unknown>
) {
super(router, name, paramNames, route);
this.params = params;
this.isResolved = true;
this.context = context;
}
resolve(transition: InternalTransition<T>): Promise<InternalRouteInfo<T>> {
// A ResolvedRouteInfo just resolved with itself.
if (transition && transition.resolvedModels) {
transition.resolvedModels[this.name] = this.context as Dict<unknown>;
}
return Promise.resolve(this);
}
}
export class UnresolvedRouteInfoByParam<T extends Route> extends InternalRouteInfo<T> {
params: Dict<unknown> = {};
constructor(
router: Router<T>,
name: string,
paramNames: string[],
params: Dict<unknown>,
route?: T
) {
super(router, name, paramNames, route);
this.params = params;
}
getModel(transition: InternalTransition<T>) {
let fullParams = this.params;
if (transition && transition[QUERY_PARAMS_SYMBOL]) {
fullParams = {};
merge(fullParams, this.params);
fullParams.queryParams = transition[QUERY_PARAMS_SYMBOL];
}
let route = this.route!;
let result: Dict<unknown> | undefined | Promise<Dict<unknown> | null | undefined>;
if (route.deserialize) {
result = route.deserialize(fullParams, transition);
} else if (route.model) {
result = route.model(fullParams, transition);
}
if (result && isTransition(result)) {
result = undefined;
}
return Promise.resolve(result);
}
}
export class UnresolvedRouteInfoByObject<T extends Route> extends InternalRouteInfo<T> {
serializer?: SerializerFunc;
constructor(
router: Router<T>,
name: string,
paramNames: string[],
context: Dict<unknown> | PromiseLike<Dict<unknown>>
) {
super(router, name, paramNames);
this.context = context;
this.serializer = this.router.getSerializer(name);
}
getModel(transition: InternalTransition<T>) {
if (this.router.log !== undefined) {
this.router.log(this.name + ': resolving provided model');
}
return super.getModel(transition);
}
/**
@private
Serializes a route using its custom `serialize` method or
by a default that looks up the expected property name from
the dynamic segment.
@param {Object} model the model to be serialized for this route
*/
serialize(model?: IModel) {
let { paramNames, context } = this;
if (!model) {
model = context as IModel;
}
let object: Dict<unknown> = {};
if (isParam(model)) {
object[paramNames[0]] = model;
return object;
}
// Use custom serialize if it exists.
if (this.serializer) {
// invoke this.serializer unbound (getSerializer returns a stateless function)
return this.serializer.call(null, model, paramNames);
} else if (this.route !== undefined) {
if (this.route.serialize) {
return this.route.serialize(model, paramNames);
}
}
if (paramNames.length !== 1) {
return;
}
let name = paramNames[0];
if (/_id$/.test(name)) {
object[name] = model.id;
} else {
object[name] = model;
}
return object;
}
}
function paramsMatch(a: Dict<unknown>, b: Dict<unknown>) {
if (!a !== !b) {
// Only one is null.
return false;
}
if (!a) {
// Both must be null.
return true;
}
// Note: this assumes that both params have the same
// number of keys, but since we're comparing the
// same routes, they should.
for (let k in a) {
if (a.hasOwnProperty(k) && a[k] !== b[k]) {
return false;
}
}
return true;
}