-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathstateService.ts
552 lines (510 loc) · 23.7 KB
/
stateService.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
/** @module state */ /** */
import {extend, defaults, silentRejection, silenceUncaughtInPromise} from "../common/common";
import {isDefined, isObject, isString} from "../common/predicates";
import {Queue} from "../common/queue";
import {services} from "../common/coreservices";
import {PathFactory} from "../path/pathFactory";
import {PathNode} from "../path/node";
import {TransitionOptions, HookResult} from "../transition/interface";
import {defaultTransOpts} from "../transition/transitionService";
import {Rejection, RejectType} from "../transition/rejectFactory";
import {Transition} from "../transition/transition";
import {StateOrName, StateDeclaration, TransitionPromise} from "./interface";
import {State} from "./stateObject";
import {TargetState} from "./targetState";
import {RawParams} from "../params/interface";
import {ParamsOrArray} from "../params/interface";
import {Param} from "../params/param";
import {Glob} from "../common/glob";
import {equalForKeys} from "../common/common";
import {HrefOptions} from "./interface";
import {bindFunctions} from "../common/common";
import {Globals} from "../globals";
import {UIRouter} from "../router";
import {StateParams} from "../params/stateParams"; // for params() return type
export class StateService {
get transition() { return this.router.globals.transition; }
get params() { return this.router.globals.params; }
get current() { return this.router.globals.current; }
get $current() { return this.router.globals.$current; }
/** @hidden */
constructor(private router: UIRouter) {
let getters = ['current', '$current', 'params', 'transition'];
let boundFns = Object.keys(StateService.prototype).filter(key => getters.indexOf(key) === -1);
bindFunctions(StateService.prototype, this, this, boundFns);
}
/**
* Handler for when [[transitionTo]] is called with an invalid state.
*
* Invokes the [[onInvalid]] callbacks, in natural order.
* Each callback's return value is checked in sequence until one of them returns an instance of TargetState.
* The results of the callbacks are wrapped in $q.when(), so the callbacks may return promises.
*
* If a callback returns an TargetState, then it is used as arguments to $state.transitionTo() and the result returned.
*/
private _handleInvalidTargetState(fromPath: PathNode[], $to$: TargetState) {
let globals = <Globals> this.router.globals;
const latestThing = () => globals.transitionHistory.peekTail();
let latest = latestThing();
let $from$ = PathFactory.makeTargetState(fromPath);
let callbackQueue = new Queue<Function>(this.router.stateProvider.invalidCallbacks.slice());
let {$q, $injector} = services;
const invokeCallback = (callback: Function) =>
$q.when($injector.invoke(callback, null, { $to$, $from$ }));
const checkForRedirect = (result: HookResult) => {
if (!(result instanceof TargetState)) {
return;
}
let target = <TargetState> result;
// Recreate the TargetState, in case the state is now defined.
target = this.target(target.identifier(), target.params(), target.options());
if (!target.valid()) return Rejection.invalid(target.error()).toPromise();
if (latestThing() !== latest) return Rejection.superseded().toPromise();
return this.transitionTo(target.identifier(), target.params(), target.options());
};
function invokeNextCallback() {
let nextCallback = callbackQueue.dequeue();
if (nextCallback === undefined) return Rejection.invalid($to$.error()).toPromise();
return invokeCallback(nextCallback).then(checkForRedirect).then(result => result || invokeNextCallback());
}
return invokeNextCallback();
}
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* A method that force reloads the current state, or a partial state hierarchy. All resolves are re-resolved,
* controllers reinstantiated, and events re-fired.
*
* @example
* <pre>
* let app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* $state.reload();
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: true
* });
* </pre>
*
* @param {string=|object=} reloadState - A state name or a state object, which is the root of the resolves to be re-resolved.
* @example
* <pre>
* //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
* //and current state is 'contacts.detail.item'
* let app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* //will reload 'contact.detail' and nested 'contact.detail.item' states
* $state.reload('contact.detail');
* }
* });
* </pre>
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
reload(reloadState?: StateOrName): Promise<State> {
return this.transitionTo(this.current, this.params, {
reload: isDefined(reloadState) ? reloadState : true,
inherit: false,
notify: false
});
};
/**
* @ngdoc function
* @name ui.router.state.$state#go
* @methodOf ui.router.state.$state
*
* @description
* Convenience method for transitioning to a new state. `$state.go` calls
* `$state.transitionTo` internally but automatically sets options to
* `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
* This allows you to easily use an absolute or relative to path and specify
* only the parameters you'd like to update (while letting unspecified parameters
* inherit from the currently active ancestor states).
*
* @example
* <pre>
* let app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
* <img src='../ngdoc_assets/StateGoExamples.png'/>
*
* @param {string|object} to Absolute state name, state object, or relative state path. Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
* transitioning to a sibling will get you the parameters for all parents, transitioning to a child
* will get you all current parameters, etc.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition.
*
* Possible success values:
*
* - $state.current
*
* <br/>Possible rejection values:
*
* - 'transition superseded' - when a newer transition has been started after this one
* - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
* - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
* when a `$stateNotFound` `event.retry` promise errors.
* - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
* - *resolve error* - when an error has occurred with a `resolve`
*
*/
go(to: StateOrName, params?: RawParams, options?: TransitionOptions): TransitionPromise {
let defautGoOpts = { relative: this.$current, inherit: true };
let transOpts = defaults(options, defautGoOpts, defaultTransOpts);
return this.transitionTo(to, params, transOpts);
};
/** Factory method for creating a TargetState */
target(identifier: StateOrName, params?: ParamsOrArray, options: TransitionOptions = {}): TargetState {
// If we're reloading, find the state object to reload from
if (isObject(options.reload) && !(<any>options.reload).name)
throw new Error('Invalid reload state object');
let reg = this.router.stateRegistry;
options.reloadState = options.reload === true ? reg.root() : reg.matcher.find(<any> options.reload, options.relative);
if (options.reload && !options.reloadState)
throw new Error(`No such reload state '${(isString(options.reload) ? options.reload : (<any>options.reload).name)}'`);
let stateDefinition = reg.matcher.find(identifier, options.relative);
return new TargetState(identifier, stateDefinition, params, options);
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* let app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string|object} to State name or state object.
* @param {object=} toParams A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
transitionTo(to: StateOrName, toParams: RawParams = {}, options: TransitionOptions = {}): TransitionPromise {
let router = this.router;
let globals = <Globals> router.globals;
let transHistory = globals.transitionHistory;
options = defaults(options, defaultTransOpts);
options = extend(options, { current: transHistory.peekTail.bind(transHistory)});
let ref: TargetState = this.target(to, toParams, options);
let latestSuccess: Transition = globals.successfulTransitions.peekTail();
const rootPath = () => [ new PathNode(this.router.stateRegistry.root()) ];
let currentPath: PathNode[] = latestSuccess ? latestSuccess.treeChanges().to : rootPath();
if (!ref.exists())
return this._handleInvalidTargetState(currentPath, ref);
if (!ref.valid())
return <TransitionPromise> silentRejection(ref.error());
/**
* Special handling for Ignored, Aborted, and Redirected transitions
*
* The semantics for the transition.run() promise and the StateService.transitionTo()
* promise differ. For instance, the run() promise may be rejected because it was
* IGNORED, but the transitionTo() promise is resolved because from the user perspective
* no error occurred. Likewise, the transition.run() promise may be rejected because of
* a Redirect, but the transitionTo() promise is chained to the new Transition's promise.
*/
const rejectedTransitionHandler = (transition: Transition) => (error: any): Promise<any> => {
if (error instanceof Rejection) {
if (error.type === RejectType.IGNORED) {
// Consider ignored `Transition.run()` as a successful `transitionTo`
router.urlRouter.update();
return services.$q.when(globals.current);
}
if (error.type === RejectType.SUPERSEDED && error.redirected && error.detail instanceof TargetState) {
// If `Transition.run()` was redirected, allow the `transitionTo()` promise to resolve successfully
// by returning the promise for the new (redirect) `Transition.run()`.
let redirect: Transition = transition.redirect(error.detail);
return redirect.run().catch(rejectedTransitionHandler(redirect));
}
if (error.type === RejectType.ABORTED) {
router.urlRouter.update();
// Fall through to default error handler
}
}
var errorHandler = this.defaultErrorHandler();
errorHandler(error);
return services.$q.reject(error);
};
let transition = this.router.transitionService.create(currentPath, ref);
let transitionToPromise = transition.run().catch(rejectedTransitionHandler(transition));
silenceUncaughtInPromise(transitionToPromise); // issue #2676
// Return a promise for the transition, which also has the transition object on it.
return extend(transitionToPromise, { transition });
};
/**
* @ngdoc function
* @name ui.router.state.$state#is
* @methodOf ui.router.state.$state
*
* @description
* Similar to {@link ui.router.state.$state#methods_includes $state.includes},
* but only checks for the full state name. If params is supplied then it will be
* tested for strict equality against the current active params object, so all params
* must match with none missing and no extras.
*
* @example
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // absolute name
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // relative name (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.is('.item')}">Item</div>
* </pre>
*
* @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
* test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it is the state.
*/
is(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {
options = defaults(options, { relative: this.$current });
let state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);
if (!isDefined(state)) return undefined;
if (this.$current !== state) return false;
return isDefined(params) && params !== null ? Param.equals(state.parameters(), this.params, params) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#includes
* @methodOf ui.router.state.$state
*
* @description
* A method to determine if the current active state is equal to or is the child of the
* state stateName. If any params are passed then they will be tested for a match as well.
* Not all the parameters need to be passed, just the ones you'd like to test for equality.
*
* @example
* Partial and relative names
* <pre>
* $state.$current.name = 'contacts.details.item';
*
* // Using partial names
* $state.includes("contacts"); // returns true
* $state.includes("contacts.details"); // returns true
* $state.includes("contacts.details.item"); // returns true
* $state.includes("contacts.list"); // returns false
* $state.includes("about"); // returns false
*
* // Using relative names (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
* </pre>
*
* Basic globbing patterns
* <pre>
* $state.$current.name = 'contacts.details.item.url';
*
* $state.includes("*.details.*.*"); // returns true
* $state.includes("*.details.**"); // returns true
* $state.includes("**.item.**"); // returns true
* $state.includes("*.details.item.url"); // returns true
* $state.includes("*.details.*.url"); // returns true
* $state.includes("*.details.*"); // returns false
* $state.includes("item.**"); // returns false
* </pre>
*
* @param {string|object} stateOrName A partial name, relative name, glob pattern,
* or state object to be searched for within the current state name.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`,
* that you'd like to test against the current active state.
* @param {object=} options An options object. The options are:
*
* - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
* .includes will test relative to `options.relative` state (or name).
*
* @returns {boolean} Returns true if it does include the state
*/
includes(stateOrName: StateOrName, params?: RawParams, options?: TransitionOptions): boolean {
options = defaults(options, { relative: this.$current });
let glob = isString(stateOrName) && Glob.fromString(<string> stateOrName);
if (glob) {
if (!glob.matches(this.$current.name)) return false;
stateOrName = this.$current.name;
}
let state = this.router.stateRegistry.matcher.find(stateOrName, options.relative), include = this.$current.includes;
if (!isDefined(state)) return undefined;
if (!isDefined(include[state.name])) return false;
// @TODO Replace with Param.equals() ?
return params ? equalForKeys(Param.values(state.parameters(), params), this.params, Object.keys(params)) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#href
* @methodOf ui.router.state.$state
*
* @description
* A url generation method that returns the compiled url for the given state populated with the given params.
*
* @example
* <pre>
* expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
* </pre>
*
* @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
* @param {object=} params An object of parameter values to fill the state's required parameters.
* @param {object=} options Options object. The options are:
*
* - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
* first parameter, then the constructed href url will be built from the first navigable ancestor (aka
* ancestor with a valid url).
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
*
* @returns {string} compiled state url
*/
href(stateOrName: StateOrName, params: RawParams, options?: HrefOptions): string {
let defaultHrefOpts = {
lossy: true,
inherit: true,
absolute: false,
relative: this.$current
};
options = defaults(options, defaultHrefOpts);
params = params || {};
let state = this.router.stateRegistry.matcher.find(stateOrName, options.relative);
if (!isDefined(state)) return null;
if (options.inherit) params = <any> this.params.$inherit(params, this.$current, state);
let nav = (state && options.lossy) ? state.navigable : state;
if (!nav || nav.url === undefined || nav.url === null) {
return null;
}
return this.router.urlRouter.href(nav.url, Param.values(state.parameters(), params), {
absolute: options.absolute
});
};
/** @hidden */
private _defaultErrorHandler: ((_error: any) => void) = function $defaultErrorHandler($error$) {
if ($error$ instanceof Error && $error$.stack) {
console.error($error$);
console.error($error$.stack);
} else if ($error$ instanceof Rejection) {
console.error($error$.toString());
if ($error$.detail && $error$.detail.stack)
console.error($error$.detail.stack);
} else {
console.error($error$);
}
};
/**
* Sets or gets the default [[transitionTo]] error handler.
*
* The error handler is called when a [[Transition]] is rejected or when any error occurred during the Transition.
* This includes errors caused by resolves and transition hooks.
*
* Note:
* This handler does not receive certain Transition rejections.
* Redirected and Ignored Transitions are not considered to be errors by [[StateService.transitionTo]].
*
* The built-in default error handler logs the error to the console.
*
* You can provide your own custom handler.
*
* @example
* ```js
*
* stateService.defaultErrorHandler(function() {
* // Do not log transitionTo errors
* });
* ```
*
* @param handler a global error handler function
* @returns the current global error handler
*/
defaultErrorHandler(handler?: (error: any) => void): (error: any) => void {
return this._defaultErrorHandler = handler || this._defaultErrorHandler;
}
/**
* @ngdoc function
* @name ui.router.state.$state#get
* @methodOf ui.router.state.$state
*
* @description
* Returns the state configuration object for any specific state or all states.
*
* @param {string|Object=} stateOrName (absolute or relative) If provided, will only get the config for
* the requested state. If not provided, returns an array of ALL state configs.
* @param {string|object=} base When stateOrName is a relative state reference, the state will be retrieved relative to context.
* @returns {Object|Array} State configuration object or array of all objects.
*/
get(): StateDeclaration[];
get(stateOrName: StateOrName): StateDeclaration;
get(stateOrName: StateOrName, base: StateOrName): StateDeclaration;
get(stateOrName?: StateOrName, base?: StateOrName): any {
let reg = this.router.stateRegistry;
if (arguments.length === 0) return reg.get();
return reg.get(stateOrName, base || this.$current);
}
}