forked from angular-ui/ui-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.js
498 lines (418 loc) · 18.5 KB
/
state.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
$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $locationProvider) {
var root, states = {}, $state;
// Builds state properties from definition passed to registerState()
var stateBuilder = {
// Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
// state.children = [];
// if (parent) parent.children.push(state);
parent: function(state) {
if (isDefined(state.parent) && state.parent) return findState(state.parent);
// regex matches any valid composite state name
// would match "contact.list" but not "contacts"
var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
return compositeName ? findState(compositeName[1]) : root;
},
// inherit 'data' from parent and override by own values (if any)
data: function(state) {
if (state.parent && state.parent.data) {
state.data = state.self.data = extend({}, state.parent.data, state.data);
}
return state.data;
},
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: function(state) {
var url = state.url;
if (isString(url)) {
if (url.charAt(0) == '^') {
return $urlMatcherFactory.compile(url.substring(1));
}
return (state.parent.navigable || root).url.concat(url);
}
if ($urlMatcherFactory.isMatcher(url) || url == null) {
return url;
}
throw new Error("Invalid url '" + url + "' in state '" + state + "'");
},
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: function(state) {
return state.url ? state : (state.parent ? state.parent.navigable : null);
},
// Derive parameters for this state and ensure they're a super-set of parent's parameters
params: function(state) {
if (!state.params) {
return state.url ? state.url.parameters() : state.parent.params;
}
if (!isArray(state.params)) throw new Error("Invalid params in state '" + state + "'");
if (state.url) throw new Error("Both params and url specicified in state '" + state + "'");
return state.params;
},
// If there is no explicit multi-view configuration, make one up so we don't have
// to handle both cases in the view directive later. Note that having an explicit
// 'views' property will mean the default unnamed view properties are ignored. This
// is also a good time to resolve view names to absolute names, so everything is a
// straight lookup at link time.
views: function(state) {
var views = {};
forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
if (name.indexOf('@') < 0) name += '@' + state.parent.name;
views[name] = view;
});
return views;
},
ownParams: function(state) {
if (!state.parent) {
return state.params;
}
var paramNames = {}; forEach(state.params, function (p) { paramNames[p] = true; });
forEach(state.parent.params, function (p) {
if (!paramNames[p]) {
throw new Error("Missing required parameter '" + p + "' in state '" + state.name + "'");
}
paramNames[p] = false;
});
var ownParams = [];
forEach(paramNames, function (own, p) {
if (own) ownParams.push(p);
});
return ownParams;
},
// Keep a full path from the root down to this state as this is needed for state activation.
path: function(state) {
return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
},
// Speed up $state.contains() as it's used a lot
includes: function(state) {
var includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
},
$delegates: {}
};
// Create a proxy through to the Type registration on the UrlMatcherFactory
this.isTypeRegistered = $urlMatcherFactory.isTypeRegistered;
this.type = function (name, handler) {
$urlMatcherFactory.type(name, handler);
return this;
};
function isRelative(stateName) {
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
}
function findState(stateOrName, base) {
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states[name]) throw new Error("State '" + name + "'' is already defined");
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state['abstract'] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, false);
}
}]);
}
return state;
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
// .decorator()
// .decorator(name)
// .decorator(name, function)
this.decorator = decorator;
function decorator(name, func) {
/*jshint validthis: true */
if (isString(name) && !isDefined(func)) {
return stateBuilder[name];
}
if (!isFunction(func) || !isString(name)) {
return this;
}
if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
stateBuilder.$delegates[name] = stateBuilder[name];
}
stateBuilder[name] = func;
return this;
}
// .state(state)
// .state(name, state)
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
// $urlRouter is injected just to ensure it gets instantiated
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$location', '$urlRouter'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $location, $urlRouter) {
var TransitionSuperseded = $q.reject(new Error('transition superseded'));
var TransitionPrevented = $q.reject(new Error('transition prevented'));
var TransitionAborted = $q.reject(new Error('transition aborted'));
var TransitionFailed = $q.reject(new Error('transition failed'));
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
$state.go = function go(to, params, options) {
return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
$state.transitionTo = function transitionTo(to, toParams, options) {
if (!isDefined(options)) options = (options === true || options === false) ? { location: options } : {};
toParams = toParams || {};
options = extend({ location: true, inherit: false, relative: null, $retry: false }, options);
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var toState = findState(to, options.relative);
var evt;
if (!isDefined(toState)) {
// Broadcast not found event and abort the transition if prevented
var redirect = { to: to, toParams: toParams, options: options };
evt = $rootScope.$broadcast('$stateNotFound', redirect, from.self, fromParams);
if (evt.defaultPrevented) return TransitionAborted;
// Allow the handler to return a promise to defer state lookup retry
if (evt.retry) {
if (options.$retry) return TransitionFailed;
var retryTransition = $state.transition = $q.when(evt.retry);
retryTransition.then(function() {
if (retryTransition !== $state.transition) return TransitionSuperseded;
redirect.options.$retry = true;
return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
},
function() {
return TransitionAborted;
});
return retryTransition;
}
// Always retry once if the $stateNotFound was not prevented
// (handles either redirect changed or state lazy-definition)
to = redirect.to;
toParams = redirect.toParams;
options = redirect.options;
toState = findState(to, options.relative);
if (!isDefined(toState)) {
if (options.relative) throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
throw new Error("No such state '" + to + "'");
}
}
if (toState['abstract']) throw new Error("Cannot transition to abstract state '" + to + "'");
if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
to = toState;
var toPath = to.path;
// Starting from the root of the path, keep all levels that haven't changed
var keep, state, locals = root.locals, toLocals = [];
for (keep = 0, state = toPath[keep];
state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams);
keep++, state = toPath[keep]) {
locals = toLocals[keep] = state.locals;
}
// If we're going to the same state and all locals are kept, we've got nothing to do.
// But clear 'transition', as we still want to cancel any other pending transitions.
// TODO: We may not want to bump 'transition' if we're called from a location change that we've initiated ourselves,
// because we might accidentally abort a legitimate transition initiated from code?
if (to === from && locals === from.locals) {
$state.transition = null;
return $q.when($state.current);
}
// Normalize/filter parameters before we pass them to event handlers etc.
toParams = normalize(to.params, toParams || {});
// Broadcast start event and cancel the transition if requested
evt = $rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams);
if (evt.defaultPrevented) return TransitionPrevented;
// Resolve locals for the remaining states, but don't update any global state just
// yet -- if anything fails to resolve the current state needs to remain untouched.
// We also set up an inheritance chain for the locals here. This allows the view directive
// to quickly look up the correct definition for each view in the current state. Even
// though we create the locals object itself outside resolveState(), it is initially
// empty and gets filled asynchronously. We need to keep track of the promise for the
// (fully resolved) current locals, and pass this down the chain.
var resolved = $q.when(locals);
for (var l=keep; l<toPath.length; l++, state=toPath[l]) {
locals = toLocals[l] = inherit(locals);
resolved = resolveState(state, toParams, state===to, resolved, locals);
}
// Once everything is resolved, we are ready to perform the actual transition
// and return a promise for the new state. We also keep track of what the
// current promise is, so that we can detect overlapping transitions and
// keep only the outcome of the last transition.
var transition = $state.transition = resolved.then(function () {
var l, entering, exiting;
if ($state.transition !== transition) return TransitionSuperseded;
// Exit 'from' states not kept
for (l=fromPath.length-1; l>=keep; l--) {
exiting = fromPath[l];
if (exiting.self.onExit) {
$injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
}
exiting.locals = null;
}
// Enter 'to' states not kept
for (l=keep; l<toPath.length; l++) {
entering = toPath[l];
entering.locals = toLocals[l];
if (entering.self.onEnter) {
$injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
}
}
// Update globals in $state
$state.$current = to;
$state.current = to.self;
$state.params = toParams;
copy($state.params, $stateParams);
$state.transition = null;
// Update $location
var toNav = to.navigable;
if (options.location && toNav) {
$location.url(toNav.url.format(toNav.locals.globals.$stateParams));
}
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
$rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
return $q.reject(error);
});
return transition;
};
$state.is = function is(stateOrName) {
var state = findState(stateOrName);
return (isDefined(state)) ? $state.$current === state : undefined;
};
$state.includes = function includes(stateOrName) {
var state = findState(stateOrName);
return (isDefined(state)) ? isDefined($state.$current.includes[state.name]) : undefined;
};
$state.href = function href(stateOrName, params, options) {
options = extend({ lossy: true, inherit: false, relative: $state.$current }, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) return null;
params = inheritParams($stateParams, params || {}, $state.$current, state);
var nav = (state && options.lossy) ? state.navigable : state;
var url = (nav && nav.url) ? nav.url.format(normalize(state.params, params || {})) : null;
return !$locationProvider.html5Mode() && url ? "#" + url : url;
};
$state.get = function (stateOrName) {
if (!isDefined(stateOrName)) {
var list = [];
forEach(states, function(state) { list.push(state.self); });
return list;
}
var state = findState(stateOrName);
return (state && state.self) ? state.self : null;
};
function resolveState(state, params, paramsAreFiltered, inherited, dst) {
// Make a restricted $stateParams with only the parameters that apply to this state if
// necessary. In addition to being available to the controller and onEnter/onExit callbacks,
// we also need $stateParams to be available for any $injector calls we make during the
// dependency resolution process.
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params, params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [ dst.resolve.then(function (globals) {
dst.globals = globals;
}) ];
if (inherited) promises.push(inherited);
// Resolve template and dependencies for all views.
forEach(state.views, function (view, name) {
var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
injectables.$template = [ function () {
return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: false }) || '';
}];
promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
// References to the controller (only instantiated at link time)
result.$$controller = view.controller;
// Provide access to the state itself for internal use
result.$$state = state;
dst[name] = result;
}));
});
// Wait for all the promises and then return the activation object
return $q.all(promises).then(function (values) {
return dst;
});
}
return $state;
}
function normalize(keys, values) {
var normalized = {};
forEach(keys, function (name) {
var value = values[name];
//normalized[name] = (value != null) ? String(value) : null;
normalized[name] = (value != null) ? value : null;
});
return normalized;
}
function equalForKeys(a, b, keys) {
// If keys not provided, assume keys from object 'a'
if (!keys) {
keys = [];
for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
}
for (var i=0; i<keys.length; i++) {
var k = keys[i];
if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
}
return true;
}
function filterByKeys(keys, values) {
var filtered = {};
forEach(keys, function (name) {
filtered[name] = values[name];
});
return filtered;
}
}
angular.module('ui.router.state')
.value('$stateParams', {})
.provider('$state', $StateProvider);