forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathng_route_shim.js
347 lines (282 loc) · 10.3 KB
/
ng_route_shim.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
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
(function () {
'use strict';
// keep a reference to compileProvider so we can register new component-directives
// on-the-fly based on $routeProvider configuration
// TODO: remove this– right now you can only bootstrap one Angular app with this hack
var $compileProvider, $q, $injector;
/**
* This module loads services that mimic ngRoute's configuration, and includes
* an anchor link directive that intercepts clicks to routing.
*
* This module is intended to be used as a stop-gap solution for projects upgrading from ngRoute.
* It intentionally does not implement all features of ngRoute.
*/
angular.module('ngRouteShim', [])
.provider('$route', $RouteProvider)
.config(['$compileProvider', function (compileProvider) {
$compileProvider = compileProvider;
}])
.factory('$routeParams', $routeParamsFactory)
.directive('a', anchorLinkDirective)
// Connects the legacy $routeProvider config shim to Component Router's config.
.run(['$route', '$rootRouter', function ($route, $rootRouter) {
$route.$$subscribe(function (routeDefinition) {
if (!angular.isArray(routeDefinition)) {
routeDefinition = [routeDefinition];
}
$rootRouter.config(routeDefinition);
});
}]);
/**
* A shimmed out provider that provides the same API as ngRoute's $routeProvider, but uses these calls
* to configure Component Router.
*/
function $RouteProvider() {
var routes = [];
var subscriptionFn = null;
var routeMap = {};
// Stats for which routes are skipped
var skipCount = 0;
var successCount = 0;
var allCount = 0;
function consoleMetrics() {
return '(' + skipCount + ' skipped / ' + successCount + ' success / ' + allCount + ' total)';
}
/**
* @ngdoc method
* @name $routeProvider#when
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*/
this.when = function(path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = angular.copy(route);
allCount++;
if (angular.isDefined(routeCopy.reloadOnSearch)) {
console.warn('Route for "' + path + '" uses "reloadOnSearch" which is not implemented.');
}
if (angular.isDefined(routeCopy.caseInsensitiveMatch)) {
console.warn('Route for "' + path + '" uses "caseInsensitiveMatch" which is not implemented.');
}
// use new wildcard format
path = reformatWildcardParams(path);
if (path[path.length - 1] == '*') {
skipCount++;
console.warn('Route for "' + path + '" ignored because it ends with *. Skipping.', consoleMetrics());
return this;
}
if (path.indexOf('?') > -1) {
skipCount++;
console.warn('Route for "' + path + '" ignored because it has optional parameters. Skipping.', consoleMetrics());
return this;
}
if (typeof route.redirectTo == 'function') {
skipCount++;
console.warn('Route for "' + path + '" ignored because lazy redirecting to a function is not yet implemented. Skipping.', consoleMetrics());
return this;
}
var routeDefinition = {
path: path,
data: routeCopy
};
routeMap[path] = routeCopy;
if (route.redirectTo) {
routeDefinition.redirectTo = [routeMap[route.redirectTo].name];
} else {
if (routeCopy.controller && !routeCopy.controllerAs) {
console.warn('Route for "' + path + '" should use "controllerAs".');
}
var componentName = routeObjToRouteName(routeCopy, path);
if (!componentName) {
throw new Error('Could not determine a name for route "' + path + '".');
}
routeDefinition.component = componentName;
routeDefinition.name = route.name || upperCase(componentName);
var directiveController = routeCopy.controller;
var componentDefinition = {
controller: directiveController,
controllerAs: routeCopy.controllerAs
};
if (routeCopy.templateUrl) componentDefinition.templateUrl = routeCopy.templateUrl;
if (routeCopy.template) componentDefinition.template = routeCopy.template;
// if we have route resolve options, prepare a wrapper controller
if (directiveController && routeCopy.resolve) {
var originalController = directiveController;
var resolvedLocals = {};
componentDefinition.controller = ['$injector', '$scope', function ($injector, $scope) {
var locals = angular.extend({
$scope: $scope
}, resolvedLocals);
return $injector.instantiate(originalController, locals);
}];
// we resolve the locals in a canActivate block
componentDefinition.controller.$canActivate = function() {
var locals = angular.extend({}, routeCopy.resolve);
angular.forEach(locals, function(value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) : $injector.invoke(value, null, null, key);
});
return $q.all(locals).then(function (locals) {
resolvedLocals = locals;
}).then(function () {
return true;
});
};
}
// register the dynamically created directive
$compileProvider.component(componentName, componentDefinition);
}
if (subscriptionFn) {
subscriptionFn(routeDefinition);
} else {
routes.push(routeDefinition);
}
successCount++;
return this;
};
this.otherwise = function(params) {
if (typeof params === 'string') {
params = {redirectTo: params};
}
this.when('/*rest', params);
return this;
};
this.$get = ['$q', '$injector', function (q, injector) {
$q = q;
$injector = injector;
var $route = {
routes: routeMap,
/**
* @ngdoc method
* @name $route#reload
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*/
reload: function() {
throw new Error('Not implemented: $route.reload');
},
/**
* @ngdoc method
* @name $route#updateParams
*/
updateParams: function(newParams) {
throw new Error('Not implemented: $route.updateParams');
},
/**
* Runs the given `fn` whenever new configs are added.
* Only one subscription is allowed.
* Passed `fn` is called synchronously.
*/
$$subscribe: function(fn) {
if (subscriptionFn) {
throw new Error('only one subscription allowed');
}
subscriptionFn = fn;
subscriptionFn(routes);
routes = [];
},
/**
* Runs a string with stats about many route configs were adapted, and how many were
* dropped because they are incompatible.
*/
$$getStats: consoleMetrics
};
return $route;
}];
}
function $routeParamsFactory($rootRouter, $rootScope) {
// the identity of this object cannot change
var paramsObj = {};
$rootScope.$on('$routeChangeSuccess', function () {
var newParams = $rootRouter.currentInstruction && $rootRouter.currentInstruction.component.params;
angular.forEach(paramsObj, function (val, name) {
delete paramsObj[name];
});
angular.forEach(newParams, function (val, name) {
paramsObj[name] = val;
});
});
return paramsObj;
}
/**
* Allows normal anchor links to kick off routing.
*/
function anchorLinkDirective($rootRouter) {
return {
restrict: 'E',
link: function (scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') {
return;
}
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var hrefAttrName = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function (event) {
if (event.which !== 1) {
return;
}
var href = element.attr(hrefAttrName);
var target = element.attr('target');
var isExternal = (['_blank', '_parent', '_self', '_top'].indexOf(target) > -1);
if (href && $rootRouter.recognize(href) && !isExternal) {
$rootRouter.navigateByUrl(href);
event.preventDefault();
}
});
}
};
}
/**
* Given a route object, attempts to find a unique directive name.
*
* @param route – route config object passed to $routeProvider.when
* @param path – route configuration path
* @returns {string|name} – a normalized (camelCase) directive name
*/
function routeObjToRouteName(route, path) {
var name = route.controllerAs;
var controller = route.controller;
if (!name && controller) {
if (angular.isArray(controller)) {
controller = controller[controller.length - 1];
}
name = controller.name;
}
if (!name) {
var segments = path.split('/');
name = segments[segments.length - 1];
}
if (name) {
name = name + 'AutoCmp';
}
return name;
}
function upperCase(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
/*
* Changes "/:foo*" to "/*foo"
*/
var WILDCARD_PARAM_RE = new RegExp('\\/:([a-z0-9]+)\\*', 'gi');
function reformatWildcardParams(path) {
return path.replace(WILDCARD_PARAM_RE, function (m, m1) {
return '/*' + m1;
});
}
}());