-
Notifications
You must be signed in to change notification settings - Fork 66
/
app-route.js
393 lines (340 loc) · 10.2 KB
/
app-route.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
/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at
http://polymer.github.io/LICENSE.txt The complete set of authors may be found at
http://polymer.github.io/AUTHORS.txt The complete set of contributors may be
found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as
part of the polymer project is also subject to an additional IP rights grant
found at http://polymer.github.io/PATENTS.txt
*/
import '@polymer/polymer/polymer-legacy.js';
import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn.js';
/**
`app-route` is an element that enables declarative, self-describing routing
for a web app.
In its typical usage, a `app-route` element consumes an object that describes
some state about the current route, via the `route` property. It then parses
that state using the `pattern` property, and produces two artifacts: some `data`
related to the `route`, and a `tail` that contains the rest of the `route` that
did not match.
Here is a basic example, when used with `app-location`:
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:page"
data="{{data}}"
tail="{{tail}}">
</app-route>
In the above example, the `app-location` produces a `route` value. Then, the
`route.path` property is matched by comparing it to the `pattern` property. If
the `pattern` property matches `route.path`, the `app-route` will set or update
its `data` property with an object whose properties correspond to the parameters
in `pattern`. So, in the above example, if `route.path` was `'/about'`, the
value of `data` would be `{"page": "about"}`.
The `tail` property represents the remaining part of the route state after the
`pattern` has been applied to a matching `route`.
Here is another example, where `tail` is used:
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:page"
data="{{routeData}}"
tail="{{subroute}}">
</app-route>
<app-route
route="{{subroute}}"
pattern="/:id"
data="{{subrouteData}}">
</app-route>
In the above example, there are two `app-route` elements. The first
`app-route` consumes a `route`. When the `route` is matched, the first
`app-route` also produces `routeData` from its `data`, and `subroute` from
its `tail`. The second `app-route` consumes the `subroute`, and when it
matches, it produces an object called `subrouteData` from its `data`.
So, when `route.path` is `'/about'`, the `routeData` object will look like
this: `{ page: 'about' }`
And `subrouteData` will be null. However, if `route.path` changes to
`'/article/123'`, the `routeData` object will look like this:
`{ page: 'article' }`
And the `subrouteData` will look like this: `{ id: '123' }`
`app-route` is responsive to bi-directional changes to the `data` objects
they produce. So, if `routeData.page` changed from `'article'` to `'about'`,
the `app-route` will update `route.path`. This in-turn will update the
`app-location`, and cause the global location bar to change its value.
@element app-route
@demo demo/index.html
@demo demo/data-loading-demo.html
@demo demo/simple-demo.html
*/
Polymer({
is: 'app-route',
/** @override */
_template: null,
properties: {
/**
* The URL component managed by this element.
*/
route: {
type: Object,
notify: true,
},
/**
* The pattern of slash-separated segments to match `route.path` against.
*
* For example the pattern "/foo" will match "/foo" or "/foo/bar"
* but not "/foobar".
*
* Path segments like `/:named` are mapped to properties on the `data`
* object.
*/
pattern: {
type: String,
},
/**
* The parameterized values that are extracted from the route as
* described by `pattern`.
*/
data: {
type: Object,
value: function() {
return {};
},
notify: true,
},
/**
* Auto activate route if path empty
*/
autoActivate: {
type: Boolean,
value: false,
},
_queryParamsUpdating: {
type: Boolean,
value: false,
},
/**
* @type {?Object}
*/
queryParams: {
type: Object,
value: function() {
return {};
},
notify: true,
},
/**
* The part of `route.path` NOT consumed by `pattern`.
*/
tail: {
type: Object,
value: function() {
return {
path: null,
prefix: null,
__queryParams: null,
};
},
notify: true,
},
/**
* Whether the current route is active. True if `route.path` matches the
* `pattern`, false otherwise.
*/
active: {
type: Boolean,
notify: true,
readOnly: true,
},
/**
* @type {?string}
*/
_matched: {
type: String,
value: '',
}
},
observers: [
'__tryToMatch(route.path, pattern)',
'__updatePathOnDataChange(data.*)',
'__tailPathChanged(tail.path)',
'__routeQueryParamsChanged(route.__queryParams)',
'__tailQueryParamsChanged(tail.__queryParams)',
'__queryParamsChanged(queryParams.*)'
],
/** @override */
created: function() {
this.linkPaths('route.__queryParams', 'tail.__queryParams');
this.linkPaths('tail.__queryParams', 'route.__queryParams');
},
/**
* Deal with the query params object being assigned to wholesale.
*/
__routeQueryParamsChanged: function(queryParams) {
if (queryParams && this.tail) {
if (this.tail.__queryParams !== queryParams) {
this.set('tail.__queryParams', queryParams);
}
if (!this.active || this._queryParamsUpdating) {
return;
}
// Copy queryParams and track whether there are any differences compared
// to the existing query params.
var copyOfQueryParams = {};
var anythingChanged = false;
for (var key in queryParams) {
copyOfQueryParams[key] = queryParams[key];
if (anythingChanged || !this.queryParams ||
queryParams[key] !== this.queryParams[key]) {
anythingChanged = true;
}
}
// Need to check whether any keys were deleted
for (var key in this.queryParams) {
if (anythingChanged || !(key in queryParams)) {
anythingChanged = true;
break;
}
}
if (!anythingChanged) {
return;
}
this._queryParamsUpdating = true;
this.set('queryParams', copyOfQueryParams);
this._queryParamsUpdating = false;
}
},
__tailQueryParamsChanged: function(queryParams) {
if (queryParams && this.route && this.route.__queryParams != queryParams) {
this.set('route.__queryParams', queryParams);
}
},
__queryParamsChanged: function(changes) {
if (!this.active || this._queryParamsUpdating) {
return;
}
this.set('route.__' + changes.path, changes.value);
},
__resetProperties: function() {
this._setActive(false);
this._matched = null;
},
__tryToMatch: function() {
if (!this.route) {
return;
}
var path = this.route.path;
var pattern = this.pattern;
if (this.autoActivate && path === '') {
path = '/';
}
if (!pattern) {
return;
}
if (!path) {
this.__resetProperties();
return;
}
var remainingPieces = path.split('/');
var patternPieces = pattern.split('/');
var matched = [];
var namedMatches = {};
for (var i = 0; i < patternPieces.length; i++) {
var patternPiece = patternPieces[i];
if (!patternPiece && patternPiece !== '') {
break;
}
var pathPiece = remainingPieces.shift();
// We don't match this path.
if (!pathPiece && pathPiece !== '') {
this.__resetProperties();
return;
}
matched.push(pathPiece);
if (patternPiece.charAt(0) == ':') {
namedMatches[patternPiece.slice(1)] = pathPiece;
} else if (patternPiece !== pathPiece) {
this.__resetProperties();
return;
}
}
this._matched = matched.join('/');
// Properties that must be updated atomically.
var propertyUpdates = {};
// this.active
if (!this.active) {
propertyUpdates.active = true;
}
// this.tail
var tailPrefix = this.route.prefix + this._matched;
var tailPath = remainingPieces.join('/');
if (remainingPieces.length > 0) {
tailPath = '/' + tailPath;
}
if (!this.tail || this.tail.prefix !== tailPrefix ||
this.tail.path !== tailPath) {
propertyUpdates.tail = {
prefix: tailPrefix,
path: tailPath,
__queryParams: this.route.__queryParams
};
}
// this.data
propertyUpdates.data = namedMatches;
this._dataInUrl = {};
for (var key in namedMatches) {
this._dataInUrl[key] = namedMatches[key];
}
// atomic update
this.setProperties(propertyUpdates, true);
},
__tailPathChanged: function(path) {
if (!this.active) {
return;
}
var tailPath = path;
var newPath = this._matched;
if (tailPath) {
if (tailPath.charAt(0) !== '/') {
tailPath = '/' + tailPath;
}
newPath += tailPath;
}
this.set('route.path', newPath);
},
__updatePathOnDataChange: function() {
if (!this.route || !this.active) {
return;
}
var newPath = this.__getLink({});
var oldPath = this.__getLink(this._dataInUrl);
if (newPath === oldPath) {
return;
}
this.set('route.path', newPath);
},
__getLink: function(overrideValues) {
var values = {tail: null};
for (var key in this.data) {
values[key] = this.data[key];
}
for (var key in overrideValues) {
values[key] = overrideValues[key];
}
var patternPieces = this.pattern.split('/');
var interp = patternPieces.map(function(value) {
if (value[0] == ':') {
value = values[value.slice(1)];
}
return value;
}, this);
if (values.tail && values.tail.path) {
if (interp.length > 0 && values.tail.path.charAt(0) === '/') {
interp.push(values.tail.path.slice(1));
} else {
interp.push(values.tail.path);
}
}
return interp.join('/');
},
});