-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathrouter.js
1829 lines (1510 loc) · 61.5 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
define("router/handler-info",
["./utils","rsvp","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var bind = __dependency1__.bind;
var merge = __dependency1__.merge;
var oCreate = __dependency1__.oCreate;
var serialize = __dependency1__.serialize;
var promiseLabel = __dependency1__.promiseLabel;
var resolve = __dependency2__.resolve;
function HandlerInfo(props) {
if (props) {
merge(this, props);
}
}
HandlerInfo.prototype = {
name: null,
handler: null,
params: null,
context: null,
log: function(payload, message) {
if (payload.log) {
payload.log(this.name + ': ' + message);
}
},
promiseLabel: function(label) {
return promiseLabel("'" + this.name + "' " + label);
},
resolve: function(async, shouldContinue, payload) {
var checkForAbort = bind(this.checkForAbort, this, shouldContinue),
beforeModel = bind(this.runBeforeModelHook, this, async, payload),
model = bind(this.getModel, this, async, payload),
afterModel = bind(this.runAfterModelHook, this, async, payload),
becomeResolved = bind(this.becomeResolved, this, payload);
return resolve(undefined, this.promiseLabel("Start handler"))
.then(checkForAbort, null, this.promiseLabel("Check for abort"))
.then(beforeModel, null, this.promiseLabel("Before model"))
.then(checkForAbort, null, this.promiseLabel("Check if aborted during 'beforeModel' hook"))
.then(model, null, this.promiseLabel("Model"))
.then(checkForAbort, null, this.promiseLabel("Check if aborted in 'model' hook"))
.then(afterModel, null, this.promiseLabel("After model"))
.then(checkForAbort, null, this.promiseLabel("Check if aborted in 'afterModel' hook"))
.then(becomeResolved, null, this.promiseLabel("Become resolved"));
},
runBeforeModelHook: function(async, payload) {
if (payload.trigger) {
payload.trigger(true, 'willResolveModel', payload, this.handler);
}
return this.runSharedModelHook(async, payload, 'beforeModel', []);
},
runAfterModelHook: function(async, payload, resolvedModel) {
// Stash the resolved model on the payload.
// This makes it possible for users to swap out
// the resolved model in afterModel.
var name = this.name;
this.stashResolvedModel(payload, resolvedModel);
return this.runSharedModelHook(async, payload, 'afterModel', [resolvedModel])
.then(function() {
// Ignore the fulfilled value returned from afterModel.
// Return the value stashed in resolvedModels, which
// might have been swapped out in afterModel.
return payload.resolvedModels[name];
}, null, this.promiseLabel("Ignore fulfillment value and return model value"));
},
runSharedModelHook: function(async, payload, hookName, args) {
this.log(payload, "calling " + hookName + " hook");
if (this.queryParams) {
args.push(this.queryParams);
}
args.push(payload);
var handler = this.handler;
return async(function() {
return handler[hookName] && handler[hookName].apply(handler, args);
}, this.promiseLabel("Handle " + hookName));
},
getModel: function(payload) {
throw new Error("This should be overridden by a subclass of HandlerInfo");
},
checkForAbort: function(shouldContinue, promiseValue) {
return resolve(shouldContinue(), this.promiseLabel("Check for abort")).then(function() {
// We don't care about shouldContinue's resolve value;
// pass along the original value passed to this fn.
return promiseValue;
}, null, this.promiseLabel("Ignore fulfillment value and continue"));
},
stashResolvedModel: function(payload, resolvedModel) {
payload.resolvedModels = payload.resolvedModels || {};
payload.resolvedModels[this.name] = resolvedModel;
},
becomeResolved: function(payload, resolvedContext) {
var params = this.params || serialize(this.handler, resolvedContext, this.names);
if (payload) {
this.stashResolvedModel(payload, resolvedContext);
payload.params = payload.params || {};
payload.params[this.name] = params;
}
return new ResolvedHandlerInfo({
context: resolvedContext,
name: this.name,
handler: this.handler,
params: params
});
},
shouldSupercede: function(other) {
// Prefer this newer handlerInfo over `other` if:
// 1) The other one doesn't exist
// 2) The names don't match
// 3) This handler has a context that doesn't match
// the other one (or the other one doesn't have one).
// 4) This handler has parameters that don't match the other.
if (!other) { return true; }
var contextsMatch = (other.context === this.context);
return other.name !== this.name ||
(this.hasOwnProperty('context') && !contextsMatch) ||
(this.hasOwnProperty('params') && !paramsMatch(this.params, other.params));
}
};
function ResolvedHandlerInfo(props) {
HandlerInfo.call(this, props);
}
ResolvedHandlerInfo.prototype = oCreate(HandlerInfo.prototype);
ResolvedHandlerInfo.prototype.resolve = function(async, shouldContinue, payload) {
// A ResolvedHandlerInfo just resolved with itself.
if (payload && payload.resolvedModels) {
payload.resolvedModels[this.name] = this.context;
}
return resolve(this, this.promiseLabel("Resolve"));
};
// These are generated by URL transitions and
// named transitions for non-dynamic route segments.
function UnresolvedHandlerInfoByParam(props) {
HandlerInfo.call(this, props);
this.params = this.params || {};
}
UnresolvedHandlerInfoByParam.prototype = oCreate(HandlerInfo.prototype);
UnresolvedHandlerInfoByParam.prototype.getModel = function(async, payload) {
var fullParams = this.params;
if (payload && payload.queryParams) {
fullParams = {};
merge(fullParams, this.params);
fullParams.queryParams = payload.queryParams;
}
var hookName = typeof this.handler.deserialize === 'function' ?
'deserialize' : 'model';
return this.runSharedModelHook(async, payload, hookName, [fullParams]);
};
// These are generated only for named transitions
// with dynamic route segments.
function UnresolvedHandlerInfoByObject(props) {
HandlerInfo.call(this, props);
}
UnresolvedHandlerInfoByObject.prototype = oCreate(HandlerInfo.prototype);
UnresolvedHandlerInfoByObject.prototype.getModel = function(async, payload) {
this.log(payload, this.name + ": resolving provided model");
return resolve(this.context);
};
function paramsMatch(a, b) {
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 handlers, they should.
for (var k in a) {
if (a.hasOwnProperty(k) && a[k] !== b[k]) {
return false;
}
}
return true;
}
__exports__.HandlerInfo = HandlerInfo;
__exports__.ResolvedHandlerInfo = ResolvedHandlerInfo;
__exports__.UnresolvedHandlerInfoByParam = UnresolvedHandlerInfoByParam;
__exports__.UnresolvedHandlerInfoByObject = UnresolvedHandlerInfoByObject;
});
define("router/router",
["route-recognizer","rsvp","./utils","./transition-state","./transition","./transition-intent/named-transition-intent","./transition-intent/url-transition-intent","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var RouteRecognizer = __dependency1__["default"];
var resolve = __dependency2__.resolve;
var reject = __dependency2__.reject;
var async = __dependency2__.async;
var Promise = __dependency2__.Promise;
var trigger = __dependency3__.trigger;
var log = __dependency3__.log;
var slice = __dependency3__.slice;
var forEach = __dependency3__.forEach;
var merge = __dependency3__.merge;
var serialize = __dependency3__.serialize;
var extractQueryParams = __dependency3__.extractQueryParams;
var getChangelist = __dependency3__.getChangelist;
var promiseLabel = __dependency3__.promiseLabel;
var TransitionState = __dependency4__.TransitionState;
var logAbort = __dependency5__.logAbort;
var Transition = __dependency5__.Transition;
var TransitionAborted = __dependency5__.TransitionAborted;
var NamedTransitionIntent = __dependency6__.NamedTransitionIntent;
var URLTransitionIntent = __dependency7__.URLTransitionIntent;
var pop = Array.prototype.pop;
function Router() {
this.recognizer = new RouteRecognizer();
this.reset();
}
Router.prototype = {
/**
The main entry point into the router. The API is essentially
the same as the `map` method in `route-recognizer`.
This method extracts the String handler at the last `.to()`
call and uses it as the name of the whole route.
@param {Function} callback
*/
map: function(callback) {
this.recognizer.delegate = this.delegate;
this.recognizer.map(callback, function(recognizer, routes) {
for (var i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) {
var route = routes[i];
recognizer.add(routes, { as: route.handler });
proceed = route.path === '/' || route.path === '' || route.handler.slice(-6) === '.index';
}
});
},
hasRoute: function(route) {
return this.recognizer.hasRoute(route);
},
// NOTE: this doesn't really belong here, but here
// it shall remain until our ES6 transpiler can
// handle cyclical deps.
transitionByIntent: function(intent, isIntermediate) {
var wasTransitioning = !!this.activeTransition;
var oldState = wasTransitioning ? this.activeTransition.state : this.state;
var newTransition;
var router = this;
try {
var newState = intent.applyToState(oldState, this.recognizer, this.getHandler, isIntermediate);
if (handlerInfosEqual(newState.handlerInfos, oldState.handlerInfos)) {
// This is a no-op transition. See if query params changed.
var queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams);
if (queryParamChangelist) {
// This is a little hacky but we need some way of storing
// changed query params given that no activeTransition
// is guaranteed to have occurred.
this._changedQueryParams = queryParamChangelist.changed;
trigger(this, newState.handlerInfos, true, ['queryParamsDidChange', queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]);
this._changedQueryParams = null;
if (!wasTransitioning && this.activeTransition) {
// One of the handlers in queryParamsDidChange
// caused a transition. Just return that transition.
return this.activeTransition;
} else {
// Running queryParamsDidChange didn't change anything.
// Just update query params and be on our way.
oldState.queryParams = finalizeQueryParamChange(this, newState.handlerInfos, newState.queryParams);
// We have to return a noop transition that will
// perform a URL update at the end. This gives
// the user the ability to set the url update
// method (default is replaceState).
newTransition = new Transition(this);
newTransition.urlMethod = 'replace';
newTransition.promise = newTransition.promise.then(function(result) {
updateURL(newTransition, oldState, true);
if (router.didTransition) {
router.didTransition(router.currentHandlerInfos);
}
return result;
}, null, promiseLabel("Transition complete"));
return newTransition;
}
}
// No-op. No need to create a new transition.
return new Transition(this);
}
if (isIntermediate) {
setupContexts(this, newState);
return;
}
// Create a new transition to the destination route.
newTransition = new Transition(this, intent, newState);
// Abort and usurp any previously active transition.
if (this.activeTransition) {
this.activeTransition.abort();
}
this.activeTransition = newTransition;
// Transition promises by default resolve with resolved state.
// For our purposes, swap out the promise to resolve
// after the transition has been finalized.
newTransition.promise = newTransition.promise.then(function(result) {
return router.async(function() {
return finalizeTransition(newTransition, result.state);
}, "Finalize transition");
}, null, promiseLabel("Settle transition promise when transition is finalized"));
if (!wasTransitioning) {
trigger(this, this.state.handlerInfos, true, ['willTransition', newTransition]);
}
return newTransition;
} catch(e) {
return new Transition(this, intent, null, e);
}
},
/**
Clears the current and target route handlers and triggers exit
on each of them starting at the leaf and traversing up through
its ancestors.
*/
reset: function() {
if (this.state) {
forEach(this.state.handlerInfos, function(handlerInfo) {
var handler = handlerInfo.handler;
if (handler.exit) {
handler.exit();
}
});
}
this.state = new TransitionState();
this.currentHandlerInfos = null;
},
activeTransition: null,
/**
var handler = handlerInfo.handler;
The entry point for handling a change to the URL (usually
via the back and forward button).
Returns an Array of handlers and the parameters associated
with those parameters.
@param {String} url a URL to process
@return {Array} an Array of `[handler, parameter]` tuples
*/
handleURL: function(url) {
// Perform a URL-based transition, but don't change
// the URL afterward, since it already happened.
var args = slice.call(arguments);
if (url.charAt(0) !== '/') { args[0] = '/' + url; }
return doTransition(this, args).method('replaceQuery');
},
/**
Hook point for updating the URL.
@param {String} url a URL to update to
*/
updateURL: function() {
throw new Error("updateURL is not implemented");
},
/**
Hook point for replacing the current URL, i.e. with replaceState
By default this behaves the same as `updateURL`
@param {String} url a URL to update to
*/
replaceURL: function(url) {
this.updateURL(url);
},
/**
Transition into the specified named route.
If necessary, trigger the exit callback on any handlers
that are no longer represented by the target route.
@param {String} name the name of the route
*/
transitionTo: function(name) {
return doTransition(this, arguments);
},
intermediateTransitionTo: function(name) {
doTransition(this, arguments, true);
},
refresh: function(pivotHandler) {
var state = this.activeTransition ? this.activeTransition.state : this.state;
var handlerInfos = state.handlerInfos;
var params = {};
for (var i = 0, len = handlerInfos.length; i < len; ++i) {
var handlerInfo = handlerInfos[i];
params[handlerInfo.name] = handlerInfo.params || {};
}
log(this, "Starting a refresh transition");
var intent = new NamedTransitionIntent({
name: handlerInfos[handlerInfos.length - 1].name,
pivotHandler: pivotHandler || handlerInfos[0].handler,
contexts: [], // TODO collect contexts...?
queryParams: this._changedQueryParams || state.queryParams || {}
});
return this.transitionByIntent(intent, false);
},
/**
Identical to `transitionTo` except that the current URL will be replaced
if possible.
This method is intended primarily for use with `replaceState`.
@param {String} name the name of the route
*/
replaceWith: function(name) {
return doTransition(this, arguments).method('replace');
},
/**
Take a named route and context objects and generate a
URL.
@param {String} name the name of the route to generate
a URL for
@param {...Object} objects a list of objects to serialize
@return {String} a URL
*/
generate: function(handlerName) {
var partitionedArgs = extractQueryParams(slice.call(arguments, 1)),
suppliedParams = partitionedArgs[0],
queryParams = partitionedArgs[1];
// Construct a TransitionIntent with the provided params
// and apply it to the present state of the router.
var intent = new NamedTransitionIntent({ name: handlerName, contexts: suppliedParams });
var state = intent.applyToState(this.state, this.recognizer, this.getHandler);
var params = {};
for (var i = 0, len = state.handlerInfos.length; i < len; ++i) {
var handlerInfo = state.handlerInfos[i];
var handlerParams = handlerInfo.params ||
serialize(handlerInfo.handler, handlerInfo.context, handlerInfo.names);
merge(params, handlerParams);
}
params.queryParams = queryParams;
return this.recognizer.generate(handlerName, params);
},
isActive: function(handlerName) {
var partitionedArgs = extractQueryParams(slice.call(arguments, 1)),
contexts = partitionedArgs[0],
queryParams = partitionedArgs[1],
activeQueryParams = this.state.queryParams;
var targetHandlerInfos = this.state.handlerInfos,
found = false, names, object, handlerInfo, handlerObj, i, len;
if (!targetHandlerInfos.length) { return false; }
var targetHandler = targetHandlerInfos[targetHandlerInfos.length - 1].name;
var recogHandlers = this.recognizer.handlersFor(targetHandler);
var index = 0;
for (len = recogHandlers.length; index < len; ++index) {
handlerInfo = targetHandlerInfos[index];
if (handlerInfo.name === handlerName) { break; }
}
if (index === recogHandlers.length) {
// The provided route name isn't even in the route hierarchy.
return false;
}
var state = new TransitionState();
state.handlerInfos = targetHandlerInfos.slice(0, index + 1);
recogHandlers = recogHandlers.slice(0, index + 1);
var intent = new NamedTransitionIntent({
name: targetHandler,
contexts: contexts
});
var newState = intent.applyToHandlers(state, recogHandlers, this.getHandler, targetHandler, true, true);
return handlerInfosEqual(newState.handlerInfos, state.handlerInfos) &&
!getChangelist(activeQueryParams, queryParams);
},
trigger: function(name) {
var args = slice.call(arguments);
trigger(this, this.currentHandlerInfos, false, args);
},
/**
@private
Pluggable hook for possibly running route hooks
in a try-catch escaping manner.
@param {Function} callback the callback that will
be asynchronously called
@return {Promise} a promise that fulfills with the
value returned from the callback
*/
async: function(callback, label) {
return new Promise(function(resolve) {
resolve(callback());
}, label);
},
/**
Hook point for logging transition status updates.
@param {String} message The message to log.
*/
log: null
};
/**
@private
Takes an Array of `HandlerInfo`s, figures out which ones are
exiting, entering, or changing contexts, and calls the
proper handler hooks.
For example, consider the following tree of handlers. Each handler is
followed by the URL segment it handles.
```
|~index ("/")
| |~posts ("/posts")
| | |-showPost ("/:id")
| | |-newPost ("/new")
| | |-editPost ("/edit")
| |~about ("/about/:id")
```
Consider the following transitions:
1. A URL transition to `/posts/1`.
1. Triggers the `*model` callbacks on the
`index`, `posts`, and `showPost` handlers
2. Triggers the `enter` callback on the same
3. Triggers the `setup` callback on the same
2. A direct transition to `newPost`
1. Triggers the `exit` callback on `showPost`
2. Triggers the `enter` callback on `newPost`
3. Triggers the `setup` callback on `newPost`
3. A direct transition to `about` with a specified
context object
1. Triggers the `exit` callback on `newPost`
and `posts`
2. Triggers the `serialize` callback on `about`
3. Triggers the `enter` callback on `about`
4. Triggers the `setup` callback on `about`
@param {Router} transition
@param {TransitionState} newState
*/
function setupContexts(router, newState, transition) {
var partition = partitionHandlers(router.state, newState);
forEach(partition.exited, function(handlerInfo) {
var handler = handlerInfo.handler;
delete handler.context;
if (handler.exit) { handler.exit(); }
});
var oldState = router.oldState = router.state;
router.state = newState;
var currentHandlerInfos = router.currentHandlerInfos = partition.unchanged.slice();
try {
forEach(partition.updatedContext, function(handlerInfo) {
return handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, false, transition);
});
forEach(partition.entered, function(handlerInfo) {
return handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, true, transition);
});
} catch(e) {
router.state = oldState;
router.currentHandlerInfos = oldState.handlerInfos;
throw e;
}
router.state.queryParams = finalizeQueryParamChange(router, currentHandlerInfos, newState.queryParams);
}
/**
@private
Helper method used by setupContexts. Handles errors or redirects
that may happen in enter/setup.
*/
function handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, enter, transition) {
var handler = handlerInfo.handler,
context = handlerInfo.context;
if (enter && handler.enter) { handler.enter(transition); }
if (transition && transition.isAborted) {
throw new TransitionAborted();
}
handler.context = context;
if (handler.contextDidChange) { handler.contextDidChange(); }
if (handler.setup) { handler.setup(context, transition); }
if (transition && transition.isAborted) {
throw new TransitionAborted();
}
currentHandlerInfos.push(handlerInfo);
return true;
}
/**
@private
This function is called when transitioning from one URL to
another to determine which handlers are no longer active,
which handlers are newly active, and which handlers remain
active but have their context changed.
Take a list of old handlers and new handlers and partition
them into four buckets:
* unchanged: the handler was active in both the old and
new URL, and its context remains the same
* updated context: the handler was active in both the
old and new URL, but its context changed. The handler's
`setup` method, if any, will be called with the new
context.
* exited: the handler was active in the old URL, but is
no longer active.
* entered: the handler was not active in the old URL, but
is now active.
The PartitionedHandlers structure has four fields:
* `updatedContext`: a list of `HandlerInfo` objects that
represent handlers that remain active but have a changed
context
* `entered`: a list of `HandlerInfo` objects that represent
handlers that are newly active
* `exited`: a list of `HandlerInfo` objects that are no
longer active.
* `unchanged`: a list of `HanderInfo` objects that remain active.
@param {Array[HandlerInfo]} oldHandlers a list of the handler
information for the previous URL (or `[]` if this is the
first handled transition)
@param {Array[HandlerInfo]} newHandlers a list of the handler
information for the new URL
@return {Partition}
*/
function partitionHandlers(oldState, newState) {
var oldHandlers = oldState.handlerInfos;
var newHandlers = newState.handlerInfos;
var handlers = {
updatedContext: [],
exited: [],
entered: [],
unchanged: []
};
var handlerChanged, contextChanged, queryParamsChanged, i, l;
for (i=0, l=newHandlers.length; i<l; i++) {
var oldHandler = oldHandlers[i], newHandler = newHandlers[i];
if (!oldHandler || oldHandler.handler !== newHandler.handler) {
handlerChanged = true;
}
if (handlerChanged) {
handlers.entered.push(newHandler);
if (oldHandler) { handlers.exited.unshift(oldHandler); }
} else if (contextChanged || oldHandler.context !== newHandler.context || queryParamsChanged) {
contextChanged = true;
handlers.updatedContext.push(newHandler);
} else {
handlers.unchanged.push(oldHandler);
}
}
for (i=newHandlers.length, l=oldHandlers.length; i<l; i++) {
handlers.exited.unshift(oldHandlers[i]);
}
return handlers;
}
function updateURL(transition, state, inputUrl) {
var urlMethod = transition.urlMethod;
if (!urlMethod) {
return;
}
var router = transition.router,
handlerInfos = state.handlerInfos,
handlerName = handlerInfos[handlerInfos.length - 1].name,
params = {};
for (var i = handlerInfos.length - 1; i >= 0; --i) {
var handlerInfo = handlerInfos[i];
merge(params, handlerInfo.params);
if (handlerInfo.handler.inaccessibleByURL) {
urlMethod = null;
}
}
if (urlMethod) {
params.queryParams = state.queryParams;
var url = router.recognizer.generate(handlerName, params);
if (urlMethod === 'replaceQuery') {
if (url !== inputUrl) {
router.replaceURL(url);
}
} else if (urlMethod === 'replace') {
router.replaceURL(url);
} else {
router.updateURL(url);
}
}
}
/**
@private
Updates the URL (if necessary) and calls `setupContexts`
to update the router's array of `currentHandlerInfos`.
*/
function finalizeTransition(transition, newState) {
try {
log(transition.router, transition.sequence, "Resolved all models on destination route; finalizing transition.");
var router = transition.router,
handlerInfos = newState.handlerInfos,
seq = transition.sequence;
// Run all the necessary enter/setup/exit hooks
setupContexts(router, newState, transition);
// Check if a redirect occurred in enter/setup
if (transition.isAborted) {
// TODO: cleaner way? distinguish b/w targetHandlerInfos?
router.state.handlerInfos = router.currentHandlerInfos;
return reject(logAbort(transition));
}
updateURL(transition, newState, transition.intent.url);
transition.isActive = false;
router.activeTransition = null;
trigger(router, router.currentHandlerInfos, true, ['didTransition']);
if (router.didTransition) {
router.didTransition(router.currentHandlerInfos);
}
log(router, transition.sequence, "TRANSITION COMPLETE.");
// Resolve with the final handler.
return handlerInfos[handlerInfos.length - 1].handler;
} catch(e) {
if (!(e instanceof TransitionAborted)) {
//var erroneousHandler = handlerInfos.pop();
var infos = transition.state.handlerInfos;
transition.trigger(true, 'error', e, transition, infos[infos.length-1].handler);
transition.abort();
}
throw e;
}
}
/**
@private
Begins and returns a Transition based on the provided
arguments. Accepts arguments in the form of both URL
transitions and named transitions.
@param {Router} router
@param {Array[Object]} args arguments passed to transitionTo,
replaceWith, or handleURL
*/
function doTransition(router, args, isIntermediate) {
// Normalize blank transitions to root URL transitions.
var name = args[0] || '/';
var lastArg = args[args.length-1];
var queryParams = {};
if (lastArg && lastArg.hasOwnProperty('queryParams')) {
queryParams = pop.call(args).queryParams;
}
var intent;
if (args.length === 0) {
log(router, "Updating query params");
// A query param update is really just a transition
// into the route you're already on.
var handlerInfos = router.state.handlerInfos;
intent = new NamedTransitionIntent({
name: handlerInfos[handlerInfos.length - 1].name,
contexts: [],
queryParams: queryParams
});
} else if (name.charAt(0) === '/') {
log(router, "Attempting URL transition to " + name);
intent = new URLTransitionIntent({ url: name });
} else {
log(router, "Attempting transition to " + name);
intent = new NamedTransitionIntent({
name: args[0],
contexts: slice.call(args, 1),
queryParams: queryParams
});
}
return router.transitionByIntent(intent, isIntermediate);
}
function handlerInfosEqual(handlerInfos, otherHandlerInfos) {
if (handlerInfos.length !== otherHandlerInfos.length) {
return false;
}
for (var i = 0, len = handlerInfos.length; i < len; ++i) {
if (handlerInfos[i] !== otherHandlerInfos[i]) {
return false;
}
}
return true;
}
function finalizeQueryParamChange(router, resolvedHandlers, newQueryParams) {
// We fire a finalizeQueryParamChange event which
// gives the new route hierarchy a chance to tell
// us which query params it's consuming and what
// their final values are. If a query param is
// no longer consumed in the final route hierarchy,
// its serialized segment will be removed
// from the URL.
var finalQueryParamsArray = [];
trigger(router, resolvedHandlers, true, ['finalizeQueryParamChange', newQueryParams, finalQueryParamsArray]);
var finalQueryParams = {};
for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) {
var qp = finalQueryParamsArray[i];
finalQueryParams[qp.key] = qp.value;
}
return finalQueryParams;
}
__exports__.Router = Router;
});
define("router/transition-intent",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
var merge = __dependency1__.merge;
function TransitionIntent(props) {
if (props) {
merge(this, props);
}
this.data = this.data || {};
}
TransitionIntent.prototype.applyToState = function(oldState) {
// Default TransitionIntent is a no-op.
return oldState;
};
__exports__.TransitionIntent = TransitionIntent;
});
define("router/transition-intent/named-transition-intent",
["../transition-intent","../transition-state","../handler-info","../utils","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) {
"use strict";
var TransitionIntent = __dependency1__.TransitionIntent;
var TransitionState = __dependency2__.TransitionState;
var UnresolvedHandlerInfoByParam = __dependency3__.UnresolvedHandlerInfoByParam;
var UnresolvedHandlerInfoByObject = __dependency3__.UnresolvedHandlerInfoByObject;
var isParam = __dependency4__.isParam;
var forEach = __dependency4__.forEach;
var extractQueryParams = __dependency4__.extractQueryParams;
var oCreate = __dependency4__.oCreate;
var merge = __dependency4__.merge;
function NamedTransitionIntent(props) {
TransitionIntent.call(this, props);
}
NamedTransitionIntent.prototype = oCreate(TransitionIntent.prototype);
NamedTransitionIntent.prototype.applyToState = function(oldState, recognizer, getHandler, isIntermediate) {
var partitionedArgs = extractQueryParams([this.name].concat(this.contexts)),
pureArgs = partitionedArgs[0],
queryParams = partitionedArgs[1],
handlers = recognizer.handlersFor(pureArgs[0]);
var targetRouteName = handlers[handlers.length-1].handler;
return this.applyToHandlers(oldState, handlers, getHandler, targetRouteName, isIntermediate);
};
NamedTransitionIntent.prototype.applyToHandlers = function(oldState, handlers, getHandler, targetRouteName, isIntermediate, checkingIfActive) {
var i;
var newState = new TransitionState();
var objects = this.contexts.slice(0);
var invalidateIndex = handlers.length;
var nonDynamicIndexes = [];
// Pivot handlers are provided for refresh transitions
if (this.pivotHandler) {
for (i = 0; i < handlers.length; ++i) {
if (getHandler(handlers[i].handler) === this.pivotHandler) {
invalidateIndex = i;
break;