/
routable.js
338 lines (265 loc) · 9.61 KB
/
routable.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
var get = Ember.get, getPath = Ember.getPath;
// The Ember Routable mixin assumes the existance of a simple
// routing shim that supports the following three behaviors:
//
// * .getURL() - this is called when the page loads
// * .setURL(newURL) - this is called from within the state
// manager when the state changes to a routable state
// * .onURLChange(callback) - this happens when the user presses
// the back or forward button
var paramForClass = function(classObject) {
var className = classObject.toString(),
parts = className.split("."),
last = parts[parts.length - 1];
return Ember.String.underscore(last) + "_id";
};
var merge = function(original, hash) {
for (var prop in hash) {
if (!hash.hasOwnProperty(prop)) { continue; }
original[prop] = hash[prop];
}
};
Ember.Routable = Ember.Mixin.create({
init: function() {
var redirection;
this.on('connectOutlets', this, this.stashContext);
if (redirection = get(this, 'redirectsTo')) {
Ember.assert("You cannot use `redirectsTo` if you already have a `connectOutlets` method", this.connectOutlets === Ember.K);
this.connectOutlets = function(router) {
router.transitionTo(redirection);
};
}
// normalize empty route to '/'
var route = get(this, 'route');
if (route === '') {
route = '/';
}
this._super();
Ember.assert("You cannot use `redirectsTo` on a state that has child states", !redirection || (!!redirection && !!get(this, 'isLeaf')));
},
/**
@private
Whenever a routable state is entered, the context it was entered with
is stashed so that we can regenerate the state's `absoluteURL` on
demand.
*/
stashContext: function(manager, context) {
var serialized = this.serialize(manager, context);
manager.setStateMeta(this, 'serialized', serialized);
if (get(this, 'isRoutable') && !get(manager, 'isRouting')) {
this.updateRoute(manager, get(manager, 'location'));
}
},
/**
@private
Whenever a routable state is entered, the router's location object
is notified to set the URL to the current absolute path.
In general, this will update the browser's URL.
*/
updateRoute: function(manager, location) {
if (get(this, 'isLeaf')) {
var path = this.absoluteRoute(manager);
location.setURL(path);
}
},
/**
@private
Get the absolute route for the current state and a given
hash.
This method is private, as it expects a serialized hash,
not the original context object.
*/
absoluteRoute: function(manager, hash) {
var parentState = get(this, 'parentState');
var path = '', generated;
// If the parent state is routable, use its current path
// as this route's prefix.
if (get(parentState, 'isRoutable')) {
path = parentState.absoluteRoute(manager, hash);
}
var matcher = get(this, 'routeMatcher'),
serialized = manager.getStateMeta(this, 'serialized');
// merge the existing serialized object in with the passed
// in hash.
hash = hash || {};
merge(hash, serialized);
generated = matcher && matcher.generate(hash);
if (generated) {
path = path + '/' + generated;
}
return path;
},
/**
@private
At the moment, a state is routable if it has a string `route`
property. This heuristic may change.
*/
isRoutable: Ember.computed(function() {
return typeof get(this, 'route') === 'string';
}).cacheable(),
/**
@private
A _RouteMatcher object generated from the current route's `route`
string property.
*/
routeMatcher: Ember.computed(function() {
if (get(this, 'route')) {
return Ember._RouteMatcher.create({ route: get(this, 'route') });
}
}).cacheable(),
/**
@private
The model class associated with the current state. This property
uses the `modelType` property, in order to allow it to be
specified as a String.
*/
modelClass: Ember.computed(function() {
var modelType = get(this, 'modelType');
if (typeof modelType === 'string') {
return Ember.getPath(window, modelType);
} else {
return modelType;
}
}).cacheable(),
/**
@private
Get the model class for the state. The heuristic is:
* The state must have a single dynamic segment
* The dynamic segment must end in `_id`
* A dynamic segment like `blog_post_id` is converted into `BlogPost`
* The name is then looked up on the passed in namespace
The process of initializing an application with a router will
pass the application's namespace into the router, which will be
used here.
*/
modelClassFor: function(namespace) {
var modelClass, routeMatcher, identifiers, match, className;
// if an explicit modelType was specified, use that
if (modelClass = get(this, 'modelClass')) { return modelClass; }
// if the router has no lookup namespace, we won't be able to guess
// the modelType
if (!namespace) { return; }
// make sure this state is actually a routable state
routeMatcher = get(this, 'routeMatcher');
if (!routeMatcher) { return; }
// only guess modelType for states with a single dynamic segment
// (no more, no fewer)
identifiers = routeMatcher.identifiers;
if (identifiers.length !== 2) { return; }
// extract the `_id` from the end of the dynamic segment; if the
// dynamic segment does not end in `_id`, we can't guess the
// modelType
match = identifiers[1].match(/^(.*)_id$/);
if (!match) { return; }
// convert the underscored type into a class form and look it up
// on the router's namespace
className = Ember.String.classify(match[1]);
return get(namespace, className);
},
/**
The default method that takes a `params` object and converts
it into an object.
By default, a params hash that looks like `{ post_id: 1 }`
will be looked up as `namespace.Post.find(1)`. This is
designed to work seamlessly with Ember Data, but will work
fine with any class that has a `find` method.
*/
deserialize: function(manager, params) {
var modelClass, routeMatcher, param;
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
return modelClass.find(params[paramForClass(modelClass)]);
}
return params;
},
/**
The default method that takes an object and converts it into
a params hash.
By default, if there is a single dynamic segment named
`blog_post_id` and the object is a `BlogPost` with an
`id` of `12`, the serialize method will produce:
{ blog_post_id: 12 }
*/
serialize: function(manager, context) {
var modelClass, routeMatcher, namespace, param, id;
if (Ember.empty(context)) { return ''; }
if (modelClass = this.modelClassFor(get(manager, 'namespace'))) {
param = paramForClass(modelClass);
id = get(context, 'id');
context = {};
context[param] = id;
}
return context;
},
/**
@private
Once `unroute` has finished unwinding, `routePath` will be called
with the remainder of the route.
For example, if you were in the /posts/1/comments state, and you
moved into the /posts/2/comments state, `routePath` will be called
on the state whose path is `/posts` with the path `/2/comments`.
*/
routePath: function(manager, path) {
if (get(this, 'isLeaf')) { return; }
var childStates = get(this, 'childStates'), match;
childStates = childStates.sort(function(a, b) {
var aDynamicSegments = getPath(a, 'routeMatcher.identifiers.length'),
bDynamicSegments = getPath(b, 'routeMatcher.identifiers.length'),
aRoute = get(a, 'route'),
bRoute = get(b, 'route');
if (aRoute.indexOf(bRoute) === 0) {
return -1;
} else if (bRoute.indexOf(aRoute) === 0) {
return 1;
}
if (aDynamicSegments !== bDynamicSegments) {
return aDynamicSegments - bDynamicSegments;
}
return getPath(b, 'route.length') - getPath(a, 'route.length');
});
var state = childStates.find(function(state) {
var matcher = get(state, 'routeMatcher');
if (match = matcher.match(path)) { return true; }
});
Ember.assert("Could not find state for path " + path, !!state);
var object = state.deserialize(manager, match.hash) || {};
manager.transitionTo(get(state, 'path'), object);
manager.send('routePath', match.remaining);
},
/**
@private
When you move to a new route by pressing the back
or forward button, this method is called first.
Its job is to move the state manager into a parent
state of the state it will eventually move into.
*/
unroutePath: function(router, path) {
// If we're at the root state, we're done
if (get(this, 'parentState') === router) {
return;
}
path = path.replace(/^(?=[^\/])/, "/");
var absolutePath = this.absoluteRoute(router);
var route = get(this, 'route');
// If the current path is empty, move up one state,
// because the index ('/') state must be a leaf node.
if (route !== '/') {
// If the current path is a prefix of the path we're trying
// to go to, we're done.
var index = path.indexOf(absolutePath),
next = path.charAt(absolutePath.length);
if (index === 0 && (next === "/" || next === "")) {
return;
}
}
// Transition to the parent and call unroute again.
var parentPath = get(get(this, 'parentState'), 'path');
router.transitionTo(parentPath);
router.send('unroutePath', path);
},
/**
The `connectOutlets` method will be triggered once a
state has been entered. It will be called with the
route's context.
*/
connectOutlets: Ember.K
});