-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
router.js
1190 lines (972 loc) · 33.7 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
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 Logger from 'ember-metal/logger';
import { assert, info } from 'ember-metal/debug';
import EmberError from 'ember-metal/error';
import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
import { defineProperty } from 'ember-metal/properties';
import EmptyObject from 'ember-metal/empty_object';
import { computed } from 'ember-metal/computed';
import assign from 'ember-metal/assign';
import run from 'ember-metal/run_loop';
import EmberObject from 'ember-runtime/system/object';
import Evented from 'ember-runtime/mixins/evented';
import EmberRouterDSL from 'ember-routing/system/dsl';
import EmberLocation from 'ember-routing/location/api';
import {
routeArgs,
getActiveTargetName,
stashParamNames,
calculateCacheKey
} from 'ember-routing/utils';
import { guidFor } from 'ember-metal/utils';
import RouterState from './router_state';
import { getOwner } from 'container/owner';
import dictionary from 'ember-metal/dictionary';
/**
@module ember
@submodule ember-routing
*/
import Router from 'router';
import 'router/transition';
function K() { return this; }
var slice = [].slice;
/**
The `Ember.Router` class manages the application state and URLs. Refer to
the [routing guide](http://emberjs.com/guides/routing/) for documentation.
@class Router
@namespace Ember
@extends Ember.Object
@uses Ember.Evented
@public
*/
var EmberRouter = EmberObject.extend(Evented, {
/**
The `location` property determines the type of URL's that your
application will use.
The following location types are currently available:
* `history` - use the browser's history API to make the URLs look just like any standard URL
* `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new`
* `none` - do not store the Ember URL in the actual browser URL (mainly used for testing)
* `auto` - use the best option based on browser capabilites: `history` if possible, then `hash` if possible, otherwise `none`
Note: If using ember-cli, this value is defaulted to `auto` by the `locationType` setting of `/config/environment.js`
@property location
@default 'hash'
@see {Ember.Location}
@public
*/
location: 'hash',
/**
Represents the URL of the root of the application, often '/'. This prefix is
assumed on all routes defined on this router.
@property rootURL
@default '/'
@public
*/
rootURL: '/',
_initRouterJs() {
var router = this.router = new Router();
router.triggerEvent = triggerEvent;
router._triggerWillChangeContext = K;
router._triggerWillLeave = K;
var dslCallbacks = this.constructor.dslCallbacks || [K];
var dsl = this._buildDSL();
dsl.route('application', { path: '/', resetNamespace: true, overrideNameAssertion: true }, function() {
for (var i = 0; i < dslCallbacks.length; i++) {
dslCallbacks[i].call(this);
}
});
if (get(this, 'namespace.LOG_TRANSITIONS_INTERNAL')) {
router.log = Logger.debug;
}
router.map(dsl.generate());
},
_buildDSL() {
let moduleBasedResolver = this._hasModuleBasedResolver();
return new EmberRouterDSL(null, {
enableLoadingSubstates: !!moduleBasedResolver
});
},
init() {
this._super(...arguments);
this._activeViews = {};
this._qpCache = new EmptyObject();
this._resetQueuedQueryParameterChanges();
this._handledErrors = dictionary(null);
},
/*
Resets all pending query paramter changes.
Called after transitioning to a new route
based on query parameter changes.
*/
_resetQueuedQueryParameterChanges() {
this._queuedQPChanges = {};
},
/**
Represents the current URL.
@method url
@return {String} The current URL.
@private
*/
url: computed(function() {
return get(this, 'location').getURL();
}),
_hasModuleBasedResolver() {
let owner = getOwner(this);
if (!owner) { return false; }
let resolver = owner.application && owner.application.__registry__ && owner.application.__registry__.resolver;
if (!resolver) { return false; }
return !!resolver.moduleBasedResolver;
},
/**
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() {
var initialURL = get(this, 'initialURL');
if (this.setupRouter()) {
if (typeof initialURL === 'undefined') {
initialURL = get(this, 'location').getURL();
}
var initialTransition = this.handleURL(initialURL);
if (initialTransition && initialTransition.error) {
throw initialTransition.error;
}
}
},
setupRouter() {
this._initRouterJs();
this._setupLocation();
var router = this.router;
var 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._setupRouter(router, location);
location.onUpdateURL((url) => {
this.handleURL(url);
});
return true;
},
/**
Handles updating the paths and notifying any listeners of the URL
change.
Triggers the router level `didTransition` hook.
For example, to notify google analytics when the route changes,
you could use this hook. (Note: requires also including GA scripts, etc.)
```javascript
var Router = Ember.Router.extend({
location: config.locationType,
didTransition: function() {
this._super(...arguments);
return ga('send', 'pageview', {
'page': this.get('url'),
'title': this.get('url')
});
}
});
```
@method didTransition
@public
@since 1.2.0
*/
didTransition(infos) {
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.
run.once(this, this.trigger, 'didTransition');
if (get(this, 'namespace').LOG_TRANSITIONS) {
Logger.log(`Transitioned into '${EmberRouter._routePath(infos)}'`);
}
},
_setOutlets() {
var handlerInfos = this.router.currentHandlerInfos;
var route;
var defaultParentState;
var liveRoutes = null;
if (!handlerInfos) {
return;
}
for (var i = 0; i < handlerInfos.length; i++) {
route = handlerInfos[i].handler;
var connections = route.connections;
var ownState;
for (var j = 0; j < connections.length; j++) {
var appended = appendLiveRoute(liveRoutes, defaultParentState, connections[j]);
liveRoutes = appended.liveRoutes;
if (appended.ownState.render.name === route.routeName || appended.ownState.render.outlet === 'main') {
ownState = appended.ownState;
}
}
if (connections.length === 0) {
ownState = representEmptyRoute(liveRoutes, defaultParentState, route);
}
defaultParentState = ownState;
}
if (!this._toplevelView) {
let owner = getOwner(this);
var OutletView = owner._lookupFactory('view:-outlet');
this._toplevelView = OutletView.create();
var instance = owner.lookup('-application-instance:main');
instance.didCreateRootView(this._toplevelView);
}
this._toplevelView.setOutletState(liveRoutes);
},
/**
Handles notifying any listeners of an impending URL
change.
Triggers the router level `willTransition` hook.
@method willTransition
@public
@since 1.11.0
*/
willTransition(oldInfos, newInfos, transition) {
run.once(this, this.trigger, 'willTransition', transition);
if (get(this, 'namespace').LOG_TRANSITIONS) {
Logger.log(`Preparing to transition from '${EmberRouter._routePath(oldInfos)}' to '${EmberRouter._routePath(newInfos)}'`);
}
},
handleURL(url) {
// 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.
url = url.split(/#(.+)?/)[0];
return this._doURLTransition('handleURL', url);
},
_doURLTransition(routerJsMethod, url) {
var transition = this.router[routerJsMethod](url || '/');
return didBeginTransition(transition, this);
},
transitionTo(...args) {
var queryParams;
if (resemblesURL(args[0])) {
return this._doURLTransition('transitionTo', args[0]);
}
var possibleQueryParams = args[args.length - 1];
if (possibleQueryParams && possibleQueryParams.hasOwnProperty('queryParams')) {
queryParams = args.pop().queryParams;
} else {
queryParams = {};
}
var targetRouteName = args.shift();
return this._doTransition(targetRouteName, args, queryParams);
},
intermediateTransitionTo() {
this.router.intermediateTransitionTo(...arguments);
updatePaths(this);
var infos = this.router.currentHandlerInfos;
if (get(this, 'namespace').LOG_TRANSITIONS) {
Logger.log(`Intermediate-transitioned into '${EmberRouter._routePath(infos)}'`);
}
},
replaceWith() {
return this.transitionTo(...arguments).method('replace');
},
generate() {
var url = this.router.generate(...arguments);
return this.location.formatURL(url);
},
/**
Determines if the supplied route is currently active.
@method isActive
@param routeName
@return {Boolean}
@private
*/
isActive(routeName) {
var router = this.router;
return router.isActive(...arguments);
},
/**
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, models, queryParams) {
return this.currentState.isActiveIntent(routeName, models, queryParams);
},
send(name, context) {
this.router.trigger(...arguments);
},
/**
Does this router instance have the given route.
@method hasRoute
@return {Boolean}
@private
*/
hasRoute(route) {
return this.router.hasRoute(route);
},
/**
Resets the state of the router by clearing the current route
handlers and deactivating them.
@private
@method reset
*/
reset() {
if (this.router) {
this.router.reset();
}
},
willDestroy() {
if (this._toplevelView) {
this._toplevelView.destroy();
this._toplevelView = null;
}
this._super(...arguments);
this.reset();
},
_lookupActiveComponentNode(templateName) {
return this._activeViews[templateName];
},
/*
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, newValue) {
this._queuedQPChanges[queryParameterName] = newValue;
run.once(this, this._fireQueryParamTransition);
},
_updatingQPChanged(queryParameterName) {
if (!this._qpUpdates) {
this._qpUpdates = {};
}
this._qpUpdates[queryParameterName] = true;
},
/*
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();
},
_connectActiveComponentNode(templateName, componentNode) {
assert('cannot connect an activeView that already exists', !this._activeViews[templateName]);
var _activeViews = this._activeViews;
function disconnectActiveView() {
delete _activeViews[templateName];
}
this._activeViews[templateName] = componentNode;
componentNode.renderNode.addDestruction({ destroy: disconnectActiveView });
},
_setupLocation() {
var location = get(this, 'location');
var rootURL = get(this, 'rootURL');
let owner = getOwner(this);
if ('string' === typeof location && owner) {
var resolvedLocation = owner.lookup(`location:${location}`);
if ('undefined' !== typeof resolvedLocation) {
location = set(this, 'location', resolvedLocation);
} else {
// Allow for deprecated registration of custom location API's
var 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();
}
}
},
_getHandlerFunction() {
var seen = new EmptyObject();
let owner = getOwner(this);
var DefaultRoute = owner._lookupFactory('route:basic');
return (name) => {
var routeName = 'route:' + name;
var handler = owner.lookup(routeName);
if (seen[name]) {
return handler;
}
seen[name] = true;
if (!handler) {
owner.register(routeName, DefaultRoute.extend());
handler = owner.lookup(routeName);
if (get(this, 'namespace.LOG_ACTIVE_GENERATION')) {
info(`generated -> ${routeName}`, { fullName: routeName });
}
}
handler.routeName = name;
return handler;
};
},
_setupRouter(router, location) {
var lastURL;
var emberRouter = this;
router.getHandler = this._getHandlerFunction();
var doUpdateURL = function() {
location.setURL(lastURL);
};
router.updateURL = function(path) {
lastURL = path;
run.once(doUpdateURL);
};
if (location.replaceURL) {
var doReplaceURL = function() {
location.replaceURL(lastURL);
};
router.replaceURL = function(path) {
lastURL = path;
run.once(doReplaceURL);
};
}
router.didTransition = function(infos) {
emberRouter.didTransition(infos);
};
router.willTransition = function(oldInfos, newInfos, transition) {
emberRouter.willTransition(oldInfos, newInfos, transition);
};
},
_serializeQueryParams(targetRouteName, queryParams) {
var groupedByUrlKey = {};
forEachQueryParam(this, targetRouteName, queryParams, function(key, value, qp) {
var urlKey = qp.urlKey;
if (!groupedByUrlKey[urlKey]) {
groupedByUrlKey[urlKey] = [];
}
groupedByUrlKey[urlKey].push({
qp: qp,
value: value
});
delete queryParams[key];
});
for (var key in groupedByUrlKey) {
var qps = groupedByUrlKey[key];
assert(`You're not allowed to have more than one controller property map to the same query param key, but both \`${qps[0].qp.scopedPropertyName}\` and \`${qps[1] ? qps[1].qp.scopedPropertyName : ''}\` map to \`${qps[0].qp.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. \`${qps[0].qp.prop}: { as: \'other-${qps[0].qp.prop}\' }\``, qps.length <= 1);
var qp = qps[0].qp;
queryParams[qp.urlKey] = qp.route.serializeQueryParam(qps[0].value, qp.urlKey, qp.type);
}
},
_deserializeQueryParams(targetRouteName, queryParams) {
forEachQueryParam(this, targetRouteName, queryParams, function(key, value, qp) {
delete queryParams[key];
queryParams[qp.prop] = qp.route.deserializeQueryParam(value, qp.urlKey, qp.type);
});
},
_pruneDefaultQueryParamValues(targetRouteName, queryParams) {
var qps = this._queryParamsFor(targetRouteName);
for (var key in queryParams) {
var qp = qps.map[key];
if (qp && qp.serializedDefaultValue === queryParams[key]) {
delete queryParams[key];
}
}
},
_doTransition(_targetRouteName, models, _queryParams) {
var targetRouteName = _targetRouteName || getActiveTargetName(this.router);
assert(`The route ${targetRouteName} was not found`, targetRouteName && this.router.hasRoute(targetRouteName));
var queryParams = {};
assign(queryParams, _queryParams);
this._prepareQueryParams(targetRouteName, models, queryParams);
var transitionArgs = routeArgs(targetRouteName, models, queryParams);
var transitionPromise = this.router.transitionTo.apply(this.router, transitionArgs);
didBeginTransition(transitionPromise, this);
return transitionPromise;
},
_prepareQueryParams(targetRouteName, models, queryParams) {
this._hydrateUnsuppliedQueryParams(targetRouteName, models, queryParams);
this._serializeQueryParams(targetRouteName, queryParams);
this._pruneDefaultQueryParamValues(targetRouteName, queryParams);
},
/**
Returns a merged query params meta object for a given route.
Useful for asking a route what its known query params are.
@private
*/
_queryParamsFor(leafRouteName) {
if (this._qpCache[leafRouteName]) {
return this._qpCache[leafRouteName];
}
var map = {};
var qps = [];
this._qpCache[leafRouteName] = {
map: map,
qps: qps
};
var routerjs = this.router;
var recogHandlerInfos = routerjs.recognizer.handlersFor(leafRouteName);
for (var i = 0, len = recogHandlerInfos.length; i < len; ++i) {
var recogHandler = recogHandlerInfos[i];
var route = routerjs.getHandler(recogHandler.handler);
var qpMeta = get(route, '_qp');
if (!qpMeta) { continue; }
assign(map, qpMeta.map);
qps.push.apply(qps, qpMeta.qps);
}
return {
qps: qps,
map: map
};
},
_hydrateUnsuppliedQueryParams(leafRouteName, contexts, queryParams) {
var state = calculatePostTransitionState(this, leafRouteName, contexts);
var handlerInfos = state.handlerInfos;
var appCache = this._bucketCache;
stashParamNames(this, handlerInfos);
for (var i = 0, len = handlerInfos.length; i < len; ++i) {
var route = handlerInfos[i].handler;
var qpMeta = get(route, '_qp');
for (var j = 0, qpLen = qpMeta.qps.length; j < qpLen; ++j) {
var qp = qpMeta.qps[j];
var presentProp = qp.prop in queryParams && qp.prop ||
qp.scopedPropertyName in queryParams && qp.scopedPropertyName;
if (presentProp) {
if (presentProp !== qp.scopedPropertyName) {
queryParams[qp.scopedPropertyName] = queryParams[presentProp];
delete queryParams[presentProp];
}
} else {
var cacheKey = calculateCacheKey(qp.ctrl, qp.parts, state.params);
queryParams[qp.scopedPropertyName] = appCache.lookup(cacheKey, qp.prop, qp.defaultValue);
}
}
}
},
_scheduleLoadingEvent(transition, originRoute) {
this._cancelSlowTransitionTimer();
this._slowTransitionTimer = run.scheduleOnce('routerTransitions', this, '_handleSlowTransition', transition, originRoute);
},
currentState: null,
targetState: null,
_handleSlowTransition(transition, originRoute) {
if (!this.router.activeTransition) {
// Don't fire an event if we've since moved on from
// the transition that put us in a loading state.
return;
}
this.set('targetState', RouterState.create({
emberRouter: this,
routerJs: this.router,
routerJsState: this.router.activeTransition.state
}));
transition.trigger(true, 'loading', transition, originRoute);
},
_cancelSlowTransitionTimer() {
if (this._slowTransitionTimer) {
run.cancel(this._slowTransitionTimer);
}
this._slowTransitionTimer = null;
},
// These three helper functions are used to ensure errors aren't
// re-raised if they're handled in a route's error action.
_markErrorAsHandled(errorGuid) {
this._handledErrors[errorGuid] = true;
},
_isErrorHandled(errorGuid) {
return this._handledErrors[errorGuid];
},
_clearHandledError(errorGuid) {
delete this._handledErrors[errorGuid];
}
});
/*
Helper function for iterating root-ward, starting
from (but not including) the provided `originRoute`.
Returns true if the last callback fired requested
to bubble upward.
@private
*/
function forEachRouteAbove(originRoute, transition, callback) {
var handlerInfos = transition.state.handlerInfos;
var originRouteFound = false;
var handlerInfo, route;
for (var i = handlerInfos.length - 1; i >= 0; --i) {
handlerInfo = handlerInfos[i];
route = handlerInfo.handler;
if (!originRouteFound) {
if (originRoute === route) {
originRouteFound = true;
}
continue;
}
if (callback(route, handlerInfos[i + 1].handler) !== true) {
return false;
}
}
return true;
}
// These get invoked when an action bubbles above ApplicationRoute
// and are not meant to be overridable.
var defaultActionHandlers = {
willResolveModel(transition, originRoute) {
originRoute.router._scheduleLoadingEvent(transition, originRoute);
},
error(error, transition, originRoute) {
// Attempt to find an appropriate error substate to enter.
var router = originRoute.router;
var tryTopLevel = forEachRouteAbove(originRoute, transition, function(route, childRoute) {
var childErrorRouteName = findChildRouteName(route, childRoute, 'error');
if (childErrorRouteName) {
router.intermediateTransitionTo(childErrorRouteName, error);
return;
}
return true;
});
if (tryTopLevel) {
// Check for top-level error state to enter.
if (routeHasBeenDefined(originRoute.router, 'application_error')) {
router.intermediateTransitionTo('application_error', error);
return;
}
}
logError(error, 'Error while processing route: ' + transition.targetName);
},
loading(transition, originRoute) {
// Attempt to find an appropriate loading substate to enter.
var router = originRoute.router;
var tryTopLevel = forEachRouteAbove(originRoute, transition, function(route, childRoute) {
var childLoadingRouteName = findChildRouteName(route, childRoute, 'loading');
if (childLoadingRouteName) {
router.intermediateTransitionTo(childLoadingRouteName);
return;
}
// Don't bubble above pivot route.
if (transition.pivotHandler !== route) {
return true;
}
});
if (tryTopLevel) {
// Check for top-level loading state to enter.
if (routeHasBeenDefined(originRoute.router, 'application_loading')) {
router.intermediateTransitionTo('application_loading');
return;
}
}
}
};
function logError(_error, initialMessage) {
var errorArgs = [];
var error;
if (_error && typeof _error === 'object' && typeof _error.errorThrown === 'object') {
error = _error.errorThrown;
} else {
error = _error;
}
if (initialMessage) { errorArgs.push(initialMessage); }
if (error) {
if (error.message) { errorArgs.push(error.message); }
if (error.stack) { errorArgs.push(error.stack); }
if (typeof error === 'string') { errorArgs.push(error); }
}
Logger.error.apply(this, errorArgs);
}
function findChildRouteName(parentRoute, originatingChildRoute, name) {
var router = parentRoute.router;
var childName;
var targetChildRouteName = originatingChildRoute.routeName.split('.').pop();
var namespace = parentRoute.routeName === 'application' ? '' : parentRoute.routeName + '.';
// First, try a named loading state, e.g. 'foo_loading'
childName = namespace + targetChildRouteName + '_' + name;
if (routeHasBeenDefined(router, childName)) {
return childName;
}
// Second, try general loading state, e.g. 'loading'
childName = namespace + name;
if (routeHasBeenDefined(router, childName)) {
return childName;
}
}
function routeHasBeenDefined(router, name) {
let owner = getOwner(router);
return router.hasRoute(name) &&
(owner.hasRegistration(`template:${name}`) || owner.hasRegistration(`route:${name}`));
}
export function triggerEvent(handlerInfos, ignoreFailure, args) {
var name = args.shift();
if (!handlerInfos) {
if (ignoreFailure) { return; }
throw new EmberError(`Can't trigger action '${name}' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call \`.send()\` on the \`Transition\` object passed to the \`model/beforeModel/afterModel\` hooks.`);
}
var eventWasHandled = false;
var handlerInfo, handler;
for (var i = handlerInfos.length - 1; i >= 0; i--) {
handlerInfo = handlerInfos[i];
handler = handlerInfo.handler;
if (handler.actions && handler.actions[name]) {
if (handler.actions[name].apply(handler, args) === true) {
eventWasHandled = true;
} else {
// Should only hit here if a non-bubbling error action is triggered on a route.
if (name === 'error') {
var errorId = guidFor(args[0]);
handler.router._markErrorAsHandled(errorId);
}
return;
}
}
}
if (defaultActionHandlers[name]) {
defaultActionHandlers[name].apply(null, args);
return;
}
if (!eventWasHandled && !ignoreFailure) {
throw new EmberError(`Nothing handled the action '${name}'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.`);
}
}
function calculatePostTransitionState(emberRouter, leafRouteName, contexts) {
var routerjs = emberRouter.router;
var state = routerjs.applyIntent(leafRouteName, contexts);
var handlerInfos = state.handlerInfos;
var params = state.params;
for (var i = 0, len = handlerInfos.length; i < len; ++i) {
var handlerInfo = handlerInfos[i];
if (!handlerInfo.isResolved) {
handlerInfo = handlerInfo.becomeResolved(null, handlerInfo.context);
}
params[handlerInfo.name] = handlerInfo.params;
}
return state;
}
function updatePaths(router) {
let infos = router.router.currentHandlerInfos;
let path = EmberRouter._routePath(infos);
let currentRouteName = infos[infos.length - 1].name;
set(router, 'currentPath', path);
set(router, 'currentRouteName', currentRouteName);
let appController = getOwner(router).lookup('controller:application');
if (!appController) {
// appController might not exist when top-level loading/error
// substates have been entered since ApplicationRoute hasn't
// actually been entered at that point.
return;
}
if (!('currentPath' in appController)) {
defineProperty(appController, 'currentPath');
}
set(appController, 'currentPath', path);
if (!('currentRouteName' in appController)) {
defineProperty(appController, 'currentRouteName');
}
set(appController, 'currentRouteName', currentRouteName);
}
EmberRouter.reopenClass({
router: null,
/**
The `Router.map` function allows you to define mappings from URLs to routes
in your application. These mappings are defined within the
supplied callback function using `this.route`.
The first parameter is the name of the route which is used by default as the
path name as well.
The second parameter is the optional options hash. Available options are:
* `path`: allows you to provide your own path as well as mark dynamic
segments.
* `resetNamespace`: false by default; when nesting routes, ember will
combine the route names to form the fully-qualified route name, which is
used with `{{link-to}}` or manually transitioning to routes. Setting
`resetNamespace: true` will cause the route not to inherit from its
parent route's names. This is handy for resources which can be accessed
in multiple places as well as preventing extremely long route names.
Keep in mind that the actual URL path behavior is still retained.
The third parameter is a function, which can be used to nest routes.
Nested routes, by default, will have the parent route tree's route name and
path prepended to it's own.
```javascript
App.Router.map(function(){
this.route('post', { path: '/post/:post_id' }, function() {
this.route('edit');
this.route('comments', { resetNamespace: true }, function() {