-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathtransition.ts
889 lines (808 loc) · 31.4 KB
/
transition.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
import { trace } from '../common/trace';
import { services } from '../common/coreservices';
import { stringify } from '../common/strings';
import { map, find, extend, mergeR, tail, omit, arrayTuples, unnestR, identity, anyTrueR } from '../common/common';
import { isObject, isUndefined } from '../common/predicates';
import { prop, propEq, val, not, is } from '../common/hof';
import { StateDeclaration, StateOrName } from '../state/interface';
import {
TransitionOptions,
TreeChanges,
IHookRegistry,
TransitionHookPhase,
RegisteredHooks,
HookRegOptions,
HookMatchCriteria,
TransitionStateHookFn,
TransitionHookFn,
} from './interface'; // has or is using
import { TransitionHook } from './transitionHook';
import { matchState, makeEvent, RegisteredHook } from './hookRegistry';
import { HookBuilder } from './hookBuilder';
import { PathNode } from '../path/pathNode';
import { PathUtils } from '../path/pathUtils';
import { StateObject } from '../state/stateObject';
import { TargetState } from '../state/targetState';
import { Param } from '../params/param';
import { Resolvable } from '../resolve/resolvable';
import { ViewConfig } from '../view/interface';
import { ResolveContext } from '../resolve/resolveContext';
import { UIRouter } from '../router';
import { UIInjector } from '../interface';
import { RawParams } from '../params/interface';
import { ResolvableLiteral } from '../resolve/interface';
import { Rejection } from './rejectFactory';
import { applyPairs, flattenR, uniqR } from '../common';
/** @internal */
const stateSelf: (_state: StateObject) => StateDeclaration = prop('self');
/**
* Represents a transition between two states.
*
* When navigating to a state, we are transitioning **from** the current state **to** the new state.
*
* This object contains all contextual information about the to/from states, parameters, resolves.
* It has information about all states being entered and exited as a result of the transition.
*/
export class Transition implements IHookRegistry {
/** @internal */
static diToken = Transition;
/**
* A unique identifier for the transition.
*
* This is an auto incrementing integer, starting from `0`.
*/
$id: number;
/**
* A reference to the [[UIRouter]] instance
*
* This reference can be used to access the router services, such as the [[StateService]]
*/
router: UIRouter;
/** @internal */
private _deferred = services.$q.defer();
/**
* This promise is resolved or rejected based on the outcome of the Transition.
*
* When the transition is successful, the promise is resolved
* When the transition is unsuccessful, the promise is rejected with the [[Rejection]] or javascript error
*/
promise: Promise<any> = this._deferred.promise;
/**
* A boolean which indicates if the transition was successful
*
* After a successful transition, this value is set to true.
* After an unsuccessful transition, this value is set to false.
*
* The value will be undefined if the transition is not complete
*/
success: boolean;
/** @internal */
_aborted: boolean;
/** @internal */
private _error: Rejection;
/** @internal Holds the hook registration functions such as those passed to Transition.onStart() */
_registeredHooks: RegisteredHooks = {};
/** @internal */
private _options: TransitionOptions;
/** @internal */
private _treeChanges: TreeChanges;
/** @internal */
private _targetState: TargetState;
/** @internal */
private _hookBuilder = new HookBuilder(this);
/** @internal */
onBefore(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onStart(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onExit(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onRetain(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onEnter(criteria: HookMatchCriteria, callback: TransitionStateHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onFinish(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onSuccess(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @inheritdoc */
onError(criteria: HookMatchCriteria, callback: TransitionHookFn, options?: HookRegOptions): Function {
return;
}
/** @internal
* Creates the transition-level hook registration functions
* (which can then be used to register hooks)
*/
private createTransitionHookRegFns() {
this.router.transitionService._pluginapi
._getEvents()
.filter((type) => type.hookPhase !== TransitionHookPhase.CREATE)
.forEach((type) => makeEvent(this, this.router.transitionService, type));
}
/** @internal */
getHooks(hookName: string): RegisteredHook[] {
return this._registeredHooks[hookName];
}
/**
* Creates a new Transition object.
*
* If the target state is not valid, an error is thrown.
*
* @internal
*
* @param fromPath The path of [[PathNode]]s from which the transition is leaving. The last node in the `fromPath`
* encapsulates the "from state".
* @param targetState The target state and parameters being transitioned to (also, the transition options)
* @param router The [[UIRouter]] instance
* @internal
*/
constructor(fromPath: PathNode[], targetState: TargetState, router: UIRouter) {
this.router = router;
this._targetState = targetState;
if (!targetState.valid()) {
throw new Error(targetState.error());
}
// current() is assumed to come from targetState.options, but provide a naive implementation otherwise.
this._options = extend({ current: val(this) }, targetState.options());
this.$id = router.transitionService._transitionCount++;
const toPath = PathUtils.buildToPath(fromPath, targetState);
this._treeChanges = PathUtils.treeChanges(fromPath, toPath, this._options.reloadState);
this.createTransitionHookRegFns();
const onCreateHooks = this._hookBuilder.buildHooksForPhase(TransitionHookPhase.CREATE);
TransitionHook.invokeHooks(onCreateHooks, () => null);
this.applyViewConfigs(router);
}
private applyViewConfigs(router: UIRouter) {
const enteringStates = this._treeChanges.entering.map((node) => node.state);
PathUtils.applyViewConfigs(router.transitionService.$view, this._treeChanges.to, enteringStates);
}
/**
* @internal
* @returns the internal from [State] object
*/
$from() {
return tail(this._treeChanges.from).state;
}
/**
* @internal
* @returns the internal to [State] object
*/
$to() {
return tail(this._treeChanges.to).state;
}
/**
* Returns the "from state"
*
* Returns the state that the transition is coming *from*.
*
* @returns The state declaration object for the Transition's ("from state").
*/
from(): StateDeclaration {
return this.$from().self;
}
/**
* Returns the "to state"
*
* Returns the state that the transition is going *to*.
*
* @returns The state declaration object for the Transition's target state ("to state").
*/
to(): StateDeclaration {
return this.$to().self;
}
/**
* Gets the Target State
*
* A transition's [[TargetState]] encapsulates the [[to]] state, the [[params]], and the [[options]] as a single object.
*
* @returns the [[TargetState]] of this Transition
*/
targetState() {
return this._targetState;
}
/**
* Determines whether two transitions are equivalent.
* @deprecated
*/
is(compare: Transition | { to?: any; from?: any }): boolean {
if (compare instanceof Transition) {
// TODO: Also compare parameters
return this.is({ to: compare.$to().name, from: compare.$from().name });
}
return !(
(compare.to && !matchState(this.$to(), compare.to, this)) ||
(compare.from && !matchState(this.$from(), compare.from, this))
);
}
/**
* Gets transition parameter values
*
* Returns the parameter values for a transition as key/value pairs.
* This object is immutable.
*
* By default, returns the new parameter values (for the "to state").
*
* #### Example:
* ```js
* var toParams = transition.params();
* ```
*
* To return the previous parameter values, supply `'from'` as the `pathname` argument.
*
* #### Example:
* ```js
* var fromParams = transition.params('from');
* ```
*
* @param pathname the name of the treeChanges path to get parameter values for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
*
* @returns transition parameter values for the desired path.
*/
params(pathname?: string): { [paramName: string]: any };
params<T>(pathname?: string): T;
params(pathname = 'to') {
return Object.freeze(this._treeChanges[pathname].map(prop('paramValues')).reduce(mergeR, {}));
}
/**
* Gets the new values of any parameters that changed during this transition.
*
* Returns any parameter values that have changed during a transition, as key/value pairs.
*
* - Any parameter values that have changed will be present on the returned object reflecting the new value.
* - Any parameters that *not* have changed will not be present on the returned object.
* - Any new parameters that weren't present in the "from" state, but are now present in the "to" state will be present on the returned object.
* - Any previous parameters that are no longer present (because the "to" state doesn't have them) will be included with a value of `undefined`.
*
* The returned object is immutable.
*
* #### Examples:
*
* Given:
* ```js
* var stateA = { name: 'stateA', url: '/stateA/:param1/param2' }
* var stateB = { name: 'stateB', url: '/stateB/:param3' }
* var stateC = { name: 'stateB.nest', url: '/nest/:param4' }
* ```
*
* #### Example 1
*
* From `/stateA/abc/def` to `/stateA/abc/xyz`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param2: 'xyz' }
* ```
*
* The value of `param2` changed to `xyz`.
* The value of `param1` stayed the same so its value is not present.
*
* #### Example 2
*
* From `/stateA/abc/def` to `/stateB/123`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param1: undefined, param2: undefined, param3: '123' }
* ```
*
* The value `param3` is present because it is a new param.
* Both `param1` and `param2` are no longer present so their value is undefined.
*
* #### Example 3
*
* From `/stateB/123` to `/stateB/123/nest/456`
*
* ```js
* var changed = transition.paramsChanged()
* // changed is { param4: '456' }
* ```
*
* The value `param4` is present because it is a new param.
* The value of `param3` did not change, so its value is not present.
*
* @returns an immutable object with changed parameter keys/values.
*/
paramsChanged(): { [paramName: string]: any };
paramsChanged<T>(): T;
paramsChanged() {
const fromParams = this.params('from');
const toParams = this.params('to');
// All the parameters declared on both the "to" and "from" paths
const allParamDescriptors: Param[] = []
.concat(this._treeChanges.to)
.concat(this._treeChanges.from)
.map((pathNode) => pathNode.paramSchema)
.reduce(flattenR, [])
.reduce(uniqR, []);
const changedParamDescriptors = Param.changed(allParamDescriptors, fromParams, toParams);
return changedParamDescriptors.reduce((changedValues, descriptor) => {
changedValues[descriptor.id] = toParams[descriptor.id];
return changedValues;
}, {});
}
/**
* Creates a [[UIInjector]] Dependency Injector
*
* Returns a Dependency Injector for the Transition's target state (to state).
* The injector provides resolve values which the target state has access to.
*
* The `UIInjector` can also provide values from the native root/global injector (ng1/ng2).
*
* #### Example:
* ```js
* .onEnter({ entering: 'myState' }, trans => {
* var myResolveValue = trans.injector().get('myResolve');
* // Inject a global service from the global/native injector (if it exists)
* var MyService = trans.injector().get('MyService');
* })
* ```
*
* In some cases (such as `onBefore`), you may need access to some resolve data but it has not yet been fetched.
* You can use [[UIInjector.getAsync]] to get a promise for the data.
* #### Example:
* ```js
* .onBefore({}, trans => {
* return trans.injector().getAsync('myResolve').then(myResolveValue =>
* return myResolveValue !== 'ABORT';
* });
* });
* ```
*
* If a `state` is provided, the injector that is returned will be limited to resolve values that the provided state has access to.
* This can be useful if both a parent state `foo` and a child state `foo.bar` have both defined a resolve such as `data`.
* #### Example:
* ```js
* .onEnter({ to: 'foo.bar' }, trans => {
* // returns result of `foo` state's `myResolve` resolve
* // even though `foo.bar` also has a `myResolve` resolve
* var fooData = trans.injector('foo').get('myResolve');
* });
* ```
*
* If you need resolve data from the exiting states, pass `'from'` as `pathName`.
* The resolve data from the `from` path will be returned.
* #### Example:
* ```js
* .onExit({ exiting: 'foo.bar' }, trans => {
* // Gets the resolve value of `myResolve` from the state being exited
* var fooData = trans.injector(null, 'from').get('myResolve');
* });
* ```
*
*
* @param state Limits the resolves provided to only the resolves the provided state has access to.
* @param pathName Default: `'to'`: Chooses the path for which to create the injector. Use this to access resolves for `exiting` states.
*
* @returns a [[UIInjector]]
*/
injector(state?: StateOrName, pathName = 'to'): UIInjector {
let path: PathNode[] = this._treeChanges[pathName];
if (state) path = PathUtils.subPath(path, (node) => node.state === state || node.state.name === state);
return new ResolveContext(path).injector();
}
/**
* Gets all available resolve tokens (keys)
*
* This method can be used in conjunction with [[injector]] to inspect the resolve values
* available to the Transition.
*
* This returns all the tokens defined on [[StateDeclaration.resolve]] blocks, for the states
* in the Transition's [[TreeChanges.to]] path.
*
* #### Example:
* This example logs all resolve values
* ```js
* let tokens = trans.getResolveTokens();
* tokens.forEach(token => console.log(token + " = " + trans.injector().get(token)));
* ```
*
* #### Example:
* This example creates promises for each resolve value.
* This triggers fetches of resolves (if any have not yet been fetched).
* When all promises have all settled, it logs the resolve values.
* ```js
* let tokens = trans.getResolveTokens();
* let promise = tokens.map(token => trans.injector().getAsync(token));
* Promise.all(promises).then(values => console.log("Resolved values: " + values));
* ```
*
* Note: Angular 1 users whould use `$q.all()`
*
* @param pathname resolve context's path name (e.g., `to` or `from`)
*
* @returns an array of resolve tokens (keys)
*/
getResolveTokens(pathname = 'to'): any[] {
return new ResolveContext(this._treeChanges[pathname]).getTokens();
}
/**
* Dynamically adds a new [[Resolvable]] (i.e., [[StateDeclaration.resolve]]) to this transition.
*
* Allows a transition hook to dynamically add a Resolvable to this Transition.
*
* Use the [[Transition.injector]] to retrieve the resolved data in subsequent hooks ([[UIInjector.get]]).
*
* If a `state` argument is provided, the Resolvable is processed when that state is being entered.
* If no `state` is provided then the root state is used.
* If the given `state` has already been entered, the Resolvable is processed when any child state is entered.
* If no child states will be entered, the Resolvable is processed during the `onFinish` phase of the Transition.
*
* The `state` argument also scopes the resolved data.
* The resolved data is available from the injector for that `state` and any children states.
*
* #### Example:
* ```js
* transitionService.onBefore({}, transition => {
* transition.addResolvable({
* token: 'myResolve',
* deps: ['MyService'],
* resolveFn: myService => myService.getData()
* });
* });
* ```
*
* @param resolvable a [[ResolvableLiteral]] object (or a [[Resolvable]])
* @param state the state in the "to path" which should receive the new resolve (otherwise, the root state)
*/
addResolvable(resolvable: Resolvable | ResolvableLiteral, state: StateOrName = ''): void {
resolvable = is(Resolvable)(resolvable) ? resolvable : new Resolvable(resolvable);
const stateName: string = typeof state === 'string' ? state : state.name;
const topath = this._treeChanges.to;
const targetNode = find(topath, (node) => node.state.name === stateName);
const resolveContext: ResolveContext = new ResolveContext(topath);
resolveContext.addResolvables([resolvable as Resolvable], targetNode.state);
}
/**
* Gets the transition from which this transition was redirected.
*
* If the current transition is a redirect, this method returns the transition that was redirected.
*
* #### Example:
* ```js
* let transitionA = $state.go('A').transition
* transitionA.onStart({}, () => $state.target('B'));
* $transitions.onSuccess({ to: 'B' }, (trans) => {
* trans.to().name === 'B'; // true
* trans.redirectedFrom() === transitionA; // true
* });
* ```
*
* @returns The previous Transition, or null if this Transition is not the result of a redirection
*/
redirectedFrom(): Transition {
return this._options.redirectedFrom || null;
}
/**
* Gets the original transition in a redirect chain
*
* A transition might belong to a long chain of multiple redirects.
* This method walks the [[redirectedFrom]] chain back to the original (first) transition in the chain.
*
* #### Example:
* ```js
* // states
* registry.register({ name: 'A', redirectTo: 'B' });
* registry.register({ name: 'B', redirectTo: 'C' });
* registry.register({ name: 'C', redirectTo: 'D' });
* registry.register({ name: 'D' });
*
* let transitionA = $state.go('A').transition
*
* $transitions.onSuccess({ to: 'D' }, (trans) => {
* trans.to().name === 'D'; // true
* trans.redirectedFrom().to().name === 'C'; // true
* trans.originalTransition() === transitionA; // true
* trans.originalTransition().to().name === 'A'; // true
* });
* ```
*
* @returns The original Transition that started a redirect chain
*/
originalTransition(): Transition {
const rf = this.redirectedFrom();
return (rf && rf.originalTransition()) || this;
}
/**
* Get the transition options
*
* @returns the options for this Transition.
*/
options(): TransitionOptions {
return this._options;
}
/**
* Gets the states being entered.
*
* @returns an array of states that will be entered during this transition.
*/
entering(): StateDeclaration[] {
return map(this._treeChanges.entering, prop('state')).map(stateSelf);
}
/**
* Gets the states being exited.
*
* @returns an array of states that will be exited during this transition.
*/
exiting(): StateDeclaration[] {
return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse();
}
/**
* Gets the states being retained.
*
* @returns an array of states that are already entered from a previous Transition, that will not be
* exited during this Transition
*/
retained(): StateDeclaration[] {
return map(this._treeChanges.retained, prop('state')).map(stateSelf);
}
/**
* Get the [[ViewConfig]]s associated with this Transition
*
* Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.
* This method fetches the `ViewConfigs` for a given path in the Transition (e.g., "to" or "entering").
*
* @param pathname the name of the path to fetch views for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
* @param state If provided, only returns the `ViewConfig`s for a single state in the path
*
* @returns a list of ViewConfig objects for the given path.
*/
views(pathname = 'entering', state?: StateObject): ViewConfig[] {
let path = this._treeChanges[pathname];
path = !state ? path : path.filter(propEq('state', state));
return path.map(prop('views')).filter(identity).reduce(unnestR, []);
}
/**
* Return the transition's tree changes
*
* A transition goes from one state/parameters to another state/parameters.
* During a transition, states are entered and/or exited.
*
* This function returns various branches (paths) which represent the changes to the
* active state tree that are caused by the transition.
*
* @param pathname The name of the tree changes path to get:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
*/
treeChanges(pathname: string): PathNode[];
treeChanges(): TreeChanges;
treeChanges(pathname?: string) {
return pathname ? this._treeChanges[pathname] : this._treeChanges;
}
/**
* Creates a new transition that is a redirection of the current one.
*
* This transition can be returned from a [[TransitionService]] hook to
* redirect a transition to a new state and/or set of parameters.
*
* @internal
*
* @returns Returns a new [[Transition]] instance.
*/
redirect(targetState: TargetState): Transition {
let redirects = 1,
trans: Transition = this;
// tslint:disable-next-line:no-conditional-assignment
while ((trans = trans.redirectedFrom()) != null) {
if (++redirects > 20) throw new Error(`Too many consecutive Transition redirects (20+)`);
}
const redirectOpts: TransitionOptions = { redirectedFrom: this, source: 'redirect' };
// If the original transition was caused by URL sync, then use { location: 'replace' }
// on the new transition (unless the target state explicitly specifies location: false).
// This causes the original url to be replaced with the url for the redirect target
// so the original url disappears from the browser history.
if (this.options().source === 'url' && targetState.options().location !== false) {
redirectOpts.location = 'replace';
}
const newOptions = extend({}, this.options(), targetState.options(), redirectOpts);
targetState = targetState.withOptions(newOptions, true);
const newTransition = this.router.transitionService.create(this._treeChanges.from, targetState);
const originalEnteringNodes = this._treeChanges.entering;
const redirectEnteringNodes = newTransition._treeChanges.entering;
// --- Re-use resolve data from original transition ---
// When redirecting from a parent state to a child state where the parent parameter values haven't changed
// (because of the redirect), the resolves fetched by the original transition are still valid in the
// redirected transition.
//
// This allows you to define a redirect on a parent state which depends on an async resolve value.
// You can wait for the resolve, then redirect to a child state based on the result.
// The redirected transition does not have to re-fetch the resolve.
// ---------------------------------------------------------
const nodeIsReloading = (reloadState: StateObject) => (node: PathNode) => {
return reloadState && node.state.includes[reloadState.name];
};
// Find any "entering" nodes in the redirect path that match the original path and aren't being reloaded
const matchingEnteringNodes: PathNode[] = PathUtils.matching(
redirectEnteringNodes,
originalEnteringNodes,
PathUtils.nonDynamicParams
).filter(not(nodeIsReloading(targetState.options().reloadState)));
// Use the existing (possibly pre-resolved) resolvables for the matching entering nodes.
matchingEnteringNodes.forEach((node, idx) => {
node.resolvables = originalEnteringNodes[idx].resolvables;
});
return newTransition;
}
/** @internal If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */
private _changedParams(): Param[] {
const tc = this._treeChanges;
/** Return undefined if it's not a "dynamic" transition, for the following reasons */
// If user explicitly wants a reload
if (this._options.reload) return undefined;
// If any states are exiting or entering
if (tc.exiting.length || tc.entering.length) return undefined;
// If to/from path lengths differ
if (tc.to.length !== tc.from.length) return undefined;
// If the to/from paths are different
const pathsDiffer: boolean = arrayTuples(tc.to, tc.from)
.map((tuple) => tuple[0].state !== tuple[1].state)
.reduce(anyTrueR, false);
if (pathsDiffer) return undefined;
// Find any parameter values that differ
const nodeSchemas: Param[][] = tc.to.map((node: PathNode) => node.paramSchema);
const [toValues, fromValues] = [tc.to, tc.from].map((path) => path.map((x) => x.paramValues));
const tuples = arrayTuples(nodeSchemas, toValues, fromValues);
return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);
}
/**
* Returns true if the transition is dynamic.
*
* A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.
*
* @returns true if the Transition is dynamic
*/
dynamic(): boolean {
const changes = this._changedParams();
return !changes ? false : changes.map((x) => x.dynamic).reduce(anyTrueR, false);
}
/**
* Returns true if the transition is ignored.
*
* A transition is ignored if no states are entered nor exited, and no parameter values have changed.
*
* @returns true if the Transition is ignored.
*/
ignored(): boolean {
return !!this._ignoredReason();
}
/** @internal */
_ignoredReason(): 'SameAsCurrent' | 'SameAsPending' | undefined {
const pending = this.router.globals.transition;
const reloadState = this._options.reloadState;
const same = (pathA, pathB) => {
if (pathA.length !== pathB.length) return false;
const matching = PathUtils.matching(pathA, pathB);
return pathA.length === matching.filter((node) => !reloadState || !node.state.includes[reloadState.name]).length;
};
const newTC = this.treeChanges();
const pendTC = pending && pending.treeChanges();
if (pendTC && same(pendTC.to, newTC.to) && same(pendTC.exiting, newTC.exiting)) return 'SameAsPending';
if (newTC.exiting.length === 0 && newTC.entering.length === 0 && same(newTC.from, newTC.to)) return 'SameAsCurrent';
}
/**
* Runs the transition
*
* This method is generally called from the [[StateService.transitionTo]]
*
* @internal
*
* @returns a promise for a successful transition.
*/
run(): Promise<any> {
const runAllHooks = TransitionHook.runAllHooks;
// Gets transition hooks array for the given phase
const getHooksFor = (phase: TransitionHookPhase) => this._hookBuilder.buildHooksForPhase(phase);
// When the chain is complete, then resolve or reject the deferred
const transitionSuccess = () => {
trace.traceSuccess(this.$to(), this);
this.success = true;
this._deferred.resolve(this.to());
runAllHooks(getHooksFor(TransitionHookPhase.SUCCESS));
};
const transitionError = (reason: Rejection) => {
trace.traceError(reason, this);
this.success = false;
this._deferred.reject(reason);
this._error = reason;
runAllHooks(getHooksFor(TransitionHookPhase.ERROR));
};
const runTransition = () => {
// Wait to build the RUN hook chain until the BEFORE hooks are done
// This allows a BEFORE hook to dynamically add additional RUN hooks via the Transition object.
const allRunHooks = getHooksFor(TransitionHookPhase.RUN);
const done = () => services.$q.when(undefined);
return TransitionHook.invokeHooks(allRunHooks, done);
};
const startTransition = () => {
const globals = this.router.globals;
globals.lastStartedTransitionId = this.$id;
globals.transition = this;
globals.transitionHistory.enqueue(this);
trace.traceTransitionStart(this);
return services.$q.when(undefined);
};
const allBeforeHooks = getHooksFor(TransitionHookPhase.BEFORE);
TransitionHook.invokeHooks(allBeforeHooks, startTransition)
.then(runTransition)
.then(transitionSuccess, transitionError);
return this.promise;
}
/** Checks if this transition is currently active/running. */
isActive = () => this.router.globals.transition === this;
/**
* Checks if the Transition is valid
*
* @returns true if the Transition is valid
*/
valid() {
return !this.error() || this.success !== undefined;
}
/**
* Aborts this transition
*
* Imperative API to abort a Transition.
* This only applies to Transitions that are not yet complete.
*/
abort() {
// Do not set flag if the transition is already complete
if (isUndefined(this.success)) {
this._aborted = true;
}
}
/**
* The Transition error reason.
*
* If the transition is invalid (and could not be run), returns the reason the transition is invalid.
* If the transition was valid and ran, but was not successful, returns the reason the transition failed.
*
* @returns a transition rejection explaining why the transition is invalid, or the reason the transition failed.
*/
error(): Rejection {
const state: StateObject = this.$to();
if (state.self.abstract) {
return Rejection.invalid(`Cannot transition to abstract state '${state.name}'`);
}
const paramDefs = state.parameters();
const values = this.params();
const invalidParams = paramDefs.filter((param) => !param.validates(values[param.id]));
if (invalidParams.length) {
const invalidValues = invalidParams.map((param) => `[${param.id}:${stringify(values[param.id])}]`).join(', ');
const detail = `The following parameter values are not valid for state '${state.name}': ${invalidValues}`;
return Rejection.invalid(detail);
}
if (this.success === false) return this._error;
}
/**
* A string representation of the Transition
*
* @returns A string representation of the Transition
*/
toString() {
const fromStateOrName = this.from();
const toStateOrName = this.to();
const avoidEmptyHash = (params: RawParams) =>
params['#'] !== null && params['#'] !== undefined ? params : omit(params, ['#']);
// (X) means the to state is invalid.
const id = this.$id,
from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,
fromParams = stringify(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),
toValid = this.valid() ? '' : '(X) ',
to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,
toParams = stringify(avoidEmptyHash(this.params()));
return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;
}
}