-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
router.ts
1860 lines (1581 loc) · 53.6 KB
/
router.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { privatize as P } from '@ember/-internals/container';
import { OutletState as GlimmerOutletState, OutletView } from '@ember/-internals/glimmer';
import { computed, get, notifyPropertyChange, set } from '@ember/-internals/metal';
import { FactoryClass, getOwner, Owner } from '@ember/-internals/owner';
import { BucketCache } from '@ember/-internals/routing';
import { A as emberA, Evented, Object as EmberObject, typeOf } from '@ember/-internals/runtime';
import Controller from '@ember/controller';
import { assert, deprecate, info } from '@ember/debug';
import { APP_CTRL_ROUTER_PROPS, ROUTER_EVENTS } from '@ember/deprecated-features';
import EmberError from '@ember/error';
import { assign } from '@ember/polyfills';
import { cancel, once, run, scheduleOnce } from '@ember/runloop';
import { DEBUG } from '@glimmer/env';
import EmberLocation, { EmberLocation as IEmberLocation } from '../location/api';
import { calculateCacheKey, extractRouteArgs, getActiveTargetName, resemblesURL } from '../utils';
import DSL from './dsl';
import Route, {
defaultSerialize,
getFullQueryParams,
hasDefaultSerialize,
RenderOptions,
ROUTE_CONNECTIONS,
ROUTER_EVENT_DEPRECATIONS,
} from './route';
import RouterState from './router_state';
/**
@module @ember/routing
*/
import { MatchCallback } from 'route-recognizer';
import Router, {
InternalRouteInfo,
logAbort,
STATE_SYMBOL,
Transition,
TransitionError,
TransitionState,
} from 'router_js';
import { EngineRouteInfo } from './engines';
function defaultDidTransition(this: EmberRouter, infos: PrivateRouteInfo[]) {
updatePaths(this);
this._cancelSlowTransitionTimer();
this.notifyPropertyChange('url');
this.set('currentState', this.targetState);
// Put this in the runloop so url will be accurate. Seems
// less surprising than didTransition being out of sync.
once(this, this.trigger, 'didTransition');
if (DEBUG) {
if (get(this, 'namespace').LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
console.log(`Transitioned into '${EmberRouter._routePath(infos)}'`);
}
}
}
function defaultWillTransition(
this: EmberRouter,
oldInfos: PrivateRouteInfo[],
newInfos: PrivateRouteInfo[],
transition: Transition
) {
once(this, this.trigger, 'willTransition', transition);
if (DEBUG) {
if (get(this, 'namespace').LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
console.log(
`Preparing to transition from '${EmberRouter._routePath(
oldInfos
)}' to '${EmberRouter._routePath(newInfos)}'`
);
}
}
}
interface RenderOutletState {
name: string;
outlet: string;
}
interface NestedOutletState {
[key: string]: OutletState;
}
interface OutletState<T extends RenderOutletState = RenderOutletState> {
render: T;
outlets: NestedOutletState;
wasUsed?: boolean;
}
interface EngineInstance extends Owner {
boot(): void;
destroy(): void;
}
export interface QueryParam {
prop: string;
urlKey: string;
type: string;
route: Route;
parts: string[];
values: {};
scopedPropertyName: string;
}
export type PrivateRouteInfo = InternalRouteInfo<Route>;
function K(this: Router<Route>) {
return this;
}
const { slice } = Array.prototype;
/**
The `EmberRouter` class manages the application state and URLs. Refer to
the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
@class EmberRouter
@extends EmberObject
@uses Evented
@public
*/
class EmberRouter extends EmberObject {
location!: string | IEmberLocation;
rootURL!: string;
_routerMicrolib!: Router<Route>;
_didSetupRouter = false;
_initialTransitionStarted = false;
currentURL: string | null = null;
currentRouteName: string | null = null;
currentPath: string | null = null;
currentRoute = null;
_qpCache = Object.create(null);
_qpUpdates = new Set();
_queuedQPChanges: { [key: string]: unknown } = {};
_bucketCache: BucketCache | undefined;
_toplevelView: OutletView | null = null;
_handledErrors = new Set();
_engineInstances: { [name: string]: { [id: string]: EngineInstance } } = Object.create(null);
_engineInfoByRoute = Object.create(null);
_slowTransitionTimer: unknown;
constructor(owner: Owner) {
super(...arguments);
this._resetQueuedQueryParameterChanges();
if (owner) {
this.namespace = owner.lookup('application:main');
this._bucketCache = owner.lookup(P`-bucket-cache:main`);
}
}
_initRouterJs() {
let location = get(this, 'location');
let router = this;
let owner = getOwner(this);
let seen = Object.create(null);
class PrivateRouter extends Router<Route> {
getRoute(name: string): Route {
let routeName = name;
let routeOwner = owner;
let engineInfo = router._engineInfoByRoute[routeName];
if (engineInfo) {
let engineInstance = router._getEngineInstance(engineInfo);
routeOwner = engineInstance;
routeName = engineInfo.localFullName;
}
let fullRouteName = `route:${routeName}`;
let route = routeOwner.lookup<Route>(fullRouteName);
if (seen[name]) {
return route!;
}
seen[name] = true;
if (!route) {
let DefaultRoute: any = routeOwner.factoryFor('route:basic')!.class;
routeOwner.register(fullRouteName, DefaultRoute.extend());
route = routeOwner.lookup(fullRouteName);
if (DEBUG) {
if (get(router, 'namespace.LOG_ACTIVE_GENERATION')) {
info(`generated -> ${fullRouteName}`, { fullName: fullRouteName });
}
}
}
route!._setRouteName(routeName);
if (engineInfo && !hasDefaultSerialize(route!)) {
throw new Error(
'Defining a custom serialize method on an Engine route is not supported.'
);
}
return route!;
}
getSerializer(name: string) {
let engineInfo = router._engineInfoByRoute[name];
// If this is not an Engine route, we fall back to the handler for serialization
if (!engineInfo) {
return;
}
return engineInfo.serializeMethod || defaultSerialize;
}
updateURL(path: string) {
once(() => {
location.setURL(path);
set(router, 'currentURL', path);
});
}
didTransition(infos: PrivateRouteInfo[]) {
if (ROUTER_EVENTS) {
if (router.didTransition !== defaultDidTransition) {
deprecate(
'You attempted to override the "didTransition" method which is deprecated. Please inject the router service and listen to the "routeDidChange" event.',
false,
{
id: 'deprecate-router-events',
until: '4.0.0',
url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events',
for: 'ember-source',
since: {
enabled: '3.11.0',
},
}
);
}
}
router.didTransition(infos);
}
willTransition(
oldInfos: PrivateRouteInfo[],
newInfos: PrivateRouteInfo[],
transition: Transition
) {
if (ROUTER_EVENTS) {
if (router.willTransition !== defaultWillTransition) {
deprecate(
'You attempted to override the "willTransition" method which is deprecated. Please inject the router service and listen to the "routeWillChange" event.',
false,
{
id: 'deprecate-router-events',
until: '4.0.0',
url: 'https://emberjs.com/deprecations/v3.x#toc_deprecate-router-events',
for: 'ember-source',
since: {
enabled: '3.11.0',
},
}
);
}
}
router.willTransition(oldInfos, newInfos, transition);
}
triggerEvent(
routeInfos: PrivateRouteInfo[],
ignoreFailure: boolean,
name: string,
args: unknown[]
) {
return triggerEvent.bind(router)(routeInfos, ignoreFailure, name, args);
}
routeWillChange(transition: Transition) {
router.trigger('routeWillChange', transition);
// in case of intermediate transition we update the current route
// to make router.currentRoute.name consistent with router.currentRouteName
// see https://github.com/emberjs/ember.js/issues/19449
if (transition.isIntermediate) {
router.set('currentRoute', transition.to);
}
}
routeDidChange(transition: Transition) {
router.set('currentRoute', transition.to);
once(() => {
router.trigger('routeDidChange', transition);
});
}
transitionDidError(error: TransitionError, transition: Transition) {
if (error.wasAborted || transition.isAborted) {
// If the error was a transition erorr or the transition aborted
// log the abort.
return logAbort(transition);
} else {
// Otherwise trigger the "error" event to attempt an intermediate
// transition into an error substate
transition.trigger(false, 'error', error.error, transition, error.route);
if (router._isErrorHandled(error.error)) {
// If we handled the error with a substate just roll the state back on
// the transition and send the "routeDidChange" event for landing on
// the error substate and return the error.
transition.rollback();
this.routeDidChange(transition);
return error.error;
} else {
// If it was not handled, abort the transition completely and return
// the error.
transition.abort();
return error.error;
}
}
}
replaceURL(url: string) {
if (location.replaceURL) {
let doReplaceURL = () => {
location.replaceURL(url);
set(router, 'currentURL', url);
};
once(doReplaceURL);
} else {
this.updateURL(url);
}
}
}
let routerMicrolib = (this._routerMicrolib = new PrivateRouter());
let dslCallbacks = (this.constructor as any).dslCallbacks || [K];
let dsl = this._buildDSL();
dsl.route(
'application',
{ path: '/', resetNamespace: true, overrideNameAssertion: true },
function () {
for (let i = 0; i < dslCallbacks.length; i++) {
dslCallbacks[i].call(this);
}
}
);
if (DEBUG) {
if (get(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) {
routerMicrolib.log = console.log.bind(console); // eslint-disable-line no-console
}
}
routerMicrolib.map(dsl.generate());
}
_buildDSL(): DSL {
let enableLoadingSubstates = this._hasModuleBasedResolver();
let router = this;
let owner = getOwner(this);
let options = {
enableLoadingSubstates,
resolveRouteMap(name: string) {
return owner.factoryFor(`route-map:${name}`)!;
},
addRouteForEngine(name: string, engineInfo: EngineRouteInfo) {
if (!router._engineInfoByRoute[name]) {
router._engineInfoByRoute[name] = engineInfo;
}
},
};
return new DSL(null, options);
}
/*
Resets all pending query parameter changes.
Called after transitioning to a new route
based on query parameter changes.
*/
_resetQueuedQueryParameterChanges() {
this._queuedQPChanges = {};
}
_hasModuleBasedResolver() {
let owner = getOwner(this);
if (!owner) {
return false;
}
let resolver = get(owner, 'application.__registry__.resolver.moduleBasedResolver');
return Boolean(resolver);
}
/**
Initializes the current router instance and sets up the change handling
event listeners used by the instances `location` implementation.
A property named `initialURL` will be used to determine the initial URL.
If no value is found `/` will be used.
@method startRouting
@private
*/
startRouting() {
if (this.setupRouter()) {
let initialURL = get(this, 'initialURL');
if (initialURL === undefined) {
initialURL = get(this, 'location').getURL();
}
let initialTransition = this.handleURL(initialURL);
if (initialTransition && initialTransition.error) {
throw initialTransition.error;
}
}
}
setupRouter() {
if (this._didSetupRouter) {
return false;
}
this._didSetupRouter = true;
this._setupLocation();
let location = get(this, 'location');
// Allow the Location class to cancel the router setup while it refreshes
// the page
if (get(location, 'cancelRouterSetup')) {
return false;
}
this._initRouterJs();
location.onUpdateURL((url: string) => {
this.handleURL(url);
});
return true;
}
_setOutlets() {
// This is triggered async during Route#willDestroy.
// If the router is also being destroyed we do not want to
// to create another this._toplevelView (and leak the renderer)
if (this.isDestroying || this.isDestroyed) {
return;
}
let routeInfos = this._routerMicrolib.currentRouteInfos;
if (!routeInfos) {
return;
}
let defaultParentState: OutletState | undefined;
let liveRoutes = null;
for (let i = 0; i < routeInfos.length; i++) {
let route = routeInfos[i].route!;
let connections = ROUTE_CONNECTIONS.get(route!);
let ownState: OutletState;
if (connections.length === 0) {
ownState = representEmptyRoute(liveRoutes, defaultParentState, route);
} else {
for (let j = 0; j < connections.length; j++) {
let appended = appendLiveRoute(liveRoutes, defaultParentState, connections[j]);
liveRoutes = appended.liveRoutes;
let { name, outlet } = appended.ownState.render;
if (name === route.routeName || outlet === 'main') {
ownState = appended.ownState;
}
}
}
defaultParentState = ownState!;
}
// when a transitionTo happens after the validation phase
// during the initial transition _setOutlets is called
// when no routes are active. However, it will get called
// again with the correct values during the next turn of
// the runloop
if (!liveRoutes) {
return;
}
if (!this._toplevelView) {
let owner = getOwner(this);
let OutletView = owner.factoryFor<OutletView, FactoryClass>('view:-outlet')!;
this._toplevelView = OutletView.create();
this._toplevelView.setOutletState(liveRoutes as GlimmerOutletState);
let instance: any = owner.lookup('-application-instance:main');
if (instance) {
instance.didCreateRootView(this._toplevelView);
}
} else {
this._toplevelView.setOutletState(liveRoutes as GlimmerOutletState);
}
}
handleURL(url: string) {
// Until we have an ember-idiomatic way of accessing #hashes, we need to
// remove it because router.js doesn't know how to handle it.
let _url = url.split(/#(.+)?/)[0];
return this._doURLTransition('handleURL', _url);
}
_doURLTransition(routerJsMethod: string, url: string) {
this._initialTransitionStarted = true;
let transition = this._routerMicrolib[routerJsMethod](url || '/');
didBeginTransition(transition, this);
return transition;
}
/**
Transition the application into another route. The route may
be either a single route or route path:
See [transitionTo](/ember/release/classes/Route/methods/transitionTo?anchor=transitionTo) for more info.
@method transitionTo
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used while
transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@return {Transition} the transition object associated with this
attempted transition
@public
*/
transitionTo(...args: unknown[]) {
if (resemblesURL(args[0])) {
assert(
`A transition was attempted from '${this.currentRouteName}' to '${args[0]}' but the application instance has already been destroyed.`,
!this.isDestroying && !this.isDestroyed
);
return this._doURLTransition('transitionTo', args[0] as string);
}
let { routeName, models, queryParams } = extractRouteArgs(args);
assert(
`A transition was attempted from '${this.currentRouteName}' to '${routeName}' but the application instance has already been destroyed.`,
!this.isDestroying && !this.isDestroyed
);
return this._doTransition(routeName, models, queryParams);
}
intermediateTransitionTo(name: string, ...args: any[]) {
this._routerMicrolib.intermediateTransitionTo(name, ...args);
updatePaths(this);
if (DEBUG) {
let infos = this._routerMicrolib.currentRouteInfos;
if (get(this, 'namespace').LOG_TRANSITIONS) {
// eslint-disable-next-line no-console
console.log(`Intermediate-transitioned into '${EmberRouter._routePath(infos)}'`);
}
}
}
replaceWith(...args: any[]) {
return this.transitionTo(...args).method('replace');
}
generate(name: string, ...args: any[]) {
let url = this._routerMicrolib.generate(name, ...args);
return (this.location as IEmberLocation).formatURL(url);
}
/**
Determines if the supplied route is currently active.
@method isActive
@param routeName
@return {Boolean}
@private
*/
isActive(routeName: string) {
return this._routerMicrolib.isActive(routeName);
}
/**
An alternative form of `isActive` that doesn't require
manual concatenation of the arguments into a single
array.
@method isActiveIntent
@param routeName
@param models
@param queryParams
@return {Boolean}
@private
@since 1.7.0
*/
isActiveIntent(routeName: string, models: {}[], queryParams: QueryParam) {
return this.currentState!.isActiveIntent(routeName, models, queryParams);
}
send(name: string, ...args: any[]) {
/*name, context*/
this._routerMicrolib.trigger(name, ...args);
}
/**
Does this router instance have the given route.
@method hasRoute
@return {Boolean}
@private
*/
hasRoute(route: string) {
return this._routerMicrolib.hasRoute(route);
}
/**
Resets the state of the router by clearing the current route
handlers and deactivating them.
@private
@method reset
*/
reset() {
this._didSetupRouter = false;
this._initialTransitionStarted = false;
if (this._routerMicrolib) {
this._routerMicrolib.reset();
}
}
willDestroy() {
if (this._toplevelView) {
this._toplevelView.destroy();
this._toplevelView = null;
}
this._super(...arguments);
this.reset();
let instances = this._engineInstances;
for (let name in instances) {
for (let id in instances[name]) {
run(instances[name][id], 'destroy');
}
}
}
/*
Called when an active route's query parameter has changed.
These changes are batched into a runloop run and trigger
a single transition.
*/
_activeQPChanged(queryParameterName: string, newValue: unknown) {
this._queuedQPChanges[queryParameterName] = newValue;
once(this, this._fireQueryParamTransition);
}
_updatingQPChanged(queryParameterName: string) {
this._qpUpdates.add(queryParameterName);
}
/*
Triggers a transition to a route based on query parameter changes.
This is called once per runloop, to batch changes.
e.g.
if these methods are called in succession:
this._activeQPChanged('foo', '10');
// results in _queuedQPChanges = { foo: '10' }
this._activeQPChanged('bar', false);
// results in _queuedQPChanges = { foo: '10', bar: false }
_queuedQPChanges will represent both of these changes
and the transition using `transitionTo` will be triggered
once.
*/
_fireQueryParamTransition() {
this.transitionTo({ queryParams: this._queuedQPChanges });
this._resetQueuedQueryParameterChanges();
}
_setupLocation() {
let location = this.location;
let rootURL = this.rootURL;
let owner = getOwner(this);
if ('string' === typeof location && owner) {
let resolvedLocation = owner.lookup<IEmberLocation>(`location:${location}`);
if (resolvedLocation !== undefined) {
location = set(this, 'location', resolvedLocation);
} else {
// Allow for deprecated registration of custom location API's
let options = {
implementation: location,
};
location = set(this, 'location', EmberLocation.create(options));
}
}
if (location !== null && typeof location === 'object') {
if (rootURL) {
set(location, 'rootURL', rootURL);
}
// Allow the location to do any feature detection, such as AutoLocation
// detecting history support. This gives it a chance to set its
// `cancelRouterSetup` property which aborts routing.
if (typeof location.detect === 'function') {
location.detect();
}
// ensure that initState is called AFTER the rootURL is set on
// the location instance
if (typeof location.initState === 'function') {
location.initState();
}
}
}
/**
Serializes the given query params according to their QP meta information.
@private
@method _serializeQueryParams
@param {Arrray<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_serializeQueryParams(routeInfos: PrivateRouteInfo[], queryParams: QueryParam) {
forEachQueryParam(
this,
routeInfos,
queryParams,
(key: string, value: unknown, qp: QueryParam) => {
if (qp) {
delete queryParams[key];
queryParams[qp.urlKey] = qp.route.serializeQueryParam(value, qp.urlKey, qp.type);
} else if (value === undefined) {
return; // We don't serialize undefined values
} else {
queryParams[key] = this._serializeQueryParam(value, typeOf(value));
}
}
);
}
/**
Serializes the value of a query parameter based on a type
@private
@method _serializeQueryParam
@param {Object} value
@param {String} type
*/
_serializeQueryParam(value: unknown, type: string) {
if (value === null || value === undefined) {
return value;
} else if (type === 'array') {
return JSON.stringify(value);
}
return `${value}`;
}
/**
Deserializes the given query params according to their QP meta information.
@private
@method _deserializeQueryParams
@param {Array<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_deserializeQueryParams(routeInfos: PrivateRouteInfo[], queryParams: QueryParam) {
forEachQueryParam(
this,
routeInfos,
queryParams,
(key: string, value: unknown, qp: QueryParam) => {
// If we don't have QP meta info for a given key, then we do nothing
// because all values will be treated as strings
if (qp) {
delete queryParams[key];
queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type);
}
}
);
}
/**
Deserializes the value of a query parameter based on a default type
@private
@method _deserializeQueryParam
@param {Object} value
@param {String} defaultType
*/
_deserializeQueryParam(value: unknown, defaultType: string) {
if (value === null || value === undefined) {
return value;
} else if (defaultType === 'boolean') {
return value === 'true';
} else if (defaultType === 'number') {
return Number(value).valueOf();
} else if (defaultType === 'array') {
return emberA(JSON.parse(value as string));
}
return value;
}
/**
Removes (prunes) any query params with default values from the given QP
object. Default values are determined from the QP meta information per key.
@private
@method _pruneDefaultQueryParamValues
@param {Array<RouteInfo>} routeInfos
@param {Object} queryParams
@return {Void}
*/
_pruneDefaultQueryParamValues(routeInfos: PrivateRouteInfo[], queryParams: {}) {
let qps = this._queryParamsFor(routeInfos);
for (let key in queryParams) {
let qp = qps.map[key];
if (qp && qp.serializedDefaultValue === queryParams[key]) {
delete queryParams[key];
}
}
}
_doTransition(
_targetRouteName: string | undefined,
models: {}[],
_queryParams: {},
_keepDefaultQueryParamValues?: boolean
) {
let targetRouteName = _targetRouteName || getActiveTargetName(this._routerMicrolib);
assert(
`The route ${targetRouteName} was not found`,
Boolean(targetRouteName) && this._routerMicrolib.hasRoute(targetRouteName)
);
this._initialTransitionStarted = true;
let queryParams = {};
this._processActiveTransitionQueryParams(targetRouteName, models, queryParams, _queryParams);
assign(queryParams, _queryParams);
this._prepareQueryParams(
targetRouteName,
models,
queryParams as QueryParam,
Boolean(_keepDefaultQueryParamValues)
);
let transition = this._routerMicrolib.transitionTo(targetRouteName, ...models, { queryParams });
didBeginTransition(transition, this);
return transition;
}
_processActiveTransitionQueryParams(
targetRouteName: string,
models: {}[],
queryParams: {},
_queryParams: {}
) {
// merge in any queryParams from the active transition which could include
// queryParams from the url on initial load.
if (!this._routerMicrolib.activeTransition) {
return;
}
let unchangedQPs = {};
let qpUpdates = this._qpUpdates;
let params = getFullQueryParams(this, this._routerMicrolib.activeTransition[STATE_SYMBOL]);
for (let key in params) {
if (!qpUpdates.has(key)) {
unchangedQPs[key] = params[key];
}
}
// We need to fully scope queryParams so that we can create one object
// that represents both passed-in queryParams and ones that aren't changed
// from the active transition.
this._fullyScopeQueryParams(targetRouteName, models, _queryParams);
this._fullyScopeQueryParams(targetRouteName, models, unchangedQPs);
assign(queryParams, unchangedQPs);
}
/**
Prepares the query params for a URL or Transition. Restores any undefined QP
keys/values, serializes all values, and then prunes any default values.
@private
@method _prepareQueryParams
@param {String} targetRouteName
@param {Array<Object>} models
@param {Object} queryParams
@param {boolean} keepDefaultQueryParamValues
@return {Void}
*/
_prepareQueryParams(
targetRouteName: string,
models: {}[],
queryParams: QueryParam,
_fromRouterService?: boolean
) {
let state = calculatePostTransitionState(this, targetRouteName, models);
this._hydrateUnsuppliedQueryParams(state, queryParams, Boolean(_fromRouterService));
this._serializeQueryParams(state.routeInfos, queryParams);
if (!_fromRouterService) {
this._pruneDefaultQueryParamValues(state.routeInfos, queryParams);
}
}
/**
Returns the meta information for the query params of a given route. This
will be overridden to allow support for lazy routes.
@private
@method _getQPMeta
@param {RouteInfo} routeInfo
@return {Object}
*/
_getQPMeta(routeInfo: PrivateRouteInfo) {
let route = routeInfo.route;
return route && get(route, '_qp');
}
/**
Returns a merged query params meta object for a given set of routeInfos.
Useful for knowing what query params are available for a given route hierarchy.
@private
@method _queryParamsFor
@param {Array<RouteInfo>} routeInfos
@return {Object}
*/
_queryParamsFor(routeInfos: PrivateRouteInfo[]) {
let routeInfoLength = routeInfos.length;
let leafRouteName = routeInfos[routeInfoLength - 1].name;
let cached = this._qpCache[leafRouteName];
if (cached !== undefined) {
return cached;
}
let shouldCache = true;
let map = {};
let qps = [];
let qpsByUrlKey = DEBUG ? {} : null;
let qpMeta;
let qp;
let urlKey;
let qpOther;
for (let i = 0; i < routeInfoLength; ++i) {
qpMeta = this._getQPMeta(routeInfos[i]);
if (!qpMeta) {
shouldCache = false;
continue;
}
// Loop over each QP to make sure we don't have any collisions by urlKey
for (let i = 0; i < qpMeta.qps.length; i++) {
qp = qpMeta.qps[i];
if (DEBUG) {
urlKey = qp.urlKey;
qpOther = qpsByUrlKey![urlKey];
if (qpOther && qpOther.controllerName !== qp.controllerName) {
assert(
`You're not allowed to have more than one controller property map to the same query param key, but both \`${qpOther.scopedPropertyName}\` and \`${qp.scopedPropertyName}\` map to \`${urlKey}\`. You can fix this by mapping one of the controller properties to a different query param key via the \`as\` config option, e.g. \`${qpOther.prop}: { as: 'other-${qpOther.prop}' }\``,
false
);
}
qpsByUrlKey![urlKey] = qp;
}
qps.push(qp);
}
assign(map, qpMeta.map);
}